feat(update): integrate managed installs and recoverable in-app updates (#6168)
Add owner-aware Stable and Preview updates with explicit consent, verified release plans, protected process handoff and bounded service recovery. Keep configuration and conversations separate from program rollback. Include the compact About controls, Windows long-path support, native package recovery checks and optional macOS Dock lifecycle integration. Preserve documented guidance for installations owned by other managers. This code integration does not publish packages, enable signing or advance the public update channel. Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
1 parent
76da55994b
commit
fbb61a373f
216 files changed
+27948
-1084
No files matched your search
@@ -1,2 +1,5 @@
|
||||
# Ensure shell scripts always use LF line endings (Docker/Linux compat)
|
||||
*.sh text eol=lf
|
||||
|
||||
# The public Sigstore fixture is signed over exact bytes, including newlines.
|
||||
tests/fixtures/sigstore/bundle_v3.txt -text
|
||||
@@ -0,0 +1,3 @@
|
||||
# This isolated signing job never installs nanobot or candidate dependencies.
|
||||
sigstore==4.5.0
|
||||
packaging==26.3
|
||||
@@ -0,0 +1,615 @@
|
||||
annotated-types==0.8.0 \
|
||||
--hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \
|
||||
--hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0
|
||||
# via pydantic
|
||||
certifi==2026.7.22 \
|
||||
--hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 \
|
||||
--hash=sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55
|
||||
# via requests
|
||||
cffi==2.1.1 \
|
||||
--hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \
|
||||
--hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \
|
||||
--hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \
|
||||
--hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \
|
||||
--hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \
|
||||
--hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \
|
||||
--hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \
|
||||
--hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \
|
||||
--hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \
|
||||
--hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \
|
||||
--hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \
|
||||
--hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \
|
||||
--hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \
|
||||
--hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \
|
||||
--hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \
|
||||
--hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \
|
||||
--hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \
|
||||
--hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \
|
||||
--hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \
|
||||
--hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \
|
||||
--hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \
|
||||
--hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \
|
||||
--hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \
|
||||
--hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \
|
||||
--hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \
|
||||
--hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \
|
||||
--hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \
|
||||
--hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \
|
||||
--hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \
|
||||
--hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \
|
||||
--hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \
|
||||
--hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \
|
||||
--hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \
|
||||
--hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \
|
||||
--hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \
|
||||
--hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \
|
||||
--hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \
|
||||
--hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \
|
||||
--hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \
|
||||
--hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \
|
||||
--hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \
|
||||
--hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \
|
||||
--hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \
|
||||
--hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \
|
||||
--hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \
|
||||
--hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \
|
||||
--hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \
|
||||
--hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \
|
||||
--hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \
|
||||
--hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \
|
||||
--hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \
|
||||
--hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \
|
||||
--hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \
|
||||
--hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \
|
||||
--hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \
|
||||
--hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \
|
||||
--hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \
|
||||
--hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \
|
||||
--hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \
|
||||
--hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \
|
||||
--hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \
|
||||
--hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \
|
||||
--hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \
|
||||
--hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \
|
||||
--hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \
|
||||
--hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \
|
||||
--hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \
|
||||
--hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \
|
||||
--hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \
|
||||
--hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \
|
||||
--hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \
|
||||
--hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \
|
||||
--hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \
|
||||
--hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \
|
||||
--hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \
|
||||
--hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \
|
||||
--hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \
|
||||
--hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \
|
||||
--hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \
|
||||
--hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \
|
||||
--hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \
|
||||
--hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \
|
||||
--hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \
|
||||
--hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \
|
||||
--hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \
|
||||
--hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \
|
||||
--hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \
|
||||
--hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \
|
||||
--hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \
|
||||
--hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \
|
||||
--hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \
|
||||
--hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \
|
||||
--hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \
|
||||
--hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \
|
||||
--hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \
|
||||
--hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \
|
||||
--hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \
|
||||
--hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \
|
||||
--hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \
|
||||
--hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264
|
||||
# via cryptography
|
||||
charset-normalizer==3.5.2 \
|
||||
--hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \
|
||||
--hash=sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf \
|
||||
--hash=sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5 \
|
||||
--hash=sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56 \
|
||||
--hash=sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26 \
|
||||
--hash=sha256:0891b9d3903c5571c03771ca669a4b0ec5618ca722a5c957d3d29cd4e5062848 \
|
||||
--hash=sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718 \
|
||||
--hash=sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93 \
|
||||
--hash=sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640 \
|
||||
--hash=sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3 \
|
||||
--hash=sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875 \
|
||||
--hash=sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e \
|
||||
--hash=sha256:1461ac396c4fdb983a675f20aa555624f0ee18ac83d832b9244ffff3d8055275 \
|
||||
--hash=sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204 \
|
||||
--hash=sha256:15bb4005af6320d259dc7593ca84a38d7fe06a421dbcf7b910ae23979101e787 \
|
||||
--hash=sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234 \
|
||||
--hash=sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3 \
|
||||
--hash=sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98 \
|
||||
--hash=sha256:195c26fb65950f8fce54e26349852b7bdd7c5f120aeefbcc440b8a20faaed4a3 \
|
||||
--hash=sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187 \
|
||||
--hash=sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d \
|
||||
--hash=sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f \
|
||||
--hash=sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7 \
|
||||
--hash=sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011 \
|
||||
--hash=sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f \
|
||||
--hash=sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869 \
|
||||
--hash=sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1 \
|
||||
--hash=sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d \
|
||||
--hash=sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847 \
|
||||
--hash=sha256:28a15fdad492a99b6eccfaaed66ef3f74050680545ea61ec8b2f4c538f1f1320 \
|
||||
--hash=sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9 \
|
||||
--hash=sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93 \
|
||||
--hash=sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd \
|
||||
--hash=sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00 \
|
||||
--hash=sha256:2cc961b171b3f3440f410489ab3573e86aea8736134ebbb40ea1338b7f0831bc \
|
||||
--hash=sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0 \
|
||||
--hash=sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09 \
|
||||
--hash=sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac \
|
||||
--hash=sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621 \
|
||||
--hash=sha256:30fcd120b732aa79317f08dee04d7de0847822e4cf7ee0e9f445bb958832252c \
|
||||
--hash=sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8 \
|
||||
--hash=sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a \
|
||||
--hash=sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51 \
|
||||
--hash=sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0 \
|
||||
--hash=sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef \
|
||||
--hash=sha256:3d14b50de6bf4d0edf857a9386836846f982b8f524e188e2e68b96d702bcf4aa \
|
||||
--hash=sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6 \
|
||||
--hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649 \
|
||||
--hash=sha256:3ddacd27458c45bdacd6bd6db644bfb730efbf9e830310186e3045c9c5be8fb2 \
|
||||
--hash=sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229 \
|
||||
--hash=sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e \
|
||||
--hash=sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd \
|
||||
--hash=sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115 \
|
||||
--hash=sha256:447441e76ec720b15e64418d32e092297340387053047c7c694f579efb0ee1d9 \
|
||||
--hash=sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c \
|
||||
--hash=sha256:44bd4fbb29dfbeba60e7d2bd000c59e4b21ddb3cc53912b14048d37092706d7c \
|
||||
--hash=sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab \
|
||||
--hash=sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253 \
|
||||
--hash=sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995 \
|
||||
--hash=sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438 \
|
||||
--hash=sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0 \
|
||||
--hash=sha256:50e3adfb96fc189eb27b1cf62d3b598b89b4bb0420d93a3d3e42e137409011be \
|
||||
--hash=sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b \
|
||||
--hash=sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7 \
|
||||
--hash=sha256:55ea99acb17b9325618de155a0cd6a2e8f5d10be008113e1d433bbb58db543b2 \
|
||||
--hash=sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a \
|
||||
--hash=sha256:588461c2e8384d309bd63e5826019b6977bc66d629b99ac8737bb795d7b2cb5a \
|
||||
--hash=sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a \
|
||||
--hash=sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c \
|
||||
--hash=sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5 \
|
||||
--hash=sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37 \
|
||||
--hash=sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e \
|
||||
--hash=sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4 \
|
||||
--hash=sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800 \
|
||||
--hash=sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055 \
|
||||
--hash=sha256:619799369eeef6366ed3e8755a5670f4f2f0fb6b30a0fd7264dc0fdc2357058e \
|
||||
--hash=sha256:62588a277bfb59def052abd940703fa35107152bf479781a878617d60faf8fb5 \
|
||||
--hash=sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c \
|
||||
--hash=sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b \
|
||||
--hash=sha256:68eb192d85ab8e5f6ec69c2bc6ac0179fbf04a5ac1569d12fbef74883fe102d0 \
|
||||
--hash=sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80 \
|
||||
--hash=sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a \
|
||||
--hash=sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4 \
|
||||
--hash=sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2 \
|
||||
--hash=sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58 \
|
||||
--hash=sha256:75a3ceed0724d625d64b86ca20aba182e4df462e04c2414fc941c0f523f06aac \
|
||||
--hash=sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc \
|
||||
--hash=sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639 \
|
||||
--hash=sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf \
|
||||
--hash=sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d \
|
||||
--hash=sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f \
|
||||
--hash=sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c \
|
||||
--hash=sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc \
|
||||
--hash=sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4 \
|
||||
--hash=sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253 \
|
||||
--hash=sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade \
|
||||
--hash=sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858 \
|
||||
--hash=sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26 \
|
||||
--hash=sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96 \
|
||||
--hash=sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8 \
|
||||
--hash=sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249 \
|
||||
--hash=sha256:8b2bfab86aa71ae13aa41a6a26aab338e0db2b8bc75434b05aea89e011ff35a4 \
|
||||
--hash=sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13 \
|
||||
--hash=sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1 \
|
||||
--hash=sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03 \
|
||||
--hash=sha256:93223adc95033dd47133a46ccfc316a0139176fd79085762e27202ec56018f03 \
|
||||
--hash=sha256:9373ad13ef0d2c0fb761e04e55bfdee5a08b52cef2c882c8fbe9935b1517152e \
|
||||
--hash=sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364 \
|
||||
--hash=sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4 \
|
||||
--hash=sha256:9bde855991b7e362c146535e3136a50bfaffc0487d38b33ca7e5edefc6e23849 \
|
||||
--hash=sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0 \
|
||||
--hash=sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a \
|
||||
--hash=sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036 \
|
||||
--hash=sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3 \
|
||||
--hash=sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21 \
|
||||
--hash=sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3 \
|
||||
--hash=sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e \
|
||||
--hash=sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413 \
|
||||
--hash=sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21 \
|
||||
--hash=sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346 \
|
||||
--hash=sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429 \
|
||||
--hash=sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685 \
|
||||
--hash=sha256:b736353c0a625bbd5fcec108576e2385db3496f4f771f785ff32e108d3c3bc45 \
|
||||
--hash=sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f \
|
||||
--hash=sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c \
|
||||
--hash=sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d \
|
||||
--hash=sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad \
|
||||
--hash=sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400 \
|
||||
--hash=sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb \
|
||||
--hash=sha256:c6708715abcf3c73b99508253e961a9967f02fe536532834149574eda6de0d1c \
|
||||
--hash=sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc \
|
||||
--hash=sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c \
|
||||
--hash=sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74 \
|
||||
--hash=sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf \
|
||||
--hash=sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604 \
|
||||
--hash=sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f \
|
||||
--hash=sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105 \
|
||||
--hash=sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a \
|
||||
--hash=sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d \
|
||||
--hash=sha256:d4a7319f304a774bed22115bc891618e45f85065ab44ea6acd07d274e750519a \
|
||||
--hash=sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1 \
|
||||
--hash=sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5 \
|
||||
--hash=sha256:d913de495d90407cd859d263bee2e5d1a4ed3eb6573c04e70d9ec619a7cbed7f \
|
||||
--hash=sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e \
|
||||
--hash=sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709 \
|
||||
--hash=sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874 \
|
||||
--hash=sha256:ddf19c062bea7a0cc80f519243d2c01dd091be0cf952a0750d4ad576709559f5 \
|
||||
--hash=sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc \
|
||||
--hash=sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95 \
|
||||
--hash=sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd \
|
||||
--hash=sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0 \
|
||||
--hash=sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d \
|
||||
--hash=sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3 \
|
||||
--hash=sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c \
|
||||
--hash=sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3 \
|
||||
--hash=sha256:e80e6c2f55656b4824d72065abb4ddd6a525c74bd78a0aab5d9fc2cf4fb5af50 \
|
||||
--hash=sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491 \
|
||||
--hash=sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5 \
|
||||
--hash=sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5 \
|
||||
--hash=sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655 \
|
||||
--hash=sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288 \
|
||||
--hash=sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd \
|
||||
--hash=sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084 \
|
||||
--hash=sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d \
|
||||
--hash=sha256:f5833ad231be5eb6553de524a70f48d71b2c8563101750531e0b80184e175cd4 \
|
||||
--hash=sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915 \
|
||||
--hash=sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1 \
|
||||
--hash=sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd \
|
||||
--hash=sha256:fc14a032f813bf5fe624d991960ea83e9715adc27e4c1830a2361eb1d02ac341 \
|
||||
--hash=sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424 \
|
||||
--hash=sha256:fd1fbe0f116b6e55da77aca2c6ddcddcfac2186cbf78bdebf40fc156efca389d \
|
||||
--hash=sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f
|
||||
# via requests
|
||||
cryptography==50.0.2 \
|
||||
--hash=sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602 \
|
||||
--hash=sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2 \
|
||||
--hash=sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047 \
|
||||
--hash=sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c \
|
||||
--hash=sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42 \
|
||||
--hash=sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18 \
|
||||
--hash=sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51 \
|
||||
--hash=sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81 \
|
||||
--hash=sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856 \
|
||||
--hash=sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2 \
|
||||
--hash=sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de \
|
||||
--hash=sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7 \
|
||||
--hash=sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd \
|
||||
--hash=sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2 \
|
||||
--hash=sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be \
|
||||
--hash=sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45 \
|
||||
--hash=sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0 \
|
||||
--hash=sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e \
|
||||
--hash=sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c \
|
||||
--hash=sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5 \
|
||||
--hash=sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452 \
|
||||
--hash=sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48 \
|
||||
--hash=sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05 \
|
||||
--hash=sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1 \
|
||||
--hash=sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93 \
|
||||
--hash=sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04 \
|
||||
--hash=sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e \
|
||||
--hash=sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67 \
|
||||
--hash=sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7 \
|
||||
--hash=sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107 \
|
||||
--hash=sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079 \
|
||||
--hash=sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134 \
|
||||
--hash=sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227 \
|
||||
--hash=sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1 \
|
||||
--hash=sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539 \
|
||||
--hash=sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e \
|
||||
--hash=sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d \
|
||||
--hash=sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c \
|
||||
--hash=sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd \
|
||||
--hash=sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020 \
|
||||
--hash=sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd \
|
||||
--hash=sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94 \
|
||||
--hash=sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a \
|
||||
--hash=sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408 \
|
||||
--hash=sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37 \
|
||||
--hash=sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e \
|
||||
--hash=sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454 \
|
||||
--hash=sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c \
|
||||
--hash=sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc \
|
||||
--hash=sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37 \
|
||||
--hash=sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767 \
|
||||
--hash=sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a \
|
||||
--hash=sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5 \
|
||||
--hash=sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc \
|
||||
--hash=sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67 \
|
||||
--hash=sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8 \
|
||||
--hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \
|
||||
--hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb \
|
||||
--hash=sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b
|
||||
# via
|
||||
# pyopenssl
|
||||
# rfc3161-client
|
||||
# sigstore
|
||||
dnspython==2.9.0 \
|
||||
--hash=sha256:9a4aedb833c3c1b49214d04d44d3032ab7a9135f7c1d29a549b4ff78fd82fda9 \
|
||||
--hash=sha256:b44dc6b18f07a8b1c56676a19fbfdb5209415b046a9cece286baafa87ff3f7f1
|
||||
# via email-validator
|
||||
email-validator==2.3.0 \
|
||||
--hash=sha256:80f13f623413e6b197ae73bb10bf4eb0908faf509ad8362c5edeb0be7fd450b4 \
|
||||
--hash=sha256:9fc05c37f2f6cf439ff414f8fc46d917929974a82244c20eb10231ba60c54426
|
||||
# via pydantic
|
||||
id==1.6.1 \
|
||||
--hash=sha256:d0732d624fb46fd4e7bc4e5152f00214450953b9e772c182c1c22964def1a069 \
|
||||
--hash=sha256:f5ec41ed2629a508f5d0988eda142e190c9c6da971100612c4de9ad9f9b237ca
|
||||
# via sigstore
|
||||
idna==3.20 \
|
||||
--hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
|
||||
--hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
|
||||
# via
|
||||
# email-validator
|
||||
# requests
|
||||
markdown-it-py==4.2.0 \
|
||||
--hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \
|
||||
--hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
|
||||
# via rich
|
||||
mdurl==0.1.2 \
|
||||
--hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \
|
||||
--hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba
|
||||
# via markdown-it-py
|
||||
packaging==26.3 \
|
||||
--hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
|
||||
--hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
|
||||
# via -r .github/release-signing-requirements.in
|
||||
platformdirs==4.13.3 \
|
||||
--hash=sha256:5e567f664eb087ab8521c0179cd8d1bd60857d271136567a39719e28e2d383ce \
|
||||
--hash=sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4
|
||||
# via sigstore
|
||||
pyasn1==0.6.4 \
|
||||
--hash=sha256:9c447d8431c947fe4c8febc4ed9e760bc29011a5b01e5c74b67025bd9fb8ce81 \
|
||||
--hash=sha256:deda9277cfd454080ec40b207fb6df82206a3a2688735233cdcd8d3d565f088b
|
||||
# via sigstore
|
||||
pycparser==3.11 \
|
||||
--hash=sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80 \
|
||||
--hash=sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc
|
||||
# via cffi
|
||||
pydantic==2.14.1 \
|
||||
--hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \
|
||||
--hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26
|
||||
# via
|
||||
# sigstore
|
||||
# sigstore-models
|
||||
# sigstore-rekor-types
|
||||
pydantic-core==2.50.1 \
|
||||
--hash=sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c \
|
||||
--hash=sha256:0048b6dddc8ef4b64fccaad878bd143b0c3882ea9936279dc11d613f6b7dd1bc \
|
||||
--hash=sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b \
|
||||
--hash=sha256:028e2f212273d4a39b1ec1e0de8166b1165a65fc0f1111452a9d94fc7c625c63 \
|
||||
--hash=sha256:062e891facce5ca296a1c37098e5e466780457f86413894b399f0cf22934f769 \
|
||||
--hash=sha256:06e01fbbfdb9be777b316a71b6c49efaf4a08b615d0a98d678cda3023f79d019 \
|
||||
--hash=sha256:06ead20d39ffd6f2f6f2a8f8a6de67ff8bb1b4f14a8a30e058502514ee2ac685 \
|
||||
--hash=sha256:0b3a6f334c6a2345ca15318ff894502a90012536404b37c844a976c76c846e0b \
|
||||
--hash=sha256:0c003c3b7f49debb893d2d85ae099ac5959c9839e2f330fadb1fcdf7a6594482 \
|
||||
--hash=sha256:131059670f1d2444269b8585cb888963994871932447c08b39ac6a51fcfef658 \
|
||||
--hash=sha256:132529c83901437ff642f585216831bf5fd7a91df66829907e155192ead62498 \
|
||||
--hash=sha256:17e722e156d0444ecaefbe640bdb60928752bf2013e2b7a11cdb099aaae19bec \
|
||||
--hash=sha256:1a9006395dece0e32e704c315eff8a00bede494f6108546cfc5539c89fef4f9a \
|
||||
--hash=sha256:1c8632d4ac04e6f91128fca584b3a8a507d81604c24eeaaad00d4be42765c32b \
|
||||
--hash=sha256:1c96fd793b73d1b92e65570132505498fe7b21eaef73cdf74e67e5dfba7ac9e4 \
|
||||
--hash=sha256:1cf41f1ae3fa155cf167a72689ad044bcc1e3c97e064123677149bdfb5dafc4a \
|
||||
--hash=sha256:1deeacb112d14d3f4fcb16b165f7dbaf76c70ba6e82f37ba042bdab51970a0b8 \
|
||||
--hash=sha256:1ef800dd7d85bcdadf4c3076e4c94e43939493558a3b69a1ea830c706d4617bb \
|
||||
--hash=sha256:1fa4c8bc12c1354c5550c0c35c1852c8c1901e89e06561724e03f8d0342e1f87 \
|
||||
--hash=sha256:2005207aafe1231315718bf6ed5d064a7300fb4772754af35ee72fc68159492e \
|
||||
--hash=sha256:23923ab9292c40da026330b1ecf4dc2618c8e86e0422e5d1fbf50d94d64ca4f8 \
|
||||
--hash=sha256:23edad659e8dbd8ca7e4e877fe6c81573abbdf215bd25a68b53e1272f58b80c7 \
|
||||
--hash=sha256:2ab756b72bd5054e4c7ef3ded331b35786cbd3cf931531a508f79a9537517064 \
|
||||
--hash=sha256:2cbd1b75b09e976ed0d6b6ca297675632ca35df86130088457cdc60ef36970ae \
|
||||
--hash=sha256:2cf91809d0721ab81592ba67bea7694821679c10b1a2e3c3460082b286c1918a \
|
||||
--hash=sha256:2df1ff41884de2bc4b307bafd7c40a691094fad2ff8e767e5b45a319257bcf4e \
|
||||
--hash=sha256:2eb75304506894a281d346220a4f7481a1b8729577c5ed2a05395991966a8396 \
|
||||
--hash=sha256:2eedf82ee4753cdab8e50044c6bd569577eebc3859b11fecf4eb9223761ff966 \
|
||||
--hash=sha256:30ddf019d082c117b5d309e5b86710c2a78909907ec1a9381feec3eec02eca0b \
|
||||
--hash=sha256:325c23f3e35cfbf0fe3486fa5f7260d1e45885173002d30a28ca019994124255 \
|
||||
--hash=sha256:32fad3a91e51b6d2039c572db04a5a873260b399f6bd62c3552671fa7a4a2899 \
|
||||
--hash=sha256:36c426eac0af8d1529ff8467e612b933346caec1fdc0d774f78f67a1a11e16c1 \
|
||||
--hash=sha256:3a5fce22f1e87d181e924e12da7d81cfe031fb3881a5ddf26ad28f141756ca43 \
|
||||
--hash=sha256:3aa9de446b793de2beb6fa2d9d0961803126c4e2a99c2f25ab59b9fd6ea125c0 \
|
||||
--hash=sha256:3e46a9eb0a0901dd6275e6b06ac3a464885ef350ec4121fe486869de8053e4bb \
|
||||
--hash=sha256:3fde4fdc6487a58d944ca87cf5adc95d5f266e872c19599f5f4c0a8a1b1f9f9f \
|
||||
--hash=sha256:409e0ea40ec30d9158f33574fd758e689f6045a0f2596701828c27816ca9687d \
|
||||
--hash=sha256:40f523349960fa30f3ea51404308ff50f9997a90df639590f47a057c1f32b415 \
|
||||
--hash=sha256:41bc8237121bd8dc8d888dfd6279fc166ffc88c1f1bf3a8bf00869680533ca4c \
|
||||
--hash=sha256:42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea \
|
||||
--hash=sha256:455a773617b5913bf5c20d0692e5787b119e52c4d40ea644ca31f5758fd31be2 \
|
||||
--hash=sha256:45b11cac094aa25725581d9304eee93c9028516b9ea80dd9e175e13a5a2c840e \
|
||||
--hash=sha256:45c6266d071c241f2a168d45bf8c54344f0effce35e7e6b73afdec11f3687568 \
|
||||
--hash=sha256:46b3301d3b5c886f77de7546e47274a5842c622ea2020b8c6524c6b66913b4a6 \
|
||||
--hash=sha256:476f6ed8e43cd1e0b460920e23571700872b284e77331cb30c4faf459cf48a4b \
|
||||
--hash=sha256:48569b0ade9edfbe065cad1d700175546592aebbb42f02adcebcc26e75b896fe \
|
||||
--hash=sha256:49c2cbb2397fe4d0987e84606e691af6cb87bc0ee1bd3e7b737f7e10b4c142f9 \
|
||||
--hash=sha256:4a53d13cdfbedbfa87f08b83c1a0a5efcc767d785a4b41934fa9cb672670493a \
|
||||
--hash=sha256:4be846f55c9477f5f3ddde8f2ce941137e16862a56d018ed885d422bb6ae02f2 \
|
||||
--hash=sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9 \
|
||||
--hash=sha256:4e834f6a8e4ff772dcc34f58ef5504147a3ea5b0f4eeb13b0f8eb2ca75ac57f1 \
|
||||
--hash=sha256:57f51b31ff826e2859120cf4737c5a758a48d96f3e97da40ccee1796d58078ff \
|
||||
--hash=sha256:5958c72adb417c39b12ac87525ac60b0d73315fcdc59e21f44ee4a5e2512c9ef \
|
||||
--hash=sha256:5dfe41f232befddb9c4377f6cfc702b51595e2d78ed082672adf8758d2c4619f \
|
||||
--hash=sha256:5f3cae32fc46121f787cb2486de9cf95a8bf72aec5cc78f64c606fa1735a6ef5 \
|
||||
--hash=sha256:64f6047f62a6c5ae08d0a6afb035667aa2d97c3d20d69762e034c5ea144d92a5 \
|
||||
--hash=sha256:6a733778df2f7087ec1100ed0b41533e4f3001976e99570fa34f57c66e7f8e3e \
|
||||
--hash=sha256:6b20a4bffabdad0db2927ac034ae3b8a681b1f7a0182f3e60b479ad2fde21ebb \
|
||||
--hash=sha256:6dbcbee53bf17196a7f745aa9bf5a9603953a1e365b1f020be3207c676a3e7c4 \
|
||||
--hash=sha256:6ed4f3cef55164b026fefb41341b7754cc6b624c75dfe7142d2ecceb5ad21c87 \
|
||||
--hash=sha256:704075d10b74f2f3c6e15407c696d88701df35fc8953f434a431add0d0074db0 \
|
||||
--hash=sha256:739dc730e6be3bd5ec2f4ab5cfc7eb047cc45fc1497b3bafec74ff2ed07df597 \
|
||||
--hash=sha256:7456d699b13954e9c0164dcb267250a10ae0dfb03e6e26d6796ab0d46e189c84 \
|
||||
--hash=sha256:756d669f04e62ec4148ecfe22be6a4484d9b1181a6ef32e205ebfd200540858b \
|
||||
--hash=sha256:7689580e72a642ab5ec64d5f55b2e33636fa43b4ebe63c0c2c965ef307c7d1aa \
|
||||
--hash=sha256:76e2e83fa6ec8cdc972d438dafc2522b3a47bee4ec0ae668b29cfb1977ab5242 \
|
||||
--hash=sha256:7816e98acc08119dc0f340ab167048ecc54126316330c1f0caf7c6756c88e28f \
|
||||
--hash=sha256:79490e33c4c0fcb933bbbcfc3a62184d8803b99f535863dfbb925e1bcb6945ad \
|
||||
--hash=sha256:7f476456ac2bb0d937f75191494a09c83a30765fea4f70f3b404942fe25f6cdf \
|
||||
--hash=sha256:844b869f118e22a41a091bdcedda8a71bc1b0f62c38d1a0c3211cece47e1d8fc \
|
||||
--hash=sha256:84bc765b282a9d5b7fe0348b8648904f25a6a04b2139da52b1dd30c8ac3a2c8f \
|
||||
--hash=sha256:84f34323a61a365b4e9295de6028474754829aaddd59c7bf1a040e7487ef8f3c \
|
||||
--hash=sha256:8812592c85d0edf423f10eadcef42716d71e8219085ad9e85b775057b7306133 \
|
||||
--hash=sha256:88e492e8b9d0312e7dc13667c30222abf284dc3b79b5302b3607b41a5784ce61 \
|
||||
--hash=sha256:8a6791afa2245e6c6b180122d105941644f5bd410bb18623b408808cc41a3102 \
|
||||
--hash=sha256:8b4c3df25bd323bf1d36a648d563cf1fc69d717451569927151bdad7cad07a77 \
|
||||
--hash=sha256:8daa7ee75245d43ad7d747e5c9ecc1b1d06552f72b14887e9276f787d57375f4 \
|
||||
--hash=sha256:93ba4e9d8210d941c200431a56b2c0400b131865947903937ed3ec5404307d2e \
|
||||
--hash=sha256:94845ff54dc5193f228cab81b2662a04bfbb892e95bdc15edf7399000ce57d54 \
|
||||
--hash=sha256:94be440c03fede26969a5ce75468e0e6a9927a1b46d9b679ee8adc1b057b0350 \
|
||||
--hash=sha256:9572c1369e9c9da2d64a7b7992c786d90ff295abc93964cfe3125e4290768070 \
|
||||
--hash=sha256:983a662de2571cb2502fc8ff47b6770b03d025d2eb314c92f77b3f07c74720ed \
|
||||
--hash=sha256:992c3514ec891fa7858099183e4d64e6bd5a5d4ff452fae29df22faa77a006bb \
|
||||
--hash=sha256:99ba9bc2b8062ea0c326a990f7f00e6530c23579de66dd246e72c4cafef950a5 \
|
||||
--hash=sha256:9d1bed94af6a63835461f3cf7502058eb166c58c4778e11d0f433cfb1bd69e19 \
|
||||
--hash=sha256:9e4472072de0137ee0d8e72d6620e85939c271d2f90f6bbb4b15c24638b79f92 \
|
||||
--hash=sha256:a27c09d86600f1bf2fe3f37e1ae697faf3143931c09322cd799da94deee923b5 \
|
||||
--hash=sha256:a29a061fec0b4e2d714f277e70a3a18125ecff803f2fea6eade2f2e53711d112 \
|
||||
--hash=sha256:a3cda0e538208e5d722bbf3698b24f19c0a7d05bc8d5f8a7f9b121ea7fa243d9 \
|
||||
--hash=sha256:a44101320cfe99432db74237545a63057dc7a88dfe792cbcad0647f2af56cb81 \
|
||||
--hash=sha256:a4aaaa791bdae1c972a7e81765f4f3571c926b8e0b9b6e47346499fb80079665 \
|
||||
--hash=sha256:a51eee75939cf811ac09b278745a6cee7dc873ccfbc8b9af3cc88fe4b7ce25b5 \
|
||||
--hash=sha256:a7c58106de36ac6a56314182958de20db8d3a29dfd5db527192cc754e4f8e7fb \
|
||||
--hash=sha256:aa8224f10880d9bf1b5993988ba153d42a8b4f3f4f511f93b1f09c93ff613c72 \
|
||||
--hash=sha256:acbf31f37c53a5ac0c34706c80b4f5107ba20b05fdd3816124bf236ef0c57dd2 \
|
||||
--hash=sha256:adc06d218a1cadfd2ec4628424d7d79ce4eba69c2965e7e7b55106f0da5208c8 \
|
||||
--hash=sha256:ae28183297fb0d2b8dc46a1f01d51f5e45825fc5afe76a835a6cb7fb34821295 \
|
||||
--hash=sha256:b0135bcdcaa0f23573f286e4cb5e0fd2962700964ed13df085b85f2b97aeab9e \
|
||||
--hash=sha256:b087b1c5be7ac687cf22eabfe4b6b608d40df23610651e93611e1f49118baf84 \
|
||||
--hash=sha256:b0d955195bbbe489ad343fcc956eacea9357b79cb22192c66cacdefcbc14b32f \
|
||||
--hash=sha256:b281a3b0f0822618fe5e3e0d8a2048b6356b14388505dc9374ccffeb69989713 \
|
||||
--hash=sha256:b6d0c2183008c188e19f4906d426b293bdc4f67ab17df8e180fe16cda208fa71 \
|
||||
--hash=sha256:bbce99252ba3167b2b6277f1829d5bf4b43b754524bddf7f944707c3db7d2253 \
|
||||
--hash=sha256:bc1f08f68dac9f9e83845a8039880aba2ab553eb9b2259c3243a313182c253fe \
|
||||
--hash=sha256:bc94f474417604bd383d2cd445d071b07dd55fedceed3ce33407bf1fcc107290 \
|
||||
--hash=sha256:bed5163e03b98bc1fa2eb05d74c63d9c5c95d8ed6254985481640fbf5e237dea \
|
||||
--hash=sha256:c17799a62c142d61b8a3c51752a7cbc87fe2ad4ccfab10e628a77b405075c662 \
|
||||
--hash=sha256:c18db21573bd2c6489f9a544b7499f0df2853958c568e5e783536ee1f690af41 \
|
||||
--hash=sha256:c3ede305158e75510be50869b319550ab072008c13d64d4ab1e094fb286b6f44 \
|
||||
--hash=sha256:c516cc5367ca3448995d42cb994bf3f4c9002d2a7c22eac9622551269ad1b807 \
|
||||
--hash=sha256:c531166c42ea7bdfecc8c50049581f05dd1993b09cc7c52bb36a14e96deaec7d \
|
||||
--hash=sha256:c73622ef819328873b53109ee4f77ceb598bffedd02daf916102be3228866b78 \
|
||||
--hash=sha256:c8dce1f1e0e5358b682a6ad3fa5e31b31d4560997b8e61417e9217c8d60f8a0c \
|
||||
--hash=sha256:cb57f304525a5e3c13333b772bf9a473f36326e9c821b2e8e1b2fd36f80ae2c3 \
|
||||
--hash=sha256:ce8c25ca38cc0e3d7753ba180808de2c0c8cb24eae0df64491e40921454e9831 \
|
||||
--hash=sha256:ceff0acc940be2715bd6ad17b24c0e5304abf44f6efd0f81ee8499e640f9dc86 \
|
||||
--hash=sha256:cf356f70551d40374eaffb1aa63f1eb6d2006681cbd7a9faea173ce0f4dd7cd2 \
|
||||
--hash=sha256:d2d82aa62521c55ddfb000ae70f88cdd8de974078f6024e821dfe5addd0c818f \
|
||||
--hash=sha256:d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f \
|
||||
--hash=sha256:d4193206b6587047437f6f11d7e776df23e1c1e23af2a54d9347275614791e10 \
|
||||
--hash=sha256:d5c0e32fdbce7f1e8ef4d11f655694bf5f4175c757a9f1dc2be09b8864e5bcf5 \
|
||||
--hash=sha256:d5e062c01286d861fd6a1c4ff6e063547b3e713067f2df033c0ff97ac2ca006b \
|
||||
--hash=sha256:d8f9e8a6c4ab04b78d61f78627370d834eb004b2869dcb28cfffa647b4ea1980 \
|
||||
--hash=sha256:d939de9c82e2126f7f48a7e658f8a85ed46d57662d53f44c49b8895fe94a3eb7 \
|
||||
--hash=sha256:de531ce1e2a3364e8767878b58f4ff728a434b4fde089781fe30b1e08e2396e0 \
|
||||
--hash=sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09 \
|
||||
--hash=sha256:e5faeaee74a57d32b3ab3aebad2e348f06d3ba946fc5d28c1728455f00a3d13a \
|
||||
--hash=sha256:e6f0cc1bb9900dc558960894adeb30b0c083366fc1d69b856209fb2ca5c36fe5 \
|
||||
--hash=sha256:e8e1d6ce820aa23317e8209a86bd65a540973c12dc7552b48a4f6c8e9926815e \
|
||||
--hash=sha256:ed1e728b39a383c81035b2459cfcb35d99dfb01f7d6ebe3a913bc1cc5b81e459 \
|
||||
--hash=sha256:ee6db2fbed51a7991302e8fac498cd67e336246026d0dfa84cf5166ce1412760 \
|
||||
--hash=sha256:efbecf43d321f7b9281441f1f213f7c21c66988b0e06c2730ba13ed47a46bb08 \
|
||||
--hash=sha256:f2c634642694e6a0dad2ab1d375589fa671fd442edd5caf7d9737b8f6ca22906 \
|
||||
--hash=sha256:f3377c8c2b3ce898423c5e5dd94c7982e30aa7717a7e6ab2470b9de364963709 \
|
||||
--hash=sha256:f5187624823423e1d1b82b1072ac41dc837389e18d3d0572cc19bbee46cd550a \
|
||||
--hash=sha256:f77ac30b19221cd9bd3fcfa3d4614eff93140d0572ab730cded17b64adca05f3 \
|
||||
--hash=sha256:fe90228920fd8ff2be62622b6bb8a2b11acd65046d50c6b130614b5879605a20
|
||||
# via pydantic
|
||||
pygments==2.21.0 \
|
||||
--hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \
|
||||
--hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c
|
||||
# via rich
|
||||
pyjwt==2.15.1 \
|
||||
--hash=sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193 \
|
||||
--hash=sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8
|
||||
# via sigstore
|
||||
pyopenssl==26.4.0 \
|
||||
--hash=sha256:28dfcce0162b9211413e26dfbfdf1d24317fbeba18fc93c12400a1856b2a0bc7 \
|
||||
--hash=sha256:f0eb0cb2d581d3ad2b9c489468485e7f2ab6727d08401bcf9d824c3caddf3c1c
|
||||
# via sigstore
|
||||
requests==2.34.2 \
|
||||
--hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \
|
||||
--hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed
|
||||
# via sigstore
|
||||
rfc3161-client==1.0.9 \
|
||||
--hash=sha256:03be7ac7919c7f4c566076b07773b81b1f1b28d447fa91c6960fb5f82fac5bc1 \
|
||||
--hash=sha256:0ac247d5aa22f3514d1e284bdc547d2ad5f101e1e5d7f6db25db2ab3a0c59f06 \
|
||||
--hash=sha256:4d33f5aaec2974239e1c62a79a6fcf32506b09095482377a8b5be3a00fa67dfb \
|
||||
--hash=sha256:5e619d7e28ffa3a46685923e6d6ba4ce2e74cb09a41c77995a0702cc1a533bc4 \
|
||||
--hash=sha256:614da494c6f8850c5d6d98c23bc291a4e4dbf2c3c9082d9907fa156f9e4a75c6 \
|
||||
--hash=sha256:66997415086d2c6e5d57a2d315157b32a9c3f4f1312877ca8eb55e2e0ddf8ce4 \
|
||||
--hash=sha256:7b703b233dbee7228d117d5f1c118363c61d523fa6f018c9217c79e3c6684f86 \
|
||||
--hash=sha256:8208999e94e1252e3f5f748f5efe59d3b9c308d04c7626be1becfbf3236c9de4 \
|
||||
--hash=sha256:908f6a775da4bdce1d39f825a4431f389542696078ef3e4ed911a068bcaf1792 \
|
||||
--hash=sha256:a7004edfbf1bb7ec7801978a39fa7a7fe385ca59673df90d7578079b6eba3b24 \
|
||||
--hash=sha256:d3cbf1991b6f3457efcb25e1d31179cac556112e6d3e65ec9e0fd70c6e9af90d \
|
||||
--hash=sha256:d4cf92f0e784ff02ff5ea1c574f8521f30953dc178092424126dbd8348034f93 \
|
||||
--hash=sha256:fac3f440a507555e684dc5daba75e33dc08f0f45fdefa48448f19001233a6b21
|
||||
# via sigstore
|
||||
rfc8785==0.1.4 \
|
||||
--hash=sha256:520d690b448ecf0703691c76e1a34a24ddcd4fc5bc41d589cb7c58ec651bcd48 \
|
||||
--hash=sha256:e545841329fe0eee4f6a3b44e7034343100c12b4ec566dc06ca9735681deb4da
|
||||
# via sigstore
|
||||
rich==15.0.0 \
|
||||
--hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \
|
||||
--hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36
|
||||
# via sigstore
|
||||
securesystemslib==1.5.1 \
|
||||
--hash=sha256:4b8d00abd93707ead10b69eb2b8582376a1364de3b0a71077de534c2ef4985e0 \
|
||||
--hash=sha256:ada8bdf817da29ece4ba91654f6a162ce7cfbadbc3ae3f840f7313f9d22675de
|
||||
# via tuf
|
||||
sigstore==4.5.0 \
|
||||
--hash=sha256:020d3e07f622b2916bf453e66ff6ff0711e1fdc5ab69e8bd8902f71d9fcb316f \
|
||||
--hash=sha256:f045b207f2e12605cf775ec38e89c5eda625d71ffa7830477db65e47ec2bc8b2
|
||||
# via -r .github/release-signing-requirements.in
|
||||
sigstore-models==0.0.6 \
|
||||
--hash=sha256:5201a68f4d7d0f8bec1e2f4378eb646b084c52609a4e31db8c385095fff68b2e \
|
||||
--hash=sha256:c766c09470c2a7e8a4a333c893f07e2001c56a3ff1757b1a246119f53169a849
|
||||
# via sigstore
|
||||
sigstore-rekor-types==0.0.18 \
|
||||
--hash=sha256:19aef25433218ebf9975a1e8b523cc84aaf3cd395ad39a30523b083ea7917ec5 \
|
||||
--hash=sha256:b62bf38c5b1a62bc0d7fe0ee51a0709e49311d137c7880c329882a8f4b2d1d78
|
||||
# via sigstore
|
||||
tuf==7.0.1 \
|
||||
--hash=sha256:5ada1db78da3518fa851e28588f4b2249b8662a28ae528f54afa2a1de541fb31 \
|
||||
--hash=sha256:d30434bda6e079ab303fb30d1b3006d939a10ca34783b1573d61cd9b802fa45c
|
||||
# via sigstore
|
||||
typing-extensions==4.16.0 \
|
||||
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
|
||||
--hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
|
||||
# via
|
||||
# pydantic
|
||||
# pydantic-core
|
||||
# pyopenssl
|
||||
# sigstore-models
|
||||
# typing-inspection
|
||||
typing-inspection==0.4.4 \
|
||||
--hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \
|
||||
--hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147
|
||||
# via pydantic
|
||||
urllib3==2.8.0 \
|
||||
--hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
|
||||
--hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
|
||||
# via
|
||||
# id
|
||||
# requests
|
||||
# tuf
|
||||
+121
-20
@@ -141,7 +141,9 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.python_required == 'true'
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 20
|
||||
# Windows runs real isolated update jobs before the complete compatibility
|
||||
# suite; that suite was still progressing at the former 20-minute job cap.
|
||||
timeout-minutes: ${{ matrix.os == 'windows-latest' && 30 || 20 }}
|
||||
env:
|
||||
PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed -p scripts.pytest_timing"
|
||||
strategy:
|
||||
@@ -152,22 +154,22 @@ jobs:
|
||||
os: ubuntu-latest
|
||||
python-version: "3.11"
|
||||
coverage: false
|
||||
# CLI command tests assert exact Rich terminal output; run them
|
||||
# serially below so xdist cannot change terminal-width rendering.
|
||||
pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py"
|
||||
# Keep exact Rich output and real prompt_toolkit pipes in a fresh
|
||||
# CLI process: long-lived workers can exceed select()'s fd limit.
|
||||
pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py"
|
||||
- name: latest, 3.14 + coverage
|
||||
os: ubuntu-latest
|
||||
python-version: "3.14"
|
||||
coverage: true
|
||||
pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py"
|
||||
pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py"
|
||||
- name: Windows, 3.14
|
||||
os: windows-latest
|
||||
python-version: "3.14"
|
||||
coverage: false
|
||||
# Real PowerShell, browser-handoff, and process-tree tests run
|
||||
# serially so xdist workers do not compete for native processes.
|
||||
# Keep threaded storage work bounded without adding another runner.
|
||||
pytest_args: "-n 3 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py"
|
||||
# Process identities run serially; isolated update jobs use case-level
|
||||
# scheduling below so one file cannot serialize all real venv work.
|
||||
# Retain main's three-worker budget and the separate native-process job.
|
||||
pytest_args: "-n 3 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py --ignore=tests/test_install_scripts.py --ignore=tests/test_update_jobs.py --ignore=tests/test_update_profiles.py"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -200,6 +202,13 @@ jobs:
|
||||
- name: Verify dependency consistency
|
||||
run: uv pip check
|
||||
|
||||
- name: Install pipx for offline installer checks
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
run: |
|
||||
uv tool install pipx==1.17.12
|
||||
uv tool dir --bin >> "$GITHUB_PATH"
|
||||
|
||||
# Channel requirements live in manifests rather than uv.lock. Avoid a
|
||||
# later uv run sync pruning the packages installed by the previous step.
|
||||
- name: Lint with ruff
|
||||
@@ -210,6 +219,27 @@ jobs:
|
||||
if: matrix.coverage
|
||||
run: uv run --no-sync basedpyright
|
||||
|
||||
- name: Check Windows update coordination before the full suite
|
||||
if: runner.os == 'Windows'
|
||||
run: >-
|
||||
uv run --no-sync python -m pytest
|
||||
tests/test_installation_lock.py
|
||||
tests/test_update_profiles.py
|
||||
tests/utils/test_helpers.py::test_atomic_record_reader_does_not_block_concurrent_replacement
|
||||
tests/gateway/test_runtime.py::test_runtime_state_publish_keeps_existing_snapshot_readable
|
||||
tests/gateway/test_runtime.py::test_runtime_state_reader_does_not_block_publish_while_decoding
|
||||
-q --junitxml=test-results/coordination.xml --timing-report=test-results/coordination.json
|
||||
|
||||
# Each update job owns its venv, HOME, profile and lock directory. Preserve
|
||||
# the real installation/restore checks, but avoid a loadfile straggler and
|
||||
# disk contention with timing-sensitive runtime-registration checks.
|
||||
- name: Run Windows isolated update jobs
|
||||
if: runner.os == 'Windows'
|
||||
run: >-
|
||||
uv run --no-sync python -m pytest tests/test_update_jobs.py
|
||||
-n 3 --dist load -vv --durations=25 --durations-min=1.0
|
||||
--junitxml=test-results/update-jobs.xml --timing-report=test-results/update-jobs.json
|
||||
|
||||
- name: Run tests with coverage
|
||||
if: matrix.coverage
|
||||
run: >-
|
||||
@@ -220,11 +250,12 @@ jobs:
|
||||
--junitxml=test-results/main.xml --timing-report=test-results/main.json
|
||||
--durations=25 --durations-min=1.0
|
||||
|
||||
- name: Run serial CLI command tests with coverage
|
||||
- name: Run serial CLI input and command tests with coverage
|
||||
if: matrix.coverage
|
||||
run: >-
|
||||
uv run --no-sync python -m pytest
|
||||
tests/cli/test_commands.py
|
||||
tests/cli/test_cli_input.py tests/cli/test_desktop_target.py
|
||||
tests/cli/test_desktop_target_entrypoints.py tests/cli/test_commands.py
|
||||
--cov=nanobot --cov-append --cov-report=term-missing:skip-covered
|
||||
--junitxml=test-results/cli.xml --timing-report=test-results/cli.json
|
||||
--durations=25 --durations-min=1.0
|
||||
@@ -237,11 +268,12 @@ jobs:
|
||||
--junitxml=test-results/main.xml --timing-report=test-results/main.json
|
||||
--durations=25 --durations-min=1.0
|
||||
|
||||
- name: Run serial CLI command compatibility tests
|
||||
- name: Run serial CLI input and command compatibility tests
|
||||
if: ${{ !matrix.coverage }}
|
||||
run: >-
|
||||
uv run --no-sync python -m pytest
|
||||
tests/cli/test_commands.py
|
||||
tests/cli/test_cli_input.py tests/cli/test_desktop_target.py
|
||||
tests/cli/test_desktop_target_entrypoints.py tests/cli/test_commands.py
|
||||
--junitxml=test-results/cli.xml --timing-report=test-results/cli.json
|
||||
--durations=25 --durations-min=1.0
|
||||
|
||||
@@ -293,6 +325,22 @@ jobs:
|
||||
--junitxml=test-results/process.xml --timing-report=test-results/process.json
|
||||
--durations=25 --durations-min=1.0
|
||||
|
||||
- name: Install pipx for offline installer checks
|
||||
shell: bash
|
||||
run: |
|
||||
uv tool install pipx==1.17.12
|
||||
uv tool dir --bin >> "$GITHUB_PATH"
|
||||
|
||||
# Installer subprocesses run here, parallel to the broad Windows suite.
|
||||
# Each case owns an isolated manager/config root, so individual cases can
|
||||
# run concurrently without sharing a console or package installation.
|
||||
# Keep four workers: three exceed this job's budget on native Windows.
|
||||
- name: Run Windows installer checks
|
||||
run: >-
|
||||
uv run --no-sync python -m pytest tests/test_install_scripts.py
|
||||
-n 4 --dist load -x -vv --durations=10
|
||||
--junitxml=test-results/installers.xml --timing-report=test-results/installers.json
|
||||
|
||||
- name: Upload Windows process test timings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -314,7 +362,7 @@ jobs:
|
||||
- name: Set up Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.6
|
||||
bun-version: 1.3.13
|
||||
|
||||
- name: Verify npm lockfile
|
||||
working-directory: webui
|
||||
@@ -361,7 +409,7 @@ jobs:
|
||||
- name: Set up Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.6
|
||||
bun-version: 1.3.13
|
||||
|
||||
- name: Install WebUI dependencies
|
||||
working-directory: webui
|
||||
@@ -391,10 +439,12 @@ jobs:
|
||||
|
||||
tui:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.tui_required == 'true'
|
||||
if: needs.changes.outputs.tui_required == 'true' || needs.changes.outputs.python_required == 'true' || needs.changes.outputs.webui_required == 'true'
|
||||
name: ${{ matrix.name }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 10
|
||||
# Native build + clean install + recovery/next-update journeys on Windows.
|
||||
# Each subprocess is separately bounded by the acceptance harness.
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -439,11 +489,10 @@ jobs:
|
||||
working-directory: tui
|
||||
run: python3 scripts/pty_smoke.py
|
||||
|
||||
- name: Set up Python for ConPTY smoke test
|
||||
if: runner.os == 'Windows'
|
||||
- name: Set up Python for native package acceptance
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.13'
|
||||
python-version: '3.11'
|
||||
|
||||
- name: Test TUI in a real ConPTY terminal
|
||||
if: runner.os == 'Windows'
|
||||
@@ -472,6 +521,58 @@ jobs:
|
||||
bun scripts/release-notices.ts win32-x64
|
||||
python scripts/package-release.py win32-x64
|
||||
|
||||
- name: Build and install the native application package
|
||||
shell: bash
|
||||
env:
|
||||
NATIVE_TARGET: ${{ runner.os == 'Windows' && 'win32-x64' || 'linux-x64' }}
|
||||
run: |
|
||||
python -m pip install --disable-pip-version-check build
|
||||
python -m build --outdir "$RUNNER_TEMP/python-dist"
|
||||
# Archive verification shares the installed launcher's dependencies.
|
||||
# Install the intermediate in this build environment, not the separate
|
||||
# clean-home environment used by the public-installer acceptance probe.
|
||||
python -m pip install --disable-pip-version-check "$(find "$RUNNER_TEMP/python-dist" -name '*.whl' -print -quit)"
|
||||
python -m scripts.build_tui_wheels \
|
||||
--wheel "$(find "$RUNNER_TEMP/python-dist" -name '*.whl' -print -quit)" \
|
||||
--tui-dir tui/dist --target "$NATIVE_TARGET" --out-dir "$RUNNER_TEMP/native-wheel"
|
||||
version="$(python -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')"
|
||||
python -I scripts/verify_installed_release.py \
|
||||
--install-wheel "$(find "$RUNNER_TEMP/native-wheel" -name '*.whl' -print -quit)" \
|
||||
--version "$version" --commit "$(git rev-parse HEAD)" --gateway \
|
||||
--report "$RUNNER_TEMP/native-install-report.json"
|
||||
|
||||
- name: Exercise updates with the default Windows path policy
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: |
|
||||
# Only this disposable runner changes. Do not require users to enable
|
||||
# machine-wide long paths for an ordinary update's atomic temp files.
|
||||
$key = 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem'
|
||||
Set-ItemProperty -Path $key -Name LongPathsEnabled -Value 0
|
||||
if ((Get-ItemPropertyValue -Path $key -Name LongPathsEnabled) -ne 0) {
|
||||
throw 'Native update acceptance requires LongPathsEnabled=0'
|
||||
}
|
||||
Write-Output 'Packaged update/recovery acceptance: LongPathsEnabled=0'
|
||||
|
||||
- name: Verify packaged upgrades and automatic service recovery
|
||||
shell: bash
|
||||
run: |
|
||||
python -I scripts/verify_packaged_update.py \
|
||||
--wheel "$(find "$RUNNER_TEMP/native-wheel" -name '*.whl' -print -quit)" \
|
||||
--commit "$(git rev-parse HEAD)" --output "$RUNNER_TEMP/packaged-update"
|
||||
|
||||
- name: Retain the native package acceptance report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: native-install-${{ runner.os }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
${{ runner.temp }}/native-install-report.json
|
||||
${{ runner.temp }}/packaged-update/packaged-update-report.json
|
||||
${{ runner.temp }}/packaged-update/*/result.json
|
||||
if-no-files-found: error
|
||||
retention-days: 3
|
||||
|
||||
docker:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.docker_required == 'true'
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
name: Approve Exact Release
|
||||
|
||||
# No schedule, release trigger or PR token. Repository administrators must first
|
||||
# protect main and release-approval, then explicitly enable the repository var.
|
||||
# This produces a signature only: it never uploads release assets or writes a feed.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: Exact previously tested version (without v)
|
||||
required: true
|
||||
type: string
|
||||
manifest_sha256:
|
||||
description: SHA-256 from the independently reviewed candidate evidence
|
||||
required: true
|
||||
type: string
|
||||
source_commit:
|
||||
description: Reviewed full source SHA
|
||||
required: true
|
||||
type: string
|
||||
candidate_commit:
|
||||
description: Tested full candidate SHA
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: release-approval
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
approve:
|
||||
if: >-
|
||||
github.repository == 'HKUDS/nanobot' && github.ref == 'refs/heads/main' &&
|
||||
vars.NANOBOT_RELEASE_SIGNING_ENABLED == 'true'
|
||||
environment: release-approval
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
env:
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
MANIFEST_SHA256: ${{ inputs.manifest_sha256 }}
|
||||
SOURCE_COMMIT: ${{ inputs.source_commit }}
|
||||
CANDIDATE_COMMIT: ${{ inputs.candidate_commit }}
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
- name: Install hash-locked signing tools, not the candidate
|
||||
run: |
|
||||
python -m pip install --require-hashes --only-binary=:all: -r .github/release-signing-requirements.txt
|
||||
- name: Fetch only the proposed manifest
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
[[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(\.dev[0-9]+|\.post[0-9]+)?$ ]]
|
||||
gh release download "v$RELEASE_VERSION" --repo "$GITHUB_REPOSITORY" \
|
||||
--pattern release-manifest.json --dir "$RUNNER_TEMP/approval"
|
||||
- name: Bind the signature to reviewed evidence
|
||||
run: |
|
||||
python -m scripts.verify_release_approval \
|
||||
--manifest "$RUNNER_TEMP/approval/release-manifest.json" \
|
||||
--sha256 "$MANIFEST_SHA256" --version "$RELEASE_VERSION" \
|
||||
--source-commit "$SOURCE_COMMIT" --candidate-commit "$CANDIDATE_COMMIT"
|
||||
- name: Sign and verify the exact manifest
|
||||
run: |
|
||||
python -m sigstore sign --no-default-files \
|
||||
--bundle "$RUNNER_TEMP/approval/release-manifest.json.sigstore.json" \
|
||||
"$RUNNER_TEMP/approval/release-manifest.json"
|
||||
python -m sigstore verify identity \
|
||||
--cert-identity 'https://github.com/HKUDS/nanobot/.github/workflows/release-approve.yml@refs/heads/main' \
|
||||
--cert-oidc-issuer 'https://token.actions.githubusercontent.com' \
|
||||
--bundle "$RUNNER_TEMP/approval/release-manifest.json.sigstore.json" \
|
||||
"$RUNNER_TEMP/approval/release-manifest.json"
|
||||
- name: Retain small approval proof for the separate publication handoff
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: release-approval-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: ${{ runner.temp }}/approval/*
|
||||
if-no-files-found: error
|
||||
retention-days: 3
|
||||
@@ -0,0 +1,188 @@
|
||||
name: Verify Release Candidate
|
||||
|
||||
# Preparation only: no cron, tags, GitHub Releases, PyPI or channel-feed writes.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
next_stable:
|
||||
description: Next stable base (for example 0.3.6); must not have a stable tag
|
||||
required: true
|
||||
type: string
|
||||
retain_installable:
|
||||
description: Retain this exact installable candidate and source for 1 day (~400 MB); not publication
|
||||
required: false
|
||||
default: false
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-candidate
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
candidate:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
SOURCE_COMMIT: ${{ github.sha }}
|
||||
NEXT_STABLE: ${{ inputs.next_stable }}
|
||||
PREVIEW_SEQUENCE: ${{ github.run_number }}
|
||||
|
||||
steps:
|
||||
- name: Set candidate directory
|
||||
run: echo "CANDIDATE_DIR=$RUNNER_TEMP/candidate" >> "$GITHUB_ENV"
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
|
||||
- uses: astral-sh/setup-uv@v4
|
||||
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.13
|
||||
|
||||
- name: Install isolated build and verification tools
|
||||
run: |
|
||||
uv venv "$RUNNER_TEMP/release-tools"
|
||||
uv pip install --python "$RUNNER_TEMP/release-tools/bin/python" -e '.[dev]' build twine
|
||||
echo "$RUNNER_TEMP/release-tools/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Prepare an exact, separate candidate
|
||||
run: |
|
||||
python -m scripts.release_candidate prepare \
|
||||
--source-commit "$SOURCE_COMMIT" --base "$NEXT_STABLE" \
|
||||
--sequence "$PREVIEW_SEQUENCE" --output "$CANDIDATE_DIR" \
|
||||
> "$RUNNER_TEMP/candidate.json"
|
||||
|
||||
- name: Verify packaging and selection contracts
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}
|
||||
run: |
|
||||
python -m pytest tests/test_release_candidate.py tests/test_releases.py \
|
||||
tests/test_release_install_guide.py tests/test_installed_release_probe.py tests/cli/test_tui_wheels.py \
|
||||
tests/cli/test_tui_release_packaging.py -q
|
||||
|
||||
- name: Check WebUI and build Python distributions
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}
|
||||
run: |
|
||||
cd webui
|
||||
bun install --frozen-lockfile
|
||||
bun run lint
|
||||
bun run test
|
||||
cd ..
|
||||
uv build --out-dir "$RUNNER_TEMP/python-dist"
|
||||
|
||||
- name: Check and cross-build the five native targets
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}/tui
|
||||
run: |
|
||||
bun install --frozen-lockfile
|
||||
bun run check
|
||||
bun run test
|
||||
for target in darwin-arm64 darwin-x64 linux-arm64 linux-x64 win32-x64; do
|
||||
bun scripts/prepare-target.ts "$target"
|
||||
bun run build -- "$target"
|
||||
done
|
||||
|
||||
- name: Ad-hoc sign macOS arm64
|
||||
uses: indygreg/apple-code-sign-action@44d0985b7f4363198e80b6fea63ac3e9dd3e9957
|
||||
with:
|
||||
input_path: ${{ env.CANDIDATE_DIR }}/tui/dist/nanobot-tui-darwin-arm64
|
||||
rcodesign_version: 0.29.0
|
||||
|
||||
- name: Ad-hoc sign macOS x64
|
||||
uses: indygreg/apple-code-sign-action@44d0985b7f4363198e80b6fea63ac3e9dd3e9957
|
||||
with:
|
||||
input_path: ${{ env.CANDIDATE_DIR }}/tui/dist/nanobot-tui-darwin-x64
|
||||
rcodesign_version: 0.29.0
|
||||
|
||||
- name: Package licensed native archives
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}/tui
|
||||
run: |
|
||||
for target in darwin-arm64 darwin-x64 linux-arm64 linux-x64 win32-x64; do
|
||||
bun scripts/prepare-target.ts "$target"
|
||||
bun scripts/release-notices.ts "$target"
|
||||
python scripts/package-release.py "$target"
|
||||
done
|
||||
|
||||
- name: Assemble and verify the complete candidate
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}
|
||||
run: |
|
||||
version="${NEXT_STABLE}.dev${PREVIEW_SEQUENCE}"
|
||||
python -m scripts.release_candidate assemble --source-commit "$SOURCE_COMMIT" \
|
||||
--wheel "$RUNNER_TEMP/python-dist/nanobot_ai-${version}-py3-none-any.whl" \
|
||||
--sdist "$RUNNER_TEMP/python-dist/nanobot_ai-${version}.tar.gz" \
|
||||
--tui-dir tui/dist --output "$RUNNER_TEMP/release-artifacts"
|
||||
python -m twine check "$RUNNER_TEMP/release-artifacts/"*.whl \
|
||||
"$RUNNER_TEMP/release-artifacts/"*.tar.gz
|
||||
|
||||
- name: Install and probe the Linux wheel without frontend build tools
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}
|
||||
run: |
|
||||
version="${NEXT_STABLE}.dev${PREVIEW_SEQUENCE}"
|
||||
uv_bin="$(command -v uv)"
|
||||
uv venv --python 3.11 "$RUNNER_TEMP/installed-candidate"
|
||||
mkdir "$RUNNER_TEMP/empty-install-path"
|
||||
env PATH="$RUNNER_TEMP/empty-install-path" "$uv_bin" pip install \
|
||||
--python "$RUNNER_TEMP/installed-candidate/bin/python" --only-binary :all: \
|
||||
"$RUNNER_TEMP/release-artifacts/nanobot_ai-${version}-py3-none-manylinux_2_17_x86_64.whl"
|
||||
uv pip check --python "$RUNNER_TEMP/installed-candidate/bin/python"
|
||||
"$RUNNER_TEMP/installed-candidate/bin/python" -I scripts/verify_installed_release.py \
|
||||
--version "$version" --commit "$(git rev-parse HEAD)" --gateway \
|
||||
--report "$RUNNER_TEMP/installed-candidate-report.json"
|
||||
|
||||
- name: Generate the exact candidate installation handoff
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}
|
||||
run: |
|
||||
python -m scripts.release_candidate instructions --source-commit "$SOURCE_COMMIT" \
|
||||
--artifacts "$RUNNER_TEMP/release-artifacts" \
|
||||
--output "$RUNNER_TEMP/install-candidate.md"
|
||||
|
||||
- name: Verify packaged Linux upgrades and service recovery
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}
|
||||
run: |
|
||||
version="${NEXT_STABLE}.dev${PREVIEW_SEQUENCE}"
|
||||
python -I scripts/verify_packaged_update.py \
|
||||
--wheel "$RUNNER_TEMP/release-artifacts/nanobot_ai-${version}-py3-none-manylinux_2_17_x86_64.whl" \
|
||||
--commit "$(git rev-parse HEAD)" --output "$RUNNER_TEMP/packaged-update"
|
||||
|
||||
# Keep the default preflight cheap: no ~400 MB archive upload per manual run.
|
||||
# These reports are not installable releases or publication approvals.
|
||||
- name: Retain identity, structural and native Linux probe reports
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: candidate-report-${{ github.run_number }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
${{ runner.temp }}/candidate.json
|
||||
${{ runner.temp }}/release-artifacts/release-manifest.json
|
||||
${{ runner.temp }}/installed-candidate-report.json
|
||||
${{ runner.temp }}/packaged-update/packaged-update-report.json
|
||||
${{ runner.temp }}/install-candidate.md
|
||||
if-no-files-found: error
|
||||
retention-days: 3
|
||||
|
||||
# Explicit, short-lived release handoff only. This is the documented
|
||||
# exception to report-only preflight; never enable it on a daily schedule.
|
||||
- name: Preserve the verified bytes and independent candidate source
|
||||
if: ${{ inputs.retain_installable }}
|
||||
working-directory: ${{ env.CANDIDATE_DIR }}
|
||||
run: |
|
||||
python -m scripts.release_candidate retain --source-commit "$SOURCE_COMMIT" \
|
||||
--artifacts "$RUNNER_TEMP/release-artifacts" \
|
||||
--output "$RUNNER_TEMP/retained-candidate"
|
||||
|
||||
- name: Retain installable candidate for approved release handoff
|
||||
if: ${{ inputs.retain_installable }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: installable-candidate-${{ github.run_number }}-${{ github.run_attempt }}
|
||||
path: ${{ runner.temp }}/retained-candidate
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
retention-days: 1
|
||||
@@ -92,5 +92,4 @@ jobs:
|
||||
if [[ "$TARGET" == win32-* ]]; then asset="${asset}.exe"; fi
|
||||
gh release upload "$TAG" \
|
||||
"tui/dist/${asset}.zip" \
|
||||
"tui/dist/${asset}.zip.sha256" \
|
||||
--clobber
|
||||
"tui/dist/${asset}.zip.sha256"
|
||||
@@ -77,7 +77,12 @@ You need **Python 3.11 or newer** and access to a [supported model provider or l
|
||||
|
||||
Choose the **stable release** for everyday use or **current source** for development and the latest features. This README describes current source; [published documentation](https://nanobot.wiki/docs/latest/getting-started/nanobot-overview) covers the released version.
|
||||
|
||||
New to terminals or model credentials? Follow [Start Without Technical Background](./docs/start-without-technical-background.md). Updating an existing instance? Stop every old nanobot process using that workspace, back up its config directory and workspace, then update and restart through the original launcher or service. See [session storage and version changes](./docs/cli-reference.md#session-storage).
|
||||
New to terminals or model credentials? Follow [Start Without Technical Background](./docs/start-without-technical-background.md). Updating an existing instance? Follow [updates and recovery](./docs/updating.md) for your installation method, backup steps and restart checks.
|
||||
|
||||
| Track | Install with | Update with | What runs |
|
||||
|---|---|---|---|
|
||||
| Stable | installer, `uv`, or pip | managed installer: WebUI update; other installs: original package tool | one released Python/WebUI/TUI version |
|
||||
| Current source | editable Git checkout | `git pull --ff-only` + editable dependency sync | Python, WebUI, and TUI from that checkout |
|
||||
|
||||
**Stable release: automatic setup (recommended)**
|
||||
|
||||
@@ -104,7 +109,9 @@ irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1 | i
|
||||
<details>
|
||||
<summary>Installer details, preview, and script review</summary>
|
||||
|
||||
The installer installs or upgrades `nanobot-ai` using an active virtual environment, `uv`, `pipx`, or a managed venv under `~/.nanobot/venv`. Fresh local desktops open the WebUI; SSH, headless, existing-config, and older-release paths use the terminal setup wizard. Keep the printed command: it identifies the environment that owns the installation.
|
||||
The default command installs or upgrades the stable PyPI release. Fresh installations use a dedicated environment under `~/.nanobot/venv`. On a fresh local desktop it opens the WebUI for model setup. That gateway keeps running after the browser or terminal closes; use the printed `gateway stop` command to stop it. SSH, headless, existing-config and older-release installs use terminal setup.
|
||||
|
||||
Existing installations keep their package manager, extras and constraints. An active ordinary venv remains an explicit target, not an installer-managed environment. The installer avoids system-wide pip and prints the command to reuse if `nanobot` is not on `PATH`.
|
||||
|
||||
To preview the plan without changing your environment, pass `--dry-run`.
|
||||
|
||||
@@ -197,7 +204,7 @@ Verify the install:
|
||||
nanobot --version
|
||||
```
|
||||
|
||||
If `nanobot` is not on `PATH`, invoke it through the method that installed it: reuse the recommended installer's command, use `uv tool run --from nanobot-ai nanobot ...` or `pipx run --spec nanobot-ai nanobot ...`, or use the Python executable from the environment where pip installed the package.
|
||||
If `nanobot` is not on `PATH`, reuse the installer's printed command or run the Python executable from the existing installation with `-I -m nanobot`. For uv/pipx, locate that environment with the original manager. Do not use a temporary tool environment to manage an existing installation.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -308,7 +315,9 @@ After model setup, keep channels and automations running when interactive launch
|
||||
nanobot gateway --background
|
||||
```
|
||||
|
||||
This starts or promotes the shared gateway to a detached process. From the TUI, `/detach` does the same before closing that client. Background mode does not configure startup after a machine reboot or restart after a crash; use an [OS-managed service](./docs/deployment.md#switch-an-existing-gateway-to-a-service) for that. Interrupted subagent tasks are not automatically relaunched after a restart, and missed scheduled times are not replayed; see [subagent recovery](./docs/concepts.md#subagents) and [automation delivery](./docs/automations.md#delivery-and-reliability).
|
||||
This starts or promotes the shared gateway to persistent background mode. Fresh official-installer environments already use that lifetime when you open `nanobot webui`; other Python installations can explicitly use `nanobot webui --detach`. Channels and automations remain active after local clients exit. Complete first-time model setup in the WebUI, and use the gateway commands below to manage the same instance.
|
||||
|
||||
From the TUI, `/detach` does the same before closing that client. Background mode does not configure startup after a machine reboot or restart after a crash; use an [OS-managed service](./docs/deployment.md#switch-an-existing-gateway-to-a-service) for that. Interrupted subagent tasks are not automatically relaunched after a restart, and missed scheduled times are not replayed; see [subagent recovery](./docs/concepts.md#subagents) and [automation delivery](./docs/automations.md#delivery-and-reliability).
|
||||
|
||||
Manage the background gateway with:
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ For shorter, outcome-focused walkthroughs, browse the [task guide index](./guide
|
||||
| Need | Read |
|
||||
|---|---|
|
||||
| Commands and flags | [CLI Reference](./cli-reference.md) |
|
||||
| Update an installation or recover an interrupted update | [Updating nanobot](./updating.md) |
|
||||
| In-chat slash commands | [In-Chat Commands](./chat-commands.md) |
|
||||
| Config, workspace, gateway, sessions, tools, and memory in plain language | [Concepts](./concepts.md) |
|
||||
| Provider/model matching and selection | [Providers and Models](./providers.md) |
|
||||
@@ -90,5 +91,7 @@ These pages explain implementation and extension points. You do not need them to
|
||||
| Set up a development environment | [Development](./development.md) and [CONTRIBUTING.md](../CONTRIBUTING.md) |
|
||||
| Add a channel package | [Channel Package Guide](./channel-package-guide.md) |
|
||||
| Build the WebUI source | [WebUI Development](../webui/README.md) |
|
||||
| Change update APIs, execution or recovery | [Update protocol](./update-protocol.md) |
|
||||
| Prepare and publish a release | [Release checklist](./releasing.md) |
|
||||
|
||||
If a command or screen no longer matches these docs, please [open an issue](https://github.com/HKUDS/nanobot/issues) with your nanobot version, operating system, and the page that needs correction.
|
||||
+26
-2
@@ -7,6 +7,7 @@ Use this page when you know what you want to run and need the command shape. For
|
||||
| Goal | Command | Notes |
|
||||
|---|---|---|
|
||||
| Check the install | `nanobot --version` | If this fails, try `python -m nanobot --version` |
|
||||
| Update an ordinary Python venv | `nanobot update` | Latest stable PyPI release; use the [installation-specific route](./updating.md#installation-owners) for other methods |
|
||||
| Create or refresh config | `nanobot onboard` | Creates `~/.nanobot/config.json` and `~/.nanobot/workspace/` |
|
||||
| Refresh config non-interactively | `nanobot onboard --refresh` | Preserves existing values and adds missing default fields without prompting |
|
||||
| Use guided setup | `nanobot onboard --wizard` | Best when you prefer prompts over hand-editing JSON |
|
||||
@@ -52,6 +53,27 @@ Desktop-only distributions use the narrow `nanobot-desktop-tui` entrypoint insid
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Updating
|
||||
|
||||
```bash
|
||||
nanobot update --check # Check the latest stable PyPI release; do not install
|
||||
nanobot update # Install it in an ordinary Python venv
|
||||
nanobot update --dev # Update source and prepare its matching interfaces
|
||||
nanobot update --plan # Save an exact review; do not install or restart
|
||||
```
|
||||
|
||||
The first two commands target stable PyPI releases, not the saved Preview subscription. `--dev` (`--update-dev`) selects source, not Preview. `--plan --channel stable` or `--plan --channel preview` inspects that channel without changing the subscription; `--channel` requires `--plan`. Saved plans are not executed by `nanobot update`.
|
||||
|
||||
Before an in-place update, back up configuration, workspace files and chat history, then stop all processes sharing that Python environment. New versions may migrate stored data. Use the original [installation-specific route](./updating.md#installation-owners) for uv, pipx, containers, system packages and Desktop; do not overwrite a manager-owned environment with pip. Already-satisfying dependencies remain installed.
|
||||
|
||||
Source updates require Git. Existing editable checkouts fast-forward their current branch to its upstream; resolve local changes, detached HEADs and divergence manually. Updating a package with `--dev` creates an editable checkout under `~/.nanobot/src/` on the official `main` branch. nanobot downloads its pinned Bun when needed; Node is not required. To return to a release, install it in a separate environment and launch outside the checkout; in-place source-to-release switching is refused.
|
||||
|
||||
After installation, restart nanobot and verify the **running** gateway's version and behavior. The CLI checks the installation, not the live process. Downgrading requires `--allow-downgrade` and compatible data; back up before using it.
|
||||
|
||||
In-place CLI updates have no automatic rollback. A failed or interrupted installation leaves an incomplete-update marker under `~/.nanobot/run/`. Stop nanobot and retry the same update from that environment. On Windows, stop processes holding installation files and retry with that environment's `python -m nanobot update` (add `--dev` for source).
|
||||
|
||||
The WebUI's **Settings → About** uses a separate reviewed update-and-restart flow for supported installations and shows owner-specific instructions for others. See [Updating nanobot](./updating.md) for Preview selection, recovery and permission limits. Source updates remain CLI-only. To inspect a saved WebUI job, use `nanobot update --job <plan-id>`; [explicit handoff retry](./updating.md#explicit-recovery-before-package-mutation) requires additional consent and an intact installation, not a post-install repair.
|
||||
|
||||
Most day-to-day commands use the default config and workspace. Advanced or multi-instance runs usually pass both paths explicitly:
|
||||
|
||||
```bash
|
||||
@@ -141,17 +163,19 @@ Interactive mode exits with `exit`, `quit`, `/exit`, `/quit`, `:q`, or `Ctrl+D`.
|
||||
|
||||
| Command | Description |
|
||||
|---|---|
|
||||
| `nanobot webui` | Create config/workspace if needed, enable the local WebUI channel after confirmation, start the gateway, open `http://127.0.0.1:8765`, and follow new gateway logs |
|
||||
| `nanobot webui` | Prepare local WebUI settings and open the browser; installer-managed environments launch persistently, other installations remain attached and follow gateway logs |
|
||||
| `nanobot webui --detach` | Explicitly start or join a persistent gateway, open the browser and return control to the terminal |
|
||||
| `nanobot webui --background` | Deprecated; prints the equivalent explicit `nanobot gateway --background` command and exits |
|
||||
| `nanobot webui --dev` | Start the gateway and Vite together at `http://127.0.0.1:5173`, with live frontend updates |
|
||||
| `nanobot webui --no-open` | Prepare and start the WebUI without opening a browser |
|
||||
| `nanobot webui --no-dock` | Suppress the macOS Dock icon; detached mode remembers this choice until the next WebUI launch |
|
||||
| `nanobot webui --port <port>` | Set the WebUI/WebSocket port |
|
||||
| `nanobot webui --gateway-port <port>` | Override the gateway health port |
|
||||
| `nanobot webui --yes` | Apply safe localhost WebUI defaults without confirmation; configure provider credentials in **Settings → Models** |
|
||||
|
||||
First-run WebUI setup binds to `127.0.0.1` by default. Use manual configuration and a WebUI password before exposing the WebSocket channel beyond localhost.
|
||||
|
||||
`--dev` is a foreground source-checkout workflow. For shell-based lifecycle management, use `nanobot gateway --background` (or `/detach` from an interactive TUI); `nanobot webui --background` prints migration guidance instead of silently changing process ownership. It installs frontend dependencies when `webui/node_modules` is missing, proxies to the configured WebSocket channel port, and stops Vite when the launcher exits. The shared on-demand gateway stops only when no other interactive client still holds it.
|
||||
`--dev` is a foreground source-checkout workflow and cannot be combined with `--detach`. It installs frontend dependencies when `webui/node_modules` is missing, proxies to the configured WebSocket channel port, and stops Vite when the launcher exits. The shared on-demand gateway stops only when no other interactive client still holds it. Installer-managed normal WebUI launches and explicit `--detach` use the gateway's persistent lifecycle; manage that same instance with the `gateway` commands below. The old `webui --background` spelling remains deprecated and prints migration guidance.
|
||||
|
||||
## Gateway
|
||||
|
||||
|
||||
+23
-27
@@ -12,7 +12,7 @@ These repository docs describe `main`, which can be newer than the released pack
|
||||
- Access to one supported AI provider, company endpoint, or local model server.
|
||||
- The credential, endpoint URL, and model ID required by that service. Local providers such as Ollama may not require a key.
|
||||
|
||||
Git and [Bun](https://bun.sh/) are only needed if you want to install from editable source code. The published installer supports macOS 13+ (Apple Silicon and Intel), Linux with glibc 2.17+ (ARM64 and x64), and Windows x64. On other platforms, use the WebUI or `nanobot --classic`. See the [terminal requirements](./cli-reference.md#agent-cli) for native TUI availability and the [release notes](https://nanobot.wiki/docs/latest/getting-started/quick-start) for package details.
|
||||
Official platform packages include the WebUI and matching native TUI for macOS 13+ (Apple Silicon and Intel), glibc 2.17+ Linux (ARM64 and x64), and Windows x64; no frontend build tools are needed. Other platforms can use the WebUI or `nanobot --classic`; see [terminal requirements](./cli-reference.md#agent-cli). Source installs need Git and use Bun, which nanobot downloads when needed.
|
||||
|
||||
## 1. Install nanobot
|
||||
|
||||
@@ -30,13 +30,13 @@ curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.
|
||||
irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1 | iex
|
||||
```
|
||||
|
||||
The installer chooses an active virtual environment, `uv`, `pipx`, or a managed environment under `~/.nanobot/venv`. It installs the stable PyPI release. At the end it prints the exact command it used to run nanobot; if `nanobot` is not on `PATH`, reuse that full command in the examples below.
|
||||
A fresh install uses a dedicated environment under `~/.nanobot/venv`, even if uv or pipx is on PATH. Existing installations keep their original manager; an active ordinary virtual environment remains an explicit target and is not adopted. The installer installs the stable PyPI release and prints the exact command it used to run nanobot. If `nanobot` is not on `PATH`, reuse that full command below.
|
||||
|
||||
If you prefer to inspect the scripts first, open [`install.sh`](../scripts/install.sh) or [`install.ps1`](../scripts/install.ps1).
|
||||
|
||||
## 2. Configure Your Model
|
||||
|
||||
Keep the installer terminal open. The browser opens the local WebUI; go to **Settings → Models** and:
|
||||
Wait for installation and startup to finish. The browser opens the local WebUI; go to **Settings → Models** and:
|
||||
|
||||
1. Choose **New preset** and give it a name. If **Convert to presets** appears, choose it first.
|
||||
2. Open **Provider** and select your provider. To add one, choose **Add provider** from the same menu, then enter and save its connection details or complete sign-in.
|
||||
@@ -79,7 +79,7 @@ Most other providers can say `not set`. This command validates local setup but d
|
||||
|
||||
## 4. Get the First Reply
|
||||
|
||||
If the installer-started WebUI is no longer running, run `nanobot webui` again. Leave that launcher open; the first-run WebUI is bound to localhost, so other devices on your network cannot reach it.
|
||||
If the installer-started WebUI is no longer running, run `nanobot webui` again. The first-run WebUI is bound to localhost, so other devices on your network cannot reach it.
|
||||
|
||||
Send:
|
||||
|
||||
@@ -89,7 +89,9 @@ Hello!
|
||||
|
||||
Any normal assistant answer is success. It proves that nanobot can load the config, reach the selected model, use the workspace, and serve the browser UI.
|
||||
|
||||
Interactive WebUI and TUI launchers share one on-demand gateway. Closing one launcher leaves it running for the others; closing the last launcher stops it. If you prefer a persistent background process, press `Ctrl+C`, then run:
|
||||
Fresh official-installer environments start a persistent gateway: closing the browser or terminal does not stop it. Other installations keep their on-demand lifetime unless you explicitly use `nanobot webui --detach` or the gateway command below. An attached on-demand launcher must stay open; closing its last local client stops that gateway.
|
||||
|
||||
To start or inspect a persistent gateway:
|
||||
|
||||
```bash
|
||||
nanobot gateway --background
|
||||
@@ -163,7 +165,7 @@ If pip reports `externally-managed-environment`, use the recommended installer,
|
||||
|
||||
**Current source**
|
||||
|
||||
Clone the repository and install it in editable mode. Bun is required so the checkout can run its matching native TUI instead of mixing current Python with an older release binary.
|
||||
Clone the repository and install it in editable mode. nanobot downloads the pinned Bun runtime to run the checkout's matching TUI; Node is not required.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/HKUDS/nanobot.git
|
||||
@@ -180,15 +182,19 @@ nanobot webui
|
||||
|
||||
The source path follows current `main` and can be newer than the published package. The editable install keeps Python pointed at the checkout; `nanobot` runs `tui/` with Bun, and `nanobot webui` automatically rebuilds `webui/` when its bundled assets are stale. All normal commands remain the same as a stable install. For development details, follow [`../CONTRIBUTING.md`](../CONTRIBUTING.md).
|
||||
|
||||
If the package is installed but the shell cannot find `nanobot`, use the runner that owns the installation. The recommended installer prints the exact command to reuse. Common forms are:
|
||||
If the shell cannot find `nanobot`, reuse the installer's printed command or run Python from the existing installation. For uv or pipx, locate that environment with the original manager; do not start a temporary tool environment to manage it. The official installer's default paths are:
|
||||
|
||||
```bash
|
||||
uv tool run --from nanobot-ai nanobot --version
|
||||
pipx run --spec nanobot-ai nanobot --version
|
||||
~/.nanobot/venv/bin/python -m nanobot --version
|
||||
~/.nanobot/venv/bin/python -I -m nanobot --version
|
||||
```
|
||||
|
||||
On Windows, the managed-environment form is `& "$HOME\.nanobot\venv\Scripts\python.exe" -m nanobot --version`. Replace `--version` with `webui`, `onboard --wizard`, or any other arguments you need. Use plain `python -m nanobot` only when that Python executable belongs to the environment where nanobot was installed.
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
& "$HOME\.nanobot\venv\Scripts\python.exe" -I -m nanobot --version
|
||||
```
|
||||
|
||||
Replace `--version` with `webui`, `onboard --wizard`, or the arguments you need. Use plain `python -m nanobot` only when that Python belongs to the installed environment.
|
||||
|
||||
## Manual Configuration Fallback
|
||||
|
||||
@@ -227,26 +233,16 @@ Replace the provider, endpoint, and model together. Do not pair a credential fro
|
||||
|
||||
## Updating
|
||||
|
||||
Upgrade with the same method you used to install:
|
||||
Open **Settings → About → Update**. Supported installations can update and restart there; others show instructions for their original package manager or deployment. Follow [Updating nanobot](./updating.md) for Preview selection, backups and recovery. Do not switch installation methods to work around an error.
|
||||
|
||||
For an ordinary Python virtual environment, the [CLI updater](./cli-reference.md#updating) is also available:
|
||||
|
||||
```bash
|
||||
# Recommended installer
|
||||
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh
|
||||
|
||||
# Or one of these
|
||||
uv tool upgrade nanobot-ai
|
||||
pipx upgrade nanobot-ai
|
||||
python -m pip install -U nanobot-ai
|
||||
nanobot update --check
|
||||
nanobot update
|
||||
```
|
||||
|
||||
For a source checkout:
|
||||
|
||||
```bash
|
||||
git pull --ff-only
|
||||
python -m pip install -e .
|
||||
```
|
||||
|
||||
Because the install is editable, normal source changes are visible immediately. Re-running the install synchronizes any changed Python dependencies; the TUI and WebUI refresh their own dependencies/assets when launched. Then check `nanobot --version`. Run `nanobot onboard --refresh` when you want to add newly introduced default fields while preserving existing settings.
|
||||
Stop affected processes and back up configuration and data first; restart and verify the running version afterward. Source checkouts should preserve local changes and follow the [development instructions](../CONTRIBUTING.md).
|
||||
|
||||
## If the First Reply Fails
|
||||
|
||||
|
||||
+220
-28
@@ -1,29 +1,74 @@
|
||||
# Release checklist
|
||||
|
||||
Use this checklist with the [Release Packaging Contract](../CONTRIBUTING.md#release-packaging-contract). Preparing a release does not publish it. Pushing a Git tag, publishing a GitHub Release, uploading to PyPI, and deploying the documentation are separate operations.
|
||||
Use this checklist with the [Release Packaging Contract](../CONTRIBUTING.md#release-packaging-contract). Preparation does not authorize publication. Pushing tags, publishing GitHub Releases, uploading to PyPI and deploying documentation are separate operations.
|
||||
|
||||
## Release cadence
|
||||
|
||||
Stable is the default feed; Preview is opt-in. Both use one update flow and require confirmation before installation. Neither a faster cadence nor a subscription permits stopping tasks or restarting a gateway automatically. See [Updating nanobot](./updating.md) for user instructions.
|
||||
|
||||
| Release | When to prepare it | Public destination | User experience |
|
||||
| --- | --- | --- | --- |
|
||||
| Stable feature release | At the planned feature milestone | Final GitHub Release and PyPI; also index its manifest for Preview subscribers | Normal update notice |
|
||||
| Stable patch | When a reviewed fix or small, compatible improvement is ready; do not wait for the next monthly milestone | Same stable destinations and checks | Normal update notice, no Preview opt-in required |
|
||||
| Preview | On maintainer request, from reviewed changes with passing checks; potentially daily | GitHub prerelease and protected `release-index` catalogue; not PyPI | Same update notice for subscribers, with risk shown before installation |
|
||||
|
||||
Packaging is maintainer-triggered, not scheduled or push-triggered. Record the requested channel, exact source and candidate identity; preparation does not authorize publication. Unchanged source, failed checks, missing assets, incomplete acceptance or absent approval leaves the last verified release in place. There is no daily-release promise. Acceptance must cover the supported stable baseline and an earlier Preview, including skipped previews, not just the previous build.
|
||||
|
||||
### Stable patch procedure
|
||||
|
||||
1. Select the supported stable baseline and reviewed fixes. If `main` contains unfinished features, branch from that baseline and backport only the required fixes. Do not relabel an unverified Preview as stable.
|
||||
2. Allocate an unused final version, update both version declarations, and follow **Prepare a candidate**. Patches require the same packaging, licensing, native startup, data-preservation and update/recovery gates as feature releases.
|
||||
3. Publish approved immutable files in order: GitHub, PyPI, public-download checks, then the catalogue's `stable` pointer. Preserve `preview` and withdrawal history. A stable patch older than an installed Preview must not be offered as a downgrade.
|
||||
4. Publish concise fix notes and required operator actions. Users without this updater need their original installation method for the first upgrade; external package/deployment owners retain their route.
|
||||
|
||||
### Maintainer-triggered Preview procedure
|
||||
|
||||
1. Select an exact reviewed `main` commit with passing required CI; skip it if its source SHA matches the last accepted candidate. Record the next unreleased stable base and an unused increasing Preview sequence.
|
||||
2. Run **Verify Release Candidate** for that ref and base. It prepares a version-only candidate, builds the WebUI and five native TUI bundles, and verifies the package set without publication. Users receive built packages, not a checkout requiring Bun.
|
||||
3. Select `retain_installable` and preserve the handoff before expiry. Complete native and packaged old-to-new update/recovery acceptance against those exact bytes. Keep candidate SHA, manifest hash, coverage, known issues and source-offer approval together; CI reports alone are neither installable artifacts nor publication consent.
|
||||
4. With separate approval, publish immutable `v<version>` at the **candidate** commit and a GitHub prerelease, never the latest stable release. Upload the complete verified set, manifest and notes; make the pinned installer source publicly reachable.
|
||||
5. Verify all public sizes/hashes and clean public install/update acceptance before advancing `preview` with a new catalogue generation. Validate against the latest catalogue, preserve `stable` and withdrawals, and serialize stable, Preview and withdrawal writes. A stale publisher must reread and revalidate.
|
||||
6. After partial upload, leave the feed unchanged and resume only from the original verified files. Lost or changed bytes require a new version and repeated acceptance. Withdraw unsafe candidates with a reason and offer a newer fix; never rewind the feed or restore user data.
|
||||
|
||||
Use Python version ordering: `0.3.6.dev42 < 0.3.6.dev43 < 0.3.6 < 0.3.7.dev1` (illustrative versions). Once a final base ships, previews need a later base; allocate it after accounting for stable patches. The workflow uses `github.run_number` for `N` in `X.Y.Z.devN`; do not reset the sequence without checking published versions. Reruns cannot replace published bytes. Rebuild and test final releases under their final identity; never rename `.devN` wheels.
|
||||
|
||||
### Launch gates and automation boundary
|
||||
|
||||
Before offering public Preview, obtain approval for index ownership/protection, publication credentials, source retention and exact packaged/public-download acceptance. Candidate preparation does not activate a public channel, schedule, protected publisher or PyPI upload. Preserve approved release bytes and source outside expiring CI storage for their required lifetime.
|
||||
|
||||
Automate steps within an explicitly requested run, not the decision to build or publish. Keep builds read-only, publication permissions in a protected stage, the last accepted source/version recorded and one serialized catalogue writer. Announce Preview availability only after verifying its public feed. Any discovery hint must be dismissible; do not show an update badge for an unavailable channel or enroll users merely because they check.
|
||||
|
||||
## Prepare a candidate
|
||||
|
||||
1. Choose the previous release and the exact candidate commit. Work in a clean worktree; do not include local configuration, session data, credentials, or unrelated changes.
|
||||
2. Update `project.version` in `pyproject.toml` and the final source-only fallback in `nanobot/__init__.py`. Private WebUI/TUI package versions are not the Python release version.
|
||||
3. Review the changes since the previous tag. Write highlights, upgrade and rollback guidance, contributor acknowledgements, and the full changelog. Verify counts against the final range; commit counts are not merged-PR counts. Coordinate security disclosures separately.
|
||||
4. Run the Python, WebUI, and TUI checks from CI. Confirm the final commit's CI status, not just an earlier PR head. Review installation, configuration, session, and API changes.
|
||||
5. Build in a clean output directory with `uv build --out-dir <artifact-directory>`. Do not set `NANOBOT_SKIP_WEBUI_BUILD`. The build hook bundles the WebUI in the sdist and wheel; the wheel is built from the sdist.
|
||||
6. Check the intermediate distributions with `twine check`, inspect their contents, and record SHA-256 hashes. Test installation in an isolated environment outside the source checkout, then test upgrading from the previous stable version using disposable configuration and sessions. Do not use a maintainer's live workspace for migration tests.
|
||||
7. Prepare the matching documentation PR in `Re-bin/nanobot-web`, following its `MAINTAINING.md`. Review English and all nine translations, preserve Nightly and previous releases, update the latest-version redirects, and run the complete site quality gate. Pin source links to the checked candidate commit; confirm those source files match the eventual tag before deploying. Never advertise an unpublished version as publicly available.
|
||||
8. Review the pinned Bun/OpenTUI licenses, corresponding-source materials, and relinking instructions now, not after pushing the tag. Verify the exact upstream revisions are retrievable and the runtime versions match the lockfile and notices. Obtain the maintainer's commitment to honor `tui/SOURCE_OFFER.md` for its entire stated period; tests cannot grant it.
|
||||
9. Build all five native TUI targets using the same scripts as the publication workflow. Include ad-hoc signatures for macOS before packaging. Verify every archive's checksum, manifest, executable architecture, required notices/licenses, and embedded source contents. Run platform-specific smoke tests where supported; record cross-compiled-only targets as such and link exact-head CI evidence instead of claiming native execution everywhere. Bundle these archives into the five platform wheels using the command below. Check all final wheels with `twine check`, validate their RECORDs, tags and installed executable permissions, and test first launch with an empty cache and `NANOBOT_TUI_NO_DOWNLOAD=1`. The installed executable must come from `site-packages/nanobot/tui/bin/`, not the checkout or a cache.
|
||||
10. Merge the release-preparation PR only after its current checks and reviews pass. Confirm the merged source tree matches the tested candidate; if it does not, rebuild and recheck before tagging. Reconcile the final changelog and documentation source references. The tag must point to this verified commit, not an unchecked later `main` tip.
|
||||
1. Choose the previous release and exact candidate commit. Use a clean worktree without local configuration, sessions, credentials or unrelated changes.
|
||||
2. Update `project.version` in `pyproject.toml` and the final source-only fallback in `nanobot/__init__.py`. Private WebUI/TUI versions are not the Python release version.
|
||||
3. Review the final tag range; prepare highlights, upgrade/rollback guidance, acknowledgements and full changelog. Verify counts: commits are not merged PRs. Coordinate security disclosures separately.
|
||||
4. Run Python, WebUI and TUI CI checks against the final commit, not an earlier PR head. Review installation, configuration, session and API changes.
|
||||
5. Run `uv build --out-dir <artifact-directory>` in a clean output directory without `NANOBOT_SKIP_WEBUI_BUILD`. The build hook bundles WebUI in sdist and wheel; the wheel is built from the sdist.
|
||||
6. Run `twine check` on intermediates, inspect contents and record SHA-256 hashes. Test installation in an isolated environment outside the checkout and upgrade from previous stable with disposable configuration/sessions, never a maintainer's live workspace.
|
||||
7. Prepare the documentation PR in `Re-bin/nanobot-web` under its `MAINTAINING.md`: review English and all nine translations, preserve Nightly and previous releases, update latest-version redirects and run the full site quality gate. Pin source links to the candidate and confirm they match the eventual tag. Do not advertise an unpublished version.
|
||||
8. Review pinned Bun/OpenTUI licenses, corresponding source and relinking instructions. Check upstream revision availability and runtime/lockfile/notice agreement. Obtain the maintainer's commitment to the [source offer](../tui/SOURCE_OFFER.md) for its full stated period, at least three years after release; tests cannot grant it.
|
||||
9. Build all five native targets with publication scripts, ad-hoc signing macOS before packaging.
|
||||
- Verify archive checksums, manifests, architecture, licenses/notices and embedded source. Run supported native smoke tests, record coverage and exact-head CI evidence, and label cross-compiled-only targets.
|
||||
- Build platform wheels below, check them with `twine check`, validate RECORDs/tags/permissions and test pip selection on all five platforms.
|
||||
- Test first launch with an empty cache and `NANOBOT_TUI_NO_DOWNLOAD=1`; the executable must come from `site-packages/nanobot/tui/bin/`, not checkout or cache.
|
||||
10. Merge release preparation only after current checks/reviews pass. Compare the merged source tree with the tested candidate; rebuild/recheck changes. Reconcile changelog and documentation links, then tag the verified commit, not an unchecked later `main` tip.
|
||||
|
||||
### Protected updater handoff compatibility
|
||||
|
||||
Restart-capable packages include `nanobot/update_contract.json`: schema version 1, with `handoff_protocols` listing positive integer protocol IDs. Protocol 1's request, protected startup and activation requirements are defined in the [update protocol](./update-protocol.md), independently of package and WebUI versions.
|
||||
|
||||
Before advertising protocol 1, run preparation, frozen-worker and actual-gateway restart tests against packaged code; verify the declaration is in both sdist and wheel. Retain an ID only while its entire contract is supported; incompatible request, startup or activation behavior needs a new ID. Older updaters may install a future package only if protocols overlap. Missing, malformed or non-overlapping declarations must be refused before shutdown and require the installation owner's external update route.
|
||||
|
||||
### OpenAI API selector compatibility window
|
||||
|
||||
The temporary `providers.openai.apiType` / `api_type` conversion is supported for exactly two consecutive releases: the first release containing `nanobot/config/provider_api_migration.py` and the next release. Record the first release tag and the final supported tag in release notes. Config saves write the new `api` declaration; there is no legacy runtime selector.
|
||||
The temporary `providers.openai.apiType` / `api_type` conversion lasts exactly two consecutive releases: the first containing `nanobot/config/provider_api_migration.py` and the next. Record the first and final supported tags in release notes. Config saves write `api`; there is no legacy runtime selector.
|
||||
|
||||
Before publishing the third release, remove `provider_api_migration.py`, its import and `ProvidersConfig._migrate_legacy_api_type`, and the legacy settings query conversion in `nanobot/webui/settings_models.py`. Remove the migration-specific tests and update the configuration documentation and release notes to require the current format. Keep the current-format routing, settings, and persistence regressions.
|
||||
Before the third release, remove `provider_api_migration.py`, its import, `ProvidersConfig._migrate_legacy_api_type`, the legacy settings query conversion in `nanobot/webui/settings_models.py` and migration-specific tests. Update configuration docs and release notes to require the current format. Keep current-format routing, settings and persistence regressions.
|
||||
|
||||
### TUI preflight without a release tag
|
||||
|
||||
Use Bun 1.3.13 and a clean checkout. The local build and packaging scripts do not require a tag or GitHub Release. Run targets sequentially because native dependency preparation modifies the shared `node_modules` directory:
|
||||
Use Bun 1.3.13 and a clean checkout; no tag or GitHub Release is required. Run targets sequentially because native dependency preparation modifies shared `node_modules`:
|
||||
|
||||
```bash
|
||||
cd tui
|
||||
@@ -35,11 +80,11 @@ bun scripts/release-notices.ts <target>
|
||||
python3 scripts/package-release.py <target>
|
||||
```
|
||||
|
||||
Repeat for `darwin-arm64`, `darwin-x64`, `linux-arm64`, `linux-x64`, and `win32-x64`. On macOS, use `codesign --force --sign - <binary>` and verify the signature. The publication workflow uses pinned `rcodesign` on Linux. Keep the ten `.zip`/`.zip.sha256` outputs in a candidate-specific directory, alongside the Python build intermediates and provenance manifest. Do not include local configuration, instance backups, or test environments in upload selections.
|
||||
Repeat for `darwin-arm64`, `darwin-x64`, `linux-arm64`, `linux-x64` and `win32-x64`. On macOS, run `codesign --force --sign - <binary>` and verify it; the publication workflow uses pinned `rcodesign` on Linux. Keep the ten `.zip`/`.zip.sha256` files with Python intermediates and provenance manifest in a candidate-specific directory, excluding configuration, backups and test environments from upload selections.
|
||||
|
||||
### Build the PyPI platform wheels
|
||||
|
||||
From the exact release checkout, after `uv build` and the native archive checks:
|
||||
After `uv build` and native archive checks, from the exact release checkout:
|
||||
|
||||
```bash
|
||||
uv run python -m scripts.build_tui_wheels \
|
||||
@@ -48,23 +93,170 @@ uv run python -m scripts.build_tui_wheels \
|
||||
--out-dir <final-wheels>
|
||||
```
|
||||
|
||||
The script verifies the Python version and RECORD, native checksums, architecture, notices and embedded source against the checkout, then writes five wheels with complete TUI bundles and regenerated RECORDs. It refuses to overwrite an existing candidate. `--target <target>` builds one platform for a targeted check. Minimum tags are macOS 13, manylinux glibc 2.17 and Windows x64; x64 builds use Bun's baseline (SSE4.2) runtime instead of requiring AVX2. Recheck both Bun and OpenTUI when upgrading either dependency. No musl or Windows ARM64 wheel is provided. Native execution checks must still validate the actual binaries; tags alone do not prove compatibility. Test pip selection for all five supported platforms.
|
||||
The script checks Python version/RECORD and native checksums, architecture, notices and source against the checkout, then writes five bundled wheels with regenerated RECORDs. It refuses existing candidates; `--target <target>` selects one platform. Minimum tags are macOS 13, manylinux glibc 2.17 and Windows x64; x64 uses Bun's baseline SSE4.2 runtime, not AVX2. Recheck Bun/OpenTUI requirements when upgrading either. There are no musl or Windows ARM64 wheels; tags do not substitute for native execution.
|
||||
|
||||
The final PyPI upload set is **five platform wheels plus one source distribution**. Do not upload the intermediate `py3-none-any.whl` or native ZIPs to PyPI. Keep the source distribution produced by the same build; it remains usable for Python/classic and WebUI installations on other platforms.
|
||||
PyPI receives **five platform wheels and one sdist**, not the intermediate universal wheel or native ZIPs. Keep the same build's platform-neutral sdist for Python/classic and WebUI on other platforms. Record source commit, version, files, hashes, checks and remaining gates; source changes require rebuilding and rechecking.
|
||||
|
||||
Keep an artifact manifest with the source commit, version, filenames, hashes, checks performed, and any remaining release gates. Rebuild and recheck if the packaged source changes.
|
||||
Final releases also require `release-manifest.json` for `stable`. Run `scripts.release_candidate assemble` as shown below from the clean final-version checkout, using that final commit as `--source-commit` without Preview preparation. GitHub receives the same wheels/sdist, ten archive/checksum files and manifest; PyPI receives only wheels/sdist. Verify final source and public bytes before catalogue advancement. A TUI-only GitHub Release cannot deliver the final release to Preview subscribers.
|
||||
|
||||
## Publish, with maintainer approval
|
||||
|
||||
1. Confirm all pre-tag gates above are complete. Create and push exactly `vX.Y.Z`; do not move or reuse a published version tag.
|
||||
2. Create the matching GitHub Release. A draft may be used while assembling its attachments. Pushing the tag alone does not run `Publish Terminal UI` or upload anything to PyPI.
|
||||
3. Attach the already verified five TUI archives and their `.sha256` files, after confirming the tag's packaged sources match the artifact manifest. Verify the uploaded bytes match their preflight hashes; never upload a naked executable.
|
||||
4. If instead rebuilding through **Publish Terminal UI**, use `tag=vX.Y.Z` and confirm the already completed compliance review. Wait for all five targets and repeat artifact checks on those new outputs. Do not substitute their new bytes under the old artifact hashes.
|
||||
5. Make the GitHub Release and all TUI attachments publicly available. Verify their public downloads for fallback/source-built installations. Supported platform-wheel installs do not need these downloads to start the TUI.
|
||||
6. Upload only the checked `nanobot_ai-X.Y.Z.tar.gz` and the five final platform wheels to PyPI. Do not upload the intermediate universal wheel or stale files from a shared `dist/` directory. This repository has no automatic PyPI publication workflow.
|
||||
7. Verify installation from PyPI, bundled WebUI startup, and bundled TUI startup without downloads in clean environments. Merge the prepared wiki PR only when the stable package is available: merging its `main` deploys the site automatically. Confirm all localized `/docs/latest/` routes select the new version and old version links still work.
|
||||
8. Publish the release announcement and add the dated entry to [Release Archive](./release-archive.md). Complete any coordinated advisory publication and reporter notification. Record links and completion status in the release tracking issue.
|
||||
### Release approval proof
|
||||
|
||||
Both Stable and Preview automatic installs require `release-manifest.json.sigstore.json` beside the manifest on the exact GitHub release. Clients verify Sigstore's production certificate chain/transparency proof and accept only `HKUDS/nanobot`'s manual `release-approve.yml` on `main`. The signed manifest must match version, wheel size/digest and, for Preview, catalogue commit/manifest binding. Verification runs before download and before shutdown, with no unsigned fallback. Unsigned historical releases remain discoverable but cannot be automatically installed; existing installations keep running.
|
||||
|
||||
Before setting the repository variable `NANOBOT_RELEASE_SIGNING_ENABLED=true`, an administrator must protect `main` and the `release-approval` environment: require independent review, prevent self-review, allow deployment only from `main`, and restrict bypass and changes to the workflow/signing requirements. Signing is disabled without that variable. No long-lived signing key or Apple Developer ID is required.
|
||||
|
||||
After candidate tests and dependency review, take version, manifest SHA-256, source SHA and candidate SHA from retained acceptance evidence, not public downloads. Upload the proposed manifest through the separately authorized release handoff, then manually run **Approve Exact Release** from `main` with those values and obtain environment review. The hash-locked job checks/signs the exact manifest without installing candidate code or writing releases, PyPI or the catalogue. Separately authorize attaching its proof, verify the public proof before advancing either channel, and preserve it with candidate evidence before its three-day CI expiry.
|
||||
|
||||
Regenerate the signing lock only in a reviewed dependency update:
|
||||
|
||||
```bash
|
||||
uv pip compile .github/release-signing-requirements.in --python-version 3.11 \
|
||||
--python-platform x86_64-manylinux_2_17 --generate-hashes --no-header \
|
||||
--output-file .github/release-signing-requirements.txt
|
||||
```
|
||||
|
||||
Review resolved dependencies; hashes are not malware review. Before the first release, prove a supported real old updater can install the signed candidate and that the candidate can install the next signed version. Private packaged recovery fixtures substitute publication authority and are not signature evidence.
|
||||
|
||||
The proof authenticates release approval, not reproducible builds or harmless code. Compromised authorized workflows/reviewers, malicious source that passes review and compromised runtime dependencies remain risks. The signing lock does not lock runtime resolution, which retains the installation owner's policy. A reviewed runtime dependency inventory, public signed upgrade continuity and verified repository protection settings remain security-release gates; do not claim comprehensive supply-chain protection without them. The first installer and checksum source also need a trusted distribution channel.
|
||||
|
||||
1. Complete pre-tag gates, then create and push exactly `vX.Y.Z`; never move or reuse a published tag.
|
||||
2. Create the matching GitHub Release. A tag push alone runs neither **Publish Terminal UI** nor PyPI publication.
|
||||
3. Attach five platform wheels, sdist, five TUI archives, their `.sha256` files and `release-manifest.json`. Confirm tag sources match the manifest and uploaded hashes match preflight. Complete approval proof before offering automatic updates; never upload a naked executable.
|
||||
4. If rebuilding via **Publish Terminal UI**, use `tag=vX.Y.Z` with compliance review confirmed. Wait for all five targets, recheck outputs, and assemble/recheck wheels and manifest from those exact archives. Never mix rebuilt archives with old wheel bytes/hashes; replacing public assets requires a new version.
|
||||
5. Make the release and complete artifact set public. Verify every file against the accepted manifest, including native fallback/source-install archives. Platform-wheel TUI startup must not need downloads.
|
||||
6. Upload only the checked `nanobot_ai-X.Y.Z.tar.gz` and five final wheels to PyPI, not the universal intermediate or stale shared `dist/` files. There is no automatic PyPI publication workflow.
|
||||
7. Verify clean PyPI installation, bundled WebUI and download-free TUI startup. After all public GitHub/PyPI files pass, advance `stable`, preserving Preview and withdrawals; check discovery for both subscriptions. Only then merge the wiki PR: its `main` deploys automatically. Confirm all localized `/docs/latest/` routes select the new version and old-version links still work.
|
||||
8. Announce the release, add its dated [Release Archive](./release-archive.md) entry, complete coordinated advisories/reporter notifications, and record links/status in the release tracking issue.
|
||||
|
||||
## If a gate fails
|
||||
|
||||
Do not publish to PyPI while a required TUI artifact or verification is missing. Keep the documentation's public `latest` on the previous stable version until the new version is usable. If a published package needs a correction, prepare a new version; do not silently replace the code behind an existing release tag. Stop all old processes and follow the documented session rollback procedure before downgrading a migrated installation.
|
||||
Do not publish to PyPI with missing TUI artifacts or verification. Keep public documentation's `latest` on the usable stable version. Correct published packages with a new version, never replacement code behind an existing tag. Before downgrading a migrated installation, stop all old processes and follow the documented session rollback procedure.
|
||||
|
||||
## Installer identity checks
|
||||
|
||||
Fresh base-package installs use the official installer's dedicated venv regardless of optional managers on PATH. `nanobot-install.json` is written before venv/download work so failed first installs retain their owner; it is not readiness proof. Existing venv/uv/pipx installations are not adopted or moved. The receipt records extras for update planning and opts `webui` into persistent background launch; unrecorded installs retain their lifecycle. Include this distinction and the instance-specific stop command in release notes.
|
||||
|
||||
Linux/Windows native CI builds a platform wheel and runs the public installer in a private home without Bun/Node/Git on PATH, then checks the managed receipt, installed WebUI, native TUI and gateway. Python/WebUI changes also require these jobs. CI retains small reports, not candidate binaries. Startup probes and offline installer fixtures do not replace packaged upgrade/recovery or public-download acceptance.
|
||||
|
||||
Run `pytest tests/test_install_scripts.py` with `uv` and `pipx` available. It uses private homes, offline fixture wheels and real managers, without a gateway or real application install: `install.sh` on Unix and Windows PowerShell with `install.ps1` on Windows. CI provisions pipx outside application dependencies. Verify these owner-preservation requirements:
|
||||
|
||||
- Launch the selected persistent environment's isolated Python, not `pipx run`, disposable tools or an arbitrary PATH executable. Existing recognized installations take priority over newly available managers; multiple recognized installs require explicit choice. An ordinary active venv is explicit; uv/pipx environments must use their manager.
|
||||
- Preserve uv constraints. Generic pipx upgrades can drop constraints/options; the installer must refuse pipx records with those settings, lock workflows or unconfirmed sources. The owner must review and preserve them. Exact wheels may replace a wheel source, not registry constraints/options; pipx upgrades must retain requested extras and refuse wheels missing recorded extras.
|
||||
- A failed selected manager must not fall through to another installation, even on first install. Verify the exact persistent package version before onboarding: a successful pinned/locked skip is not target installation. Restarted gateway identity is a separate check.
|
||||
|
||||
Verify the exact-handoff options against the pinned installer, not an older script: `install.sh --wheel <path> --sha256 <published-hash>` / `install.ps1 -Wheel <path> -Sha256 <published-hash>`, or `install.sh --release <version> --manifest-sha256 <trusted-manifest-hash>` / `install.ps1 -Release <version> -ManifestSha256 <trusted-manifest-hash>`. Wheel mode verifies checksum/package/version; release mode selects one of five native tags for the target Python and verifies size/hash/identity before invoking the original owner. No frontend toolchain or extra selector package is installed; the manager still checks Python/dependencies. Hashes must come from trusted metadata, not an unknown publisher.
|
||||
|
||||
Release downloads use official GitHub HTTPS hosts and configured HTTPS proxy; retain wheel sources at their recorded paths, including `~/.nanobot/downloads/releases` or `NANOBOT_RELEASE_CACHE`. Failed partial downloads are removed. Wheel-mode `--dry-run` / `-DryRun` verifies without installation/setup; release-mode dry-run checks only the manifest, creating no wheel/cache/environment/setup and proving neither wheel bytes nor dependency resolution.
|
||||
|
||||
These exact-version handoffs do not discover Preview, change subscriptions, stop gateways or back up data. Require stopped writers and backup first. Review extras and recorded options for plain pip, suffixed/custom installs and external owners; see the [user guide](./updating.md) and [update protocol](./update-protocol.md). Installer fixtures alone do not establish live maintenance, backup or restart safety.
|
||||
|
||||
### Packaged upgrade and recovery acceptance
|
||||
|
||||
Linux/Windows native CI runs `scripts/verify_packaged_update.py` against its wheel; manual candidate preparation uses the assembled Linux wheel. Run macOS acceptance against the candidate's macOS wheel:
|
||||
|
||||
```bash
|
||||
<build-tools-python> -I scripts/verify_packaged_update.py \
|
||||
--wheel <exact-native-wheel> --commit <candidate-commit> \
|
||||
--output <new-private-acceptance-directory>
|
||||
```
|
||||
|
||||
Build tools need project Python dependencies. The probe creates disposable venv/account/configuration/workspace and loopback gateways, without maintainer data, models or credentials. It records the unchanged healthy target's SHA-256 and candidate commit; faulted private wheels must never be uploaded.
|
||||
|
||||
On a local macOS desktop, add `--dock` to verify the real AppKit helper alongside these journeys. The managed receipt must make `nanobot webui --yes --no-open` detach automatically; each applicable running version must have one helper, preserve desktop intent through upgrade/recovery and a second start, and remove its helper on stop. Historical packages without Dock support gain the icon only after their first healthy upgrade and an explicit WebUI launch. This is process/lifecycle acceptance, not a visual Dock-click test; do not enable it on headless CI or claim native Windows/Linux icon coverage.
|
||||
|
||||
Require normal and consecutive upgrades, skipped Preview, import/startup failure, backup failure after shutdown, worker termination, partial metadata loss and interruption between program-restoration renames. Each successful journey must show the expected version in a new gateway run, a retained verified backup, authenticated history reads, continued writes and a second ordinary start. Each recovered service must then update to the healthy target with the same account/conversations. Faults affect the first job; backup failure must survive its automatic retry, while a separately confirmed next update can make a healthy backup. The instrumented intermediate Preview's second hop installs the unchanged final wheel.
|
||||
|
||||
Compare configuration, retained legacy-source bytes, canonical SQLite records, WebUI transcripts and pending `delivery/outbox.sqlite3` records separately. Cover canonical-only, display-only and mixed history without inventing canonical records for display-only chats; SQLite checkpoint byte changes alone are not data loss. Retain the protocol-1 parked-gateway regression across old/new protected-store inventories: no outbox initialization, migration or writes outside the old grant before activation. See the [update protocol](./update-protocol.md) for scope and lease requirements.
|
||||
|
||||
Default baselines are labelled target-derived fixtures, not historical compatibility evidence. For release acceptance, add `--baseline-wheel <previously-accepted-wheel>` and repeat with supported stable and older Preview packages, including skipped Preview. Baseline feed transport is instrumented; the healthy target is unchanged. Include a retained pre-SQLite updater to check JSONL migration's canonical message bodies separately from display history. If recovery restores JSONL code, mark SQLite checks not applicable, not passed. Packages without this updater need separately recorded installation-owner bootstrap acceptance.
|
||||
|
||||
Exercise consecutive updates in the same disposable account with existing conversations through each applicable owner: official installer, uv tool, pipx, ordinary pip venv and source. Check recorded constraints/options before/after, execute the offered command, verify the restarted gateway, append a message and start again. Policy refusal must leave installation unchanged; custom owner-reviewed updates do not prove automatic recovery. Container replacement requires a real engine and retained data volumes, not a mocked marker.
|
||||
|
||||
For installer-owned background recovery, verify one exact-target repair, then original-program restoration only before activation and only with unchanged protected data, including restart/health verification without browser or terminal intervention. Data changes, activation, live owners or changed installation ownership must prevent unsafe rollback. Other owners retain their repair route. Never delete jobs/fences or automatically restore old configuration/chat data. Exercise native Windows locks/renames. Loss of both supervisor and worker, permanent storage damage and incompatible data writes are not automatically recoverable; retain these limits in release notes and the operator guide.
|
||||
|
||||
Keep private evidence until review; it can contain program generations/backups and is not an upload set. CI retains small reports, including completed cases after a later failure; only all selected journeys passing produces aggregate success. Partial reports or a timeout are not an overall pass. Record actual native OS/CPU coverage separately from installer/startup fixtures: Linux x64, Windows x64 and macOS arm64 do not establish macOS x64 or Linux arm64 coverage. Controlled release transport and fault injection prove neither public downloads nor interactive UI; complete those gates before claiming them.
|
||||
|
||||
## Stable and Preview subscriptions
|
||||
|
||||
Use [Updating nanobot](./updating.md) for Settings → About and CLI instructions. Release acceptance must preserve opt-in consent: Preview is off even on development builds; switching saves/checks a feed, not installation approval. Require separate exact-version confirmation and a Preview risk warning. Profiles sharing an environment/account share its subscription; other installations/accounts do not. Environment replacement may require reselection; browser storage is not authoritative.
|
||||
|
||||
| Current install / requested channel | Required acceptance result |
|
||||
| --- | --- |
|
||||
| Stable → Preview, a newer verified preview exists | Offer that exact preview; install only after confirmation. |
|
||||
| Preview → Preview | Offer only a higher verified version, including a final release. |
|
||||
| Preview → Stable, stable is newer | Offer the final release; keep Stable selected. |
|
||||
| Preview → Stable, stable is older | Save Stable and wait for a newer final release; keep running the preview. |
|
||||
| Preview subscriber installs a final release | Keep Preview selected for the next development cycle. |
|
||||
| Current preview was withdrawn | Warn even without a safe newer replacement; never silently downgrade. |
|
||||
| Feed offline, incomplete, missing or incompatible | Return non-success; retain subscription and allow rechecking. |
|
||||
|
||||
Stable checking/planning requires complete PyPI wheels/sdist. Preview uses `release-index/catalogue.json` and exact GitHub manifests, never PyPI `--pre` or arbitrary branches. Validate targets against the gateway interpreter/platform, not the browser. Index final releases for Preview subscribers too; advance only after verifying all referenced public assets.
|
||||
|
||||
Versions, tags and manifest hashes are immutable. Increment generation; never rewind or clear published pointers, remove withdrawals or reuse bad versions. To stop offering a version, retain its pointer and withdraw it. Serialize writers and validate `ReleaseCatalogue.validate_successor(previous)` against the latest catalogue. Clients reject rewrites relative to their last accepted catalogue; that check is not cryptographic signing.
|
||||
|
||||
Acceptance must invalidate reviews on every channel change, including Stable → Preview → Stable; cancel inactive staged work through normal stop checks and retain diagnostics. Active preparation, committed shutdown, admitted installation or failed mutation blocks switching until settled/recovered. Reject stale-tab writes and reread after lost responses, never automatically retry installation. Detailed transaction rules belong in the [update protocol](./update-protocol.md).
|
||||
|
||||
Discovery grants no installation authority. Only the official managed venv and supported POSIX uv transactions support the reviewed stop/install/restart flow; pipx, source, container, system-managed, unsupported uv/platform and desktop distributions retain their owner/distributor route. Remote browsers without package-install permission may read status but not change subscription. Older clients must get actionable failures for unrepresentable statuses, never false “up to date.” Verify these boundaries before announcing a public channel.
|
||||
|
||||
## Non-publishing preview preflight
|
||||
|
||||
**Verify Release Candidate** is manual, read-only preparation: no tags/releases, PyPI or catalogue writes. It builds/checks five platform wheels, sdist and licensed fallback archives. Cross-compilation is neither native execution nor release approval.
|
||||
|
||||
Default retention is small identity/manifest/probe reports and installation guide for **three days**, without installable binaries. `retain_installable` preserves those exact checked artifacts plus a self-contained shallow Git repository for **one day** (about 400 MB). Keep this storage exception off for routine preflight or schedules; assess storage and call it out explicitly in workflow-change PRs before merge. Preserve approved handoffs before expiry; rebuilding expired files cannot reuse their verification. The source contains only candidate/source-parent history, not configuration or untracked files. `handoff.json` is written only after copied artifacts verify; interruption is not an accepted handoff.
|
||||
|
||||
After assembly, the workflow installs the Linux x64 wheel and binary dependencies into a separate venv without Bun/Node/Git on the install PATH. Isolated Python checks version/commit/import identity, all Vite-manifest assets including lazy chunks through the installed handler, and bundled TUI `--desktop-protocol` with downloads disabled and empty private HOME. With `--gateway`, it starts a private foreground CLI gateway with no provider/MCP configuration, disabled heartbeat and two loopback ports, then checks readiness, protected version identity, HTML and process/listener cleanup. Unix shutdown must be graceful; Windows termination is labelled, not graceful-shutdown evidence. No model task or external channel is exercised.
|
||||
|
||||
On another supported platform, check a disposable native installation without changing its package:
|
||||
|
||||
```bash
|
||||
<installed-venv-python> -I scripts/verify_installed_release.py \
|
||||
--version <candidate-version> --commit <candidate-commit> \
|
||||
--gateway --report <new-report-path>
|
||||
```
|
||||
|
||||
Use the candidate commit, not its parent. The probe rejects checkout imports/unisolated invocation and avoids user configuration/credentials. Omit `--gateway` for assets/TUI only. Reports identify OS/CPU/probes and are success-only, never overwritten; failure cleans up children and prints a bounded redacted log tail. This is package/startup evidence, not interactive UI, managed restart, migration, public-download or five-platform E2E acceptance.
|
||||
|
||||
For local preparation, use a full source SHA and new output outside the checkout (illustrative base/sequence):
|
||||
|
||||
```bash
|
||||
python -m scripts.release_candidate prepare \
|
||||
--source-commit <full-commit-sha> --base 0.3.6 --sequence 42 \
|
||||
--output <new-candidate-directory>
|
||||
```
|
||||
|
||||
Preparation leaves the checkout untouched and deterministically creates a version-only commit for identical inputs. Build Python distributions and all native targets from it, then run from the candidate:
|
||||
|
||||
```bash
|
||||
python -m scripts.release_candidate assemble --source-commit <original-source-sha> \
|
||||
--wheel <intermediates>/nanobot_ai-0.3.6.dev42-py3-none-any.whl \
|
||||
--sdist <intermediates>/nanobot_ai-0.3.6.dev42.tar.gz \
|
||||
--tui-dir tui/dist --output <new-artifact-directory>
|
||||
```
|
||||
|
||||
Assembly refuses existing output and emits the manifest only after complete-set, version/commit, WebUI, RECORD, native/source and permissions checks. It compares sdist sources/resources against tracked candidate files with packaging exclusions, and all wheels' application/WebUI bytes against the sdist. Commit markers and RECORDs alone are insufficient; these comparisons do not prove reproducible frontend/native compilation. Recheck with `python -m scripts.release_candidate verify --source-commit <original-source-sha> --artifacts <artifact-directory>`; it may reuse an identical manifest, never replace different bytes.
|
||||
|
||||
Generate the handoff from the same candidate:
|
||||
|
||||
```bash
|
||||
python -m scripts.release_candidate instructions --source-commit <original-source-sha> \
|
||||
--artifacts <artifact-directory> --output <new-install-guide-path.md>
|
||||
```
|
||||
|
||||
The generator rechecks artifacts/manifest and writes a non-overwriting guide outside the immutable upload directory. When both installers match the supported implementation, commands fetch the exact candidate's installer with the retained manifest hash for automatic platform selection; older candidates keep manual commands, never mutable `main` or assumed flags. Publication must make pinned installer source reachable.
|
||||
|
||||
The guide records version, source/candidate commits, five hash-bound wheel URLs and separate new/existing base-package commands for uv, pipx and pip venv. Commands verify local size/SHA-256 with the standard library before manager invocation; URL hash fragments alone are insufficient for the tested uv commands. Retain wheel paths recorded by managers. Manual commands move to an advanced section when automatic entry is supported; no new manifest schema or installer executable is introduced.
|
||||
|
||||
Before offering the guide, publish/verify exact public files and add release changes, native coverage, migration/recovery instructions and stop/backup prerequisites. Review extras and locked/suffixed/external-owner options; independently verify installed version and restarted gateway. Manager fixtures do not prove restart/migration, and the guide is neither publication approval nor channel selection.
|
||||
|
||||
The candidate clone borrows source Git objects; preserve its source repository until retained in an approved permanent ref. Partial assembly has no accepted manifest and must not be uploaded. Source-offer commitment, native launch, clean install, upgrade/recovery and publication gates still apply. Missing public assets must be recovered from original verified files, never overwritten by rebuilds.
|
||||
|
||||
Retain an exact local handoff outside temporary build storage:
|
||||
|
||||
```bash
|
||||
python -m scripts.release_candidate retain --source-commit <original-source-sha> \
|
||||
--artifacts <verified-artifact-directory> --output <new-retained-directory>
|
||||
```
|
||||
|
||||
Only `artifacts/` is the upload set; `source.git/`, `install.md` and `handoff.json` are maintenance evidence, not PyPI packages. Restore with `git clone --no-local <retained>/source.git <new-checkout>`, check HEAD against `handoff.json`, and rerun `release_candidate verify` on retained artifacts before separately approved publication. Keep native reports and release notes alongside them; retention adds no native, migration, interactive UI or public-download evidence.
|
||||
@@ -102,13 +102,13 @@ If the installer finishes without opening the browser and `nanobot` is available
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
If the terminal cannot find `nanobot`, take the exact command printed by the installer and replace its final arguments with `webui`. That command may begin with `uv tool run`, `pipx run`, or the full path to nanobot's private Python environment.
|
||||
If the terminal cannot find `nanobot`, take the exact command printed by the installer and replace its final arguments with `webui`. It uses the Python executable from the persistent installation, not a temporary tool environment.
|
||||
|
||||
On SSH, a computer without a desktop, an existing configuration, or an older nanobot release, the installer may open the terminal wizard instead. Choose **Quick Start** there and follow its prompts.
|
||||
|
||||
## 5. Get the First Reply
|
||||
|
||||
Leave the WebUI terminal open. If the browser did not open automatically, copy the complete login link printed in that terminal, including everything after `#`, into your browser. The bare `http://127.0.0.1:8765` address does not sign a new browser in. Keep the login link private: it contains a credential.
|
||||
Wait for the startup summary. If the browser did not open automatically, copy the complete login link printed in that terminal, including everything after `#`, into your browser. The bare `http://127.0.0.1:8765` address does not sign a new browser in. Keep the login link private: it contains a credential. Fresh official-installer environments keep running in the background; if the launcher remains attached, leave that terminal open.
|
||||
|
||||
Send this message:
|
||||
|
||||
@@ -137,7 +137,7 @@ You can also follow the steps yourself using the controls and guides below. Add
|
||||
|
||||
Repository docs show the current development version. If your stable package does not yet show **Channels**, use the [Chat Apps guide](./chat-apps.md) or update to a release that includes it.
|
||||
|
||||
Some runtime changes ask you to restart nanobot. Use the restart action shown by the WebUI, or return to the terminal, press `Ctrl+C`, and run `nanobot webui` again.
|
||||
Some runtime changes ask you to restart nanobot. Use the restart action shown by the WebUI or `nanobot gateway restart` for a background gateway. For an attached on-demand launcher, press `Ctrl+C` and run `nanobot webui` again.
|
||||
|
||||
For a chat platform's account, bot, token, or permission prerequisites, use the [Chat Apps guide](./chat-apps.md). For local models and provider-specific recipes, use the [Provider Cookbook](./provider-cookbook.md).
|
||||
|
||||
@@ -166,7 +166,7 @@ nanobot agent -m "Hello!"
|
||||
| `nanobot: command not found` | Reuse the exact nanobot command printed by the installer; it points to the isolated environment that contains the package |
|
||||
| `401`, unauthorized, or invalid API key | The key is wrong, expired, or belongs to a different provider |
|
||||
| Model not found | The model ID is misspelled or unavailable to your provider account |
|
||||
| Browser does not open | Copy the complete login link printed by the launcher, including the fragment after `#`, and keep the terminal running |
|
||||
| Browser does not open | Copy the complete login link printed by the launcher, including the fragment after `#`; keep the terminal open if the launcher is attached |
|
||||
| Browser opens but messages fail | Test `nanobot agent -m "Hello!"` to separate a model problem from a WebUI problem |
|
||||
| A change was saved but nothing changed | Restart nanobot so the running process reloads the config |
|
||||
|
||||
@@ -182,4 +182,4 @@ Run:
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
Leave that launcher open while you use nanobot. Pressing `Ctrl+C` disconnects it; the shared gateway stops when it was the last local WebUI or TUI client. After the normal foreground start and model setup work, use `nanobot gateway --background` when you want the gateway to stay online with no clients; then manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`.
|
||||
A fresh official-installer environment starts a background gateway and returns control to the terminal. Closing the browser does not stop it. Manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`; use the exact commands printed for your instance. Other installation methods keep their attached on-demand launch: leave that launcher open, or explicitly use `nanobot webui --detach` after setup. The last attached client stops an on-demand gateway, not a background gateway. See [updates and recovery](./updating.md) for the matching installation method.
|
||||
@@ -0,0 +1,88 @@
|
||||
# Update protocol
|
||||
|
||||
This document is for gateway, client and updater maintainers. For installation choices, WebUI steps and recovery commands, see the [user update guide](updating.md). Release approval, catalogue and artifact schemas belong to the [release contract](releasing.md).
|
||||
|
||||
## Ownership and approval boundaries
|
||||
|
||||
The gateway owns policy, installation inspection and durable update state; clients present reviews and explicit consent. Reviewing a release, preparing files, approving shutdown, admitting package mutation and activating a gateway are separate decisions. None can be inferred from another's progress, a lost response or elapsed time.
|
||||
|
||||
An [immutable plan](../nanobot/update_plan.py) binds an exact release artifact to the interpreter/environment snapshot, ownership receipts, extras, channel revision and known gateway profiles. Its lifetime is at most fifteen minutes. Preparation and shutdown preflight revalidate that target, never substitute a new latest version. Changed environment metadata, ownership, profiles, channel revision, expiry or release eligibility blocks progress. Planning and preflight share the installation's `releases` history: catalogue rollback or changed contents under the same generation must not become acceptable through a fresh per-job cache. A network failure is not a fresh successful check. See [release discovery](../nanobot/release_feed.py) and the [release contract](releasing.md) for approval and download rules.
|
||||
|
||||
[Manager policy](../nanobot/update_manager.py) comes from the owner's receipt, not dependency-based guesses. Its hash binds the complete private settings; the review uses a credential-free summary of extras, constraints, source, pins/locks and additional package names. An absent `owner_restriction` is not execution eligibility. Supported pipx receipt schemas are `0.5` and `0.12`; reading them does not enable pipx execution or newer manager flags. The native uv transaction is limited to compatible POSIX uv `0.11.16` registry tools and preserves receipt policy. Unfrozen external resolver policy requires the owner's workflow. A plain-venv transaction requires explicit extras, including `[]` for the base package; installer- or manager-recorded extras cannot be replaced by a client.
|
||||
|
||||
## Client interface
|
||||
|
||||
Capabilities are optional additions to the [WebUI contract](../nanobot/webui/client_contract.py), not package-version comparisons or a higher protocol floor. Action names below have the prefix `settings.nanobot.update.`; read paths have the prefix `/api/settings/nanobot-update/`.
|
||||
|
||||
| Capability | Interface |
|
||||
| --- | --- |
|
||||
| `webui.update-plans.v1` | `plan`; `GET plan?id=<id>` |
|
||||
| `webui.update-jobs.read.v1` | `GET job?id=<id>` |
|
||||
| `webui.update-jobs.prepare.v1` | `prepare`, `settle` for interrupted preparation |
|
||||
| `webui.update-jobs.execute.v1` | `execute` |
|
||||
| `webui.update-jobs.retry-handoff.v1` | `retry` |
|
||||
| `webui.update-jobs.settle-handoff.v1` | `settle` also retires inactive, uncommitted handoffs |
|
||||
| `webui.update-channels.v1` | `channel` with the saved revision |
|
||||
| `webui.update-flow.v1` | Client flow using review, preparation, execution and reconnection |
|
||||
|
||||
All routes require authentication. Actions require an authenticated WebSocket; plain HTTP cannot create plans or mutate jobs. Preparation, settlement, execution, retry and channel changes also require the existing local-browser or explicit remote package-install permission and runtime admission checks. Review does not require installation permission. Desktop's native surface retains its distributor's updater. [Transport routing](../nanobot/webui/settings_routes.py) and the [settings handler](../nanobot/webui/settings_system.py) own these checks; update responses are `no-store`.
|
||||
|
||||
`plan` accepts only `channel`, `restart_running` (default `false`) and optional `extras`. The default channel is the installation preference, or Stable when absent. It cannot accept a download URL, command, environment path or caller-supplied plan. `restart_running=true` selects known running background gateways with explicit lifetime and cooperative shutdown support, not stopped profiles or unknown supervisors. Inline eligibility requires the requesting gateway and every running peer in the reviewed stop/restart selection, with no unconfirmed owner.
|
||||
|
||||
The review separates `installation_allowed` (caller policy) from `execution_available` and `execution_blocked_reason` (exact-plan eligibility). Neither authorizes execution. `validity` is a local snapshot result: `current`, `expired`, `installation_changed`, `profiles_changed` or `channel_changed`. Reading a saved review can inspect the current installation and profiles, but does not contact the release feed or choose another target.
|
||||
|
||||
Job actions use `id`; execution additionally requires `confirm_restart: true`, and retry requires `previous_confirmation_id`. A job read returns durable facts including `recorded_phase`, `attempt`, `mutation_started`, `updated_at` and `execution_confirmation_id`, not worker liveness or permission to retry. Missing jobs return 404, invalid identifiers 400, and corrupt or misbound records 409. Reads do not start the installation's Python, contact release services or take its runtime lease; an active writer or incomplete-install marker does not hide history. Environment-path scoping can retain history after a reinstall, but does not authorize resuming the predecessor's job. Raw logs, resolver credentials and diagnostic messages are not exposed. Recovery flags distinguish automatic recovery selection, supervisor ownership and restored service. A returned recovery command is display-only.
|
||||
|
||||
[Record publication](../nanobot/utils/atomic_file.py) is atomic, never delete-then-copy. Windows snapshot readers share deletion so polling can coexist with POSIX-style replacement on supported filesystems. Sharing and permission failures remain errors, not permission to publish partial records.
|
||||
|
||||
Channel changes use revision checks, invalidate old reviews and retire only safely settled inactive jobs. They never install, downgrade or discard active work. Consumers recover lost preparation/execution responses by reading the same job; a missing journal or transport timeout alone is not authority to submit a replacement operation.
|
||||
|
||||
## Preparation leases and settlement
|
||||
|
||||
[Preparation](../nanobot/update_jobs.py) saves the immutable plan and a preparation journal before native inspection or resolution. It compares fresh environment metadata before and after staging, verifies the exact nanobot wheel and stages the resolved dependency transaction without changing installed files. Pip preparation retains its configured package-source trust policy; credential-bearing resolver files remain private and temporary. There is no source-build or global-manager fallback. For uv, a sealed private preparation cache and recorded dependency versions bind the offline transaction without rewriting the shared cache or saved policy.
|
||||
|
||||
The frozen worker and helpers are standard-library-only and stored outside the installation. [Preparation children](../nanobot/update_process.py) start with `-I -S`, acquire their own runtime and native-preparation leases, validate the preparation generation, then initialize the target's site. Those leases cover `.pth`/site hooks, the actual probe or pip command and `atexit` cleanup, even if the parent disappears. Python commands run in the lease-owning process on POSIX and Windows. Native uv uses POSIX `exec` with retained descriptors; inherited handles do not transfer Windows byte-range lock ownership. Failed `exec` restores descriptor inheritance flags. These leases do not contain arbitrary descendants spawned by custom hooks.
|
||||
|
||||
Cancellation does not release preparation ownership until native work actually returns. An orphan native child blocks another preparation and coordinated shutdown. A `preparing` record alone proves neither liveness nor completion. Settlement requires both parent and native preparation leases, revokes that generation and records `preparation_failed`; it neither deletes staging nor starts an install. Late children from the revoked generation cannot run. Older parent-only lease records cannot establish this proof. Retrying preparation must retain the same immutable plan; changed consent needs a new ID.
|
||||
|
||||
The immutable `request.json`, written after inputs and initial status are flushed, is the preparation commit record. A `ready` journal alone is insufficient. Preparation grants no package-mutation authority.
|
||||
|
||||
## Confirmation generations and offline execution
|
||||
|
||||
The [job service](../nanobot/update_service.py) persists execution confirmation before launching a detached owner. Each confirmation may claim the operation once. Replaying execute, repeating a retry or presenting a stale predecessor returns history, not another attempt. Explicit retry replaces exactly `previous_confirmation_id` while worker and preflight leases are free; delayed launchers with the replaced confirmation cannot start. The original target, artifacts, plan expiry, release checks and selected runtime identities still apply. Retry cannot extend the review or repair mutation.
|
||||
|
||||
Confirmation identity and expiry are separate checks. Launch consent is short-lived and bound to the immutable request. Under its lease, the supervisor validates that identity before publishing even its first journal or launching work. Completion and bounded recovery, including restoration, retain the same identity without reapplying the launch-window expiry. Fresh local repair can renew approval only for an already admitted exact job, not prepared files alone; it rechecks inputs and environment, preserves and verifies the original backup once created, and never resolves or downloads a release.
|
||||
|
||||
The [offline worker](../nanobot/update_worker.py) uses the base Python with `-I -S`. Its actual installer child owns exclusive installation/data leases before target site initialization and rechecks ownership, environment, inputs and approval before mutation. Pip's CLI runs in that same single-use Python process on both POSIX and Windows, retaining locks through exit cleanup. It accepts only staged wheels with network resolution, builds and destination/configuration overrides disabled. Native uv retains its leases through POSIX `exec` and applies the sealed transaction offline.
|
||||
|
||||
A pending-install fence and data reservation survive interrupted mutation. Repair cannot overwrite unrelated package changes or a different target installed by another updater. Restart-phase recovery retries restart, not installation. Installed-package verification uses a separately lease-owning child and a completion checkpoint: the target must import from the correct environment, application files including bundled assets must match the wheel, and dependency checks must pass. Without restart participants the result is `installed`, not a verified running gateway.
|
||||
|
||||
## Shutdown and maintenance
|
||||
|
||||
[Installation leases](../nanobot/installation_lock.py) are account-scoped by the real environment path, independent of profile home and symlink aliases. Cooperating runtimes hold shared OS locks; mutation needs exclusive access. Lock files must never be removed or replaced: a PID file is not ownership. Ordinary startup refuses an active updater or pending-install fence. These leases do not discover older runtimes, arbitrary imports, other accounts or external supervisors.
|
||||
|
||||
The detached owner's [old-runtime preflight](../nanobot/update_handoff.py) owns a shared lease before application imports, revalidates the exact release using shared release history, closes the release client and requests [cooperative shutdown](../nanobot/update_stop.py). Every selected gateway must hold its idle admission gate before any stop is committed. Refusal before commit reopens intake; a durable commit is irrevocable and is not undone by a later failure. The owner waits for actual gateway and preflight process exit, not inactive receipts, before acquiring exclusive installation/data leases and admitting installation. Shutdown consent alone is not mutation approval.
|
||||
|
||||
[Runtime admission](../nanobot/runtime_admission.py) accounts for accepted and detached work through cleanup without cancelling active tasks. Channel setup and provider sign-in owners must stay busy until native workers, callbacks and cleanup actually exit; cancelling an awaiter, expiring a flow or returning a QR/browser response does not establish idle. Failed cleanup retains ownership for retry. See the [connector lifecycle](../nanobot/channels/connect.py) and [sign-in registry](../nanobot/webui/settings_services.py). A loaded connector without that lifecycle cannot claim coordinated-update idleness.
|
||||
|
||||
Handoff settlement requires free worker, preflight and stop-coordinator leases and refuses committed shutdown, installation admission or mutation. It records `cancelled` without deleting saved files or launching work; repeated settlement is safe. An uncertain response is resolved by reading the old job.
|
||||
|
||||
## Data protection and protected restart
|
||||
|
||||
[Profile receipts](../nanobot/update_profiles.py) preserve known stopped profiles for backup and retain original launch selectors, paths and process/run identities, not configuration contents or arbitrary environment variables. A PID alone is not liveness. A new run, changed inventory or unconfirmed owner invalidates review; inventory does not authorize stopping a supervisor or starting a previously stopped profile.
|
||||
|
||||
[Data leases](../nanobot/data_access.py) protect overlapping named stores even across cooperating Python installations. Reservations bind the exact job and scope across crashes. [Backups](../nanobot/update_backup.py) cover recorded nanobot stores and required receipts, not entire homes, arbitrary projects or external services. Redirected paths, symlinks/reparse points, special files, changing data or insufficient space block backup. The original backup is verified and retained across retries, never replaced by post-mutation data. Automatic data rollback is unavailable.
|
||||
|
||||
[Protected restart](../nanobot/update_restart.py) launches only reviewed participants through lease-owning frozen entrypoints using their saved selectors. A startup grant permits initialization of one participant's exact reserved data scope, not agent/tool/scheduler work or broader paths; its bearer is removed before normal runtime configuration. Grants cannot expand an older updater's reservation. For protocol-1 grants predating the lazy delivery store, that store takes an ordinary lease and cannot initialize, migrate or write before activation.
|
||||
|
||||
Gateways remain in maintenance until their actual run identities, target versions and readiness are verified. Durable activation names those exact runs; a generic HTTP success or receipt is insufficient. Verification after intake opens precedes fence/reservation cleanup and `succeeded`. A crash during finalization resumes cleanup only, not reinstall or activation. Clients additionally require authenticated reconnection to the target-running gateway before reporting update completion.
|
||||
|
||||
The optional macOS Dock helper belongs to the gateway, starts only after activation and exits when its owner stops. It holds no installation/data lease and is not loaded by the frozen updater or recovery supervisor. Its instance-scoped visibility intent survives reviewed restart/recovery; the helper does not own update execution or completion.
|
||||
|
||||
## Recovery and compatibility limits
|
||||
|
||||
For installer-owned dedicated venvs with selected background participants, [automatic recovery](../nanobot/update_fallback.py) preserves a verified sibling program/dependency snapshot before mutation. An independent supervisor can try the already admitted exact target once, then restore only the original program before candidate activation and only if protected user-file contents still match the original backup. Backup failure before mutation can restart the intact original program. Restoration uses journaled same-filesystem renames, retains the failed generation and replays one transient filesystem failure; duplicate launches do not gain another recovery budget.
|
||||
|
||||
Restored service is not update success: the wire result remains `failed` for older clients and adds `service_restored`. Successful upgrades may remove their redundant program snapshot but retain the data backup. Changed data or durable activation forbids older-program restoration; only same-target completion remains safe. Corrupt snapshots, changed ownership, persistent filesystem faults, missing base Python or loss of both supervisor and worker can require operator recovery. This is neither malware remediation nor an OS boot-time recovery service.
|
||||
|
||||
Compatibility is explicit, not inferred from versions. Protocol 1 covers worker request schema 4, frozen `-I -S` startup with child-owned installation leases, scoped data-startup grants and activation bound to the exact restarted run. The target must declare a supported protected-handoff contract; see [release compatibility](releasing.md#protected-updater-handoff-compatibility) for its schema and publication requirements. External managers, unsupported layouts and older jobs are not silently adopted. Hosts without settlement/retry capabilities retain their existing status/recovery route rather than accepting unsupported actions. The [standalone launcher](../nanobot/update_recovery.py) uses the saved worker and original base Python independently of a broken application environment; user commands and operational limits remain in the [update guide](updating.md).
|
||||
@@ -0,0 +1,109 @@
|
||||
# Updating nanobot
|
||||
|
||||
Use the update method that owns your installation. If your version does not include the WebUI updater, first upgrade through the original installer or package manager. This does not convert an existing installation into an installer-managed one.
|
||||
|
||||
## Update from the WebUI
|
||||
|
||||
1. Open the blue update entry in the sidebar or **Settings → About → Update**. Opening the dialog only checks the installation; it does not install or restart anything.
|
||||
2. Review the exact version and affected gateways. Active work must finish before shutdown. Gateways that were already stopped are not started by the update.
|
||||
3. Choose **Update & restart**. nanobot downloads and verifies the required files, backs up affected profiles, installs the update, and restarts the selected background gateways—not your computer or browser.
|
||||
4. Wait for **Update complete**, which requires a reconnected gateway running the target version. Choose **Done** to reload the updated interface. If you hide the dialog, reopen it through **Settings → About → View details**.
|
||||
|
||||
Inline updates support fresh official-installer environments and compatible POSIX uv 0.11.16 registry tool installations running a background gateway. Other installations show their own update instructions in the dialog; see [Installation owners](#installation-owners). Remote browsers need the gateway's explicit package-install permission.
|
||||
|
||||
On a local macOS desktop, the background WebUI's Dock icon stays available after closing the terminal and disappears when the gateway stops. A restarted or restored gateway recreates it after activation; it may disappear during package replacement and is not an update progress indicator. `--no-dock` remembers your choice for that instance. See the [Dock controls](webui.md#macos-dock-icon).
|
||||
|
||||
Automatic installation requires official release approval and verified package checksums for both Stable and Preview. If verification fails, keep using the current version, retry later, and report persistent errors to a maintainer. Do not disable verification or install a replacement file from an error message. Verification confirms release approval; it is not a guarantee that all application or dependency code is harmless.
|
||||
|
||||
## Stable and Preview
|
||||
|
||||
**Settings → About → Receive preview updates** is off by default. Enable it to try new features earlier, with a higher risk of bugs. The preference applies to this installation, not just the browser; changing it requires the same local or remote permission as installing packages. It never downloads, installs, or restarts on its own.
|
||||
|
||||
Turn it off to receive only stable updates. If your Preview is newer than the latest stable release, nanobot keeps it until a newer stable release is available; it does not downgrade or restore old data. Installing a final release while Preview is enabled keeps Preview enabled for the next development cycle. You can skip intermediate previews.
|
||||
|
||||
Stable fixes can arrive between feature releases. Preview availability depends on verified publication, not a promise of daily updates. Package-manager commands outside nanobot do not read this preference; choose their version or channel explicitly.
|
||||
|
||||
## Installation owners
|
||||
|
||||
When inline installation is unavailable, the update dialog identifies the installation method and guides you through its update. Run copied commands **on the gateway computer, as the original installation account**. For containers, use the deployment host rather than treating a container path as a host path.
|
||||
|
||||
| Installation | Update route |
|
||||
| --- | --- |
|
||||
| Fresh official installer | Use WebUI **Update & restart** for a compatible release. Existing unrecorded environments are not automatically adopted. |
|
||||
| uv registry tool | Use the supported inline flow above, or `uv tool upgrade nanobot-ai` in its original environment. Keep recorded extras, constraints and additional packages; a pin needs an explicitly reviewed new constraint. |
|
||||
| pipx | Use `pipx upgrade nanobot-ai` only for an unconstrained registry install without recorded pip options. Otherwise preserve the original requirement, index/options, suffix and injected packages through the owner's workflow. |
|
||||
| Ordinary pip venv | Use that environment's Python with `-m pip install --upgrade 'nanobot-ai[<your existing extras>]'`; omit brackets for the base package. Do not guess optional extras. |
|
||||
| Source checkout | Preserve local changes, update the selected ref and environment, and follow the [development instructions](../CONTRIBUTING.md). Source is not the Preview release channel. |
|
||||
| Docker / Compose | Pull or build the selected image and recreate the service with its existing data volumes. Do not pip-install into a running container. |
|
||||
| OS package, service manager or Desktop | Use the distributor or deployment's updater and launcher. |
|
||||
|
||||
For an external update, stop all affected writers, back up configuration and data, update through the original installation method, then restart the same profiles through their original launcher. New versions may migrate stored data. Verify the **running** version in **About** and check that configuration and conversations remain available. Package-manager success alone does not verify the gateway, and manual updates do not inherit the managed updater's automatic recovery.
|
||||
|
||||
Do not switch package managers to work around an error. Fixed wheel sources, locked requirements and custom installations need their original settings reviewed. If a fresh official installation fails, fix the reported prerequisite or network error and rerun the same installer command.
|
||||
|
||||
## Recover an interrupted update
|
||||
|
||||
Refreshing restores saved progress, **not installation consent**. A staged update may ask you to review and confirm it again. A disconnected page cannot tell whether the worker stopped: do not start another installation while it reconnects. Closing the browser does not stop the managed update or its recovery.
|
||||
|
||||
**Check again** only reads saved status. **Review update** asks the gateway to settle an interrupted preparation or failed handoff before opening a fresh review. Settlement is refused while an owner is active or the operation has progressed too far to discard safely. It does not prepare or install another update; that requires a separate **Update & restart** confirmation.
|
||||
|
||||
If settlement is refused or its response is lost, the saved job remains available for status checks and recovery. A timeout or missing response is not permission to create a second update. After package changes have begun, use recovery rather than trying another installation.
|
||||
|
||||
## Automatic service recovery
|
||||
|
||||
For installer-owned dedicated environments with supported background gateways, the update confirmation also authorizes bounded recovery of that exact operation. nanobot retains a separate copy of the original program and dependencies before changing packages; insufficient space aborts installation.
|
||||
|
||||
If installation fails, recovery tries the already approved target once using saved files. If that also fails before the new gateway is activated, it can restore the original program and restart the reviewed gateways **only if protected user data is unchanged**. The dialog reports **Previous version restored**, not update success. A restored service needs a fresh review before another update.
|
||||
|
||||
Recovery never replaces current configuration or conversations with an old backup. Changed user data, missing or corrupt saved files, changed installation ownership, persistent disk errors, a missing base Python, or loss of both recovery processes can require operator help. Keep the saved job and backup; do not delete recovery markers or install over them. This is not recovery after every power loss or a guarantee against malicious code. Other installation methods retain their original recovery route.
|
||||
|
||||
## Standalone recovery
|
||||
|
||||
When automatic recovery is unavailable or reports failure, the WebUI can show a repair command containing the saved job ID and exact Python and launcher paths. Copy that command and run it **on the gateway computer, as the original OS user**. It does not require a working nanobot environment, but it does need the original base Python.
|
||||
|
||||
The following examples assume the gateway uses your terminal's normal home directory and a Python 3.11+ command. Prefer the exact paths shown by the WebUI when they differ.
|
||||
|
||||
macOS / Linux:
|
||||
|
||||
```sh
|
||||
python3 -I -S ~/.nanobot/updates/recover.py <job-id>
|
||||
python3 -I -S ~/.nanobot/updates/recover.py <job-id> --repair
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
python -I -S "$env:USERPROFILE\.nanobot\updates\recover.py" <job-id>
|
||||
python -I -S "$env:USERPROFILE\.nanobot\updates\recover.py" <job-id> --repair
|
||||
```
|
||||
|
||||
The first command only inspects the job. `--repair` shows its saved version, environment and backup, then asks for confirmation; `--yes` skips that prompt only when used with `--repair`. Repair reuses the same verified files without downloading another release. If installation finished but restart failed, it retries restart rather than reinstalling packages. Merely preparing files does not make a job eligible for repair.
|
||||
|
||||
Keep the original job directory and backup until recovery is verified. Missing or changed files and an independently modified environment require operator repair. Do not restore backups over live data. Downgrading and restoring user data are separate, owner-managed operations.
|
||||
|
||||
## Review an exact release
|
||||
|
||||
```bash
|
||||
nanobot update --plan
|
||||
nanobot update --plan --channel preview
|
||||
```
|
||||
|
||||
These commands save a plan showing the installation method, installed and running versions, exact target, download details and expected action. They may write plan and metadata-cache files, but do not install, stop tasks or restart gateways. `--channel` is a one-time inspection; it does not change your saved subscription.
|
||||
|
||||
Plans expire after fifteen minutes. Execution rechecks the reviewed release and refuses changed installations, withdrawn releases or changed artifacts. A plan is not installation permission. The separate `nanobot update`, `--check` and `--dev` commands do not execute saved plans; see the [CLI reference](cli-reference.md#updating).
|
||||
|
||||
## Explicit recovery before package mutation
|
||||
|
||||
If shutdown failed **before package changes began** and the application environment is still intact, you can inspect the saved job and explicitly retry its reviewed operation:
|
||||
|
||||
```bash
|
||||
nanobot update --job <plan-id>
|
||||
nanobot update --job <plan-id> --retry-handoff \
|
||||
--previous-confirmation <execution-confirmation-id> --confirm-restart
|
||||
```
|
||||
|
||||
Read the saved facts and original plan before running the second command: it approves shutdown, installation and restart, not just a connection check. The same plan must still be valid, and live owners prevent retry. An accepted request is not proof of completion; check the saved result and running gateway.
|
||||
|
||||
These commands cannot repair a broken installation or packages already changed by an interrupted update. Use [standalone recovery](#standalone-recovery) instead.
|
||||
|
||||
For contributor-facing APIs, ownership and execution rules, see [Update protocol](update-protocol.md). Maintainers should use the [release checklist](releasing.md).
|
||||
+14
-4
@@ -16,17 +16,17 @@ Use the launcher:
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
`nanobot webui` asks for one confirmation on a new installation, creates the config/workspace, enables the local WebSocket channel, and generates a WebUI bootstrap secret when one is missing. It starts or joins the same on-demand gateway used by the native TUI and opens the browser. With a fresh config, it can open before a model is configured so you can finish setup in **Settings → Models**. The first-run path binds the WebUI to `127.0.0.1` by default, so it is not available from other devices on your LAN. The startup summary groups the login link, model setup guidance, config, and exit controls with blank lines. While attached, the launcher displays new gateway warnings and errors; use the printed logs command for full output.
|
||||
`nanobot webui` asks for one confirmation on a new installation, creates the config/workspace, enables the local WebSocket channel, and generates a WebUI bootstrap secret when one is missing. It starts or joins the same gateway used by the native TUI and opens the browser. Fresh official-installer environments start it persistently and return control to the terminal; other installations keep the attached on-demand launch. With a fresh config, it can open before a model is configured so you can finish setup in **Settings → Models**. The first-run path binds the WebUI to `127.0.0.1` by default, so it is not available from other devices on your LAN. The startup summary groups the login link, model setup guidance, config, and exit controls with blank lines. While attached, the launcher displays new gateway warnings and errors; use the printed logs command for full output.
|
||||
|
||||
After model setup, explicitly promote the shared gateway when you do not want to keep a client open:
|
||||
Outside an installer-managed environment, use `nanobot webui --detach` to open the browser and keep the gateway running after the terminal closes. Alternatively, start or promote the same shared gateway explicitly:
|
||||
|
||||
```bash
|
||||
nanobot gateway --background
|
||||
```
|
||||
|
||||
`nanobot webui --background` is retained only to print migration guidance. This keeps one unambiguous owner for persistent process lifecycle.
|
||||
`nanobot webui --background` remains deprecated and prints migration guidance. All launch routes use the same gateway lifecycle owner and state.
|
||||
|
||||
Each foreground WebUI or TUI launcher releases only its own client. The last interactive launcher stops an on-demand gateway. `nanobot gateway --background` makes the gateway persistent; manage it with `nanobot gateway status`, `nanobot gateway logs`, `nanobot gateway restart`, and `nanobot gateway stop`.
|
||||
Each foreground WebUI or TUI launcher releases only its own client. The last interactive launcher stops an on-demand gateway, but not a persistent one. Manage the persistent gateway with `nanobot gateway status`, `nanobot gateway logs`, `nanobot gateway restart`, and `nanobot gateway stop`. Use the printed instance-specific commands when you selected a custom config or workspace. `--detach --dev` is unsupported; development remains attached.
|
||||
|
||||
The browser signs in automatically using the generated credential in the launch URL. The terminal also prints the complete login link: if automatic opening fails, copy that link into your browser, including the fragment after `#`. In WSL, the launcher opens your Windows default browser through Windows PowerShell; an explicit `BROWSER` setting takes precedence. If Windows integration is unavailable, open the printed link in your Windows browser. The plain page address does not sign in a new browser. Treat the login link as a credential and do not share it.
|
||||
|
||||
@@ -56,6 +56,16 @@ Manual config still works. Same-machine localhost WebUI access can run without a
|
||||
|
||||
The WebUI is served by the WebSocket channel on port `8765` by default. The gateway health endpoint, `18790` by default, is not the browser UI.
|
||||
|
||||
### macOS Dock icon
|
||||
|
||||
In a local macOS desktop session, `nanobot webui` shows the nanobot cat in the Dock. Click it to open the current local WebUI in your default browser. `--no-open` keeps the icon but does not open a page automatically. SSH, headless, Windows and Linux launches keep their existing behavior. A one-shot connection to an unmanaged gateway does not leave an icon behind.
|
||||
|
||||
Ordinary foreground launchers for the same instance, browser address and installation share an icon. The last WebUI launcher removes it when it exits, including after a terminal crash. For `--detach` and official-installer automatic background launch, the gateway owns the icon instead: closing the terminal does not remove it. An ordinary restart, successful update or supported automatic restoration shows it again once that gateway is activated. The icon can disappear while the service is stopped for an update; it is not an update-progress indicator. `nanobot gateway stop` removes it without changing configuration or chats.
|
||||
|
||||
Use `--no-dock` to disable the icon for a launcher. In detached mode this also remembers the choice for that instance's later restarts; running `nanobot webui` without it enables the background icon again. The request is stored beside the runtime state as a small `.dock` file, without a URL or credentials. Choosing **Hide Dock Icon** or quitting the icon hides only this shortcut, not the gateway or its tasks. It stays hidden until another explicit launch or service restart. The icon is not a standalone launcher to keep pinned when nanobot is stopped.
|
||||
|
||||
The helper uses the installed Python and macOS frameworks, with no Xcode, extra Python dependency, executable download or separate updater. Its temporary application wrapper is private to the OS user. The login URL stays in memory and a private socket, never in process arguments or a file. The helper holds no installation or data lease, and protected restart does not start it until activation. A missing image or unavailable desktop does not prevent WebUI startup, updates or independent recovery. Non-loopback browser addresses continue to use the normal browser launcher.
|
||||
|
||||
## Navigate a long conversation
|
||||
|
||||
On wide screens, use the message rail on the left to browse saved prompts; click one to jump to it. You can also search prompt summaries from the header. The WebUI loads messages near the selected prompt rather than the entire conversation. Scroll backward or forward to browse, or use the bottom arrow to return to the latest messages. If loading fails, your current content stays visible and you can retry. Older compatible hosts may only support navigation among messages that are already loaded.
|
||||
|
||||
+2
-2
@@ -15,8 +15,8 @@ WebUI behavior:
|
||||
- Skips when `NANOBOT_SKIP_WEBUI_BUILD=1` is set.
|
||||
- Reuses `nanobot/web/dist/` only when it is already fresh, unless
|
||||
`NANOBOT_FORCE_WEBUI_BUILD=1` is set.
|
||||
- Uses `bun` when available, otherwise falls back to `npm`. The chosen tool
|
||||
performs `install` followed by `run build`.
|
||||
- Uses `bun` when available, otherwise falls back to `npm`, or provisions Bun
|
||||
when neither is available. Bun builds use `--bun` so Node is not required.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
+101
-68
@@ -65,6 +65,7 @@ from nanobot.events import NO_EVENTS, AgentEvent, EventSink
|
||||
from nanobot.llm_usage.context import source_from_request
|
||||
from nanobot.providers.base import LLMProvider, LLMUsage, ProviderConversationState
|
||||
from nanobot.providers.factory import ProviderSnapshot
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.runtime_context import (
|
||||
RUNTIME_CONTEXT_HISTORY_META,
|
||||
RUNTIME_CONTEXT_MESSAGE_META,
|
||||
@@ -970,13 +971,14 @@ class AgentLoop:
|
||||
|
||||
async def discard_session(self, key: str) -> None:
|
||||
"""Stop active work for *key* and forget its cached session."""
|
||||
self._discarding_sessions.add(key)
|
||||
try:
|
||||
await self.sessions.state.discard(key)
|
||||
await self._cancel_active_tasks(key)
|
||||
finally:
|
||||
self.discard_session_file_state(key)
|
||||
self._discarding_sessions.discard(key)
|
||||
with self.bus.admission.activity():
|
||||
self._discarding_sessions.add(key)
|
||||
try:
|
||||
await self.sessions.state.discard(key)
|
||||
await self._cancel_active_tasks(key)
|
||||
finally:
|
||||
self.discard_session_file_state(key)
|
||||
self._discarding_sessions.discard(key)
|
||||
|
||||
def discard_session_file_state(self, key: str) -> None:
|
||||
"""Forget ephemeral file-read state for a reset or removed session."""
|
||||
@@ -1393,16 +1395,19 @@ class AgentLoop:
|
||||
|
||||
async def _check_expired_sessions_if_due(self) -> None:
|
||||
"""Scan idle sessions without blocking the event loop."""
|
||||
if self.bus.admission.paused:
|
||||
return
|
||||
now = time.monotonic()
|
||||
if now < self._next_idle_compact_check_at:
|
||||
return
|
||||
self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s
|
||||
try:
|
||||
await self.auto_compact.check_expired(
|
||||
self.schedule_background,
|
||||
self.runtime_for_session,
|
||||
active_session_keys=self._pending_queues.keys(),
|
||||
)
|
||||
with self.bus.admission.activity():
|
||||
await self.auto_compact.check_expired(
|
||||
self.schedule_background,
|
||||
self.runtime_for_session,
|
||||
active_session_keys=self._pending_queues.keys(),
|
||||
)
|
||||
except SessionOperationQueueFullError:
|
||||
logger.debug("Skipping idle archival while session storage is busy")
|
||||
|
||||
@@ -1414,7 +1419,10 @@ class AgentLoop:
|
||||
|
||||
while self._running:
|
||||
try:
|
||||
msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)
|
||||
# Keep dequeue and admission in this task. wait_for would
|
||||
# dequeue in another task, leaving a false-idle handoff gap.
|
||||
async with asyncio.timeout(1.0):
|
||||
msg = await self.bus.consume_inbound()
|
||||
except asyncio.TimeoutError:
|
||||
await self._check_expired_sessions_if_due()
|
||||
continue
|
||||
@@ -1431,14 +1439,15 @@ class AgentLoop:
|
||||
logger.warning("Error consuming inbound message: {}, continuing...", e)
|
||||
continue
|
||||
|
||||
try:
|
||||
await self._dispatch_inbound(msg)
|
||||
except (SessionOperationQueueFullError, SessionConflictError) as exc:
|
||||
key = self._effective_session_key(msg)
|
||||
logger.warning("Session input rejected for {}: {}", key, exc)
|
||||
if msg.is_user_input:
|
||||
delivery = self.turn_delivery_factory.unrouted(msg, key)
|
||||
await delivery.fail(publish_completion=key not in self._pending_queues)
|
||||
with self.bus.admission.activity():
|
||||
try:
|
||||
await self._dispatch_inbound(msg)
|
||||
except (SessionOperationQueueFullError, SessionConflictError) as exc:
|
||||
key = self._effective_session_key(msg)
|
||||
logger.warning("Session input rejected for {}: {}", key, exc)
|
||||
if msg.is_user_input:
|
||||
delivery = self.turn_delivery_factory.unrouted(msg, key)
|
||||
await delivery.fail(publish_completion=key not in self._pending_queues)
|
||||
finally:
|
||||
await self.aclose()
|
||||
|
||||
@@ -1491,6 +1500,23 @@ class AgentLoop:
|
||||
return
|
||||
await self._enqueue_session_message(routed_msg)
|
||||
|
||||
def maintenance(self) -> AbstractContextManager[None]:
|
||||
"""Close task intake only when this runtime's accepted work is finished.
|
||||
|
||||
The gateway shares the bus gate with cron and local trigger intake.
|
||||
This does not stop other processes or channel/configuration writes;
|
||||
those must be shut down before an updater takes a data backup.
|
||||
"""
|
||||
return self.bus.admission.pause_if_idle(self._has_pending_work)
|
||||
|
||||
def _has_pending_work(self) -> bool:
|
||||
return bool(
|
||||
self.bus.inbound_size or self._pending_queues or self._deferred_automation_turns
|
||||
or self.bus.has_pending_events or self._active_tasks or self._background_tasks
|
||||
or self._close_lock.locked()
|
||||
or self.subagents.has_pending_work or self._exec_session_manager.has_pending_work
|
||||
)
|
||||
|
||||
def preserve_inflight_turns_on_shutdown(self) -> None:
|
||||
"""Keep durable checkpoints when the owning gateway exits.
|
||||
|
||||
@@ -1523,6 +1549,7 @@ class AgentLoop:
|
||||
|
||||
async def _enqueue_session_message(self, msg: InboundMessage) -> None:
|
||||
"""Admit session work without waiting for its execution or result."""
|
||||
self.bus.admission.check()
|
||||
session_key = self._effective_session_key(msg)
|
||||
if not self.subagents.accepts_result(msg, session_key):
|
||||
return
|
||||
@@ -1808,6 +1835,11 @@ class AgentLoop:
|
||||
|
||||
def schedule_background(self, coro: Coroutine[Any, Any, Any]) -> None:
|
||||
"""Schedule a coroutine as a tracked background task (drained on shutdown)."""
|
||||
try:
|
||||
self.bus.admission.check()
|
||||
except RuntimeMaintenanceError:
|
||||
coro.close()
|
||||
raise
|
||||
task = asyncio.create_task(coro)
|
||||
self._background_tasks.add(task)
|
||||
task.add_done_callback(self._background_task_done)
|
||||
@@ -2657,53 +2689,54 @@ class AgentLoop:
|
||||
)
|
||||
# Share the dispatch lock so direct calls serialize with bus turns.
|
||||
lock = self._get_session_lock(session_key)
|
||||
temporary_parent = False
|
||||
try:
|
||||
async with lock:
|
||||
kwargs: dict[str, Any] = {
|
||||
"session_key": session_key,
|
||||
"on_progress": on_progress,
|
||||
"on_stream": on_stream,
|
||||
"on_stream_end": on_stream_end,
|
||||
"ephemeral": ephemeral,
|
||||
}
|
||||
if _session_policy is not None:
|
||||
# Isolate per-run state before any early save or checkpoint;
|
||||
# the cached conversation must survive a temporary SDK turn.
|
||||
session = (await self.sessions.state.read(session_key) or Session(key=session_key)
|
||||
if not _session_policy.persist
|
||||
else await self.sessions.state.get(session_key))
|
||||
temporary_parent = not _session_policy.persist and not session.persisted
|
||||
session.policy = SessionPolicy(
|
||||
persist=session.policy.persist and _session_policy.persist,
|
||||
log_content=session.policy.log_content and _session_policy.log_content,
|
||||
disabled_tools=session.policy.disabled_tools | _session_policy.disabled_tools,
|
||||
)
|
||||
kwargs["session"] = session
|
||||
if _run_extra_hooks_for_ephemeral:
|
||||
kwargs["run_extra_hooks_for_ephemeral"] = True
|
||||
if hooks is not None:
|
||||
kwargs["hooks"] = hooks
|
||||
if hook_factories is not None:
|
||||
kwargs["hook_factories"] = hook_factories
|
||||
if tools is not None:
|
||||
kwargs["tools"] = tools
|
||||
if runtime is not None:
|
||||
kwargs["runtime"] = runtime
|
||||
if on_runtime_admitted is not None:
|
||||
kwargs["on_runtime_admitted"] = on_runtime_admitted
|
||||
if attributes is not None:
|
||||
kwargs["attributes"] = dict(attributes)
|
||||
try:
|
||||
return await self._process_message(msg, **kwargs)
|
||||
finally:
|
||||
if temporary_parent:
|
||||
parent = self.sessions.state.peek_header(session_key)
|
||||
if parent is not None and not parent.policy.persist:
|
||||
await self.sessions.state.delete(session_key, expected_generation=parent.generation)
|
||||
finally:
|
||||
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
|
||||
self.runtime_event_publisher.clear_turn(session_key)
|
||||
with self.bus.admission.activity():
|
||||
temporary_parent = False
|
||||
try:
|
||||
async with lock:
|
||||
kwargs: dict[str, Any] = {
|
||||
"session_key": session_key,
|
||||
"on_progress": on_progress,
|
||||
"on_stream": on_stream,
|
||||
"on_stream_end": on_stream_end,
|
||||
"ephemeral": ephemeral,
|
||||
}
|
||||
if _session_policy is not None:
|
||||
# Isolate per-run state before any early save or checkpoint;
|
||||
# the cached conversation must survive a temporary SDK turn.
|
||||
session = (await self.sessions.state.read(session_key) or Session(key=session_key)
|
||||
if not _session_policy.persist
|
||||
else await self.sessions.state.get(session_key))
|
||||
temporary_parent = not _session_policy.persist and not session.persisted
|
||||
session.policy = SessionPolicy(
|
||||
persist=session.policy.persist and _session_policy.persist,
|
||||
log_content=session.policy.log_content and _session_policy.log_content,
|
||||
disabled_tools=session.policy.disabled_tools | _session_policy.disabled_tools,
|
||||
)
|
||||
kwargs["session"] = session
|
||||
if _run_extra_hooks_for_ephemeral:
|
||||
kwargs["run_extra_hooks_for_ephemeral"] = True
|
||||
if hooks is not None:
|
||||
kwargs["hooks"] = hooks
|
||||
if hook_factories is not None:
|
||||
kwargs["hook_factories"] = hook_factories
|
||||
if tools is not None:
|
||||
kwargs["tools"] = tools
|
||||
if runtime is not None:
|
||||
kwargs["runtime"] = runtime
|
||||
if on_runtime_admitted is not None:
|
||||
kwargs["on_runtime_admitted"] = on_runtime_admitted
|
||||
if attributes is not None:
|
||||
kwargs["attributes"] = dict(attributes)
|
||||
try:
|
||||
return await self._process_message(msg, **kwargs)
|
||||
finally:
|
||||
if temporary_parent:
|
||||
parent = self.sessions.state.peek_header(session_key)
|
||||
if parent is not None and not parent.policy.persist:
|
||||
await self.sessions.state.delete(session_key, expected_generation=parent.generation)
|
||||
finally:
|
||||
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
|
||||
self.runtime_event_publisher.clear_turn(session_key)
|
||||
|
||||
def _get_session_lock(self, session_key: str) -> asyncio.Lock:
|
||||
"""Return the shared lock while allowing idle session entries to expire."""
|
||||
|
||||
@@ -544,6 +544,7 @@ class SubagentManager:
|
||||
runtime: LLMRuntime | None, *, announce: bool, origin_turn_id: str | None,
|
||||
session_policy: SessionPolicy | None,
|
||||
) -> _SubagentTask:
|
||||
self.bus.admission.check()
|
||||
if runtime is None:
|
||||
runtime = self._compat_spawn_runtime()
|
||||
if temperature is not None:
|
||||
@@ -1003,6 +1004,11 @@ class SubagentManager:
|
||||
"""Return the number of currently running subagents."""
|
||||
return len(self._running_tasks)
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""Completed turns may still own exec cleanup, including failed cleanup."""
|
||||
return bool(self._tasks) or self._exec_session_manager.has_pending_work
|
||||
|
||||
def get_running_count_by_session(self, session_key: str) -> int:
|
||||
"""Return the number of currently running subagents for a session."""
|
||||
return sum(
|
||||
|
||||
@@ -238,7 +238,10 @@ class _ExecSession:
|
||||
finally:
|
||||
stopped.cancel()
|
||||
await asyncio.gather(stopped, return_exceptions=True)
|
||||
from nanobot.agent.tools.shell import ExecTool, _reap_pid # pyright: ignore[reportPrivateUsage]
|
||||
from nanobot.agent.tools.shell import (
|
||||
ExecTool,
|
||||
_reap_pid, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
|
||||
ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
|
||||
_reap_pid(self.process.pid)
|
||||
@@ -253,6 +256,18 @@ class _ExecSession:
|
||||
self._state_changed.clear()
|
||||
await self._state_changed.wait()
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""Include pipe draining and failed/in-flight process-tree cleanup."""
|
||||
cleanup = self._kill_task
|
||||
return (
|
||||
self.finished_at is None
|
||||
or not self._stdout_task.done() or not self._stderr_task.done()
|
||||
or (cleanup is not None and (
|
||||
not cleanup.done() or cleanup.cancelled() or cleanup.exception() is not None
|
||||
))
|
||||
)
|
||||
|
||||
async def _watch_timeout(self) -> None:
|
||||
"""Supervise execution budgets independently of tool waits and log reads."""
|
||||
while not self._completion_task.done():
|
||||
@@ -371,13 +386,16 @@ class _ExecSession:
|
||||
await asyncio.shield(self._completion_task)
|
||||
|
||||
async def _begin_stop(self, reason: FinishReason) -> None:
|
||||
if self.finished_at is not None:
|
||||
if not self.has_pending_work:
|
||||
return
|
||||
if self._execution_exited and self._stop_reason is None:
|
||||
return
|
||||
if self._stop_reason is None:
|
||||
self._stop_reason = reason
|
||||
if self._kill_task is None:
|
||||
if self._kill_task is None or (
|
||||
self._kill_task.done()
|
||||
and (self._kill_task.cancelled() or self._kill_task.exception() is not None)
|
||||
):
|
||||
self.cleanup_error = None
|
||||
self._kill_task = asyncio.create_task(self._kill())
|
||||
self._kill_task.add_done_callback(self._on_kill_done)
|
||||
@@ -391,8 +409,8 @@ class _ExecSession:
|
||||
logger.opt(exception=error if tool_log_content_allowed() else False).error(
|
||||
"Failed to terminate exec session {}", self.session_id,
|
||||
)
|
||||
if (task.cancelled() or error is not None) and self._kill_task is task:
|
||||
self._kill_task = None
|
||||
# Retain failed cleanup as unsettled work, even if the parent exited.
|
||||
# kill() replaces it on an explicit retry.
|
||||
|
||||
async def _kill(self) -> None:
|
||||
from nanobot.agent.tools.shell import ExecTool
|
||||
@@ -410,9 +428,18 @@ class ExecSessionManager:
|
||||
self.result_retention = result_retention
|
||||
self._sessions: dict[str, _ExecSession] = {}
|
||||
self._starting: dict[str, tuple[str | None, asyncio.Task[_ExecSession]]] = {}
|
||||
self._stopping_launches: set[asyncio.Task[_ExecSession]] = set()
|
||||
self._lock = asyncio.Lock()
|
||||
self._closed = False
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""Inspect owned work without polling, terminating or removing sessions."""
|
||||
return bool(
|
||||
self._lock.locked() or self._starting or self._stopping_launches
|
||||
or any(s.has_pending_work for s in self._sessions.values())
|
||||
)
|
||||
|
||||
async def start(
|
||||
self,
|
||||
*,
|
||||
@@ -574,7 +601,6 @@ class ExecSessionManager:
|
||||
async with self._lock:
|
||||
self._closed = True
|
||||
sessions: list[_ExecSession] = list(self._sessions.values())
|
||||
self._sessions.clear()
|
||||
launches = [task for _, task in self._starting.values()]
|
||||
self._starting.clear()
|
||||
return await self._stop_owned(sessions, launches, "shutdown")
|
||||
@@ -583,9 +609,9 @@ class ExecSessionManager:
|
||||
"""Terminate all sessions owned by owner_session_key. Returns count."""
|
||||
async with self._lock:
|
||||
victims: list[_ExecSession] = []
|
||||
for sid, s in list(self._sessions.items()):
|
||||
for s in self._sessions.values():
|
||||
if s.owner_session_key == owner_session_key:
|
||||
victims.append(self._sessions.pop(sid))
|
||||
victims.append(s)
|
||||
launches = [
|
||||
task for owner, task in self._starting.values() if owner == owner_session_key
|
||||
]
|
||||
@@ -598,6 +624,10 @@ class ExecSessionManager:
|
||||
self, sessions: list[_ExecSession], launches: list[asyncio.Task[_ExecSession]],
|
||||
reason: FinishReason,
|
||||
) -> int:
|
||||
# Removed startup reservations must stay visible until cancellation drains.
|
||||
self._stopping_launches.update(launches)
|
||||
for task in launches:
|
||||
task.add_done_callback(self._stopping_launches.discard)
|
||||
results: list[None | BaseException] = list(await asyncio.gather(
|
||||
*(session.kill(reason) for session in sessions),
|
||||
self._cancel_launches(launches),
|
||||
@@ -609,10 +639,10 @@ class ExecSessionManager:
|
||||
for session, result in zip(sessions, results, strict=True)
|
||||
if isinstance(result, BaseException)
|
||||
]
|
||||
if failures:
|
||||
async with self._lock:
|
||||
for session, _ in failures:
|
||||
self._sessions[session.session_id] = session
|
||||
async with self._lock:
|
||||
for session, result in zip(sessions, results, strict=True):
|
||||
if not isinstance(result, BaseException):
|
||||
self._sessions.pop(session.session_id, None)
|
||||
errors = [result for _, result in failures]
|
||||
if isinstance(startup_error, BaseException):
|
||||
errors.append(startup_error)
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
"""Provision the Bun runtime used by source installations and package builds."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from filelock import FileLock
|
||||
|
||||
BUN_VERSION = "1.3.13"
|
||||
# SHA-256 of the official bun-v1.3.13 release archives.
|
||||
_ARCHIVES = {
|
||||
"linux-x64-baseline": "9d8a24292a7068090205daac0a5a223f5f69736f5287e37bf88d3b4031edc750",
|
||||
"linux-x64-musl-baseline": "88ca7c7ad235b498f549eea2f770f434e9f0f5e9ba95168a2d3a1f235184c394",
|
||||
"linux-aarch64": "70bae41b3908b0a120e1e58c5c8af30e74afae3b8d11b0d3fdd8e787ddfb4b22",
|
||||
"linux-aarch64-musl": "5385e978107ce4934298d8d6afe9bfbb898683f6cc23e6753a0da60bc60c5b81",
|
||||
"darwin-x64-baseline": "a98ba6a480f22fda9b343626b906a4e26aa53618bf85d2bc5928ecf2ba45f0ed",
|
||||
"darwin-aarch64": "5467e3f65dba526b9fea98f0cce04efafc0c63e169733ec27b876a3ad32da190",
|
||||
"windows-x64-baseline": "c68c7903c1190101590cc1b2129835f47211b3b37ae87759f2b97d6534aa3ad1",
|
||||
}
|
||||
|
||||
|
||||
class BunUnavailableError(RuntimeError):
|
||||
"""The required runtime could not be prepared for this platform."""
|
||||
|
||||
|
||||
@contextmanager
|
||||
def bun_environment(executable: str) -> Generator[dict[str, str]]:
|
||||
"""Run lifecycle scripts' `node` commands with Bun, without a global Node shim."""
|
||||
env = os.environ.copy()
|
||||
runtime = Path(shutil.which(executable) or executable).resolve()
|
||||
if os.name == "nt" and runtime.suffix.lower() in {".cmd", ".bat"}:
|
||||
runtime = Path(subprocess.check_output(
|
||||
[str(runtime), "-p", "process.execPath"], text=True, timeout=10,
|
||||
).strip())
|
||||
# `bun --bun install` does not alias node in dependency lifecycle scripts.
|
||||
# Only this subprocess tree sees the alias; Windows hardlinks need no admin rights.
|
||||
with tempfile.TemporaryDirectory(prefix="nanobot-bun-") as temporary:
|
||||
node = Path(temporary) / ("node.exe" if os.name == "nt" else "node")
|
||||
try:
|
||||
node.hardlink_to(runtime)
|
||||
except OSError:
|
||||
shutil.copy2(runtime, node)
|
||||
env["PATH"] = os.pathsep.join((temporary, str(runtime.parent), env.get("PATH", "")))
|
||||
yield env
|
||||
|
||||
|
||||
def _matches_version(executable: str) -> bool:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[executable, "--version"], capture_output=True, text=True, timeout=10,
|
||||
)
|
||||
return result.returncode == 0 and result.stdout.strip() == BUN_VERSION
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
|
||||
|
||||
def _target() -> str:
|
||||
system = {"Linux": "linux", "Darwin": "darwin", "Windows": "windows"}.get(
|
||||
platform.system(), "unknown",
|
||||
)
|
||||
arch = {"x86_64": "x64", "amd64": "x64", "arm64": "aarch64", "aarch64": "aarch64"}.get(
|
||||
platform.machine().lower(), "unknown",
|
||||
)
|
||||
musl = system == "linux" and (
|
||||
platform.libc_ver()[0] == "musl" or any(Path("/lib").glob("ld-musl-*.so.1"))
|
||||
)
|
||||
target = f"{system}-{arch}" + ("-musl" if musl else "")
|
||||
if arch == "x64":
|
||||
target += "-baseline"
|
||||
if target not in _ARCHIVES:
|
||||
raise BunUnavailableError(f"Automatic Bun setup is not supported on {system}/{arch}.")
|
||||
return target
|
||||
|
||||
|
||||
def ensure_bun(
|
||||
*, cache_dir: Path | None = None, output: Callable[[str], None] = print,
|
||||
) -> str:
|
||||
"""Return the pinned runtime, downloading a verified executable when missing."""
|
||||
existing = shutil.which("bun")
|
||||
if existing and _matches_version(existing):
|
||||
return existing
|
||||
target = _target()
|
||||
root = cache_dir or Path.home() / ".nanobot" / "tools" / "bun"
|
||||
directory = root / BUN_VERSION / target
|
||||
executable = directory / ("bun.exe" if os.name == "nt" else "bun")
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
with FileLock(str(directory / "install.lock"), timeout=180):
|
||||
if executable.is_file() and _matches_version(str(executable)):
|
||||
return str(executable)
|
||||
output(f"Downloading Bun {BUN_VERSION} ({target})…")
|
||||
url = f"https://github.com/oven-sh/bun/releases/download/bun-v{BUN_VERSION}/bun-{target}.zip"
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=60) as response:
|
||||
raw = response.read(128 * 1024 * 1024 + 1)
|
||||
if hashlib.sha256(raw).hexdigest() != _ARCHIVES[target]:
|
||||
raise BunUnavailableError("Bun download failed checksum verification. Retry the download.")
|
||||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||||
member = archive.getinfo(f"bun-{target}/{executable.name}")
|
||||
if member.file_size > 256 * 1024 * 1024:
|
||||
raise BunUnavailableError("Bun archive contains an oversized executable.")
|
||||
content = archive.read(member)
|
||||
with tempfile.TemporaryDirectory(prefix=".install-", dir=directory) as temporary:
|
||||
candidate = Path(temporary) / executable.name
|
||||
candidate.write_bytes(content)
|
||||
candidate.chmod(0o755)
|
||||
if not _matches_version(str(candidate)):
|
||||
raise BunUnavailableError("Downloaded Bun cannot run on this system.")
|
||||
os.replace(candidate, executable)
|
||||
except (OSError, ValueError, KeyError, zipfile.BadZipFile) as exc:
|
||||
raise BunUnavailableError(f"Could not prepare Bun {BUN_VERSION}: {exc}") from exc
|
||||
return str(executable)
|
||||
+11
-2
@@ -11,6 +11,7 @@ from loguru import logger
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.outbound_events import outbound_message_for_event
|
||||
from nanobot.events import AgentEvent
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
|
||||
_EventT = TypeVar("_EventT", bound=AgentEvent)
|
||||
EventHandler = Callable[[AgentEvent], Awaitable[None] | None]
|
||||
@@ -28,7 +29,8 @@ class MessageBus:
|
||||
``publish_event``. Local state transitions never wait for network sends.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, *, admission: RuntimeAdmission | None = None):
|
||||
self.admission = admission if admission is not None else RuntimeAdmission()
|
||||
self.inbound: asyncio.Queue[InboundMessage] = asyncio.Queue()
|
||||
self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()
|
||||
self._handlers: list[EventHandler] = []
|
||||
@@ -37,7 +39,9 @@ class MessageBus:
|
||||
|
||||
async def publish_inbound(self, msg: InboundMessage) -> None:
|
||||
"""Publish a message from a channel to the agent."""
|
||||
await self.inbound.put(msg)
|
||||
self.admission.check()
|
||||
# This queue is unbounded. Admission and enqueue must not yield apart.
|
||||
self.inbound.put_nowait(msg)
|
||||
|
||||
async def consume_inbound(self) -> InboundMessage:
|
||||
"""Consume the next inbound message (blocks until available)."""
|
||||
@@ -81,6 +85,11 @@ class MessageBus:
|
||||
"""Number of pending outbound messages."""
|
||||
return self.outbound.qsize()
|
||||
|
||||
@property
|
||||
def has_pending_events(self) -> bool:
|
||||
"""Scheduled local subscribers may still start agent background work."""
|
||||
return bool(self._pending)
|
||||
|
||||
@overload
|
||||
def subscribe(
|
||||
self, handler: Callable[[_EventT], Awaitable[None] | None],
|
||||
|
||||
@@ -107,6 +107,16 @@ class BaseChannel(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
def has_pending_delivery(self) -> bool:
|
||||
"""Whether delivery outlives an awaited ``send``/streaming call.
|
||||
|
||||
The manager already accounts for awaited sends and retries. Channels
|
||||
that enqueue their own writes must expose that work here, including
|
||||
transport cleanup, before a gateway can be considered idle.
|
||||
"""
|
||||
return False
|
||||
|
||||
def progress_transport_defaults(self) -> tuple[bool, bool] | None:
|
||||
"""Return channel-owned defaults for progress and tool-hint messages.
|
||||
|
||||
|
||||
@@ -3,10 +3,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
QueryParams = Mapping[str, list[str]]
|
||||
|
||||
|
||||
class ChannelConnector(Protocol):
|
||||
"""Channel-owned setup actions called by the settings request owner."""
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]: ...
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class ManagedChannelConnector(ChannelConnector, Protocol):
|
||||
"""Setup whose detached work can participate in gateway maintenance.
|
||||
|
||||
The synchronous property must stay true through awaited cleanup. ``close``
|
||||
returns only after owned writers have stopped; failure retains ownership.
|
||||
Settings requests account for their own awaited work separately.
|
||||
"""
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool: ...
|
||||
|
||||
async def close(self) -> None: ...
|
||||
|
||||
|
||||
class ChannelConnectError(Exception):
|
||||
"""User-facing channel connection failure."""
|
||||
|
||||
@@ -21,4 +43,6 @@ def query_first(query: QueryParams, key: str) -> str | None:
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
__all__ = ["ChannelConnectError", "QueryParams", "query_first"]
|
||||
__all__ = [
|
||||
"ChannelConnectError", "ChannelConnector", "ManagedChannelConnector", "QueryParams", "query_first",
|
||||
]
|
||||
@@ -46,6 +46,20 @@ class FeishuConnectStore:
|
||||
self._sessions: dict[str, FeishuConnectSession] = {}
|
||||
self._completion_lock = threading.Lock()
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
# Registration only advances inside an owned settings request. Expired
|
||||
# QR records have no listener or detached writer to keep alive.
|
||||
now = time.monotonic()
|
||||
return any(session.deadline > now for session in tuple(self._sessions.values()))
|
||||
|
||||
async def close(self) -> None:
|
||||
def clear() -> None:
|
||||
with self._completion_lock:
|
||||
self._sessions.clear()
|
||||
|
||||
await asyncio.to_thread(clear)
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
"""Handle one generic settings connection action."""
|
||||
if action == "start":
|
||||
|
||||
@@ -11,8 +11,10 @@ from nanobot.channels.feishu.connect import FeishuConnectStore
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("shutdown", [False, True])
|
||||
async def test_feishu_cancel_wins_over_inflight_confirmation(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
shutdown: bool,
|
||||
) -> None:
|
||||
poll_started = threading.Event()
|
||||
release_poll = threading.Event()
|
||||
@@ -52,15 +54,20 @@ async def test_feishu_cancel_wins_over_inflight_confirmation(
|
||||
|
||||
store = FeishuConnectStore()
|
||||
started = await store.handle("start", {})
|
||||
assert store.has_pending_work is True
|
||||
query = {"session_id": [started["session_id"]]}
|
||||
poll_task = asyncio.create_task(store.handle("poll", query))
|
||||
assert await asyncio.to_thread(poll_started.wait, 5)
|
||||
|
||||
cancelled = await store.handle("cancel", query)
|
||||
if shutdown:
|
||||
await store.close()
|
||||
else:
|
||||
cancelled = await store.handle("cancel", query)
|
||||
assert cancelled["status"] == "cancelled"
|
||||
release_poll.set()
|
||||
completed = await poll_task
|
||||
|
||||
assert cancelled["status"] == "cancelled"
|
||||
assert store.has_pending_work is False
|
||||
assert completed["status"] == "cancelled"
|
||||
assert saved_results == []
|
||||
|
||||
|
||||
@@ -28,9 +28,10 @@ class LinearConnectSession:
|
||||
flow: LinearOAuthFlow
|
||||
config: LinearConfig
|
||||
state: LinearStateStore
|
||||
server: LinearServerLease
|
||||
server: LinearServerLease | None
|
||||
completion_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
|
||||
result: dict[str, Any] | None = None
|
||||
expiry_task: asyncio.Task[None] | None = None
|
||||
|
||||
|
||||
class LinearConnectStore:
|
||||
@@ -39,6 +40,16 @@ class LinearConnectStore:
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, LinearConnectSession] = {}
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
# A deadline alone does not close the callback/webhook listener. Cached
|
||||
# success, however, is retained only after releasing that listener.
|
||||
return any(session.server is not None for session in self._sessions.values())
|
||||
|
||||
async def close(self) -> None:
|
||||
for session_id in tuple(self._sessions):
|
||||
await self.cancel(session_id)
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
await self._cleanup()
|
||||
if action == "start":
|
||||
@@ -103,12 +114,19 @@ class LinearConnectStore:
|
||||
f"Unable to start the Linear callback listener on {config.host}:{config.port}: {exc}",
|
||||
status=502,
|
||||
) from exc
|
||||
self._sessions[flow.session_id] = LinearConnectSession(
|
||||
session = LinearConnectSession(
|
||||
flow=flow,
|
||||
config=config,
|
||||
state=state,
|
||||
server=lease,
|
||||
)
|
||||
self._sessions[flow.session_id] = session
|
||||
session.expiry_task = asyncio.create_task(
|
||||
self._expire_session(session), name=f"linear-connect-expire-{flow.session_id}",
|
||||
)
|
||||
session.expiry_task.add_done_callback(
|
||||
lambda task: task.exception() if not task.cancelled() else None,
|
||||
)
|
||||
return {
|
||||
"session_id": flow.session_id,
|
||||
"status": "pending",
|
||||
@@ -129,6 +147,7 @@ class LinearConnectStore:
|
||||
if self._sessions.get(session_id) is not session:
|
||||
return _terminal(session_id, "cancelled", "Linear authorization cancelled.")
|
||||
if session.result is not None:
|
||||
await self._release_listener(session)
|
||||
return dict(session.result)
|
||||
flow = session.flow
|
||||
if time.monotonic() >= flow.deadline:
|
||||
@@ -169,8 +188,7 @@ class LinearConnectStore:
|
||||
}
|
||||
# A browser may miss the first successful poll while switching tabs.
|
||||
# Retain its result until the session expires, but release the callback listener.
|
||||
OAUTH_FLOWS.remove(flow)
|
||||
await asyncio.to_thread(session.server.close)
|
||||
await self._release_listener(session)
|
||||
return dict(session.result)
|
||||
|
||||
async def cancel(self, session_id: str) -> dict[str, Any]:
|
||||
@@ -291,11 +309,26 @@ class LinearConnectStore:
|
||||
await self.cancel(session_id)
|
||||
|
||||
async def _close_session(self, session_id: str) -> None:
|
||||
session = self._sessions.pop(session_id, None)
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None:
|
||||
return
|
||||
expiry_task = session.expiry_task
|
||||
if expiry_task is not None and expiry_task is not asyncio.current_task():
|
||||
expiry_task.cancel()
|
||||
await asyncio.gather(expiry_task, return_exceptions=True)
|
||||
await self._release_listener(session)
|
||||
self._sessions.pop(session_id, None)
|
||||
|
||||
async def _expire_session(self, session: LinearConnectSession) -> None:
|
||||
await asyncio.sleep(max(0, session.flow.deadline - time.monotonic()))
|
||||
await self.cancel(session.flow.session_id)
|
||||
|
||||
@staticmethod
|
||||
async def _release_listener(session: LinearConnectSession) -> None:
|
||||
OAUTH_FLOWS.remove(session.flow)
|
||||
await asyncio.to_thread(session.server.close)
|
||||
if session.server is not None:
|
||||
await asyncio.to_thread(session.server.close)
|
||||
session.server = None
|
||||
|
||||
|
||||
def _load_linear_config() -> LinearConfig:
|
||||
|
||||
@@ -37,7 +37,8 @@ class LinearWebhookError(ValueError):
|
||||
|
||||
class _ReusableThreadingHTTPServer(ThreadingHTTPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
# server_close() must join request writers, not only stop accepting sockets.
|
||||
daemon_threads = False
|
||||
|
||||
|
||||
class SharedLinearHttpServer:
|
||||
@@ -65,6 +66,10 @@ class SharedLinearHttpServer:
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def setup(self) -> None:
|
||||
super().setup()
|
||||
self.connection.settimeout(5)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == owner.config.oauth_callback_path:
|
||||
@@ -99,6 +104,7 @@ class SharedLinearHttpServer:
|
||||
self.send_response(status.value)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Connection", "close")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.end_headers()
|
||||
@@ -124,7 +130,7 @@ class SharedLinearHttpServer:
|
||||
self._server.server_close()
|
||||
self._server = None
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
self._thread.join(timeout=2)
|
||||
self._thread.join()
|
||||
self._thread = None
|
||||
|
||||
def _handle_oauth_callback(
|
||||
@@ -192,10 +198,11 @@ class LinearServerLease:
|
||||
self._closed = False
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
_release_server(self._server)
|
||||
with _SERVER_GUARD:
|
||||
if self._closed:
|
||||
return
|
||||
_release_server(self._server)
|
||||
self._closed = True
|
||||
|
||||
|
||||
_SERVER_GUARD = threading.RLock()
|
||||
@@ -222,10 +229,10 @@ def _release_server(server: SharedLinearHttpServer) -> None:
|
||||
with _SERVER_GUARD:
|
||||
if _shared_server is not server:
|
||||
return
|
||||
server._references -= 1 # pyright: ignore[reportPrivateUsage]
|
||||
if server._references <= 0: # pyright: ignore[reportPrivateUsage]
|
||||
if server._references == 1: # pyright: ignore[reportPrivateUsage]
|
||||
server.close()
|
||||
_shared_server = None
|
||||
server._references -= 1 # pyright: ignore[reportPrivateUsage]
|
||||
|
||||
|
||||
def _handler_response(
|
||||
@@ -237,6 +244,7 @@ def _handler_response(
|
||||
handler.send_response(status.value)
|
||||
handler.send_header("Content-Type", content_type)
|
||||
handler.send_header("Content-Length", str(len(body)))
|
||||
handler.send_header("Connection", "close")
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("X-Content-Type-Options", "nosniff")
|
||||
handler.end_headers()
|
||||
|
||||
@@ -6,6 +6,7 @@ import hmac
|
||||
import http.client
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timezone
|
||||
@@ -287,12 +288,14 @@ def test_oauth_callback_does_not_report_cancelled_authorization_as_connected(
|
||||
lease.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("concurrent", [False, True])
|
||||
@pytest.mark.parametrize("concurrent, close_fails_once", [(False, False), (True, False), (False, True)])
|
||||
async def test_successful_authorization_survives_repeated_polls(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, concurrent: bool,
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, concurrent: bool, close_fails_once: bool,
|
||||
) -> None:
|
||||
state = LinearStateStore(tmp_path / "linear.sqlite3")
|
||||
lease = Mock(spec=LinearServerLease)
|
||||
if close_fails_once:
|
||||
lease.close.side_effect = [RuntimeError("listener close failed"), None]
|
||||
|
||||
async def exchange_code(_code: str, _verifier: str) -> LinearInstallation:
|
||||
await asyncio.sleep(0)
|
||||
@@ -310,11 +313,16 @@ async def test_successful_authorization_survives_repeated_polls(
|
||||
store = linear_connect.LinearConnectStore()
|
||||
started_at = time.monotonic()
|
||||
started = await store.handle("start", {})
|
||||
assert store.has_pending_work is True
|
||||
session_id = started["session_id"]
|
||||
query = {"session_id": [session_id]}
|
||||
oauth_state = parse_qs(urlparse(started["authorization_url"]).query)["state"][0]
|
||||
try:
|
||||
assert OAUTH_FLOWS.complete(oauth_state, code="authorization-code", error=None)
|
||||
if close_fails_once:
|
||||
with pytest.raises(RuntimeError, match="listener close failed"):
|
||||
await store.handle("poll", query)
|
||||
assert store.has_pending_work is True
|
||||
if concurrent:
|
||||
first, repeated = await asyncio.gather(
|
||||
store.handle("poll", query), store.handle("poll", query),
|
||||
@@ -323,11 +331,12 @@ async def test_successful_authorization_survives_repeated_polls(
|
||||
first = await store.handle("poll", query)
|
||||
repeated = await store.handle("poll", query)
|
||||
assert first["status"] == "succeeded"
|
||||
assert store.has_pending_work is False
|
||||
assert repeated == first
|
||||
assert (await store.handle("poll", query)) == first
|
||||
assert state.has_installations("client-id")
|
||||
client.exchange_code.assert_awaited_once()
|
||||
lease.close.assert_called_once()
|
||||
assert lease.close.call_count == (2 if close_fails_once else 1)
|
||||
assert (await store.handle("poll", {"session_id": ["unknown"]}))["status"] == "expired"
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -340,6 +349,73 @@ async def test_successful_authorization_survives_repeated_polls(
|
||||
await store.cancel(session_id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_shutdown_joins_real_webhook_writer(tmp_path, monkeypatch) -> None:
|
||||
port = _free_port()
|
||||
state = LinearStateStore(tmp_path / "linear.sqlite3")
|
||||
write_entered, allow_write, listener_stopped = threading.Event(), threading.Event(), threading.Event()
|
||||
enqueue = state.enqueue_webhook
|
||||
monkeypatch.setattr(linear_connect, "_load_linear_config", lambda: _config(port))
|
||||
monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
|
||||
|
||||
def enqueue_after_release(delivery, payload):
|
||||
write_entered.set()
|
||||
assert allow_write.wait(3)
|
||||
return enqueue(delivery, payload)
|
||||
|
||||
monkeypatch.setattr(state, "enqueue_webhook", enqueue_after_release)
|
||||
store = linear_connect.LinearConnectStore()
|
||||
started = await store.start()
|
||||
lease = store._sessions[started["session_id"]].server
|
||||
server = lease._server._server
|
||||
shutdown_listener = server.shutdown
|
||||
|
||||
def shutdown_and_signal():
|
||||
shutdown_listener()
|
||||
listener_stopped.set()
|
||||
|
||||
monkeypatch.setattr(server, "shutdown", shutdown_and_signal)
|
||||
request = asyncio.create_task(asyncio.to_thread(_post_webhook, port, _agent_webhook()))
|
||||
closing = None
|
||||
try:
|
||||
assert await asyncio.to_thread(write_entered.wait, 1)
|
||||
closing = asyncio.create_task(store.close())
|
||||
assert await asyncio.to_thread(listener_stopped.wait, 1)
|
||||
assert not closing.done()
|
||||
assert store.has_pending_work is True
|
||||
finally:
|
||||
allow_write.set()
|
||||
response = await request
|
||||
if closing is not None:
|
||||
await closing
|
||||
else:
|
||||
await store.close()
|
||||
assert response[0] == 200
|
||||
assert store.has_pending_work is False
|
||||
assert not store._sessions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_abandoned_authorization_releases_listener_without_poll(tmp_path, monkeypatch) -> None:
|
||||
state = LinearStateStore(tmp_path / "linear.sqlite3")
|
||||
lease = Mock(spec=LinearServerLease)
|
||||
monkeypatch.setattr(linear_connect, "_load_linear_config", _config)
|
||||
monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
|
||||
monkeypatch.setattr(linear_connect, "acquire_http_server", lambda *_args: lease)
|
||||
monkeypatch.setattr("nanobot.channels.linear.oauth.FLOW_TTL_SECONDS", 0.02)
|
||||
store = linear_connect.LinearConnectStore()
|
||||
started = await store.start()
|
||||
task = store._sessions[started["session_id"]].expiry_task
|
||||
assert task is not None
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.shield(task), timeout=1)
|
||||
assert store.has_pending_work is False
|
||||
assert not store._sessions
|
||||
lease.close.assert_called_once()
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_store_lists_and_disconnects_workspaces(
|
||||
tmp_path: Path,
|
||||
|
||||
@@ -787,7 +787,7 @@ describe("Linear channel UI", () => {
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Remove workspace" }));
|
||||
const confirm = await screen.findByRole("alertdialog", { name: "Remove nanobot?" });
|
||||
fireEvent.click(within(confirm).getByRole("button", { name: "Remove workspace" }));
|
||||
expect(await screen.findByRole("button", { name: "Connect Linear" })).toBeEnabled();
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());
|
||||
expect(screen.queryByText("Linear authorization cancelled.")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Continue in Linear" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
+65
-13
@@ -152,8 +152,11 @@ class ChannelManager:
|
||||
self._channel_errors: dict[str, str] = {}
|
||||
self._channel_tasks: dict[str, asyncio.Task[None]] = {}
|
||||
self._dispatch_task: asyncio.Task[None] | None = None
|
||||
self._restart_notice_task: asyncio.Task[None] | None = None
|
||||
self._outbound_tasks: dict[asyncio.Task[None], tuple[str, str]] = {}
|
||||
self._outbound_tails: dict[tuple[str, str], asyncio.Task[None]] = {}
|
||||
self._outbound_pending: list[OutboundMessage] = []
|
||||
self._outbound_dispatching = False
|
||||
self._outbound_slots = asyncio.Semaphore(_OUTBOUND_PENDING_LIMIT)
|
||||
self._outbound_sends = asyncio.Semaphore(_OUTBOUND_CONCURRENCY)
|
||||
self._stopping_channels: set[str] = set()
|
||||
@@ -161,9 +164,12 @@ class ChannelManager:
|
||||
self._origin_reply_fingerprints: OrderedDict[tuple[str, str, str], str] = OrderedDict()
|
||||
self._outbox = DeliveryOutbox(self._config_path.parent / "delivery" / "outbox.sqlite3")
|
||||
self._scheduled_deliveries: set[str] = set()
|
||||
self.bus.outbound_recorder = self._outbox.record
|
||||
self.bus.outbound_recorder = self._record_scheduled
|
||||
|
||||
self._init_channels()
|
||||
self._remove_delivery_check: Callable[[], None] | None = (
|
||||
self.bus.admission.register_pending_work(lambda: self.has_pending_delivery)
|
||||
)
|
||||
|
||||
def _channel_section(
|
||||
self,
|
||||
@@ -404,6 +410,8 @@ class ChannelManager:
|
||||
errors = self._channel_errors = {}
|
||||
errors.pop(name, None)
|
||||
try:
|
||||
if name != "websocket":
|
||||
await self.bus.admission.wait_until_open()
|
||||
await channel.start()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
@@ -624,6 +632,10 @@ class ChannelManager:
|
||||
|
||||
async def start_all(self) -> None:
|
||||
"""Start all channels and the outbound dispatcher."""
|
||||
if self._remove_delivery_check is None:
|
||||
self._remove_delivery_check = self.bus.admission.register_pending_work(
|
||||
lambda: self.has_pending_delivery,
|
||||
)
|
||||
if not self.channels:
|
||||
logger.warning("No channels enabled")
|
||||
return
|
||||
@@ -647,7 +659,8 @@ class ChannelManager:
|
||||
notice = consume_restart_notice_from_env()
|
||||
if not notice:
|
||||
return None
|
||||
return asyncio.create_task(self._send_restart_notice_when_started(notice))
|
||||
self._restart_notice_task = asyncio.create_task(self._send_restart_notice_when_started(notice))
|
||||
return self._restart_notice_task
|
||||
|
||||
async def _send_restart_notice_when_started(
|
||||
self,
|
||||
@@ -657,6 +670,7 @@ class ChannelManager:
|
||||
poll_s: float = _RESTART_NOTICE_START_POLL_S,
|
||||
) -> None:
|
||||
"""Deliver a restart notice after the target channel starts."""
|
||||
await self.bus.admission.wait_until_open()
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + timeout_s
|
||||
target = self.channels.get(notice.channel)
|
||||
@@ -703,9 +717,18 @@ class ChannelManager:
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._dispatch_task
|
||||
|
||||
if self._restart_notice_task:
|
||||
self._restart_notice_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await self._restart_notice_task
|
||||
self._restart_notice_task = None
|
||||
|
||||
# Stop all channels
|
||||
for name in list(self.channels):
|
||||
await self._stop_channel(name)
|
||||
if self._remove_delivery_check is not None:
|
||||
self._remove_delivery_check()
|
||||
self._remove_delivery_check = None
|
||||
|
||||
@staticmethod
|
||||
def _fingerprint_content(content: str) -> str:
|
||||
@@ -745,6 +768,25 @@ class ChannelManager:
|
||||
|
||||
return False
|
||||
|
||||
def _record_scheduled(self, msg: OutboundMessage) -> None:
|
||||
if msg.delivery is not None:
|
||||
with self.bus.admission.activity():
|
||||
self._outbox.record(msg)
|
||||
|
||||
@property
|
||||
def has_pending_delivery(self) -> bool:
|
||||
"""A synchronous idle check, including channel-owned transport queues.
|
||||
|
||||
Read on the gateway event loop immediately before closing admission.
|
||||
This is delivery liveness, not proof that every channel writer stopped.
|
||||
"""
|
||||
return bool(
|
||||
self.bus.outbound_size or self._outbound_pending or self._outbound_dispatching
|
||||
or self._outbound_tasks
|
||||
or (self._restart_notice_task is not None and not self._restart_notice_task.done())
|
||||
or any(channel.has_pending_delivery for channel in self.channels.values())
|
||||
)
|
||||
|
||||
async def _cancel_outbound(self, channel: str | None = None) -> None:
|
||||
tasks = [task for task, key in self._outbound_tasks.items()
|
||||
if channel is None or key[0] == channel]
|
||||
@@ -839,15 +881,17 @@ class ChannelManager:
|
||||
self._outbox.finish(msg, "sent")
|
||||
|
||||
async def _recover_scheduled(self) -> None:
|
||||
for msg in self._outbox.ready():
|
||||
channel = self.channels.get(msg.channel)
|
||||
if channel is None:
|
||||
self._outbox.finish(msg, "failed", "channel_disabled")
|
||||
else:
|
||||
await self._queue_outbound(channel, msg)
|
||||
with self.bus.admission.activity():
|
||||
for msg in self._outbox.ready():
|
||||
channel = self.channels.get(msg.channel)
|
||||
if channel is None:
|
||||
self._outbox.finish(msg, "failed", "channel_disabled")
|
||||
else:
|
||||
await self._queue_outbound(channel, msg)
|
||||
|
||||
async def _dispatch_outbound(self) -> None:
|
||||
try:
|
||||
await self.bus.admission.wait_until_open()
|
||||
await self._dispatch_outbound_loop()
|
||||
finally:
|
||||
await self._cancel_outbound()
|
||||
@@ -858,11 +902,12 @@ class ChannelManager:
|
||||
|
||||
# Buffer for messages that couldn't be processed during delta coalescing
|
||||
# (since asyncio.Queue doesn't support push_front)
|
||||
pending: list[OutboundMessage] = []
|
||||
pending = self._outbound_pending
|
||||
next_recovery = 0.0
|
||||
|
||||
while True:
|
||||
try:
|
||||
await self.bus.admission.wait_until_open()
|
||||
if time.monotonic() >= next_recovery:
|
||||
next_recovery = time.monotonic() + RETRY_SECONDS
|
||||
try:
|
||||
@@ -873,10 +918,15 @@ class ChannelManager:
|
||||
if pending:
|
||||
msg = pending.pop(0)
|
||||
else:
|
||||
msg = await asyncio.wait_for(
|
||||
self.bus.consume_outbound(),
|
||||
timeout=1.0
|
||||
)
|
||||
# wait_for creates a child task: it can remove the last
|
||||
# queued message before this dispatcher records ownership.
|
||||
# Keep dequeue and the busy claim in the same task.
|
||||
async with asyncio.timeout(1.0):
|
||||
msg = await self.bus.consume_outbound()
|
||||
self._outbound_dispatching = True
|
||||
# Intake can close while an empty queue is awaited. Retain the
|
||||
# message, but do not start another transport write while paused.
|
||||
await self.bus.admission.wait_until_open()
|
||||
|
||||
event = msg.event
|
||||
progress_event = event if isinstance(event, ProgressEvent) else None
|
||||
@@ -945,6 +995,8 @@ class ChannelManager:
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
finally:
|
||||
self._outbound_dispatching = False
|
||||
|
||||
@staticmethod
|
||||
async def _send_reasoning_delta(
|
||||
|
||||
@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from packaging.requirements import InvalidRequirement, Requirement
|
||||
|
||||
from nanobot.channels.connect import ChannelConnector
|
||||
from nanobot.channels.contracts import ChannelManagementSpec, ChannelSetupSpec
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -93,7 +94,7 @@ class ChannelPlugin:
|
||||
)
|
||||
return channel_cls
|
||||
|
||||
def load_connector(self) -> Any:
|
||||
def load_connector(self) -> ChannelConnector:
|
||||
"""Construct the optional channel-owned interactive connector."""
|
||||
if self.connector is None:
|
||||
raise ImportError(f"Channel plugin '{self.name}' does not provide a connector")
|
||||
@@ -110,7 +111,9 @@ class ChannelPlugin:
|
||||
f"Channel plugin '{self.name}' connector '{self.connector}' "
|
||||
"does not provide handle()"
|
||||
)
|
||||
return connector
|
||||
# Dynamic plugin edge: handle() is the established connector contract.
|
||||
# Lifecycle support is optional and checked by its maintenance owner.
|
||||
return cast(ChannelConnector, connector)
|
||||
|
||||
|
||||
def _target_parts(target: str, *, label: str) -> tuple[str, str]:
|
||||
|
||||
@@ -93,6 +93,19 @@ class QQConnectStore:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, QQConnectSession] = {}
|
||||
self._commits: dict[str, asyncio.Task[None]] = {}
|
||||
self._closed = False
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
now = time.monotonic()
|
||||
return bool(self._commits) or any(session.deadline > now for session in self._sessions.values())
|
||||
|
||||
async def close(self) -> None:
|
||||
self._closed = True
|
||||
self._sessions.clear()
|
||||
if self._commits:
|
||||
await asyncio.shield(asyncio.gather(*self._commits.values(), return_exceptions=True))
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
if action == "start":
|
||||
@@ -134,6 +147,10 @@ class QQConnectStore:
|
||||
# A transient portal error is not proof the scan failed; keep waiting.
|
||||
return _pending(session, "Waiting for QQ scan...")
|
||||
|
||||
self._cleanup()
|
||||
if self._sessions.get(session_id) is not session:
|
||||
return _payload(session_id, "expired", "This QQ login has expired. Start again.")
|
||||
|
||||
status = result.get("status")
|
||||
if status == 3:
|
||||
self._sessions.pop(session_id, None)
|
||||
@@ -151,7 +168,13 @@ class QQConnectStore:
|
||||
if not app_id or not secret:
|
||||
return _payload(session_id, "failed", "QQ confirmed the scan but returned no credentials.")
|
||||
|
||||
await asyncio.to_thread(save_credentials, app_id, secret)
|
||||
# Cancelling the awaiting request cannot stop a file-writing thread.
|
||||
# Retain ownership until the writer finishes, including during shutdown.
|
||||
commit = asyncio.create_task(asyncio.to_thread(save_credentials, app_id, secret))
|
||||
self._commits[session_id] = commit
|
||||
commit.add_done_callback(lambda task: self._commits.pop(session_id, None))
|
||||
commit.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)
|
||||
await asyncio.shield(commit)
|
||||
session.credentials = (app_id, secret)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
@@ -161,6 +184,8 @@ class QQConnectStore:
|
||||
|
||||
async def cancel(self, session_id: str) -> dict[str, Any]:
|
||||
self._sessions.pop(session_id, None)
|
||||
if commit := self._commits.get(session_id):
|
||||
await asyncio.shield(asyncio.gather(commit, return_exceptions=True))
|
||||
return _payload(session_id, "cancelled", "QQ login cancelled.")
|
||||
|
||||
async def login(self) -> tuple[str, str] | None:
|
||||
@@ -181,6 +206,8 @@ class QQConnectStore:
|
||||
self._sessions.pop(session.id, None)
|
||||
|
||||
def _new_session(self, task_id: str, key: str) -> QQConnectSession:
|
||||
if self._closed:
|
||||
raise ChannelConnectError("QQ connection store is closed", status=409)
|
||||
session = QQConnectSession(
|
||||
id=secrets.token_urlsafe(18),
|
||||
task_id=task_id,
|
||||
|
||||
@@ -48,9 +48,11 @@ async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pyte
|
||||
started = await store.start()
|
||||
assert started["status"] == "pending"
|
||||
assert started["qr_url"].endswith("task_id=task-1&_wv=2")
|
||||
assert store.has_pending_work
|
||||
|
||||
polled = await store.poll(started["session_id"])
|
||||
assert polled["status"] == "succeeded"
|
||||
assert not store.has_pending_work
|
||||
assert await store.poll(started["session_id"]) == {
|
||||
"session_id": started["session_id"],
|
||||
"status": "expired",
|
||||
@@ -64,6 +66,117 @@ async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pyte
|
||||
assert qq["allowFrom"] == ["42"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("stop", ["cancel", "close", "expire"])
|
||||
async def test_qq_late_portal_result_cannot_save_after_session_ends(
|
||||
monkeypatch: pytest.MonkeyPatch, _isolated_config: Path, stop: str,
|
||||
):
|
||||
key = base64.b64encode(b"k" * 32).decode()
|
||||
polling = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
async def fake_poll(_task_id: str) -> dict[str, Any]:
|
||||
polling.set()
|
||||
await release.wait()
|
||||
return {"status": 2, "bot_appid": "1024", "bot_encrypt_secret": _encrypt("new", key)}
|
||||
|
||||
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
|
||||
store = QQConnectStore()
|
||||
session = store._new_session("task", key)
|
||||
before = _isolated_config.read_bytes()
|
||||
poll = asyncio.create_task(store.poll(session.id))
|
||||
try:
|
||||
await asyncio.wait_for(polling.wait(), timeout=5)
|
||||
if stop == "cancel":
|
||||
await store.cancel(session.id)
|
||||
elif stop == "close":
|
||||
await store.close()
|
||||
else:
|
||||
session.deadline = 0
|
||||
assert not store.has_pending_work
|
||||
finally:
|
||||
release.set()
|
||||
assert (await poll)["status"] == "expired"
|
||||
assert _isolated_config.read_bytes() == before
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("stop", ["cancel", "close"])
|
||||
async def test_qq_cleanup_waits_for_writer_after_poll_request_is_cancelled(
|
||||
monkeypatch: pytest.MonkeyPatch, _isolated_config: Path, stop: str,
|
||||
):
|
||||
from nanobot.runtime_admission import RuntimeAdmission, RuntimeBusyError
|
||||
|
||||
key = base64.b64encode(b"k" * 32).decode()
|
||||
saving = threading.Event()
|
||||
release = threading.Event()
|
||||
original_save = connect.save_credentials
|
||||
|
||||
async def fake_poll(_task_id: str) -> dict[str, Any]:
|
||||
return {"status": 2, "bot_appid": "1024", "bot_encrypt_secret": _encrypt("new", key)}
|
||||
|
||||
def slow_save(app_id: str, secret: str) -> None:
|
||||
saving.set()
|
||||
if not release.wait(timeout=5):
|
||||
raise TimeoutError("credential writer was not released")
|
||||
original_save(app_id, secret)
|
||||
|
||||
monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
|
||||
monkeypatch.setattr(connect, "save_credentials", slow_save)
|
||||
store = QQConnectStore()
|
||||
admission = RuntimeAdmission()
|
||||
admission.register_pending_work(lambda: store.has_pending_work)
|
||||
session = store._new_session("task", key)
|
||||
poll = asyncio.create_task(store.poll(session.id))
|
||||
cleanup: asyncio.Task[None | dict[str, Any]] | None = None
|
||||
try:
|
||||
assert await asyncio.to_thread(saving.wait, 5)
|
||||
poll.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await poll
|
||||
session.deadline = 0
|
||||
cleanup = asyncio.create_task(store.close() if stop == "close" else store.cancel(session.id))
|
||||
await asyncio.sleep(0)
|
||||
assert not cleanup.done()
|
||||
assert store.has_pending_work
|
||||
with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("an active credential writer must block an update")
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(poll, return_exceptions=True)
|
||||
if cleanup is not None:
|
||||
await cleanup
|
||||
await store.close()
|
||||
assert not store.has_pending_work
|
||||
with admission.pause_if_idle(lambda: False):
|
||||
assert admission.paused
|
||||
saved = json.loads(_isolated_config.read_text(encoding="utf-8"))["channels"]["qq"]
|
||||
assert (saved["appId"], saved["secret"], saved["allowFrom"]) == ("1024", "new", ["42"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qq_close_during_start_does_not_leave_a_new_session(monkeypatch: pytest.MonkeyPatch):
|
||||
creating = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
|
||||
async def fake_create() -> tuple[str, str]:
|
||||
creating.set()
|
||||
await release.wait()
|
||||
return "late-task", base64.b64encode(b"k" * 32).decode()
|
||||
|
||||
monkeypatch.setattr(connect, "create_bind_task", fake_create)
|
||||
store = QQConnectStore()
|
||||
start = asyncio.create_task(store.start())
|
||||
try:
|
||||
await asyncio.wait_for(creating.wait(), timeout=5)
|
||||
await store.close()
|
||||
finally:
|
||||
release.set()
|
||||
with pytest.raises(connect.ChannelConnectError, match="closed"):
|
||||
await start
|
||||
assert not store.has_pending_work
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qq_connect_keeps_waiting_on_transient_portal_errors(monkeypatch: pytest.MonkeyPatch):
|
||||
async def fake_create() -> tuple[str, str]:
|
||||
|
||||
@@ -29,6 +29,7 @@ from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
mark_websocket_turn_transcript_persistence_failed,
|
||||
@@ -705,6 +706,15 @@ class WebSocketChannel(BaseChannel):
|
||||
async def handler(connection: ServerConnection) -> None:
|
||||
await self._connection_loop(connection)
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
async def handle_binary(request: web.BaseRequest) -> web.StreamResponse:
|
||||
try:
|
||||
with self.bus.admission.activity():
|
||||
return await self._uploads.handle(request)
|
||||
except RuntimeMaintenanceError:
|
||||
return web.json_response({"error": "Gateway update is being verified"}, status=503)
|
||||
|
||||
async def prune_uploads() -> None:
|
||||
while not stop_event.is_set():
|
||||
self._uploads.store.prune()
|
||||
@@ -720,7 +730,7 @@ class WebSocketChannel(BaseChannel):
|
||||
failures = 0
|
||||
while not stop_event.is_set():
|
||||
server: Server | None = None
|
||||
bridge = BinaryHTTPBridge(self._uploads.handle)
|
||||
bridge = BinaryHTTPBridge(handle_binary)
|
||||
was_serving = False
|
||||
started_at = 0.0
|
||||
try:
|
||||
@@ -969,6 +979,16 @@ class WebSocketChannel(BaseChannel):
|
||||
name=f"websocket-outbound-{id(connection):x}",
|
||||
)
|
||||
|
||||
@property
|
||||
def has_pending_delivery(self) -> bool:
|
||||
# send() only enqueues a frame. buffered_bytes includes the frame that
|
||||
# a writer has removed from its queue but has not finished transmitting.
|
||||
return bool(self._outbound_retire_tasks) or any(
|
||||
state.buffered_bytes or not state.queue.empty()
|
||||
or (state.writer is not None and not state.writer.done())
|
||||
for state in self._connection_outbound.values()
|
||||
)
|
||||
|
||||
async def _drain_connection_outbound(
|
||||
self,
|
||||
connection: ServerConnection,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Production listener regressions for HTTP upload + small WS references."""
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import aiohttp
|
||||
@@ -9,6 +10,8 @@ from websockets.asyncio.client import connect
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.config.loader import load_config
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
@@ -48,6 +51,134 @@ async def event(ws, name):
|
||||
return payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("finish", [True, False], ids=["complete", "disconnect"])
|
||||
async def test_streaming_upload_blocks_maintenance_until_written_or_cleaned(gateway, finish):
|
||||
channel, bus, http_url, ws_url = gateway
|
||||
port = int(http_url.rsplit(":", 1)[1])
|
||||
store = channel.gateway.uploads.store
|
||||
async with connect(ws_url) as ws:
|
||||
capability = (await event(ws, "ready"))["upload"]
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
try:
|
||||
writer.write((
|
||||
f"POST {capability['path']} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n"
|
||||
f"Authorization: Bearer {capability['token']}\r\n"
|
||||
"Content-Type: image/png\r\nContent-Length: 8\r\n\r\npart"
|
||||
).encode())
|
||||
await writer.drain()
|
||||
async with asyncio.timeout(3):
|
||||
while store._active == 0:
|
||||
await asyncio.sleep(.01)
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Maintenance ignored an in-progress binary write")
|
||||
assert not bus.admission.paused
|
||||
if finish:
|
||||
writer.write(b"done")
|
||||
await writer.drain()
|
||||
response = await asyncio.wait_for(reader.read(), timeout=3)
|
||||
assert response.startswith(b"HTTP/1.1 201"), response
|
||||
else:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
async with asyncio.timeout(3):
|
||||
while store._active:
|
||||
await asyncio.sleep(.01)
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
assert bus.admission.paused
|
||||
if not finish:
|
||||
assert not tuple(store._journal.iterdir())
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
|
||||
async def test_threaded_settings_write_stays_busy_after_browser_disconnect(gateway, monkeypatch):
|
||||
channel, bus, _, ws_url = gateway
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
settings = channel.gateway.settings
|
||||
original = settings.config.run_serialized
|
||||
|
||||
def delayed_save(*args, **kwargs):
|
||||
entered.set()
|
||||
assert release.wait(10), "Test did not release the settings writer"
|
||||
return original(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(settings.config, "run_serialized", delayed_save)
|
||||
|
||||
def connection_url():
|
||||
token = channel.gateway.tokens.issue_token(300, audience="webui")
|
||||
return ws_url.replace("test-secret", token)
|
||||
|
||||
def request(identifier, value):
|
||||
return json.dumps({"type": "webui_request", "request_id": identifier,
|
||||
"action": "settings.runtime_config.update",
|
||||
"payload": {"values": {"agents.defaults.max_tool_iterations": value}}})
|
||||
|
||||
try:
|
||||
async with connect(connection_url()) as ws:
|
||||
await event(ws, "ready")
|
||||
await ws.send(request("slow-write", 31))
|
||||
assert await asyncio.to_thread(entered.wait, 3)
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Maintenance ignored a threaded settings write")
|
||||
# Existing mutation ownership deliberately survives a lost browser;
|
||||
# losing its delivery task must not make the gateway appear idle.
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Browser disconnect released an unfinished write")
|
||||
operation = channel._commands.request_operations["slow-write"].task
|
||||
release.set()
|
||||
result = await asyncio.wait_for(asyncio.shield(operation), timeout=5)
|
||||
assert result.status is None, result
|
||||
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 31
|
||||
async with connect(connection_url()) as ws:
|
||||
await event(ws, "ready")
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
await ws.send(request("blocked-write", 32))
|
||||
rejected = await event(ws, "webui_response")
|
||||
assert rejected["error"]["status"] == 503
|
||||
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 31
|
||||
await ws.send(request("after-abort", 33))
|
||||
assert (await event(ws, "webui_response"))["ok"] is True
|
||||
assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 33
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
async def test_http_route_is_busy_until_its_async_work_finishes(gateway, monkeypatch):
|
||||
channel, bus, http_url, _ = gateway
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
route = channel.gateway.http._dispatch_resolved
|
||||
|
||||
async def delayed_route(*args, **kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return await route(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(channel.gateway.http, "_dispatch_resolved", delayed_route)
|
||||
async with aiohttp.ClientSession(headers={"Authorization": "Bearer test-secret"}) as http:
|
||||
request = asyncio.create_task(http.get(http_url + "/webui/bootstrap"))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), timeout=3)
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Maintenance ignored a running HTTP handler")
|
||||
release.set()
|
||||
async with await asyncio.wait_for(request, timeout=3) as response:
|
||||
assert response.status == 200
|
||||
await response.read()
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
async with http.get(http_url + "/webui/bootstrap") as response:
|
||||
assert response.status == 503
|
||||
async with http.get(http_url + "/webui/bootstrap") as response:
|
||||
assert response.status == 200
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(request, return_exceptions=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime,name", [
|
||||
("image/png", "image.png"), ("text/csv", "report.csv"), ("video/webm", "clip.webm"),
|
||||
])
|
||||
|
||||
@@ -16,6 +16,7 @@ from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.websocket import runtime
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
@@ -64,7 +65,7 @@ class _RecordingConnection:
|
||||
|
||||
|
||||
def _channel() -> WebSocketChannel:
|
||||
bus = MagicMock(spec=MessageBus)
|
||||
bus = MessageBus()
|
||||
config = WebSocketConfig(
|
||||
enabled=True,
|
||||
allow_from=["*"],
|
||||
@@ -129,9 +130,24 @@ async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() ->
|
||||
assert await _next_text(connection) == "first"
|
||||
assert await _next_text(connection) == "last"
|
||||
assert connections[0].sent.empty()
|
||||
async with asyncio.timeout(2):
|
||||
while manager._outbound_tasks or bus.outbound_size:
|
||||
await asyncio.sleep(0)
|
||||
# The manager's send has finished; the physical transport still owns
|
||||
# its final frames. A shutdown idle check must include that second queue.
|
||||
assert channel.has_pending_delivery
|
||||
with pytest.raises(RuntimeBusyError):
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("The blocked WebSocket transport was missed")
|
||||
assert not bus.admission.paused
|
||||
connections[0].release_send.set()
|
||||
assert await _next_text(connections[0]) == "first"
|
||||
assert await _next_text(connections[0]) == "last"
|
||||
async with asyncio.timeout(2):
|
||||
while manager.has_pending_delivery:
|
||||
await asyncio.sleep(0)
|
||||
with bus.admission.pause_if_idle(lambda: False):
|
||||
assert bus.admission.paused
|
||||
finally:
|
||||
dispatcher.cancel()
|
||||
await asyncio.gather(dispatcher, return_exceptions=True)
|
||||
@@ -142,6 +158,26 @@ async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() ->
|
||||
assert not channel._connection_outbound
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delivery_remains_busy_until_timed_out_transport_is_retired(monkeypatch) -> None:
|
||||
monkeypatch.setattr(runtime, "_OUTBOUND_SEND_TIMEOUT_S", 0.02)
|
||||
channel = _channel()
|
||||
connection = _RecordingConnection(block_first_send=True, block_close=True)
|
||||
channel._attach(cast(Any, connection), "chat-retiring")
|
||||
try:
|
||||
await channel.send(_message("chat-retiring", "reply"))
|
||||
await asyncio.wait_for(connection.closed.wait(), 2)
|
||||
assert connection.send_cancelled.is_set()
|
||||
assert channel.has_pending_delivery
|
||||
connection.release_close.set()
|
||||
await asyncio.wait_for(_wait_for_retire_tasks(channel), 2)
|
||||
assert not channel.has_pending_delivery
|
||||
finally:
|
||||
connection.release_send.set()
|
||||
connection.release_close.set()
|
||||
await channel._cleanup_connection(cast(Any, connection))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_slow_tui_does_not_block_a_different_topic() -> None:
|
||||
channel = _channel()
|
||||
|
||||
@@ -34,6 +34,15 @@ class WeixinConnectStore:
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, WeixinConnectSession] = {}
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
# Poll/commit are awaited by the settings request owner, not detached.
|
||||
return any(session.deadline > time.monotonic() for session in self._sessions.values())
|
||||
|
||||
async def close(self) -> None:
|
||||
for session_id in tuple(self._sessions):
|
||||
await self.cancel(session_id)
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
"""Handle one generic settings connection action."""
|
||||
if action == "start":
|
||||
|
||||
@@ -57,10 +57,12 @@ async def test_weixin_connect_store_saves_confirmed_qr_login(
|
||||
started = await store.start()
|
||||
assert started["status"] == "pending"
|
||||
assert started["qr_url"] == "https://qr.example/1"
|
||||
assert store.has_pending_work is True
|
||||
|
||||
completed = await store.poll(started["session_id"])
|
||||
assert completed["status"] == "succeeded"
|
||||
assert completed["account"] == "wx-user"
|
||||
assert store.has_pending_work is False
|
||||
|
||||
saved = json.loads((state_dir / "account.json").read_text())
|
||||
assert saved["token"] == "wx-token"
|
||||
@@ -177,9 +179,11 @@ async def test_weixin_reconnect_keeps_existing_account_until_scan_succeeds(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("shutdown", [False, True])
|
||||
async def test_weixin_cancel_wins_over_inflight_confirmation(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
shutdown: bool,
|
||||
) -> None:
|
||||
state_dir = tmp_path / "weixin-state"
|
||||
config_path = tmp_path / "config.json"
|
||||
@@ -214,15 +218,20 @@ async def test_weixin_cancel_wins_over_inflight_confirmation(
|
||||
|
||||
store = WeixinConnectStore()
|
||||
started = await store.handle("start", {})
|
||||
assert store.has_pending_work is True
|
||||
query = {"session_id": [started["session_id"]]}
|
||||
poll_task = asyncio.create_task(store.handle("poll", query))
|
||||
await asyncio.wait_for(poll_started.wait(), timeout=5)
|
||||
|
||||
cancelled = await store.handle("cancel", query)
|
||||
if shutdown:
|
||||
await store.close()
|
||||
else:
|
||||
cancelled = await store.handle("cancel", query)
|
||||
assert cancelled["status"] == "cancelled"
|
||||
release_poll.set()
|
||||
completed = await poll_task
|
||||
|
||||
assert cancelled["status"] == "cancelled"
|
||||
assert store.has_pending_work is False
|
||||
assert completed["status"] == "cancelled"
|
||||
assert not (state_dir / "account.json").exists()
|
||||
|
||||
|
||||
@@ -799,6 +799,7 @@ async def test_manager_surfaces_actionable_weixin_auth_error_without_traceback(
|
||||
)
|
||||
manager = manager_mod.ChannelManager.__new__(manager_mod.ChannelManager)
|
||||
manager._channel_errors = {}
|
||||
manager.bus = channel.bus
|
||||
|
||||
await manager._start_channel("weixin", channel)
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ if TYPE_CHECKING:
|
||||
_NATIVE_STOP_TIMEOUT_SECONDS = 10.0
|
||||
_DATABASE_REPLACE_TIMEOUT_SECONDS = 10.0
|
||||
_FINALIZE_POLL_WAIT_SECONDS = 0.05
|
||||
_CONNECT_TTL_SECONDS = 600
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -36,6 +37,9 @@ class WhatsAppConnectSession:
|
||||
deadline: float
|
||||
qr_url: str = ""
|
||||
finalize_task: asyncio.Task[None] | None = None
|
||||
stop_task: asyncio.Task[None] | None = None
|
||||
discard_task: asyncio.Task[None] | None = None
|
||||
expiry_task: asyncio.Task[None] | None = None
|
||||
|
||||
|
||||
class WhatsAppConnectStore:
|
||||
@@ -44,6 +48,17 @@ class WhatsAppConnectStore:
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, WhatsAppConnectSession] = {}
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""Keep login/native workers owned until completion or confirmed cleanup."""
|
||||
return any(
|
||||
session.finalize_task is None
|
||||
or not session.finalize_task.done()
|
||||
or not self._session_stopped(session)
|
||||
or (session.discard_task is not None and not session.discard_task.done())
|
||||
for session in self._sessions.values()
|
||||
)
|
||||
|
||||
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
|
||||
if action == "start":
|
||||
force = (query_first(query, "force") or "").strip().lower() in {
|
||||
@@ -99,9 +114,13 @@ class WhatsAppConnectStore:
|
||||
target_path=target_path,
|
||||
pending_path=pending_path,
|
||||
created_wall=now_wall,
|
||||
deadline=time.monotonic() + 600,
|
||||
deadline=time.monotonic() + _CONNECT_TTL_SECONDS,
|
||||
)
|
||||
self._sessions[session_id] = session
|
||||
session.expiry_task = asyncio.create_task(
|
||||
self._expire_session(session), name=f"whatsapp-connect-expire-{session.id}",
|
||||
)
|
||||
session.expiry_task.add_done_callback(self._observe_task)
|
||||
|
||||
qr_wait = asyncio.create_task(self._wait_for_qr(session))
|
||||
try:
|
||||
@@ -113,6 +132,7 @@ class WhatsAppConnectStore:
|
||||
finally:
|
||||
if not qr_wait.done():
|
||||
qr_wait.cancel()
|
||||
await asyncio.gather(qr_wait, return_exceptions=True)
|
||||
return self._pending_payload(session)
|
||||
|
||||
async def poll(self, session_id: str) -> dict[str, Any]:
|
||||
@@ -124,6 +144,9 @@ class WhatsAppConnectStore:
|
||||
"status": "expired",
|
||||
"message": "This WhatsApp login has expired. Start again.",
|
||||
}
|
||||
if session.discard_task is not None:
|
||||
# A concurrent poll must not promote a login being cancelled.
|
||||
return await self.cancel(session_id)
|
||||
if not session.result.done():
|
||||
return self._pending_payload(session)
|
||||
|
||||
@@ -138,21 +161,25 @@ class WhatsAppConnectStore:
|
||||
# Finish fast clients in this request without letting native shutdown
|
||||
# block the polling response path.
|
||||
await asyncio.wait({finalize_task}, timeout=_FINALIZE_POLL_WAIT_SECONDS)
|
||||
if session.discard_task is not None:
|
||||
return await self.cancel(session_id)
|
||||
if not finalize_task.done():
|
||||
payload = self._pending_payload(session)
|
||||
payload["qr_url"] = ""
|
||||
payload["message"] = "Finishing the WhatsApp connection."
|
||||
return payload
|
||||
|
||||
self._sessions.pop(session_id, None)
|
||||
try:
|
||||
finalize_task.result()
|
||||
except Exception as exc:
|
||||
if self._session_stopped(session):
|
||||
self._sessions.pop(session_id, None)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "failed",
|
||||
"message": f"WhatsApp QR login failed: {exc}",
|
||||
}
|
||||
self._sessions.pop(session_id, None)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"status": "succeeded",
|
||||
@@ -162,15 +189,21 @@ class WhatsAppConnectStore:
|
||||
async def _finalize_session(self, session: WhatsAppConnectSession) -> None:
|
||||
try:
|
||||
session.result.result()
|
||||
await self._close_session(session)
|
||||
await self._commit_database(session.pending_path, session.target_path)
|
||||
except BaseException:
|
||||
await self._close_session(session)
|
||||
self._remove_database(session.pending_path)
|
||||
raise
|
||||
# A stop timeout is not proof that the native SQLite writer exited.
|
||||
# Preserve its database and ownership for an explicit cleanup retry.
|
||||
await self._close_session(session)
|
||||
try:
|
||||
await self._commit_database(session.pending_path, session.target_path)
|
||||
except BaseException:
|
||||
self._remove_database(session.pending_path)
|
||||
raise
|
||||
|
||||
async def cancel(self, session_id: str) -> dict[str, Any]:
|
||||
session = self._sessions.pop(session_id, None)
|
||||
session = self._sessions.get(session_id)
|
||||
if session is not None:
|
||||
await self._discard_session(session)
|
||||
return {
|
||||
@@ -186,17 +219,30 @@ class WhatsAppConnectStore:
|
||||
if time.monotonic() >= session.deadline
|
||||
]
|
||||
for session_id in expired:
|
||||
session = self._sessions.pop(session_id)
|
||||
await self._discard_session(session)
|
||||
await self.cancel(session_id)
|
||||
|
||||
async def _expire_session(self, session: WhatsAppConnectSession) -> None:
|
||||
await asyncio.sleep(max(0, session.deadline - time.monotonic()))
|
||||
await self.cancel(session.id)
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Stop every login client before the gateway event loop closes."""
|
||||
sessions = tuple(self._sessions.values())
|
||||
self._sessions.clear()
|
||||
for session in sessions:
|
||||
await self._discard_session(session)
|
||||
|
||||
async def _discard_session(self, session: WhatsAppConnectSession) -> None:
|
||||
task = session.discard_task
|
||||
if task is None or task.done():
|
||||
task = asyncio.create_task(
|
||||
self._discard_and_remove(session), name=f"whatsapp-connect-discard-{session.id}",
|
||||
)
|
||||
task.add_done_callback(self._observe_task)
|
||||
session.discard_task = task
|
||||
# Closing a browser/request must not drop the native writer's owner.
|
||||
await asyncio.shield(task)
|
||||
|
||||
async def _discard_and_remove(self, session: WhatsAppConnectSession) -> None:
|
||||
finalize_task = session.finalize_task
|
||||
if (
|
||||
finalize_task is not None
|
||||
@@ -205,9 +251,10 @@ class WhatsAppConnectStore:
|
||||
if not finalize_task.done():
|
||||
finalize_task.cancel()
|
||||
await asyncio.gather(finalize_task, return_exceptions=True)
|
||||
else:
|
||||
await self._close_session(session)
|
||||
await self._close_session(session)
|
||||
self._remove_database(session.pending_path)
|
||||
if self._sessions.get(session.id) is session:
|
||||
del self._sessions[session.id]
|
||||
|
||||
@staticmethod
|
||||
async def _connect(
|
||||
@@ -229,36 +276,55 @@ class WhatsAppConnectStore:
|
||||
while not session.qr_url and not session.result.done():
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
async def _close_session(self, session: WhatsAppConnectSession) -> None:
|
||||
task = session.stop_task
|
||||
if task is None or (task.done() and not task.cancelled() and task.exception() is not None):
|
||||
task = asyncio.create_task(
|
||||
self._stop_session(session), name=f"whatsapp-connect-stop-{session.id}",
|
||||
)
|
||||
task.add_done_callback(self._observe_task)
|
||||
session.stop_task = task
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.shield(task), timeout=_NATIVE_STOP_TIMEOUT_SECONDS)
|
||||
except TimeoutError as exc:
|
||||
raise RuntimeError(
|
||||
"WhatsApp is still stopping. Retry cancelling the connection before updating."
|
||||
) from exc
|
||||
|
||||
@staticmethod
|
||||
async def _close_session(session: WhatsAppConnectSession) -> None:
|
||||
def _observe_task(task: asyncio.Task[None]) -> None:
|
||||
if not task.cancelled():
|
||||
task.exception()
|
||||
|
||||
@staticmethod
|
||||
def _session_stopped(session: WhatsAppConnectSession) -> bool:
|
||||
task = session.stop_task
|
||||
return task is not None and task.done() and not task.cancelled() and task.exception() is None
|
||||
|
||||
@staticmethod
|
||||
async def _stop_session(session: WhatsAppConnectSession) -> None:
|
||||
if session.expiry_task is not None:
|
||||
session.expiry_task.cancel()
|
||||
await asyncio.gather(session.expiry_task, return_exceptions=True)
|
||||
if not session.result.done():
|
||||
session.result.cancel()
|
||||
if not session.connect_task.done():
|
||||
session.connect_task.cancel()
|
||||
with suppress(Exception, asyncio.CancelledError):
|
||||
await session.connect_task
|
||||
native_task: asyncio.Task[Any] | None = None
|
||||
if session.connect_task.done() and not session.connect_task.cancelled():
|
||||
with suppress(Exception, asyncio.CancelledError):
|
||||
native_task = session.connect_task.result()
|
||||
elif not session.result.cancelled():
|
||||
session.result.exception()
|
||||
# Both Stop and Neonize use asyncio.to_thread in the supported SDK.
|
||||
# Cancellation cannot join those threads. Signal, then await actual return;
|
||||
# the bounded caller may time out without cancelling this owned task.
|
||||
await session.client.stop()
|
||||
await asyncio.shield(asyncio.gather(session.connect_task, return_exceptions=True))
|
||||
if session.connect_task.cancelled():
|
||||
raise RuntimeError("WhatsApp connection shutdown could not be verified")
|
||||
native_task = session.connect_task.result()
|
||||
client_native_task = getattr(session.client, "connect_task", None)
|
||||
if native_task is None and isinstance(client_native_task, asyncio.Task):
|
||||
native_task = cast(asyncio.Task[Any], client_native_task)
|
||||
with suppress(Exception):
|
||||
await asyncio.wait_for(session.client.stop(), timeout=5)
|
||||
if native_task is not None:
|
||||
if not native_task.done():
|
||||
try:
|
||||
# Stop only signals neonize's Go worker. Wait for that worker
|
||||
# to return so Windows releases its SQLite file handle before
|
||||
# the temporary login database is promoted.
|
||||
await asyncio.wait_for(
|
||||
asyncio.shield(native_task),
|
||||
timeout=_NATIVE_STOP_TIMEOUT_SECONDS,
|
||||
)
|
||||
except TimeoutError:
|
||||
native_task.cancel()
|
||||
await asyncio.gather(native_task, return_exceptions=True)
|
||||
await asyncio.shield(asyncio.gather(native_task, return_exceptions=True))
|
||||
if native_task.cancelled():
|
||||
raise RuntimeError("WhatsApp native shutdown could not be verified")
|
||||
|
||||
@staticmethod
|
||||
def _build_channel() -> tuple[WhatsAppChannel, Path]:
|
||||
@@ -327,7 +393,7 @@ class WhatsAppConnectStore:
|
||||
"session_id": session.id,
|
||||
"status": "pending",
|
||||
"interval_ms": 2000,
|
||||
"expires_at_ms": int((session.created_wall + 600) * 1000),
|
||||
"expires_at_ms": int((session.created_wall + _CONNECT_TTL_SECONDS) * 1000),
|
||||
"message": "Waiting for the WhatsApp scan.",
|
||||
}
|
||||
if session.qr_url:
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
@@ -41,7 +42,8 @@ class _FakeClient:
|
||||
await self.native_stop.wait()
|
||||
self.native_released = True
|
||||
return
|
||||
await asyncio.Event().wait()
|
||||
await self.native_stop.wait()
|
||||
self.native_released = True
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self.stop_gate is not None:
|
||||
@@ -107,6 +109,7 @@ async def test_whatsapp_connect_commits_new_session_after_scan(
|
||||
assert completed["status"] == "succeeded"
|
||||
assert target.read_bytes() == b"new-session"
|
||||
assert channel.client.stopped is True
|
||||
assert store.has_pending_work is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -121,6 +124,7 @@ async def test_whatsapp_connect_cancel_preserves_existing_session(
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
|
||||
started = await store.start(force=True)
|
||||
assert store.has_pending_work is True
|
||||
pending_path = Path(channel.config.database_path)
|
||||
pending_path.write_bytes(b"partial-session")
|
||||
cancelled = await store.cancel(started["session_id"])
|
||||
@@ -129,6 +133,7 @@ async def test_whatsapp_connect_cancel_preserves_existing_session(
|
||||
assert target.read_bytes() == b"working-session"
|
||||
assert not pending_path.exists()
|
||||
assert channel.client.stopped is True
|
||||
assert store.has_pending_work is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -147,6 +152,7 @@ async def test_whatsapp_connect_clears_qr_while_finishing_login(
|
||||
|
||||
assert finishing["status"] == "pending"
|
||||
assert finishing["qr_url"] == ""
|
||||
assert store.has_pending_work is True
|
||||
|
||||
stop_gate.set()
|
||||
await asyncio.sleep(0)
|
||||
@@ -224,3 +230,132 @@ async def test_whatsapp_connect_store_closes_pending_login(
|
||||
assert started["status"] == "pending"
|
||||
assert not pending_path.exists()
|
||||
assert channel.client.stopped is True
|
||||
assert store.has_pending_work is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("action", ["cancel", "finalize"])
|
||||
async def test_native_thread_timeout_keeps_database_and_can_retry_cleanup(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, action: str,
|
||||
) -> None:
|
||||
"""A cancelled asyncio wrapper cannot prove a native SQLite writer stopped."""
|
||||
target = tmp_path / "neonize.db"
|
||||
target.write_bytes(b"working-session")
|
||||
native_entered, native_release, native_exited = (
|
||||
threading.Event(), threading.Event(), threading.Event(),
|
||||
)
|
||||
channel = _FakeChannel(complete=action == "finalize", linger_until_stopped=True)
|
||||
store = WhatsAppConnectStore()
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
monkeypatch.setattr("nanobot.channels.whatsapp.connect._NATIVE_STOP_TIMEOUT_SECONDS", 0.03)
|
||||
|
||||
def native_writer() -> None:
|
||||
native_entered.set()
|
||||
assert native_release.wait(3)
|
||||
native_exited.set()
|
||||
|
||||
async def connect() -> None:
|
||||
await channel.client.qr_handler(b"whatsapp-qr-payload")
|
||||
Path(channel.config.database_path).write_bytes(b"new-session")
|
||||
if channel.client.complete:
|
||||
channel.client.result.set_result(None)
|
||||
await asyncio.to_thread(native_writer)
|
||||
|
||||
monkeypatch.setattr(channel.client, "connect", connect)
|
||||
started = await store.start(force=True)
|
||||
pending = Path(channel.config.database_path)
|
||||
try:
|
||||
assert await asyncio.to_thread(native_entered.wait, 1)
|
||||
if action == "cancel":
|
||||
with pytest.raises(RuntimeError, match="still stopping"):
|
||||
await store.cancel(started["session_id"])
|
||||
else:
|
||||
result = await store.poll(started["session_id"])
|
||||
assert result["status"] == "failed"
|
||||
assert "still stopping" in result["message"]
|
||||
assert store.has_pending_work is True
|
||||
assert channel.client.connect_task is not None
|
||||
assert not channel.client.connect_task.done()
|
||||
assert not native_exited.is_set()
|
||||
assert pending.read_bytes() == b"new-session"
|
||||
assert target.read_bytes() == b"working-session"
|
||||
finally:
|
||||
native_release.set()
|
||||
await store.cancel(started["session_id"])
|
||||
assert native_exited.is_set()
|
||||
assert store.has_pending_work is False
|
||||
assert not pending.exists()
|
||||
assert target.read_bytes() == b"working-session"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelling_cleanup_waiter_keeps_owned_shutdown(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
|
||||
) -> None:
|
||||
target = tmp_path / "neonize.db"
|
||||
stop_gate = asyncio.Event()
|
||||
channel = _FakeChannel(complete=False, stop_gate=stop_gate)
|
||||
store = WhatsAppConnectStore()
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
started = await store.start(force=True)
|
||||
pending = Path(channel.config.database_path)
|
||||
pending.write_bytes(b"partial-session")
|
||||
waiter = asyncio.create_task(store.cancel(started["session_id"]))
|
||||
await asyncio.sleep(0)
|
||||
waiter.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await waiter
|
||||
assert store.has_pending_work is True
|
||||
assert pending.exists()
|
||||
stop_gate.set()
|
||||
await store.close()
|
||||
assert store.has_pending_work is False
|
||||
assert channel.client.native_released is True
|
||||
assert not pending.exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_abandoned_login_expires_without_another_browser_poll(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
|
||||
) -> None:
|
||||
target = tmp_path / "neonize.db"
|
||||
channel = _FakeChannel(complete=False)
|
||||
store = WhatsAppConnectStore()
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
monkeypatch.setattr("nanobot.channels.whatsapp.connect._CONNECT_TTL_SECONDS", 0.02)
|
||||
started = await store.start(force=True)
|
||||
session = store._sessions[started["session_id"]]
|
||||
try:
|
||||
await asyncio.wait_for(channel.client.native_stop.wait(), timeout=1)
|
||||
assert session.discard_task is not None
|
||||
await asyncio.wait_for(asyncio.shield(session.discard_task), timeout=1)
|
||||
assert store.has_pending_work is False
|
||||
assert channel.client.native_released is True
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_during_finalize_does_not_promote_login_database(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
|
||||
) -> None:
|
||||
target = tmp_path / "neonize.db"
|
||||
target.write_bytes(b"working-session")
|
||||
stop_gate = asyncio.Event()
|
||||
channel = _FakeChannel(complete=True, stop_gate=stop_gate)
|
||||
store = WhatsAppConnectStore()
|
||||
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
|
||||
started = await store.start(force=True)
|
||||
assert (await store.poll(started["session_id"]))["status"] == "pending"
|
||||
cancelling = asyncio.create_task(store.cancel(started["session_id"]))
|
||||
await asyncio.sleep(0)
|
||||
polling = asyncio.create_task(store.poll(started["session_id"]))
|
||||
try:
|
||||
assert store.has_pending_work is True
|
||||
finally:
|
||||
stop_gate.set()
|
||||
cancelled, polled = await asyncio.gather(cancelling, polling)
|
||||
assert cancelled["status"] == polled["status"] == "cancelled"
|
||||
assert target.read_bytes() == b"working-session"
|
||||
assert not Path(channel.config.database_path).exists()
|
||||
assert store.has_pending_work is False
|
||||
@@ -0,0 +1,238 @@
|
||||
"""Windowless AppKit helper. Run as an isolated stdlib-only script, not an agent.
|
||||
|
||||
Only the parent launcher can pass the listening socket. Its private connections
|
||||
contain browser URLs and act as lifetime leases; no configuration is persisted.
|
||||
AppKit stays on the main thread. The socket thread sleeps in select, not a GUI
|
||||
polling loop, and EOF from every launcher removes the icon.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes as c
|
||||
import ipaddress
|
||||
import selectors
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
def is_local_browser_url(url: str) -> bool:
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
local = parts.hostname == "localhost" or ipaddress.ip_address(parts.hostname or "").is_loopback
|
||||
return (parts.scheme == "http" and local and parts.port is not None
|
||||
and parts.port > 0 and parts.username is None and parts.password is None
|
||||
and not any(ord(char) < 32 or ord(char) == 127 for char in url))
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
class _Clients:
|
||||
def __init__(self) -> None:
|
||||
self.urls: dict[socket.socket, str] = {}
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def current_url(self) -> str | None:
|
||||
with self.lock:
|
||||
return next(reversed(self.urls.values()), None)
|
||||
|
||||
def add(self, connection: socket.socket, url: str) -> None:
|
||||
with self.lock:
|
||||
self.urls[connection] = url
|
||||
|
||||
def remove(self, connection: socket.socket) -> None:
|
||||
with self.lock:
|
||||
self.urls.pop(connection, None)
|
||||
|
||||
|
||||
def _serve(listener: socket.socket, address: Path, clients: _Clients, stop: Callable[[], None]) -> None:
|
||||
import fcntl
|
||||
|
||||
listener.setblocking(False)
|
||||
with selectors.DefaultSelector() as selector, (address.parent / "start.lock").open("a") as lock:
|
||||
selector.register(listener, selectors.EVENT_READ)
|
||||
|
||||
def accept() -> None:
|
||||
connection, _ = listener.accept()
|
||||
connection.settimeout(0.5)
|
||||
try:
|
||||
with connection.makefile("rb") as stream:
|
||||
line = stream.readline(8193)
|
||||
if not line.endswith(b"\n") or len(line) > 8192:
|
||||
raise ValueError("Invalid Dock request")
|
||||
url = line[:-1].decode("utf-8")
|
||||
if not is_local_browser_url(url):
|
||||
raise ValueError("Invalid Dock URL")
|
||||
clients.add(connection, url)
|
||||
selector.register(connection, selectors.EVENT_READ)
|
||||
connection.sendall(b"1")
|
||||
connection.setblocking(False)
|
||||
except (OSError, ValueError):
|
||||
clients.remove(connection)
|
||||
try:
|
||||
selector.unregister(connection)
|
||||
except KeyError:
|
||||
pass
|
||||
connection.close()
|
||||
|
||||
try:
|
||||
while True:
|
||||
for key, _ in selector.select(timeout=None if clients.current_url() else 0.1):
|
||||
connection = key.fileobj
|
||||
if connection is listener:
|
||||
accept()
|
||||
elif isinstance(connection, socket.socket):
|
||||
# No commands after the initial URL. EOF (including SIGKILL)
|
||||
# releases only this launcher's presence, never the gateway.
|
||||
selector.unregister(connection)
|
||||
clients.remove(connection)
|
||||
connection.close()
|
||||
if clients.current_url() is not None:
|
||||
continue
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
continue
|
||||
try:
|
||||
# Serialize last-client exit against a new launcher's handshake.
|
||||
while True:
|
||||
try:
|
||||
accept()
|
||||
except BlockingIOError:
|
||||
break
|
||||
if clients.current_url() is None:
|
||||
listener.close()
|
||||
address.unlink(missing_ok=True)
|
||||
return
|
||||
finally:
|
||||
fcntl.flock(lock, fcntl.LOCK_UN)
|
||||
finally:
|
||||
listener.close()
|
||||
stop()
|
||||
|
||||
|
||||
class _AppKit:
|
||||
"""Small, explicit Objective-C ABI adapter; no third-party bridge or compiler."""
|
||||
|
||||
def __init__(self, icon: Path, clients: _Clients) -> None:
|
||||
self.objc = c.CDLL("/usr/lib/libobjc.A.dylib")
|
||||
self.framework = c.CDLL("/System/Library/Frameworks/AppKit.framework/AppKit")
|
||||
for name, arguments, result in (
|
||||
("objc_getClass", [c.c_char_p], c.c_void_p),
|
||||
("sel_registerName", [c.c_char_p], c.c_void_p),
|
||||
("objc_allocateClassPair", [c.c_void_p, c.c_char_p, c.c_size_t], c.c_void_p),
|
||||
("class_addMethod", [c.c_void_p, c.c_void_p, c.c_void_p, c.c_char_p], c.c_bool),
|
||||
("objc_registerClassPair", [c.c_void_p], None),
|
||||
):
|
||||
function = getattr(self.objc, name)
|
||||
function.argtypes = arguments
|
||||
function.restype = result
|
||||
self.clients = clients
|
||||
self.callbacks: list[Any] = []
|
||||
self.pool = self.send(self.cls("NSAutoreleasePool"), "new")
|
||||
self.app = self.send(self.cls("NSApplication"), "sharedApplication")
|
||||
self.send(self.app, "setActivationPolicy:", 0, types=(c.c_long,), result=c.c_bool)
|
||||
if self.send(self.app, "activationPolicy", result=c.c_long) != 0:
|
||||
raise OSError("No desktop application session")
|
||||
image = self.send(self.send(self.cls("NSImage"), "alloc"), "initWithContentsOfFile:",
|
||||
self.string(str(icon)), types=(c.c_void_p,))
|
||||
if not image:
|
||||
raise OSError("Dock image unavailable")
|
||||
self.send(self.app, "setApplicationIconImage:", image, types=(c.c_void_p,), result=None)
|
||||
delegate_class = self.objc.objc_allocateClassPair(self.cls("NSObject"), b"NanobotDock", 0)
|
||||
|
||||
def open_page(_self: int, _cmd: int, _sender: int) -> None:
|
||||
url = self.clients.current_url()
|
||||
if url is None:
|
||||
return
|
||||
target = self.send(self.cls("NSURL"), "URLWithString:", self.string(url), types=(c.c_void_p,))
|
||||
workspace = self.send(self.cls("NSWorkspace"), "sharedWorkspace")
|
||||
if not self.send(workspace, "openURL:", target, types=(c.c_void_p,), result=c.c_bool):
|
||||
alert = self.send(self.cls("NSAlert"), "new")
|
||||
self.send(alert, "setMessageText:", self.string("Could not open the browser"),
|
||||
types=(c.c_void_p,), result=None)
|
||||
self.send(alert, "setInformativeText:", self.string("Use the WebUI link in your terminal."),
|
||||
types=(c.c_void_p,), result=None)
|
||||
self.send(alert, "runModal", result=c.c_long)
|
||||
|
||||
def reopen(_self: int, _cmd: int, sender: int, _visible: bool) -> bool:
|
||||
open_page(_self, _cmd, sender)
|
||||
return False
|
||||
|
||||
for selector, callback, signature, result, arguments in (
|
||||
("openPage:", open_page, b"v@:@", None, (c.c_void_p,)),
|
||||
("applicationShouldHandleReopen:hasVisibleWindows:", reopen, b"B@:@B",
|
||||
c.c_bool, (c.c_void_p, c.c_bool)),
|
||||
):
|
||||
wrapped = c.CFUNCTYPE(result, c.c_void_p, c.c_void_p, *arguments)(callback)
|
||||
self.callbacks.append(wrapped) # Objective-C does not retain Python callbacks.
|
||||
if not self.objc.class_addMethod(delegate_class, self.selector(selector),
|
||||
c.cast(wrapped, c.c_void_p), signature):
|
||||
raise OSError("Dock delegate unavailable")
|
||||
self.objc.objc_registerClassPair(delegate_class)
|
||||
self.delegate = self.send(delegate_class, "new")
|
||||
self.send(self.app, "setDelegate:", self.delegate, types=(c.c_void_p,), result=None)
|
||||
menu = self.send(self.cls("NSMenu"), "new")
|
||||
for title, action, key, target in (
|
||||
("Open nanobot", "openPage:", "o", self.delegate),
|
||||
("Hide Dock Icon", "terminate:", "q", self.app),
|
||||
):
|
||||
item = self.send(self.send(self.cls("NSMenuItem"), "alloc"),
|
||||
"initWithTitle:action:keyEquivalent:", self.string(title),
|
||||
self.selector(action), self.string(key),
|
||||
types=(c.c_void_p, c.c_void_p, c.c_void_p))
|
||||
self.send(item, "setTarget:", target, types=(c.c_void_p,), result=None)
|
||||
self.send(menu, "addItem:", item, types=(c.c_void_p,), result=None)
|
||||
root = self.send(self.cls("NSMenuItem"), "new")
|
||||
self.send(root, "setSubmenu:", menu, types=(c.c_void_p,), result=None)
|
||||
bar = self.send(self.cls("NSMenu"), "new")
|
||||
self.send(bar, "addItem:", root, types=(c.c_void_p,), result=None)
|
||||
self.send(self.app, "setMainMenu:", bar, types=(c.c_void_p,), result=None)
|
||||
self.send(self.app, "finishLaunching", result=None)
|
||||
|
||||
def cls(self, name: str) -> int:
|
||||
return self.objc.objc_getClass(name.encode())
|
||||
|
||||
def selector(self, name: str) -> int:
|
||||
return self.objc.sel_registerName(name.encode())
|
||||
|
||||
def string(self, value: str) -> int:
|
||||
return self.send(self.cls("NSString"), "stringWithUTF8String:", value.encode(), types=(c.c_char_p,))
|
||||
|
||||
def send(self, target: int, selector: str, *args: object,
|
||||
types: tuple[Any, ...] = (), result: Any = c.c_void_p) -> Any:
|
||||
# Give every objc_msgSend its actual ABI. Its variadic C declaration is
|
||||
# not sufficient on Apple Silicon (and pointers must not truncate).
|
||||
function = c.CFUNCTYPE(result, c.c_void_p, c.c_void_p, *types)(("objc_msgSend", self.objc))
|
||||
return function(target, self.selector(selector), *args)
|
||||
|
||||
def stop(self) -> None:
|
||||
pool = self.send(self.cls("NSAutoreleasePool"), "new")
|
||||
self.send(self.app, "performSelectorOnMainThread:withObject:waitUntilDone:",
|
||||
self.selector("terminate:"), None, False,
|
||||
types=(c.c_void_p, c.c_void_p, c.c_bool), result=None)
|
||||
self.send(pool, "drain", result=None)
|
||||
|
||||
def run(self) -> None:
|
||||
self.send(self.app, "run", result=None)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if sys.platform != "darwin" or len(sys.argv) != 4:
|
||||
raise SystemExit(64)
|
||||
listener = socket.socket(fileno=int(sys.argv[1]))
|
||||
if (listener.family != socket.AF_UNIX or listener.type != socket.SOCK_STREAM
|
||||
or listener.getsockname() != sys.argv[2]):
|
||||
raise SystemExit(64)
|
||||
clients = _Clients()
|
||||
app = _AppKit(Path(sys.argv[3]), clients)
|
||||
threading.Thread(target=_serve, args=(listener, Path(sys.argv[2]), clients, app.stop), daemon=True).start()
|
||||
app.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -19,6 +19,7 @@ from nanobot.cli.runtime_config import (
|
||||
_model_display,
|
||||
_print_agent_start_error,
|
||||
)
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
console = Console()
|
||||
|
||||
@@ -117,6 +118,20 @@ def agent(
|
||||
raise typer.Exit(exit_code)
|
||||
return
|
||||
|
||||
from nanobot.config.home import get_home_path
|
||||
from nanobot.config.loader import get_config_path
|
||||
from nanobot.config.paths import get_data_dir
|
||||
from nanobot.data_access import data_access, profile_data_paths
|
||||
|
||||
paths = profile_data_paths(home=get_home_path(), data_dir=get_data_dir(),
|
||||
config=get_config_path(), workspace=runtime_config.workspace_path)
|
||||
with data_access(paths):
|
||||
_run_classic(runtime_config, message=message, session_id=session_id, markdown=markdown, logs=logs)
|
||||
|
||||
|
||||
def _run_classic(runtime_config: Config, *, message: str | None, session_id: str | None,
|
||||
markdown: bool, logs: bool) -> None:
|
||||
"""Keep the data lease through writer initialization, execution and cleanup."""
|
||||
from nanobot.agent.hooks import create_file_edit_activity_hook
|
||||
from nanobot.agent.tools.image_generation import register_image_generation_tool
|
||||
from nanobot.agent.tools.mcp import MCPProvider
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Dock artwork
|
||||
|
||||
`dock-icon.png` is a deterministic composition of the existing MIT-licensed nanobot cat from `webui/public/brand/nanobot_icon_512.png` (SHA-256 `d4cf9edb3c30b9e43d02fcd9974c87a8046afbf1b13903c68100ab510bd2cd41`). The cat is uniformly scaled without redrawing or recoloring. The user-approved design uses a 1024-pixel canvas, an 824-pixel rounded white tile at (100, 100), and a 656-pixel cat at (184, 168). Its optical center is 16 pixels below the tile center; shadows are separate from the original art.
|
||||
|
||||
The packaged helper loads this PNG through AppKit. It needs neither a generated application executable nor an icon compiler at installation or launch. Keep artwork changes independent of the WebUI brand asset and of gateway lifecycle policy.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 225 KiB |
@@ -57,6 +57,7 @@ from nanobot.cli.runtime_config import ( # noqa: E402
|
||||
_print_model_setup_steps,
|
||||
_provider_setup_error,
|
||||
)
|
||||
from nanobot.cli.update import update # noqa: E402
|
||||
from nanobot.cli.webui import webui # noqa: E402
|
||||
from nanobot.cli.webui_support import ( # noqa: E402
|
||||
_prepare_webui_bundle_for_gateway,
|
||||
@@ -96,6 +97,7 @@ app = typer.Typer(
|
||||
)
|
||||
|
||||
console = Console()
|
||||
app.command()(update)
|
||||
|
||||
# Server-console pairing stays outside the agent/gateway lifecycle.
|
||||
from nanobot.cli.remote import app as remote_app # noqa: E402
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Best-effort macOS Dock presence for local WebUI clients and gateways.
|
||||
|
||||
The icon owns no gateway lease or user data. Open local sockets keep one helper
|
||||
alive; the OS closes them even when a launcher is killed. Everything executable
|
||||
comes from the current installation, never a download or generated shell script.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
import plistlib
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from collections.abc import Generator
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
from uuid import uuid4
|
||||
|
||||
from filelock import FileLock
|
||||
from loguru import logger
|
||||
|
||||
_WORKER = Path(__file__).with_name("_macos_dock.py")
|
||||
_ICON = Path(__file__).with_name("assets") / "dock-icon.png"
|
||||
_STARTUP_TIMEOUT = 10
|
||||
|
||||
|
||||
def _desktop_available() -> bool:
|
||||
if sys.platform != "darwin" or any(os.environ.get(key) for key in (
|
||||
"SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY",
|
||||
)):
|
||||
return False
|
||||
try:
|
||||
return os.getuid() != 0 and Path("/dev/console").stat().st_uid == os.getuid()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _private_directory(path: Path) -> None:
|
||||
path.mkdir(mode=0o700, exist_ok=True)
|
||||
info = path.lstat()
|
||||
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
|
||||
raise PermissionError("Dock directory must be private to this user")
|
||||
|
||||
|
||||
def _directory(instance: Path, url: str) -> Path:
|
||||
# Keep AF_UNIX paths short and isolate installations, instances and dev URLs.
|
||||
# macOS AF_UNIX addresses are limited to 104 bytes. TMPDIR can be an arbitrary
|
||||
# long path (including during isolated update acceptance); this directory is
|
||||
# private, owner-checked and contains neither the URL nor user data.
|
||||
root = Path("/tmp") / f"nanobot-dock-{os.getuid()}"
|
||||
_private_directory(root)
|
||||
origin = urlsplit(url)._replace(query="", fragment="").geturl()
|
||||
identity = "\0".join((str(instance), sys.executable, str(_WORKER), origin)).encode()
|
||||
digest = hashlib.sha256(identity + _WORKER.read_bytes() + _ICON.read_bytes()).hexdigest()
|
||||
directory = root / digest[:12]
|
||||
_private_directory(directory)
|
||||
return directory
|
||||
|
||||
|
||||
def _bundle(directory: Path) -> Path:
|
||||
"""Give the existing interpreter a Dock identity, without copying its runtime."""
|
||||
contents = directory / "nanobot.app" / "Contents"
|
||||
executable = contents / "MacOS" / "nanobot"
|
||||
executable.parent.mkdir(parents=True, exist_ok=True)
|
||||
resources = contents / "Resources"
|
||||
resources.mkdir(exist_ok=True)
|
||||
if not executable.is_symlink():
|
||||
executable.symlink_to(sys.executable)
|
||||
elif os.readlink(executable) != sys.executable:
|
||||
raise ValueError("Dock interpreter does not match this installation")
|
||||
shutil.copyfile(_ICON, resources / "dock-icon.png")
|
||||
(contents / "Info.plist").write_bytes(plistlib.dumps({
|
||||
"CFBundleExecutable": "nanobot",
|
||||
"CFBundleIdentifier": f"dev.nanobot.webui.{directory.name}",
|
||||
"CFBundleName": "nanobot",
|
||||
"CFBundleDisplayName": "nanobot",
|
||||
"CFBundlePackageType": "APPL",
|
||||
"CFBundleIconFile": "dock-icon.png",
|
||||
"LSMinimumSystemVersion": "13.0",
|
||||
"NSHighResolutionCapable": True,
|
||||
}))
|
||||
return executable
|
||||
|
||||
|
||||
def _connect(address: Path) -> socket.socket | None:
|
||||
connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
connection.settimeout(2)
|
||||
try:
|
||||
connection.connect(str(address))
|
||||
return connection
|
||||
except (FileNotFoundError, ConnectionRefusedError):
|
||||
connection.close()
|
||||
return None
|
||||
except OSError:
|
||||
connection.close()
|
||||
raise
|
||||
|
||||
|
||||
def _attach(directory: Path, url: str) -> socket.socket:
|
||||
address = directory / "s"
|
||||
process: subprocess.Popen[bytes] | None = None
|
||||
connection: socket.socket | None = None
|
||||
with FileLock(str(directory / "start.lock"), timeout=_STARTUP_TIMEOUT):
|
||||
try:
|
||||
connection = _connect(address)
|
||||
if connection is None:
|
||||
if address.exists():
|
||||
if not stat.S_ISSOCK(address.lstat().st_mode):
|
||||
raise ValueError("Unexpected Dock socket path")
|
||||
address.unlink()
|
||||
executable = _bundle(directory)
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener:
|
||||
listener.bind(str(address))
|
||||
listener.listen()
|
||||
process = subprocess.Popen(
|
||||
[str(executable), "-I", "-S", str(_WORKER), str(listener.fileno()),
|
||||
str(address), str(_ICON)],
|
||||
pass_fds=(listener.fileno(),), stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
)
|
||||
# Reap our child without making its lifetime depend on this thread.
|
||||
threading.Thread(target=process.wait, daemon=True).start()
|
||||
connection = _connect(address)
|
||||
if connection is None:
|
||||
raise OSError("Dock helper did not start")
|
||||
# Connecting to the inherited listener is immediate, but the helper
|
||||
# loads AppKit before acknowledging readiness. A cold post-update
|
||||
# launch can exceed the short socket-connect deadline. Keep this
|
||||
# bounded off the gateway event loop, including concurrent joiners.
|
||||
connection.settimeout(_STARTUP_TIMEOUT)
|
||||
# Credentials stay in the private local socket, never argv or a file.
|
||||
connection.sendall(url.encode("utf-8") + b"\n")
|
||||
if connection.recv(1) != b"1":
|
||||
raise OSError("Dock helper did not become ready")
|
||||
return connection
|
||||
except BaseException:
|
||||
# Ctrl-C can arrive during startup, before the context owns this socket.
|
||||
# Clean up the new helper too, then propagate the original interruption.
|
||||
if connection is not None:
|
||||
connection.close()
|
||||
if process is not None and process.poll() is None:
|
||||
process.terminate()
|
||||
raise
|
||||
|
||||
|
||||
@contextmanager
|
||||
def dock_icon(url: str, *, instance: Path, enabled: bool = True) -> Generator[None]:
|
||||
"""Show a shared icon while this WebUI launcher is attached; never own its service."""
|
||||
connection: socket.socket | None = None
|
||||
if enabled and _desktop_available():
|
||||
from nanobot.cli._macos_dock import is_local_browser_url
|
||||
|
||||
try:
|
||||
if is_local_browser_url(url):
|
||||
connection = _attach(_directory(instance, url), url)
|
||||
except (OSError, ValueError, TimeoutError) as exc:
|
||||
# Do not include exception text: URL/installation details are private.
|
||||
logger.debug("Dock startup failure category: {}", type(exc).__name__)
|
||||
logger.warning("Dock icon unavailable; WebUI can still be used in your browser.")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if connection is not None:
|
||||
connection.close()
|
||||
|
||||
|
||||
def request_gateway_icon(instance: Path, *, enabled: bool) -> None:
|
||||
"""Remember desktop intent, not a service lease, credential, or restart command."""
|
||||
if not _desktop_available():
|
||||
return
|
||||
from nanobot.utils.atomic_file import atomic_write_text
|
||||
|
||||
try:
|
||||
instance.parent.mkdir(parents=True, exist_ok=True)
|
||||
atomic_write_text(instance.with_suffix(".dock"), f"{'show' if enabled else 'hide'}:{uuid4().hex}")
|
||||
except OSError:
|
||||
logger.warning("Dock preference unavailable; WebUI can still be used in your browser.")
|
||||
|
||||
|
||||
def _watch_gateway_icon(url: str, instance: Path, stopped: threading.Event) -> None:
|
||||
"""One bounded native handshake off the event loop for each explicit request."""
|
||||
selected = ""
|
||||
presence = ExitStack()
|
||||
try:
|
||||
while not stopped.is_set():
|
||||
try:
|
||||
with instance.with_suffix(".dock").open(encoding="ascii") as stream:
|
||||
request = stream.read(64)
|
||||
except (OSError, UnicodeError):
|
||||
request = ""
|
||||
if request != selected:
|
||||
replacement = ExitStack()
|
||||
if request.startswith("show:"):
|
||||
# Join before releasing our old connection, so reopening the
|
||||
# launcher cannot race the last-client cleanup of a live icon.
|
||||
replacement.enter_context(dock_icon(url, instance=instance))
|
||||
presence.close()
|
||||
presence = replacement
|
||||
selected = request
|
||||
stopped.wait(0.5)
|
||||
finally:
|
||||
presence.close()
|
||||
|
||||
|
||||
async def watch_gateway_icon(url: str, *, instance: Path, activated: asyncio.Event) -> None:
|
||||
"""Own optional Dock presence only after ordinary/protected startup is activated.
|
||||
|
||||
The persisted request lets an existing gateway observe a detached launcher and
|
||||
lets the next gateway generation restore it. No updater or data format changes.
|
||||
Quitting the icon is respected until another explicit request or service start.
|
||||
"""
|
||||
if not _desktop_available():
|
||||
return
|
||||
await activated.wait()
|
||||
stopped = threading.Event()
|
||||
watcher = asyncio.create_task(asyncio.to_thread(_watch_gateway_icon, url, instance, stopped))
|
||||
try:
|
||||
await asyncio.shield(watcher)
|
||||
finally:
|
||||
stopped.set()
|
||||
# Never leave a still-starting helper behind when the gateway is cancelled.
|
||||
await watcher
|
||||
+53
-4
@@ -7,8 +7,7 @@ import sys
|
||||
from contextlib import suppress
|
||||
|
||||
from nanobot.cli.process_identity import set_cli_process_identity
|
||||
from nanobot.utils.log_config import configure_console_logging
|
||||
from nanobot.utils.rotating_output import configure_background_output_from_env
|
||||
from nanobot.installation_lock import InstallationBusyError, installation_access
|
||||
|
||||
_ROOT_OPTIONS = frozenset(
|
||||
{
|
||||
@@ -48,7 +47,8 @@ def _native_tui_candidate(args: list[str]) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _configure_windows_console() -> None:
|
||||
def configure_windows_console() -> None:
|
||||
"""Keep multilingual output usable for CLI and protected gateway startup."""
|
||||
if sys.platform != "win32" or sys.stdout.encoding == "utf-8":
|
||||
return
|
||||
os.environ["PYTHONIOENCODING"] = "utf-8"
|
||||
@@ -61,6 +61,8 @@ def _configure_windows_console() -> None:
|
||||
|
||||
def _run_agent(args: list[str], *, prog_name: str) -> None:
|
||||
"""Run the shared agent command without importing the complete CLI graph."""
|
||||
from nanobot.utils.log_config import configure_console_logging
|
||||
|
||||
configure_console_logging(sys.stderr)
|
||||
import typer
|
||||
|
||||
@@ -72,8 +74,46 @@ def _run_agent(args: list[str], *, prog_name: str) -> None:
|
||||
command.main(args=args, prog_name=prog_name)
|
||||
|
||||
|
||||
def _command_args(args: list[str]) -> list[str]:
|
||||
"""Skip only global home selectors, not arguments belonging to a subcommand."""
|
||||
position = 0
|
||||
while position < len(args):
|
||||
argument = args[position]
|
||||
if argument == "--home":
|
||||
position += 2
|
||||
elif argument.startswith("--home="):
|
||||
position += 1
|
||||
else:
|
||||
return args[position:]
|
||||
return []
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Acquire a runtime lease before loading application code."""
|
||||
args = _command_args(sys.argv[1:])
|
||||
saved_update = args[:1] == ["update"] and any(argument.split("=", 1)[0] == "--job" for argument in args[1:])
|
||||
if args[:1] == ["update"] and not saved_update:
|
||||
# The update entrypoint takes its own exclusive lease only for execution.
|
||||
# Saved pre-mutation recovery instead owns a read lease before imports;
|
||||
# its detached worker can replace files only after this process exits.
|
||||
_dispatch()
|
||||
return
|
||||
try:
|
||||
# Keep the repair/stop path usable after an interrupted older updater.
|
||||
# These commands still take a lease and cannot run during a live install.
|
||||
diagnostics = args[:1] in (["--help"], ["-h"], ["--version"], ["-v"])
|
||||
stop_or_inspect = args[:2] in (["gateway", "stop"], ["gateway", "status"], ["gateway", "logs"])
|
||||
with installation_access(allow_incomplete=diagnostics or stop_or_inspect):
|
||||
_dispatch()
|
||||
except InstallationBusyError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
raise SystemExit(1) from exc
|
||||
|
||||
|
||||
def _dispatch() -> None:
|
||||
"""Dispatch native TUI startup without importing the complete CLI graph."""
|
||||
from nanobot.utils.rotating_output import configure_background_output_from_env
|
||||
|
||||
configure_background_output_from_env()
|
||||
raw_args = sys.argv[1:]
|
||||
# Installed completion scripts call ``nanobot`` without positional arguments
|
||||
@@ -83,7 +123,16 @@ def main() -> None:
|
||||
agent_args = None if shell_completion else _agent_invocation_args(raw_args)
|
||||
dispatch_args = ["agent", *agent_args] if agent_args is not None else raw_args
|
||||
set_cli_process_identity(dispatch_args)
|
||||
_configure_windows_console()
|
||||
configure_windows_console()
|
||||
if not shell_completion and raw_args[:1] == ["update"]:
|
||||
import typer
|
||||
|
||||
from nanobot.cli.update import update
|
||||
|
||||
update_app = typer.Typer(add_completion=False)
|
||||
update_app.command()(update)
|
||||
typer.main.get_command(update_app).main(args=raw_args[1:], prog_name="nanobot update")
|
||||
return
|
||||
if not shell_completion and not raw_args:
|
||||
from nanobot.cli.desktop_target import dispatch_bare_desktop_target
|
||||
|
||||
|
||||
@@ -241,6 +241,7 @@ def create_gateway_app(
|
||||
run_gateway(
|
||||
cfg,
|
||||
port=port,
|
||||
verbose=verbose,
|
||||
webui_bundle_mode=interactive_build_mode(),
|
||||
unconfigured_provider_error=unconfigured_provider_error,
|
||||
gateway_instance=instance,
|
||||
|
||||
+105
-21
@@ -3,11 +3,11 @@
|
||||
import asyncio
|
||||
import signal
|
||||
from collections.abc import Awaitable, Callable, Coroutine, Iterable
|
||||
from contextlib import suppress
|
||||
from dataclasses import replace
|
||||
from contextlib import ExitStack, suppress
|
||||
from dataclasses import asdict, replace
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import typer
|
||||
from loguru import logger
|
||||
@@ -26,6 +26,7 @@ from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.cli import terminal as cli_terminal
|
||||
from nanobot.cli.dock import watch_gateway_icon
|
||||
from nanobot.cli.runtime_config import _migrate_cron_store
|
||||
from nanobot.cli.webui_support import (
|
||||
_gateway_health_bind_note,
|
||||
@@ -40,9 +41,10 @@ from nanobot.cli.webui_support import (
|
||||
_webui_display_url,
|
||||
_webui_endpoint_reachable,
|
||||
)
|
||||
from nanobot.config.paths import is_default_workspace
|
||||
from nanobot.config.paths import get_data_dir, is_default_workspace
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.gateway.runtime import GatewayInstance
|
||||
from nanobot.gateway.runtime import GatewayHealthIdentity, GatewayInstance, GatewayRuntime
|
||||
from nanobot.installation_lock import installation_access
|
||||
from nanobot.security.network import is_loopback_host
|
||||
from nanobot.session.keys import (
|
||||
HEARTBEAT_SESSION_KEY,
|
||||
@@ -58,6 +60,10 @@ from nanobot.webui.build import BuildMode
|
||||
from nanobot.webui.dev import WebUIDevError, WebUIDevServer
|
||||
from nanobot.webui.sidebar_state import read_webui_sidebar_state
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.update_profiles import ProfileReceipt
|
||||
from nanobot.update_restart import GatewayStartup
|
||||
|
||||
__all__ = ["_run_gateway"]
|
||||
|
||||
console = Console()
|
||||
@@ -414,6 +420,7 @@ def _run_gateway(
|
||||
config: Config,
|
||||
*,
|
||||
port: int | None = None,
|
||||
verbose: bool = False,
|
||||
open_browser_url: str | None = None,
|
||||
open_browser_ready_url: str | None = None,
|
||||
webui_static_dist: bool = True,
|
||||
@@ -424,8 +431,61 @@ def _run_gateway(
|
||||
unconfigured_provider_error: str | None = None,
|
||||
webui_dev_server: WebUIDevServer | None = None,
|
||||
gateway_instance: GatewayInstance | None = None,
|
||||
update_startup: "GatewayStartup | None" = None,
|
||||
) -> None:
|
||||
"""Shared gateway runtime; ``open_browser_url`` opens a tab once channels are up."""
|
||||
"""Claim the installation and profile before initializing any runtime writers."""
|
||||
from nanobot.config.loader import get_config_path
|
||||
from nanobot.update_profiles import record_gateway_profile
|
||||
|
||||
port = port if port is not None else config.gateway.port
|
||||
instance = gateway_instance or GatewayInstance.resolve(config_path=get_config_path())
|
||||
gateway_runtime = GatewayRuntime(paths=instance.paths)
|
||||
with installation_access(allow_incomplete=update_startup is not None):
|
||||
if update_startup is not None:
|
||||
update_startup.validate_installation()
|
||||
with (
|
||||
gateway_runtime.foreground_instance(instance.start_options(port=port, verbose=verbose)),
|
||||
record_gateway_profile(instance, gateway_runtime, data_dir=get_data_dir(),
|
||||
workspace=config.workspace_path, port=port, verbose=verbose,
|
||||
grant=update_startup.grant if update_startup else None,
|
||||
cooperative_stop=True) as profile,
|
||||
):
|
||||
if update_startup is not None:
|
||||
update_startup.validate_profile(profile)
|
||||
_run_claimed_gateway(
|
||||
config, port=port, gateway_instance=instance, gateway_runtime=gateway_runtime,
|
||||
health_identity=profile.health_identity, update_startup=update_startup,
|
||||
update_profile=profile,
|
||||
open_browser_url=open_browser_url, open_browser_ready_url=open_browser_ready_url,
|
||||
webui_static_dist=webui_static_dist, webui_bundle_mode=webui_bundle_mode,
|
||||
webui_runtime_surface=webui_runtime_surface,
|
||||
webui_runtime_capabilities=webui_runtime_capabilities,
|
||||
health_server_enabled=health_server_enabled,
|
||||
unconfigured_provider_error=unconfigured_provider_error,
|
||||
webui_dev_server=webui_dev_server,
|
||||
)
|
||||
|
||||
|
||||
def _run_claimed_gateway(
|
||||
config: Config,
|
||||
*,
|
||||
port: int,
|
||||
gateway_instance: GatewayInstance,
|
||||
gateway_runtime: GatewayRuntime,
|
||||
health_identity: GatewayHealthIdentity,
|
||||
open_browser_url: str | None,
|
||||
open_browser_ready_url: str | None,
|
||||
webui_static_dist: bool,
|
||||
webui_bundle_mode: BuildMode,
|
||||
webui_runtime_surface: str,
|
||||
webui_runtime_capabilities: dict[str, Any] | None,
|
||||
health_server_enabled: bool,
|
||||
unconfigured_provider_error: str | None,
|
||||
webui_dev_server: WebUIDevServer | None,
|
||||
update_startup: "GatewayStartup | None" = None,
|
||||
update_profile: "ProfileReceipt | None" = None,
|
||||
) -> None:
|
||||
"""Initialize and run only while the caller holds the gateway lifecycle claim."""
|
||||
from nanobot.agent.model_presets import load_model_preset_catalog
|
||||
from nanobot.agent.tools.message import MessageTool
|
||||
from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
@@ -455,7 +515,6 @@ def _run_gateway(
|
||||
from nanobot.triggers.local_store import LocalTriggerStore
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
|
||||
port = port if port is not None else config.gateway.port
|
||||
webui_url = _webui_browser_url(config)
|
||||
gateway_host_for_browser = _host_for_local_browser(config.gateway.host)
|
||||
if health_server_enabled and _tcp_endpoint_reachable(gateway_host_for_browser, port):
|
||||
@@ -514,19 +573,12 @@ def _run_gateway(
|
||||
session_manager = SessionManager(config.workspace_path)
|
||||
|
||||
# Use the same runtime identity for foreground and managed gateway processes.
|
||||
from nanobot.config.loader import get_config_path
|
||||
from nanobot.gateway.runtime import (
|
||||
GatewayClientLease,
|
||||
GatewayRuntime,
|
||||
monitor_gateway_clients,
|
||||
)
|
||||
|
||||
instance = gateway_instance or GatewayInstance.resolve(
|
||||
config_path=get_config_path(),
|
||||
)
|
||||
config_path = str(instance.config_path)
|
||||
gateway_runtime = GatewayRuntime(paths=instance.paths)
|
||||
gateway_start_options = instance.start_options(port=port)
|
||||
config_path = str(gateway_instance.config_path)
|
||||
|
||||
# Preserve existing single-workspace installs, but keep custom workspaces clean.
|
||||
if is_default_workspace(config.workspace_path):
|
||||
@@ -534,7 +586,7 @@ def _run_gateway(
|
||||
|
||||
# Create cron service with workspace-scoped store
|
||||
cron_store_path = config.workspace_path / "cron" / "jobs.json"
|
||||
cron = CronService(cron_store_path)
|
||||
cron = CronService(cron_store_path, admission=bus.admission)
|
||||
trigger_store = LocalTriggerStore(config.workspace_path)
|
||||
|
||||
webui_route_policy = WebuiTurnRoutePolicy(session_manager)
|
||||
@@ -851,6 +903,8 @@ def _run_gateway(
|
||||
|
||||
if method == "GET" and path == "/health":
|
||||
ready, payload = _gateway_readiness_payload(channels)
|
||||
payload["runtime"] = asdict(health_identity)
|
||||
payload["maintenance"] = bus.admission.paused
|
||||
body = _json.dumps(payload)
|
||||
status = "200 OK" if ready else "503 Service Unavailable"
|
||||
content_type = "application/json"
|
||||
@@ -957,6 +1011,8 @@ def _run_gateway(
|
||||
console.print(f"[yellow]Could not open browser ({e}); visit {display_url}[/yellow]")
|
||||
|
||||
async def run() -> None:
|
||||
startup_gate = ExitStack()
|
||||
desktop_activated = asyncio.Event()
|
||||
tasks: list[asyncio.Task[Any]] = []
|
||||
shutdown_task: asyncio.Task[Any] | None = None
|
||||
runtime_tasks: asyncio.Future[list[Any]] | None = None
|
||||
@@ -971,15 +1027,20 @@ def _run_gateway(
|
||||
)
|
||||
try:
|
||||
await agent.subagents.recover_interrupted()
|
||||
await cron.start()
|
||||
# Re-read once on first admission to close the watcher subscription window.
|
||||
agent.runtime_resolver.invalidate()
|
||||
# Recovery must finish before WebSocket and other channels begin
|
||||
# accepting new input. That makes a new user message reliably
|
||||
# supersede an old recoverable turn instead of racing its queue.
|
||||
await recovery.scan()
|
||||
if update_startup is not None:
|
||||
# Recovery may reconstruct queued work, but no consumer or
|
||||
# external listener has started. Keep that work parked too.
|
||||
startup_gate.enter_context(bus.admission.pause_before_start())
|
||||
await cron.start()
|
||||
async def _run_agent() -> None:
|
||||
try:
|
||||
await bus.admission.wait_until_open()
|
||||
await mcp_provider.connect()
|
||||
await agent.run()
|
||||
finally:
|
||||
@@ -1012,6 +1073,7 @@ def _run_gateway(
|
||||
store=trigger_store,
|
||||
submit_turn=agent.submit_local_trigger_turn,
|
||||
is_channel_enabled=lambda name: channels.get_channel(name) is not None,
|
||||
admission=bus.admission,
|
||||
),
|
||||
name="nanobot-local-triggers",
|
||||
),
|
||||
@@ -1020,6 +1082,28 @@ def _run_gateway(
|
||||
name="nanobot-gateway-client-monitor",
|
||||
),
|
||||
])
|
||||
if update_startup is not None:
|
||||
async def activate(startup: "GatewayStartup") -> None:
|
||||
await startup.wait_for_activation(health_identity)
|
||||
startup_gate.close()
|
||||
desktop_activated.set()
|
||||
|
||||
tasks.append(asyncio.create_task(activate(update_startup), name="nanobot-update-activation"))
|
||||
else:
|
||||
desktop_activated.set()
|
||||
if _webui_channel_enabled(config):
|
||||
tasks.append(asyncio.create_task(
|
||||
watch_gateway_icon(webui_url, instance=gateway_instance.paths.state_path,
|
||||
activated=desktop_activated),
|
||||
name="nanobot-dock",
|
||||
))
|
||||
if update_profile is not None:
|
||||
from nanobot.update_stop import watch_gateway_stop
|
||||
|
||||
tasks.append(asyncio.create_task(
|
||||
watch_gateway_stop(update_profile, agent.maintenance, shutdown_event, startup_gate),
|
||||
name="nanobot-update-stop",
|
||||
))
|
||||
if health_server_enabled:
|
||||
tasks.append(asyncio.create_task(
|
||||
_health_server(config.gateway.host, port),
|
||||
@@ -1085,12 +1169,12 @@ def _run_gateway(
|
||||
)
|
||||
await bus.drain()
|
||||
finally:
|
||||
# On a failed/aborted startup, keep intake closed until all
|
||||
# runtime consumers have been cancelled and cleanup finished.
|
||||
startup_gate.close()
|
||||
restore_shutdown_handlers()
|
||||
|
||||
with (
|
||||
gateway_runtime.foreground_instance(gateway_start_options),
|
||||
webui_turn_coordinator.connected(),
|
||||
):
|
||||
with webui_turn_coordinator.connected():
|
||||
if health_server_enabled:
|
||||
gateway_runtime.publish_health_host(config.gateway.host)
|
||||
asyncio.run(run())
|
||||
+16
-13
@@ -17,6 +17,7 @@ from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from nanobot import __version__
|
||||
from nanobot.bun import BunUnavailableError, bun_environment, ensure_bun
|
||||
from nanobot.cli.process_identity import named_executable
|
||||
from nanobot.cli.runtime_config import _model_display
|
||||
from nanobot.cli.webui_support import (
|
||||
@@ -187,12 +188,12 @@ def resolve_tui_command(*, data_dir: Path | None = None) -> list[str]:
|
||||
asset = f"nanobot-tui-{system}-{machine}{suffix}"
|
||||
source_dir = _source_checkout_tui_dir()
|
||||
if source_dir is not None:
|
||||
bun = shutil.which("bun")
|
||||
if not bun:
|
||||
raise TuiUnavailableError(
|
||||
"this source checkout requires Bun to run its matching TUI; "
|
||||
"install Bun, then run `nanobot agent` again"
|
||||
)
|
||||
try:
|
||||
bun = ensure_bun()
|
||||
except BunUnavailableError as exc:
|
||||
available = shutil.which("bun")
|
||||
hint = f" (Bun found at {available!r} but could not be used)" if available else ""
|
||||
raise TuiUnavailableError(f"{exc}{hint}") from exc
|
||||
return _resolve_source_tui_command(source_dir, bun, data_dir=data_dir)
|
||||
|
||||
packaged = Path(__file__).resolve().parents[1] / "tui" / "bin" / asset
|
||||
@@ -229,13 +230,15 @@ def _resolve_source_tui_command(
|
||||
) -> list[str]:
|
||||
dependency = source_dir / "node_modules" / "@opentui" / "core"
|
||||
try:
|
||||
install = subprocess.run(
|
||||
[bun, "install", "--frozen-lockfile"],
|
||||
cwd=source_dir,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
with bun_environment(bun) as env:
|
||||
install = subprocess.run(
|
||||
[bun, "install", "--frozen-lockfile"],
|
||||
cwd=source_dir,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
env=env,
|
||||
)
|
||||
except OSError as exc:
|
||||
raise TuiUnavailableError(f"could not install TUI dependencies: {exc}") from exc
|
||||
if install.returncode != 0 or not dependency.is_dir():
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Command-line updates for release and source installations."""
|
||||
|
||||
import asyncio
|
||||
import subprocess
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
import typer
|
||||
|
||||
|
||||
def update(
|
||||
dev: bool = typer.Option(False, "--dev", "--update-dev", help="Install or update an editable source checkout and build its WebUI."),
|
||||
check: bool = typer.Option(False, "--check", help="Check the latest stable release without installing."),
|
||||
allow_downgrade: bool = typer.Option(False, "--allow-downgrade", help="Allow an intentional return to an older stable release. Back up data first."),
|
||||
plan: bool = typer.Option(False, "--plan", help="Save an exact release plan without installing or restarting."),
|
||||
channel: Literal["stable", "preview"] | None = typer.Option(None, "--channel", help="Release channel to inspect with --plan (default: saved subscription)."),
|
||||
job: str | None = typer.Option(None, "--job", help="Read an exact saved job in this installation; does not install."),
|
||||
retry_handoff: bool = typer.Option(False, "--retry-handoff", help="With --job, explicitly retry shutdown before package mutation."),
|
||||
previous_confirmation: str | None = typer.Option(None, "--previous-confirmation", help="The execution confirmation from the job being retried."),
|
||||
confirm_restart: bool = typer.Option(False, "--confirm-restart", help="Confirm the saved plan's shutdown, installation and restart."),
|
||||
) -> None:
|
||||
"""Update nanobot in the current Python environment."""
|
||||
if job is not None or retry_handoff or previous_confirmation is not None or confirm_restart:
|
||||
if job is None or dev or check or allow_downgrade or plan or channel is not None:
|
||||
raise typer.BadParameter("Use --job separately from release selection and legacy update flags.")
|
||||
if retry_handoff != (previous_confirmation is not None and confirm_restart):
|
||||
raise typer.BadParameter("Retry requires --retry-handoff, --previous-confirmation and --confirm-restart together.")
|
||||
if not retry_handoff and (previous_confirmation is not None or confirm_restart):
|
||||
raise typer.BadParameter("Reading --job cannot authorize a restart.")
|
||||
_saved_job(job, previous_confirmation if retry_handoff else None)
|
||||
return
|
||||
|
||||
from nanobot import __version__
|
||||
from nanobot.update import latest_release, update_installation
|
||||
|
||||
if plan:
|
||||
if dev or check or allow_downgrade:
|
||||
raise typer.BadParameter("Use --plan with --channel, without execution flags.")
|
||||
from nanobot.update_plan import describe_plan, preview_release_update
|
||||
|
||||
try:
|
||||
typer.echo(describe_plan(asyncio.run(preview_release_update(channel))))
|
||||
except (RuntimeError, OSError, ValueError, subprocess.SubprocessError, httpx.HTTPError) as exc:
|
||||
typer.echo(f"Could not prepare update plan: {exc}", err=True)
|
||||
raise typer.Exit(1) from exc
|
||||
return
|
||||
if channel is not None:
|
||||
raise typer.BadParameter("Channel inspection requires --plan; confirm channel-aware installation in Settings → About.")
|
||||
|
||||
if check and dev:
|
||||
raise typer.BadParameter("--check checks PyPI releases; use it without --dev.")
|
||||
try:
|
||||
if check:
|
||||
from nanobot.installation_lock import installation_access
|
||||
|
||||
with installation_access():
|
||||
typer.echo(f"Installed: {__version__}\nLatest release: {latest_release()}")
|
||||
return
|
||||
result = update_installation(dev=dev, allow_downgrade=allow_downgrade, output=typer.echo)
|
||||
except (RuntimeError, OSError, ValueError) as exc:
|
||||
typer.echo(f"Update failed: {exc}", err=True)
|
||||
raise typer.Exit(1) from exc
|
||||
if result["requires_restart"]:
|
||||
typer.echo(f"Installed nanobot {result['version']}. Restart nanobot to use it; the running process has not been verified.")
|
||||
else:
|
||||
typer.echo(f"nanobot {result['version']} is already installed. No files changed.")
|
||||
|
||||
|
||||
def _saved_job(plan_id: str, previous_confirmation: str | None) -> None:
|
||||
from nanobot.installation_lock import installation_access, installation_state_dir
|
||||
from nanobot.update_jobs import read_update_job, retry_handoff
|
||||
from nanobot.update_service import UpdateRetryRequest
|
||||
|
||||
try:
|
||||
# The console bootstrap also owns this before importing application
|
||||
# dependencies. Do not use this route to repair a mutated environment.
|
||||
with installation_access():
|
||||
job = read_update_job(plan_id)
|
||||
if previous_confirmation is not None:
|
||||
request = UpdateRetryRequest(id=plan_id, previous_confirmation_id=previous_confirmation,
|
||||
confirm_restart=True)
|
||||
retry_handoff(installation_state_dir() / "jobs" / request.id, request.previous_confirmation_id)
|
||||
job = read_update_job(plan_id)
|
||||
typer.echo(job.model_dump_json(indent=2))
|
||||
except (OSError, RuntimeError, ValueError, KeyError) as exc:
|
||||
typer.echo("Could not read or retry this saved handoff. No automatic repair was started.", err=True)
|
||||
raise typer.Exit(1) from exc
|
||||
+45
-1
@@ -1,5 +1,8 @@
|
||||
"""WebUI CLI command."""
|
||||
|
||||
import hashlib
|
||||
import sys
|
||||
from contextlib import ExitStack
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
@@ -7,6 +10,7 @@ from pydantic import ValidationError
|
||||
from rich.console import Console
|
||||
|
||||
from nanobot.cli import terminal as cli_terminal
|
||||
from nanobot.cli.dock import dock_icon, request_gateway_icon
|
||||
from nanobot.cli.runtime_config import (
|
||||
_print_config_error,
|
||||
_print_runtime_config_validation_error,
|
||||
@@ -84,6 +88,8 @@ def webui(
|
||||
help="Run the Vite development server with live frontend updates",
|
||||
),
|
||||
no_open: bool = typer.Option(False, "--no-open", help="Do not open a browser"),
|
||||
no_dock: bool = typer.Option(False, "--no-dock", help="Do not show the macOS Dock icon"),
|
||||
detach: bool = typer.Option(False, "--detach", help="Keep the gateway running and return to the terminal"),
|
||||
yes: bool = typer.Option(
|
||||
False,
|
||||
"--yes",
|
||||
@@ -98,6 +104,14 @@ def webui(
|
||||
GatewayInstance,
|
||||
GatewayRuntime,
|
||||
)
|
||||
from nanobot.installation_receipt import RECEIPT_NAME, managed_extras
|
||||
|
||||
receipt = Path(sys.prefix) / RECEIPT_NAME
|
||||
if receipt.exists() and not dev:
|
||||
managed_extras(str(Path(sys.prefix).resolve()), hashlib.sha256(receipt.read_bytes()).hexdigest())
|
||||
detach = True
|
||||
if detach and dev:
|
||||
raise typer.BadParameter("--detach cannot keep a Vite development server alive")
|
||||
|
||||
cli_terminal._ensure_interactive_tty_mode()
|
||||
config_path = _resolve_webui_config_path(config)
|
||||
@@ -207,7 +221,7 @@ def webui(
|
||||
def announce_ready(url: str, *, managed: bool) -> None:
|
||||
_print_webui_ready(
|
||||
runtime_config, config_path, url, workspace=workspace, dev=dev, managed=managed,
|
||||
provider_error=provider_error,
|
||||
provider_error=provider_error, detached=detach,
|
||||
)
|
||||
if not no_open:
|
||||
_open_webui_browser(url, wait=False)
|
||||
@@ -228,8 +242,31 @@ def webui(
|
||||
)
|
||||
raise typer.Exit(1)
|
||||
|
||||
if detach:
|
||||
status = runtime.status()
|
||||
if existing_gateway and not status.running:
|
||||
raise typer.BadParameter("The existing gateway has another owner; use its launch command")
|
||||
request_gateway_icon(runtime.paths.state_path, enabled=not no_dock)
|
||||
if changed_webui and status.running:
|
||||
result = runtime.restart(start_options, timeout_s=20)
|
||||
if result.ok:
|
||||
# Restart retains the old lifetime; detached launch promotes it.
|
||||
result = runtime.start_background(start_options)
|
||||
else:
|
||||
result = runtime.start_background(start_options)
|
||||
if not result.ok and result.message != "gateway_already_running":
|
||||
console.print(f"[red]Gateway could not start: {result.message}[/red]")
|
||||
raise typer.Exit(1)
|
||||
if not _wait_for_webui(webui_url, timeout_s=20):
|
||||
console.print("[red]WebUI did not become ready. Check the gateway logs.[/red]")
|
||||
console.print(f"Logs: {runtime.paths.log_path}", markup=False)
|
||||
raise typer.Exit(1)
|
||||
announce_ready(webui_url, managed=True)
|
||||
return
|
||||
|
||||
lease = GatewayClientLease(runtime, kind="webui")
|
||||
lease.acquire()
|
||||
desktop = ExitStack()
|
||||
try:
|
||||
if not existing_gateway:
|
||||
console.print("[dim]Starting WebUI…[/dim]")
|
||||
@@ -249,6 +286,9 @@ def webui(
|
||||
output=lambda message: console.print(message, style="dim", markup=False),
|
||||
) as dev_server:
|
||||
managed = not existing_gateway or runtime.status().running
|
||||
desktop.enter_context(dock_icon(
|
||||
dev_browser_url, instance=runtime.paths.state_path, enabled=not no_dock,
|
||||
))
|
||||
announce_ready(dev_browser_url, managed=managed)
|
||||
if managed:
|
||||
_attach_to_background_gateway(
|
||||
@@ -268,8 +308,12 @@ def webui(
|
||||
return
|
||||
|
||||
managed = not existing_gateway or runtime.status().running
|
||||
desktop.enter_context(dock_icon(
|
||||
webui_url, instance=runtime.paths.state_path, enabled=managed and not no_dock,
|
||||
))
|
||||
announce_ready(webui_url, managed=managed)
|
||||
if managed:
|
||||
_attach_to_background_gateway(runtime, log_cursor=log_cursor)
|
||||
finally:
|
||||
desktop.close()
|
||||
lease.release(wait_for_stop=False)
|
||||
@@ -549,6 +549,7 @@ def _print_webui_ready(
|
||||
dev: bool,
|
||||
managed: bool,
|
||||
provider_error: str | None = None,
|
||||
detached: bool = False,
|
||||
) -> None:
|
||||
"""Show one ready state and a complete browser handoff in the local terminal."""
|
||||
ws_cfg = _webui_config_dict(config)
|
||||
@@ -575,7 +576,11 @@ def _print_webui_ready(
|
||||
console.print()
|
||||
log_command = _gateway_instance_command("logs", config_path=config_path, workspace=workspace)
|
||||
console.print(Text(f"Logs: {log_command}", style="dim"), soft_wrap=True)
|
||||
if managed:
|
||||
if detached:
|
||||
stop_command = _gateway_instance_command("stop", config_path=config_path, workspace=workspace)
|
||||
lifecycle = "Running in the background. Closing the browser or terminal does not stop nanobot.\n"
|
||||
lifecycle += f"Stop nanobot: {stop_command}"
|
||||
elif managed:
|
||||
lifecycle = "Keep this terminal open while using WebUI.\n"
|
||||
lifecycle += "Ctrl+C stops development mode." if dev else "Press Ctrl+C to exit."
|
||||
else:
|
||||
|
||||
@@ -26,6 +26,7 @@ from nanobot.cron.types import (
|
||||
CronSchedule,
|
||||
CronStore,
|
||||
)
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META
|
||||
from nanobot.utils.helpers import atomic_write_text
|
||||
from nanobot.utils.run_records import (
|
||||
@@ -202,7 +203,10 @@ class CronService:
|
||||
store_path: Path,
|
||||
on_job: Callable[[CronJob], Coroutine[Any, Any, str | CronRunResult | None]] | None = None,
|
||||
max_sleep_ms: int = 300_000, # 5 minutes
|
||||
*,
|
||||
admission: RuntimeAdmission | None = None,
|
||||
):
|
||||
self.admission = admission if admission is not None else RuntimeAdmission()
|
||||
self.store_path = store_path
|
||||
self._action_path = store_path.parent / "action.jsonl"
|
||||
self._run_records_dir = store_path.parent / "runs"
|
||||
@@ -550,6 +554,13 @@ class CronService:
|
||||
|
||||
async def _on_timer(self) -> None:
|
||||
"""Handle timer tick - run due jobs."""
|
||||
# Do not spin on an overdue timestamp or consume jobs while paused.
|
||||
# stop() cancels this waiter; an aborted maintenance wakes it normally.
|
||||
await self.admission.wait_until_open()
|
||||
with self.admission.activity():
|
||||
await self._run_timer()
|
||||
|
||||
async def _run_timer(self) -> None:
|
||||
reload_store = self._active_executions == 0
|
||||
self._active_executions += 1
|
||||
try:
|
||||
@@ -934,6 +945,10 @@ class CronService:
|
||||
|
||||
async def run_job(self, job_id: str, force: bool = False) -> bool:
|
||||
"""Manually run a job without disturbing the service's running state."""
|
||||
with self.admission.activity():
|
||||
return await self._run_job(job_id, force)
|
||||
|
||||
async def _run_job(self, job_id: str, force: bool) -> bool:
|
||||
reload_store = self._active_executions == 0
|
||||
self._active_executions += 1
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
"""Account-scoped leases for named nanobot stores shared by Python installations.
|
||||
|
||||
Runtimes share leases; backup/install maintenance requires exclusive access. Two
|
||||
lease namespaces cover overlapping store roots in both directions. This coordinates
|
||||
participating runtimes, not older versions, other accounts, external databases or
|
||||
arbitrary project files.
|
||||
Each process must acquire its own lease; a parent's exit must not unlock a pip child.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Generator, Iterable
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
from uuid import UUID
|
||||
|
||||
from nanobot.installation_lock import FileLease, InstallationBusyError, file_access
|
||||
from nanobot.utils.atomic_file import atomic_write_lines, read_atomic_bytes
|
||||
|
||||
_DATA_STORES = (
|
||||
"sessions", "webui", "media", "auth", "pairing.json", "cron", "delivery",
|
||||
"llm_usage.sqlite3", "llm_usage.sqlite3-wal", "llm_usage.sqlite3-shm",
|
||||
"whatsapp-auth", "weixin", "matrix-store", "linear", "mochat", "cli-apps/installed.json",
|
||||
)
|
||||
_WORKSPACE_STORES = (
|
||||
".nanobot", "memory", "skills", "sessions", "cron", "triggers",
|
||||
"AGENTS.md", "TOOLS.md", "SOUL.md", "USER.md", "HEARTBEAT.md",
|
||||
)
|
||||
_MAX_RESERVATION_BYTES = 16 * 1024 * 1024
|
||||
|
||||
|
||||
def _stored_roots(raw: object) -> tuple[str, ...]:
|
||||
if not isinstance(raw, list):
|
||||
raise ValueError("Invalid data maintenance scope")
|
||||
values = cast(list[object], raw)
|
||||
if not 1 <= len(values) <= 40_000 or any(
|
||||
not isinstance(root, str) or len(root) > 4096 or "\0" in root or not Path(root).is_absolute()
|
||||
for root in values
|
||||
):
|
||||
raise ValueError("Invalid data maintenance scope")
|
||||
return tuple(cast(list[str], values))
|
||||
|
||||
|
||||
def _covered(requested: tuple[str, ...], reserved: tuple[str, ...]) -> bool:
|
||||
allowed = set(map(Path, reserved))
|
||||
return all(any(parent in allowed for parent in (path, *path.parents)) for path in map(Path, requested))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Reservation:
|
||||
job_id: str
|
||||
roots: tuple[str, ...]
|
||||
grants: dict[str, tuple[str, tuple[str, ...]]] = field(default_factory=dict)
|
||||
|
||||
def save(self, path: Path) -> None:
|
||||
encoded = json.dumps({
|
||||
"schema_version": 1, "job_id": self.job_id, "roots": self.roots,
|
||||
"grants": {participant: {"token_sha256": digest, "roots": scope}
|
||||
for participant, (digest, scope) in self.grants.items()},
|
||||
})
|
||||
if len(encoded.encode("utf-8")) + 1 > _MAX_RESERVATION_BYTES:
|
||||
raise ValueError("Data maintenance reservation is too large")
|
||||
atomic_write_lines(path, [encoded])
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def _reservation(path: Path) -> _Reservation | None:
|
||||
"""Read a bounded, atomically replaced reservation; corruption never means idle."""
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid data maintenance reservation")
|
||||
try:
|
||||
encoded = read_atomic_bytes(path, max_bytes=_MAX_RESERVATION_BYTES + 1)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
if len(encoded) > _MAX_RESERVATION_BYTES:
|
||||
raise ValueError("Data maintenance reservation is too large")
|
||||
raw: object = json.loads(encoded)
|
||||
if raw is None:
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("Invalid data maintenance reservation")
|
||||
record = cast(dict[str, object], raw)
|
||||
owner, roots = record.get("job_id"), record.get("roots")
|
||||
if (record.get("schema_version") != 1 or not isinstance(owner, str)
|
||||
or str(UUID(owner)) != owner):
|
||||
raise ValueError("Invalid data maintenance reservation")
|
||||
scope = _stored_roots(roots)
|
||||
raw_grants = record.get("grants", {})
|
||||
if not isinstance(raw_grants, dict):
|
||||
raise ValueError("Invalid maintenance startup grants")
|
||||
grant_values = cast(dict[object, object], raw_grants)
|
||||
if len(grant_values) > 1024:
|
||||
raise ValueError("Invalid maintenance startup grants")
|
||||
grants: dict[str, tuple[str, tuple[str, ...]]] = {}
|
||||
for participant, raw_grant in grant_values.items():
|
||||
if not isinstance(participant, str) or not re.fullmatch(r"[0-9a-f]{64}", participant) or not isinstance(raw_grant, dict):
|
||||
raise ValueError("Invalid maintenance startup participant")
|
||||
grant = cast(dict[str, object], raw_grant)
|
||||
digest = grant.get("token_sha256")
|
||||
if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
|
||||
raise ValueError("Invalid maintenance startup grant")
|
||||
granted_scope = _stored_roots(grant.get("roots"))
|
||||
if not _covered(granted_scope, scope):
|
||||
raise ValueError("Maintenance startup scope exceeds the reserved data")
|
||||
grants[participant] = digest, granted_scope
|
||||
return _Reservation(owner, scope, grants)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DataStartupGrant:
|
||||
"""Process-local bearer for one reviewed participant, not task admission.
|
||||
|
||||
The lifecycle owner must pass it only to the intended verified startup and
|
||||
keep agent/tool/scheduler admission closed. This coordinates cooperating
|
||||
runtimes; it is not an OS security boundary against the same account.
|
||||
"""
|
||||
|
||||
job_id: str
|
||||
participant: str
|
||||
token: str = field(repr=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (str(UUID(self.job_id)) != self.job_id or not re.fullmatch(r"[0-9a-f]{64}", self.participant)
|
||||
or not re.fullmatch(r"[0-9a-f]{64}", self.token)):
|
||||
raise ValueError("Invalid maintenance startup grant")
|
||||
|
||||
@property
|
||||
def digest(self) -> str:
|
||||
return hashlib.sha256(self.token.encode()).hexdigest()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DataLease:
|
||||
"""Reservation operations are valid only inside the owning data_access context."""
|
||||
|
||||
roots: tuple[str, ...]
|
||||
reservation_path: Path
|
||||
job_id: str | None
|
||||
exclusive: bool
|
||||
_files: tuple[FileLease, ...] = field(default=(), repr=False, compare=False)
|
||||
|
||||
@contextmanager
|
||||
def inherit_for_exec(self) -> Generator[None]:
|
||||
"""Retain all store leases in a dedicated POSIX installer's exec handoff."""
|
||||
with ExitStack() as stack:
|
||||
for lease in self._files:
|
||||
stack.enter_context(lease.inherit_for_exec())
|
||||
yield
|
||||
|
||||
def reserve(self) -> None:
|
||||
"""Keep participating writers out through handoff, crash and repair."""
|
||||
if self.job_id is None or not self.exclusive:
|
||||
raise ValueError("Only an update job may reserve data maintenance")
|
||||
# Starting another package mutation revokes every old startup grant.
|
||||
_Reservation(self.job_id, self.roots).save(self.reservation_path)
|
||||
|
||||
def grant_startup(self, participant: str, paths: Iterable[str | Path]) -> DataStartupGrant:
|
||||
"""Authorize one runtime during a shared, job-owned post-install handoff.
|
||||
|
||||
Must be called inside data_access(paths, job_id=...) after installation
|
||||
verification. No exclusive data locks are held while the child starts.
|
||||
A live participant retains its own OS lease and cannot be reauthorized.
|
||||
"""
|
||||
if self.job_id is None or self.exclusive:
|
||||
raise ValueError("Startup grants require a shared maintenance handoff")
|
||||
grant = DataStartupGrant(self.job_id, participant, os.urandom(32).hex())
|
||||
scope = _canonical_roots(paths)
|
||||
if not scope or not _covered(scope, self.roots):
|
||||
raise ValueError("Startup grant exceeds the reviewed data scope")
|
||||
current = _reservation(self.reservation_path)
|
||||
if current is None or (current.job_id, current.roots) != (self.job_id, self.roots):
|
||||
raise ValueError("Data maintenance belongs to a different job or scope")
|
||||
if participant not in current.grants and len(current.grants) >= 1024:
|
||||
raise ValueError("Too many maintenance startup participants")
|
||||
try:
|
||||
with file_access(self.reservation_path.parent / f"startup-{participant}.lock", exclusive=True):
|
||||
current.grants[participant] = grant.digest, scope
|
||||
current.save(self.reservation_path)
|
||||
except BlockingIOError as exc:
|
||||
raise InstallationBusyError("This maintenance startup participant is still running") from exc
|
||||
return grant
|
||||
|
||||
def release_reservation(self) -> None:
|
||||
"""Clear only this job's reservation after verification or safe cancellation."""
|
||||
if self.job_id is None:
|
||||
raise ValueError("Only an update job may release data maintenance")
|
||||
current = _reservation(self.reservation_path)
|
||||
if current is None:
|
||||
return
|
||||
if (current.job_id, current.roots) != (self.job_id, self.roots):
|
||||
raise ValueError("Data maintenance belongs to a different job or scope")
|
||||
# Atomic replacement also flushes the directory; a crash cannot lose an
|
||||
# unsynced unlink and resurrect an apparently cleared reservation.
|
||||
atomic_write_lines(self.reservation_path, ["null"])
|
||||
|
||||
def grant_profile_startup(self, participant: str, *, home: Path, data_dir: Path,
|
||||
config: Path, workspace: Path) -> DataStartupGrant:
|
||||
"""Honor a protocol-1 handoff without granting its new lazy store early."""
|
||||
paths = profile_data_paths(home=home, data_dir=data_dir, config=config, workspace=workspace)
|
||||
delivery = (data_dir / "delivery").absolute()
|
||||
if not _covered(_canonical_roots((delivery,)), self.roots):
|
||||
paths = tuple(path for path in paths if path != delivery)
|
||||
# Every other store must still be covered by the immutable reservation.
|
||||
# profile_data_access holds the deferred store's ordinary lease, and the
|
||||
# runtime admission gate keeps its lazy owner inactive until activation.
|
||||
return self.grant_startup(participant, paths)
|
||||
|
||||
|
||||
def _canonical_roots(paths: Iterable[str | Path]) -> tuple[str, ...]:
|
||||
roots: set[str] = set()
|
||||
for raw in paths:
|
||||
path = Path(raw)
|
||||
if not path.is_absolute():
|
||||
raise ValueError("Data stores must use absolute paths")
|
||||
roots.add(str(path.resolve()).casefold())
|
||||
return tuple(sorted(roots))
|
||||
|
||||
|
||||
def profile_data_paths(*, home: Path, data_dir: Path, config: Path, workspace: Path) -> tuple[Path, ...]:
|
||||
"""One store inventory for runtime leases and scoped update backups.
|
||||
|
||||
Keep store symlinks visible here: backup must reject them, not silently expand
|
||||
its read scope. Lease identity alone resolves aliases so runtimes cannot race.
|
||||
CLI/config workspace paths may be relative; bind them to this runtime's cwd
|
||||
without following symlinks before passing the inventory to strict leases.
|
||||
"""
|
||||
return tuple(path.absolute() for path in (
|
||||
config, home / "history" / "cli_history", home / "sessions",
|
||||
*(data_dir / name for name in _DATA_STORES),
|
||||
*(workspace / name for name in _WORKSPACE_STORES),
|
||||
))
|
||||
|
||||
|
||||
@contextmanager
|
||||
def profile_data_access(*, home: Path, data_dir: Path, config: Path, workspace: Path,
|
||||
grant: DataStartupGrant | None = None) -> Generator[None]:
|
||||
"""Lease current stores without expanding an older updater's startup grant.
|
||||
|
||||
Protocol 1 predates the delivery store. That owner is lazy and cannot open
|
||||
its database until runtime admission opens. Under an exact legacy grant,
|
||||
lease delivery normally, separately from protected initialization. No data
|
||||
migration or delivery write is permitted before activation. New updaters
|
||||
include it in the ordinary full backup/reservation scope.
|
||||
"""
|
||||
paths = profile_data_paths(home=home, data_dir=data_dir, config=config, workspace=workspace)
|
||||
delivery = (data_dir / "delivery").absolute()
|
||||
legacy = tuple(path for path in paths if path != delivery)
|
||||
if grant is not None:
|
||||
pending = _reservation(Path.home() / ".nanobot/updates/data-locks/maintenance.json")
|
||||
if (pending is not None and pending.job_id == grant.job_id
|
||||
and pending.grants.get(grant.participant) == (grant.digest, _canonical_roots(legacy))):
|
||||
with data_access(legacy, grant=grant), data_access((delivery,)):
|
||||
yield
|
||||
return
|
||||
with data_access(paths, grant=grant):
|
||||
yield
|
||||
|
||||
|
||||
def finish_data_handoff(paths: Iterable[str | Path], *, job_id: str) -> None:
|
||||
"""Finish cleanup of a durably verified handoff, including after a crash.
|
||||
|
||||
Unlike starting a handoff this can find its reservation already cleared.
|
||||
Caller must have persisted verified runtime success. The owner lock and
|
||||
exact job/scope check prevent clearing another maintenance reservation;
|
||||
running children keep their own data leases throughout this cleanup.
|
||||
"""
|
||||
roots = _canonical_roots(paths)
|
||||
if not roots or str(UUID(job_id)) != job_id:
|
||||
raise ValueError("Data handoff completion requires its original identity and scope")
|
||||
directory = Path.home() / ".nanobot" / "updates" / "data-locks"
|
||||
with file_access(directory / "maintenance.lock", exclusive=True):
|
||||
DataLease(roots, directory / "maintenance.json", job_id, False).release_reservation()
|
||||
|
||||
|
||||
def require_no_pending_data_update() -> None:
|
||||
"""Reject a known unfinished transaction before stopping another gateway.
|
||||
|
||||
This is an early check, not a maintenance grant. The worker must still obtain
|
||||
exclusive installation/data leases and validate the reservation after shutdown.
|
||||
"""
|
||||
directory = Path.home() / ".nanobot" / "updates" / "data-locks"
|
||||
try:
|
||||
with file_access(directory / "maintenance.lock", exclusive=True):
|
||||
if _reservation(directory / "maintenance.json") is not None:
|
||||
raise InstallationBusyError("Another data update is unfinished; recover it before stopping this gateway")
|
||||
except BlockingIOError as exc:
|
||||
raise InstallationBusyError("Another data update is active; this gateway was not stopped") from exc
|
||||
|
||||
|
||||
@contextmanager
|
||||
def data_access(paths: Iterable[str | Path], *, updating: bool = False,
|
||||
job_id: str | None = None, grant: DataStartupGrant | None = None) -> Generator[DataLease]:
|
||||
"""Refuse overlapping live writers/maintenance without waiting or killing them.
|
||||
|
||||
Writers claim roots in one namespace and ancestors in the other; maintenance
|
||||
does the reverse, exclusively. Neither a parent nor a child store can bypass
|
||||
the other's lease. Disjoint runtime data stays available; maintenance jobs in
|
||||
this account serialize deliberately rather than require a live lock registry.
|
||||
Leases are nonblocking, ordered and released together after partial failure.
|
||||
An exclusive job may reserve its roots across process handoff. Only that same
|
||||
job and exact scope can resume maintenance; a crash does not lift the fence.
|
||||
|
||||
After verifying package files, the owner may use shared access with job_id to
|
||||
grant restricted child startup. The owner retains the maintenance lock, while
|
||||
each granted child holds its own shared data and exclusive participant leases.
|
||||
Only the owner releases the reservation after runtime verification; context
|
||||
exit never clears it. A grant permits data initialization, not normal work.
|
||||
"""
|
||||
canonical = _canonical_roots(paths)
|
||||
roots = set(map(Path, canonical))
|
||||
if job_id is not None and (not roots or str(UUID(job_id)) != job_id):
|
||||
raise ValueError("Data maintenance requires a canonical job identity")
|
||||
if grant is not None and (updating or job_id is not None):
|
||||
raise ValueError("A startup participant cannot act as the maintenance owner")
|
||||
leases: set[tuple[str, str]] = set()
|
||||
for path in roots:
|
||||
requested, ancestors = (path,), (path, *path.parents)
|
||||
for namespace, items in (
|
||||
("writers", requested if updating else ancestors),
|
||||
("maintenance", ancestors if updating else requested),
|
||||
):
|
||||
for item in items:
|
||||
# Conservatively merge case aliases, including on macOS volumes
|
||||
# where normcase alone does not normalize path identity.
|
||||
leases.add((namespace, str(item).casefold()))
|
||||
directory = Path.home() / ".nanobot" / "updates" / "data-locks"
|
||||
with ExitStack() as stack:
|
||||
held: list[FileLease] = []
|
||||
try:
|
||||
if updating or job_id is not None:
|
||||
# One reservation per account, including Windows stores on
|
||||
# different drives that have no shared filesystem ancestor.
|
||||
held.append(stack.enter_context(file_access(directory / "maintenance.lock", exclusive=True)))
|
||||
if grant is not None:
|
||||
held.append(stack.enter_context(file_access(directory / f"startup-{grant.participant}.lock", exclusive=True)))
|
||||
for namespace, key in sorted(leases):
|
||||
name = hashlib.sha256(os.fsencode(key)).hexdigest()
|
||||
held.append(stack.enter_context(file_access(directory / f"{namespace}-{name}.lock", exclusive=updating)))
|
||||
except BlockingIOError as exc:
|
||||
raise InstallationBusyError(
|
||||
"Nanobot data is in use by another runtime or update. Stop its writers "
|
||||
"before retrying; no data lease was granted."
|
||||
) from exc
|
||||
path = directory / "maintenance.json"
|
||||
pending = _reservation(path)
|
||||
if pending is None and (grant is not None or (job_id is not None and not updating)):
|
||||
raise InstallationBusyError("Data maintenance handoff is no longer reserved")
|
||||
if pending is not None:
|
||||
owner, reserved = pending.job_id, pending.roots
|
||||
if updating or job_id is not None:
|
||||
if (job_id, canonical) != (owner, reserved):
|
||||
raise InstallationBusyError("Data maintenance belongs to an unfinished update; resume that job first")
|
||||
elif grant is not None:
|
||||
if grant.job_id != owner or pending.grants.get(grant.participant) != (grant.digest, canonical):
|
||||
raise InstallationBusyError("Startup grant does not match this participant's reserved data scope")
|
||||
else:
|
||||
requested = set(map(Path, canonical))
|
||||
ancestors = {parent for root in requested for parent in (root, *root.parents)}
|
||||
if any(root in ancestors or any(parent in requested for parent in root.parents)
|
||||
for root in map(Path, reserved)):
|
||||
raise InstallationBusyError("Nanobot data is reserved by an unfinished update; check its saved job before restarting")
|
||||
yield DataLease(canonical, path, job_id, updating, tuple(held))
|
||||
@@ -15,7 +15,7 @@ import time
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Generator, Literal, cast
|
||||
@@ -47,19 +47,30 @@ GatewayLaunchMode = Literal["foreground", "background", "unknown"]
|
||||
GatewayLifetime = Literal["explicit", "on_demand"]
|
||||
|
||||
|
||||
def _gateway_health_ready(host: str, port: int, *, timeout_s: float = 0.4) -> bool:
|
||||
@dataclass(frozen=True)
|
||||
class GatewayHealthIdentity:
|
||||
"""Opaque local instance/run identity; never configuration paths or credentials."""
|
||||
|
||||
instance_id: str
|
||||
run_id: str
|
||||
version: str
|
||||
|
||||
|
||||
def _gateway_health_ready(host: str, port: int, *, timeout_s: float = 0.4,
|
||||
expected: GatewayHealthIdentity | None = None,
|
||||
maintenance: bool | None = None) -> bool:
|
||||
"""Read readiness from the management listener without using proxy settings."""
|
||||
connect_host = "127.0.0.1" if host in {"", "0.0.0.0"} else "::1" if host == "::" else host
|
||||
connection = http.client.HTTPConnection(connect_host, port, timeout=timeout_s)
|
||||
try:
|
||||
connection.request("GET", "/health")
|
||||
response = connection.getresponse()
|
||||
body = response.read(1024)
|
||||
body = response.read(4097)
|
||||
except (OSError, http.client.HTTPException, TimeoutError):
|
||||
return False
|
||||
finally:
|
||||
connection.close()
|
||||
if response.status != 200:
|
||||
if response.status != 200 or len(body) > 4096:
|
||||
return False
|
||||
try:
|
||||
raw_payload = cast(object, json.loads(body.decode("utf-8")))
|
||||
@@ -68,6 +79,15 @@ def _gateway_health_ready(host: str, port: int, *, timeout_s: float = 0.4) -> bo
|
||||
if not isinstance(raw_payload, dict):
|
||||
return False
|
||||
payload = cast(dict[str, object], raw_payload)
|
||||
if maintenance is not None and payload.get("maintenance") is not maintenance:
|
||||
return False
|
||||
if expected is not None:
|
||||
raw_identity = payload.get("runtime")
|
||||
if payload.get("ready") is not True or not isinstance(raw_identity, dict):
|
||||
return False
|
||||
identity = cast(dict[str, object], raw_identity)
|
||||
if any(identity.get(key) != value for key, value in asdict(expected).items()):
|
||||
return False
|
||||
return (
|
||||
payload.get("status") == "ok"
|
||||
and payload.get("ready") is not False
|
||||
@@ -340,6 +360,26 @@ class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
|
||||
state["health_host"] = host
|
||||
self._write_state(state)
|
||||
|
||||
def verify_ready(self, expected: GatewayHealthIdentity, *, maintenance: bool | None = None) -> bool:
|
||||
"""Bind health to one live local process, not merely a responding port.
|
||||
|
||||
This is local lifecycle evidence, not remote authentication. Missing
|
||||
identity metadata on an older host cannot confirm an update restart.
|
||||
"""
|
||||
state = self._read_state()
|
||||
if not state:
|
||||
return False
|
||||
pid, host, port = state.get("pid"), state.get("health_host"), state.get("port")
|
||||
if (type(pid) is not int or type(port) is not int or not 0 < port < 65536
|
||||
or not isinstance(host, str) or not self._is_pid_running(pid)
|
||||
or not self._record_matches_process(state, pid)):
|
||||
return False
|
||||
if not _gateway_health_ready(host, port, expected=expected, maintenance=maintenance):
|
||||
return False
|
||||
# The process may have exited or been replaced while the HTTP probe ran.
|
||||
return (self._read_state() == state and self._is_pid_running(pid)
|
||||
and self._record_matches_process(state, pid))
|
||||
|
||||
@contextmanager
|
||||
def foreground_instance(self, options: GatewayStartOptions) -> Generator[None]:
|
||||
"""Publish this process and own its stop signal across asyncio.run()."""
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Coordinate nanobot entrypoints with updates of their shared Python installation.
|
||||
|
||||
This module uses only the standard library so startup and a detached update worker
|
||||
can use the same lock without importing dependencies they are about to replace.
|
||||
The OS releases leases on process exit, including a crash. Never unlink the lock
|
||||
file: replacing its inode would let two processes acquire different locks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO
|
||||
|
||||
from nanobot.utils.atomic_file import io_path
|
||||
|
||||
|
||||
class InstallationBusyError(RuntimeError):
|
||||
"""Another runtime or updater holds an incompatible installation lease."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileLease:
|
||||
"""An OS lease owned by the enclosing file_access context."""
|
||||
|
||||
_handle: BinaryIO = field(repr=False)
|
||||
|
||||
@contextmanager
|
||||
def inherit_for_exec(self) -> Generator[None]:
|
||||
"""Keep a dedicated POSIX worker's lease when exec replaces its program.
|
||||
|
||||
Enter only immediately around exec, not a spawned child or normal runtime
|
||||
work. The new program must retain the descriptors and must not delegate
|
||||
mutation to unprotected children. Windows byte-range locks do not provide
|
||||
this ownership transfer. A failed exec restores the original FD flags.
|
||||
"""
|
||||
if os.name != "posix":
|
||||
raise OSError("Lease inheritance requires a POSIX exec handoff")
|
||||
descriptor = self._handle.fileno()
|
||||
original = os.get_inheritable(descriptor)
|
||||
os.set_inheritable(descriptor, True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.set_inheritable(descriptor, original)
|
||||
|
||||
|
||||
def installation_id(environment: str | Path | None = None) -> str:
|
||||
return hashlib.sha256(os.fsencode(Path(environment or sys.prefix).resolve())).hexdigest()[:32]
|
||||
|
||||
|
||||
def installation_state_dir(environment: str | Path | None = None) -> Path:
|
||||
# Deliberately independent of --home/config/workspace: profiles sharing this
|
||||
# interpreter must not get independent update locks.
|
||||
return Path.home() / ".nanobot" / "updates" / installation_id(environment)
|
||||
|
||||
|
||||
def pending_update_path(environment: str | Path | None = None) -> Path:
|
||||
return Path.home() / ".nanobot" / "run" / f"update-{installation_id(environment)[:16]}.pending"
|
||||
|
||||
|
||||
def _lock_windows(handle: BinaryIO, *, exclusive: bool) -> None:
|
||||
import ctypes
|
||||
import msvcrt
|
||||
from ctypes import wintypes
|
||||
|
||||
class Overlapped(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("Internal", ctypes.c_size_t), ("InternalHigh", ctypes.c_size_t),
|
||||
("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD),
|
||||
("hEvent", wintypes.HANDLE),
|
||||
]
|
||||
|
||||
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
lock = kernel.LockFileEx
|
||||
lock.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD,
|
||||
wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(Overlapped)]
|
||||
lock.restype = wintypes.BOOL
|
||||
overlap = Overlapped()
|
||||
# LOCKFILE_FAIL_IMMEDIATELY, plus LOCKFILE_EXCLUSIVE_LOCK for an updater.
|
||||
if not lock(msvcrt.get_osfhandle(handle.fileno()), 1 | (2 if exclusive else 0),
|
||||
0, 1, 0, ctypes.byref(overlap)):
|
||||
code = ctypes.get_last_error()
|
||||
if code in {32, 33}: # sharing/lock violation
|
||||
raise BlockingIOError(errno.EAGAIN, "Installation is in use")
|
||||
raise ctypes.WinError(code)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def file_access(path: Path, *, exclusive: bool) -> Generator[FileLease]:
|
||||
"""Hold a nonblocking OS lease; never replace or delete its file."""
|
||||
path = io_path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
descriptor = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
|
||||
with os.fdopen(descriptor, "a+b") as handle:
|
||||
try:
|
||||
if sys.platform == "win32":
|
||||
_lock_windows(handle, exclusive=exclusive)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(handle, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB)
|
||||
except OSError as exc:
|
||||
if exc.errno in {errno.EAGAIN, errno.EACCES}:
|
||||
raise BlockingIOError(errno.EAGAIN, "The file lease is held") from exc
|
||||
raise
|
||||
yield FileLease(handle)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def installation_access(*, updating: bool = False, allow_incomplete: bool = False,
|
||||
environment: str | Path | None = None) -> Generator[FileLease]:
|
||||
"""Hold a shared runtime lease, or refuse an update until all runtimes exit.
|
||||
|
||||
This protects cooperating entrypoints in this account, not arbitrary Python
|
||||
imports or externally managed deployments. Process-owner shutdown/restart is
|
||||
still required before enabling an in-app installation handoff. Diagnostics and
|
||||
stop commands may allow an incomplete install; they still cannot race a writer.
|
||||
"""
|
||||
acquired = False
|
||||
try:
|
||||
with file_access(installation_state_dir(environment) / "runtime.lock", exclusive=updating) as lease:
|
||||
acquired = True
|
||||
if not updating and not allow_incomplete and io_path(pending_update_path(environment)).exists():
|
||||
raise InstallationBusyError(
|
||||
"A previous update did not finish. Check its saved update state at "
|
||||
f"{installation_state_dir(environment)} before repairing this installation. "
|
||||
"Do not start a different update. No automatic rollback was performed."
|
||||
)
|
||||
yield lease
|
||||
except BlockingIOError as exc:
|
||||
if not acquired:
|
||||
message = (
|
||||
"This installation is in use. Stop its nanobot gateways and clients before updating; "
|
||||
"no processes were stopped and no package files were changed."
|
||||
if updating else
|
||||
"This installation is being updated. Wait for the update to finish before starting nanobot."
|
||||
)
|
||||
raise InstallationBusyError(message) from exc
|
||||
raise
|
||||
@@ -0,0 +1,28 @@
|
||||
"""The official installer's explicit package selection, not inferred dependencies.
|
||||
|
||||
The installer records selection before creating a dedicated environment, so retry
|
||||
survives first-install failure. The receipt alone does not prove installation or
|
||||
readiness. Existing uv, pipx, source and unrecorded venvs are never adopted implicitly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
RECEIPT_NAME = "nanobot-install.json"
|
||||
|
||||
|
||||
def managed_extras(environment: str, expected_sha256: str) -> list[str]:
|
||||
path = Path(environment) / RECEIPT_NAME
|
||||
if path.is_symlink() or path.stat().st_size > 4096:
|
||||
raise ValueError("Invalid installer receipt")
|
||||
payload = path.read_bytes()
|
||||
if hashlib.sha256(payload).hexdigest() != expected_sha256:
|
||||
raise ValueError("Installer receipt changed")
|
||||
record = json.loads(payload)
|
||||
if record != {"schema_version": 1, "owner": "nanobot-installer",
|
||||
"environment": str(Path(environment).resolve()), "extras": []}:
|
||||
raise ValueError("This installation selection needs its owner's update workflow")
|
||||
return []
|
||||
@@ -6,6 +6,7 @@ import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from importlib.metadata import PackageNotFoundError, distribution
|
||||
from pathlib import Path
|
||||
@@ -223,10 +224,24 @@ def install_extra(
|
||||
*,
|
||||
runner: Any = run_install_command,
|
||||
) -> InstallResult:
|
||||
install_args, label = install_args_for_extra(extra, deps)
|
||||
return install_packages(install_args, label, runner=runner, log_name=extra)
|
||||
|
||||
|
||||
def install_packages(
|
||||
install_args: list[str],
|
||||
label: str,
|
||||
*,
|
||||
upgrade: bool = False,
|
||||
runner: Callable[..., subprocess.CompletedProcess[str]] = run_install_command,
|
||||
log_name: str | None = None,
|
||||
) -> InstallResult:
|
||||
"""Install into the running interpreter, bootstrapping pip only when needed."""
|
||||
import importlib
|
||||
|
||||
install_args, label = install_args_for_extra(extra, deps)
|
||||
pip_cmd = [sys.executable, "-m", "pip", "install", *install_args]
|
||||
pip_options = ["--upgrade", "--upgrade-strategy", "only-if-needed"] if upgrade else []
|
||||
extra = log_name or label
|
||||
pip_cmd = [sys.executable, "-m", "pip", "install", *pip_options, *install_args]
|
||||
if not install_args:
|
||||
logger.info("Optional feature '{}' has no installable dependencies for this platform", extra)
|
||||
return InstallResult(True, label, pip_cmd)
|
||||
@@ -242,7 +257,9 @@ def install_extra(
|
||||
failed_proc = proc
|
||||
if missing_pip(proc):
|
||||
if shutil.which("uv"):
|
||||
uv_cmd = ["uv", "pip", "install", "--python", sys.executable, *install_args]
|
||||
uv_options = ["--upgrade-package", "nanobot-ai"] if upgrade else []
|
||||
uv_args = ["--reinstall" if arg == "--force-reinstall" else arg for arg in install_args]
|
||||
uv_cmd = ["uv", "pip", "install", "--python", sys.executable, *uv_options, *uv_args]
|
||||
uv_env = os.environ.copy()
|
||||
if index_url := os.environ.get("PIP_INDEX_URL", "").strip():
|
||||
uv_env["UV_INDEX_URL"] = index_url
|
||||
|
||||
@@ -23,6 +23,7 @@ from typing import Any, Generic, Literal, TypeVar, cast
|
||||
|
||||
from filelock import FileLock
|
||||
|
||||
from nanobot.utils.atomic_file import read_atomic_bytes, replace_atomic
|
||||
from nanobot.utils.rotating_output import (
|
||||
BACKGROUND_LOG_BACKUP_COUNT_ENV,
|
||||
BACKGROUND_LOG_MAX_BYTES_ENV,
|
||||
@@ -477,8 +478,7 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
|
||||
|
||||
def _read_state(self) -> dict[str, Any] | None:
|
||||
try:
|
||||
with self.paths.state_path.open(encoding="utf-8") as handle:
|
||||
payload = json.load(handle)
|
||||
payload = json.loads(read_atomic_bytes(self.paths.state_path).decode("utf-8"))
|
||||
except (OSError, json.JSONDecodeError, ValueError):
|
||||
return None
|
||||
return cast(dict[str, Any], payload) if isinstance(payload, dict) else None
|
||||
@@ -497,7 +497,7 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
|
||||
handle.write("\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
tmp_path.replace(self.paths.state_path)
|
||||
replace_atomic(tmp_path, self.paths.state_path)
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ class GitHubCopilotOAuthFlow:
|
||||
self._error: Exception | None = None
|
||||
self._commit_lock = threading.Lock()
|
||||
self._saved = False
|
||||
self._thread = threading.Thread(target=self._run, daemon=True, name="github-device-login")
|
||||
|
||||
@property
|
||||
def remaining_seconds(self) -> int:
|
||||
@@ -36,6 +37,14 @@ class GitHubCopilotOAuthFlow:
|
||||
def expired(self) -> bool:
|
||||
return self._cancelled.is_set() or self.remaining_seconds <= 0
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
return self._thread.is_alive()
|
||||
|
||||
def wait_closed(self) -> None:
|
||||
if self._thread.ident is not None:
|
||||
self._thread.join()
|
||||
|
||||
def cancel(self) -> None:
|
||||
with self._commit_lock:
|
||||
self._cancelled.set()
|
||||
@@ -63,7 +72,10 @@ class GitHubCopilotOAuthFlow:
|
||||
self._ready.set()
|
||||
|
||||
def start(self) -> None:
|
||||
threading.Thread(target=self._run, daemon=True, name="github-device-login").start()
|
||||
with self._commit_lock:
|
||||
if self.expired:
|
||||
raise RuntimeError("GitHub sign-in expired or cancelled. Start again.")
|
||||
self._thread.start()
|
||||
if not self._ready.wait(timeout=15):
|
||||
self.cancel()
|
||||
raise RuntimeError("GitHub sign-in timed out. Start again.")
|
||||
@@ -72,7 +84,7 @@ class GitHubCopilotOAuthFlow:
|
||||
if self._error is not None:
|
||||
raise RuntimeError("GitHub sign-in failed. Start again.") from None
|
||||
|
||||
def complete(self) -> OAuthToken | None:
|
||||
def complete(self, _authorization_response: str | None = None) -> OAuthToken | None:
|
||||
# Approval alone must not change credentials after the UI was closed.
|
||||
# Commit only through the live flow's completion endpoint, serialized
|
||||
# with cancellation (including sign-out).
|
||||
|
||||
@@ -17,6 +17,7 @@ from urllib.parse import parse_qs, urlsplit
|
||||
from oauth_cli_kit import login_oauth_interactive
|
||||
from oauth_cli_kit.models import OAuthToken
|
||||
from oauth_cli_kit.providers import OPENAI_CODEX_PROVIDER
|
||||
from oauth_cli_kit.storage import FileTokenStorage
|
||||
|
||||
_AUTHORIZATION_URL_TIMEOUT_S = 5.0
|
||||
_CALLBACK = urlsplit(OPENAI_CODEX_PROVIDER.redirect_uri)
|
||||
@@ -32,6 +33,22 @@ class OpenAICodexOAuthInputError(OpenAICodexOAuthError):
|
||||
"""A recoverable error in a callback URL pasted by the user."""
|
||||
|
||||
|
||||
class _LoginTokenStorage(FileTokenStorage):
|
||||
"""Use the SDK's public storage seam to exclude cancelled/expired writes."""
|
||||
|
||||
def __init__(self, cancelled: threading.Event, lock: threading.Lock, deadline: float) -> None:
|
||||
super().__init__(token_filename=OPENAI_CODEX_PROVIDER.token_filename)
|
||||
self._cancelled = cancelled
|
||||
self._commit_lock = lock
|
||||
self._deadline = deadline
|
||||
|
||||
def save(self, token: OAuthToken) -> None:
|
||||
with self._commit_lock:
|
||||
if self._cancelled.is_set() or time.monotonic() >= self._deadline:
|
||||
raise OpenAICodexOAuthError("OpenAI Codex sign-in expired or was cancelled.")
|
||||
super().save(token)
|
||||
|
||||
|
||||
class OpenAICodexOAuthLoginFlow:
|
||||
"""Expose oauth-cli-kit's blocking prompt as a two-stage WebUI flow."""
|
||||
|
||||
@@ -51,6 +68,8 @@ class OpenAICodexOAuthLoginFlow:
|
||||
self._result: Future[OAuthToken] = Future()
|
||||
self._ready = threading.Event()
|
||||
self._submission_lock = threading.Lock()
|
||||
self._commit_lock = threading.Lock()
|
||||
self._cancelled = threading.Event()
|
||||
self._submitted = False
|
||||
self._thread = threading.Thread(
|
||||
target=self._run,
|
||||
@@ -66,8 +85,20 @@ class OpenAICodexOAuthLoginFlow:
|
||||
def remaining_seconds(self) -> int:
|
||||
return max(0, int(self._expires_at - time.monotonic()))
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
return self._thread.is_alive()
|
||||
|
||||
def wait_closed(self) -> None:
|
||||
"""Join the worker, including the SDK's token exchange and cleanup."""
|
||||
if self._thread.ident is not None:
|
||||
self._thread.join()
|
||||
|
||||
def start(self) -> OpenAICodexOAuthLoginFlow:
|
||||
self._thread.start()
|
||||
with self._commit_lock:
|
||||
if self._cancelled.is_set():
|
||||
raise OpenAICodexOAuthError("OpenAI Codex sign-in was cancelled.")
|
||||
self._thread.start()
|
||||
wait_s = min(
|
||||
_AUTHORIZATION_URL_TIMEOUT_S,
|
||||
max(0.0, self._expires_at - time.monotonic()),
|
||||
@@ -126,8 +157,6 @@ class OpenAICodexOAuthLoginFlow:
|
||||
def cancel(self) -> None:
|
||||
"""Unblock an abandoned interactive login."""
|
||||
self._fail(OpenAICodexOAuthError("OpenAI Codex sign-in was cancelled."))
|
||||
if threading.current_thread() is not self._thread:
|
||||
self._thread.join(timeout=0.5)
|
||||
|
||||
def _run(self) -> None:
|
||||
try:
|
||||
@@ -135,6 +164,7 @@ class OpenAICodexOAuthLoginFlow:
|
||||
print_fn=self._capture_output,
|
||||
prompt_fn=self._prompt_for_callback,
|
||||
provider=OPENAI_CODEX_PROVIDER,
|
||||
storage=_LoginTokenStorage(self._cancelled, self._commit_lock, self._expires_at),
|
||||
proxy=self._proxy,
|
||||
open_browser=self._open_browser,
|
||||
)
|
||||
@@ -176,6 +206,8 @@ class OpenAICodexOAuthLoginFlow:
|
||||
return value
|
||||
|
||||
def _fail(self, error: OpenAICodexOAuthError) -> None:
|
||||
with self._commit_lock:
|
||||
self._cancelled.set()
|
||||
try:
|
||||
self._result.set_exception(error)
|
||||
except Exception:
|
||||
@@ -193,11 +225,17 @@ def start_openai_codex_oauth_login(
|
||||
open_browser: bool = True,
|
||||
) -> OpenAICodexOAuthLoginFlow:
|
||||
"""Start a non-blocking wrapper around oauth-cli-kit's Codex login."""
|
||||
return OpenAICodexOAuthLoginFlow(
|
||||
flow = OpenAICodexOAuthLoginFlow(
|
||||
proxy=proxy,
|
||||
timeout_s=timeout_s,
|
||||
open_browser=open_browser,
|
||||
).start()
|
||||
)
|
||||
try:
|
||||
return flow.start()
|
||||
except BaseException:
|
||||
flow.cancel()
|
||||
flow.wait_closed()
|
||||
raise
|
||||
|
||||
|
||||
def complete_openai_codex_oauth_login(
|
||||
|
||||
@@ -144,10 +144,26 @@ class XAIOAuthLoginFlow:
|
||||
name="nanobot-xai-grok-oauth-callback",
|
||||
daemon=True,
|
||||
)
|
||||
self._server_thread.start()
|
||||
self._timeout_timer = threading.Timer(timeout_s, self._expire)
|
||||
self._timeout_timer.daemon = True
|
||||
self._timeout_timer.start()
|
||||
|
||||
def start(self) -> XAIOAuthLoginFlow:
|
||||
with self._lock:
|
||||
self._raise_if_finished()
|
||||
self._server_thread.start()
|
||||
self._timeout_timer.start()
|
||||
return self
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
return self._server_thread.is_alive() or self._timeout_timer.is_alive()
|
||||
|
||||
def wait_closed(self) -> None:
|
||||
# Join outside _lock: the expiry timer can be waiting to acquire it.
|
||||
if self._timeout_timer.ident is not None:
|
||||
self._timeout_timer.join()
|
||||
if self._server_thread.ident is not None:
|
||||
self._server_thread.join()
|
||||
|
||||
@property
|
||||
def expired(self) -> bool:
|
||||
@@ -253,8 +269,8 @@ class XAIOAuthLoginFlow:
|
||||
self._closed = True
|
||||
self._timeout_timer.cancel()
|
||||
self._stop_event.set()
|
||||
if threading.current_thread() is not self._server_thread:
|
||||
self._server_thread.join(timeout=2)
|
||||
if self._server_thread.ident is None:
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
def get_xai_oauth_storage_path() -> Path:
|
||||
@@ -309,6 +325,7 @@ def login_xai_oauth(
|
||||
return flow.wait(callback_timeout_s)
|
||||
finally:
|
||||
flow.cancel()
|
||||
flow.wait_closed()
|
||||
|
||||
|
||||
def start_xai_oauth_login(
|
||||
@@ -317,6 +334,15 @@ def start_xai_oauth_login(
|
||||
timeout_s: float = 600,
|
||||
) -> XAIOAuthLoginFlow:
|
||||
"""Create a non-blocking OAuth flow for browser or pasted-callback completion."""
|
||||
return create_xai_oauth_login(proxy=proxy, timeout_s=timeout_s).start()
|
||||
|
||||
|
||||
def create_xai_oauth_login(
|
||||
*,
|
||||
proxy: str | None = None,
|
||||
timeout_s: float = 600,
|
||||
) -> XAIOAuthLoginFlow:
|
||||
"""Prepare the flow so a gateway can own it before starting its threads."""
|
||||
discovery = _discover(proxy)
|
||||
verifier, challenge = _generate_pkce()
|
||||
state = secrets.token_urlsafe(32)
|
||||
@@ -475,6 +501,10 @@ def _make_callback_server(
|
||||
result_queue: queue.Queue[_CallbackResult],
|
||||
) -> ThreadingHTTPServer:
|
||||
class CallbackHandler(BaseHTTPRequestHandler):
|
||||
def setup(self) -> None:
|
||||
super().setup()
|
||||
self.connection.settimeout(5)
|
||||
|
||||
def do_OPTIONS(self) -> None: # noqa: N802
|
||||
if self.path.split("?", 1)[0] != "/callback":
|
||||
self.send_error(HTTPStatus.NOT_FOUND)
|
||||
@@ -530,7 +560,11 @@ def _make_callback_server(
|
||||
# Callback query strings contain an authorization code.
|
||||
return
|
||||
|
||||
return ThreadingHTTPServer(("127.0.0.1", 0), CallbackHandler)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), CallbackHandler)
|
||||
# The listener's server_close must join accepted requests too, not merely
|
||||
# close the listening socket while handlers still run application code.
|
||||
server.daemon_threads = False
|
||||
return server
|
||||
|
||||
|
||||
def _serve_callback_server(
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
"""Resolve and revalidate exact release artifacts without installing anything.
|
||||
|
||||
Stable releases are read from PyPI; previews use the project's protected catalogue.
|
||||
Neither source can provide commands, another repository, or arbitrary download hosts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import platform
|
||||
import re
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path
|
||||
from typing import Literal, Self
|
||||
from urllib.parse import unquote, urljoin, urlsplit
|
||||
from uuid import uuid4
|
||||
from zipfile import ZipFile
|
||||
|
||||
import httpx
|
||||
from filelock import FileLock
|
||||
from packaging.specifiers import SpecifierSet
|
||||
from packaging.tags import Tag, sys_tags
|
||||
from packaging.utils import canonicalize_name, parse_wheel_filename
|
||||
from packaging.version import Version
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from nanobot.release_trust import verify_release_approval
|
||||
from nanobot.releases import (
|
||||
RELEASE_DOWNLOAD,
|
||||
Channel,
|
||||
ReleaseArtifact,
|
||||
ReleaseCatalogue,
|
||||
ReleaseManifest,
|
||||
ReleasePointer,
|
||||
ReleaseRecord,
|
||||
release_filenames,
|
||||
release_version,
|
||||
)
|
||||
from nanobot.security.network import PinnedDNSAsyncTransport
|
||||
from nanobot.utils.atomic_file import atomic_write_lines
|
||||
|
||||
CATALOGUE_URL = "https://raw.githubusercontent.com/HKUDS/nanobot/release-index/catalogue.json"
|
||||
PYPI_URL = "https://pypi.org/pypi/nanobot-ai"
|
||||
_DOWNLOAD_HOSTS = {"github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com",
|
||||
"files.pythonhosted.org"}
|
||||
_METADATA_HOSTS = {"pypi.org", "raw.githubusercontent.com", *_DOWNLOAD_HOSTS}
|
||||
|
||||
|
||||
class ReleaseFeedError(RuntimeError):
|
||||
"""No verified update can be offered or downloaded."""
|
||||
|
||||
def __init__(self, message: str, *, code: Literal["unavailable", "publishing", "unsupported", "withdrawn"] = "unavailable") -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def _url(url: str, hosts: set[str]) -> str:
|
||||
parsed = urlsplit(url)
|
||||
if (parsed.scheme != "https" or parsed.hostname not in hosts
|
||||
or parsed.username is not None or parsed.password is not None
|
||||
or parsed.port not in (None, 443) or parsed.fragment):
|
||||
raise ValueError("Release URL must use an approved HTTPS host")
|
||||
return url
|
||||
|
||||
|
||||
class ReleaseTarget(ReleaseRecord):
|
||||
version: str
|
||||
artifact: ReleaseArtifact
|
||||
url: str
|
||||
source: Literal["pypi", "github"]
|
||||
pointer: ReleasePointer | None = None
|
||||
catalogue_generation: int = Field(default=0, ge=0)
|
||||
|
||||
_version = field_validator("version")(release_version)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_identity(self) -> Self:
|
||||
name, version, _, tags = parse_wheel_filename(self.artifact.filename)
|
||||
if name != "nanobot-ai" or str(version) != self.version or any(t.platform == "any" for t in tags):
|
||||
raise ValueError("Expected a matching native nanobot wheel")
|
||||
_url(self.url, {"files.pythonhosted.org"} if self.source == "pypi" else {"github.com"})
|
||||
if unquote(urlsplit(self.url).path.rsplit("/", 1)[-1]) != self.artifact.filename:
|
||||
raise ValueError("Wheel URL and filename differ")
|
||||
if self.source == "github":
|
||||
expected = f"https://github.com/HKUDS/nanobot/releases/download/v{self.version}/{self.artifact.filename}"
|
||||
if self.url != expected or not self.pointer or self.pointer.version != self.version or self.catalogue_generation < 1:
|
||||
raise ValueError("GitHub target must identify the exact official candidate")
|
||||
elif self.pointer is not None or self.catalogue_generation or Version(self.version).is_prerelease:
|
||||
raise ValueError("PyPI discovery is for stable releases")
|
||||
return self
|
||||
|
||||
|
||||
class _PyPIInfo(BaseModel):
|
||||
name: str
|
||||
version: str
|
||||
requires_python: str
|
||||
|
||||
|
||||
class _PyPIFile(BaseModel):
|
||||
model_config = ConfigDict(strict=True)
|
||||
filename: str
|
||||
size: int = Field(gt=0, le=2 * 1024**3)
|
||||
url: str
|
||||
digests: dict[str, str]
|
||||
yanked: bool
|
||||
requires_python: str | None = None
|
||||
|
||||
|
||||
class _PyPIRelease(BaseModel):
|
||||
info: _PyPIInfo
|
||||
urls: list[_PyPIFile] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class _CatalogueCache(ReleaseRecord):
|
||||
catalogue: ReleaseCatalogue
|
||||
etag: str | None = Field(default=None, max_length=200)
|
||||
|
||||
@field_validator("etag")
|
||||
@classmethod
|
||||
def header_value(cls, value: str | None) -> str | None:
|
||||
if value is not None and ("\r" in value or "\n" in value):
|
||||
raise ValueError("Invalid catalogue ETag")
|
||||
return value
|
||||
|
||||
|
||||
class ReleaseFeed:
|
||||
"""One bounded HTTP client for checking, exact-target revalidation and download.
|
||||
|
||||
The cache is only a generation/ETag guard. Network failure is never a successful
|
||||
fresh check. A supplied transport is the test seam; production uses pinned DNS.
|
||||
"""
|
||||
|
||||
def __init__(self, cache_dir: Path, *, transport: httpx.AsyncBaseTransport | None = None,
|
||||
python_version: str | None = None, supported_tags: list[Tag] | None = None) -> None:
|
||||
self.cache_dir = cache_dir
|
||||
self.python_version = python_version or platform.python_version()
|
||||
self.tags = list(sys_tags()) if supported_tags is None else supported_tags
|
||||
self.client = httpx.AsyncClient(
|
||||
transport=transport or PinnedDNSAsyncTransport(), trust_env=False,
|
||||
timeout=20, follow_redirects=False,
|
||||
headers={"User-Agent": "nanobot-release-check", "Accept-Encoding": "identity"},
|
||||
)
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *_: object) -> None:
|
||||
await self.client.aclose()
|
||||
|
||||
@asynccontextmanager
|
||||
async def _stream(self, url: str, *, hosts: set[str], etag: str | None = None) -> AsyncGenerator[httpx.Response]:
|
||||
"""Validate every redirect and keep the final response open for its reader."""
|
||||
headers = {"If-None-Match": etag} if etag else {}
|
||||
for _ in range(4):
|
||||
_url(url, hosts)
|
||||
async with self.client.stream("GET", url, headers=headers) as response:
|
||||
if response.status_code in {301, 302, 303, 307, 308}:
|
||||
location = response.headers.get("location")
|
||||
if not location:
|
||||
raise ReleaseFeedError("Release redirect has no destination")
|
||||
url = urljoin(url, location)
|
||||
headers = {}
|
||||
continue
|
||||
yield response
|
||||
return
|
||||
raise ReleaseFeedError("Too many release redirects")
|
||||
|
||||
async def _read(self, url: str, *, limit: int, etag: str | None = None) -> tuple[bytes | None, str | None]:
|
||||
async with self._stream(url, hosts=_METADATA_HOSTS, etag=etag) as response:
|
||||
if response.status_code == 304 and etag is not None:
|
||||
return None, etag
|
||||
response.raise_for_status()
|
||||
data = bytearray()
|
||||
async for chunk in response.aiter_bytes():
|
||||
data.extend(chunk)
|
||||
if len(data) > limit:
|
||||
raise ReleaseFeedError("Release metadata exceeds its size limit")
|
||||
return bytes(data), response.headers.get("etag")
|
||||
|
||||
def _cached(self) -> _CatalogueCache | None:
|
||||
path = self.cache_dir / "catalogue.json"
|
||||
if not path.exists():
|
||||
return None
|
||||
if path.stat().st_size > 512 * 1024:
|
||||
raise ReleaseFeedError("Release cache is invalid; no update was selected")
|
||||
return _CatalogueCache.model_validate_json(path.read_bytes())
|
||||
|
||||
async def catalogue(self) -> ReleaseCatalogue:
|
||||
cached = self._cached()
|
||||
payload, etag = await self._read(CATALOGUE_URL, limit=256 * 1024, etag=cached.etag if cached else None)
|
||||
if payload is None:
|
||||
if cached is None:
|
||||
raise ReleaseFeedError("Release catalogue returned no data")
|
||||
candidate = cached
|
||||
else:
|
||||
candidate = _CatalogueCache(catalogue=ReleaseCatalogue.model_validate_json(payload), etag=etag)
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
with FileLock(str(self.cache_dir / "catalogue.lock"), timeout=5):
|
||||
previous = self._cached()
|
||||
if previous:
|
||||
try:
|
||||
candidate.catalogue.validate_successor(previous.catalogue)
|
||||
except ValueError as exc:
|
||||
raise ReleaseFeedError(str(exc)) from exc
|
||||
atomic_write_lines(self.cache_dir / "catalogue.json", [candidate.model_dump_json()])
|
||||
return candidate.catalogue
|
||||
|
||||
async def stable(self, version: str | None = None) -> ReleaseTarget:
|
||||
suffix = f"/{release_version(version)}" if version else ""
|
||||
payload, _ = await self._read(f"{PYPI_URL}{suffix}/json", limit=4 * 1024 * 1024)
|
||||
release = _PyPIRelease.model_validate_json(payload or b"")
|
||||
identity = release_version(release.info.version)
|
||||
if canonicalize_name(release.info.name) != "nanobot-ai" or Version(identity).is_prerelease:
|
||||
raise ReleaseFeedError("PyPI did not return a stable nanobot release")
|
||||
if version and identity != version:
|
||||
raise ReleaseFeedError("PyPI returned a different version than requested")
|
||||
required = {name for name in release_filenames(identity) if name.endswith((".whl", ".tar.gz"))}
|
||||
if {file.filename for file in release.urls} != required or len(release.urls) != len(required):
|
||||
raise ReleaseFeedError("The stable release is incomplete; no source-build fallback was selected", code="publishing")
|
||||
if any(file.yanked for file in release.urls):
|
||||
raise ReleaseFeedError("The release has been withdrawn from PyPI", code="withdrawn")
|
||||
if not SpecifierSet(release.info.requires_python).contains(self.python_version, prereleases=True):
|
||||
raise ReleaseFeedError(f"Release requires Python {release.info.requires_python}", code="unsupported")
|
||||
for tag in self.tags:
|
||||
for file in release.urls:
|
||||
if not file.filename.endswith(".whl") or tag not in parse_wheel_filename(file.filename)[3]:
|
||||
continue
|
||||
if file.requires_python and not SpecifierSet(file.requires_python).contains(self.python_version, prereleases=True):
|
||||
continue
|
||||
return ReleaseTarget(
|
||||
version=identity, source="pypi", url=file.url,
|
||||
artifact=ReleaseArtifact(filename=file.filename, size=file.size, sha256=file.digests["sha256"]),
|
||||
)
|
||||
raise ReleaseFeedError("No compatible wheel is available for this Python and platform", code="unsupported")
|
||||
|
||||
async def latest(self, channel: Channel) -> ReleaseTarget:
|
||||
if channel == "stable":
|
||||
return await self.stable()
|
||||
catalogue = await self.catalogue()
|
||||
pointer = catalogue.latest(channel)
|
||||
if pointer is None:
|
||||
raise ReleaseFeedError("No eligible preview is available")
|
||||
return await self._from_pointer(pointer, catalogue.generation)
|
||||
|
||||
async def discover(self, channel: Channel, current_version: str) -> tuple[ReleaseTarget | None, bool]:
|
||||
"""Select from one catalogue snapshot and report withdrawal independently.
|
||||
|
||||
Stable installations do not depend on the Preview catalogue. A preview
|
||||
leaving that channel still checks its withdrawal status until replaced.
|
||||
"""
|
||||
if channel == "stable" and not Version(current_version).is_prerelease:
|
||||
return await self.stable(), False
|
||||
try:
|
||||
catalogue = await self.catalogue()
|
||||
except (ReleaseFeedError, httpx.HTTPError, ValueError, OSError):
|
||||
if channel != "stable":
|
||||
raise
|
||||
# An unavailable Preview index must not prevent leaving Preview for
|
||||
# a verified newer final. Do not infer that the installed preview is
|
||||
# safe/current when no such successor can replace it.
|
||||
target = await self.stable()
|
||||
if Version(target.version) <= Version(current_version):
|
||||
raise
|
||||
return target, False
|
||||
withdrawn = current_version in catalogue.withdrawn
|
||||
try:
|
||||
if channel == "stable":
|
||||
return await self.stable(), withdrawn
|
||||
pointer = catalogue.latest(channel)
|
||||
return (await self._from_pointer(pointer, catalogue.generation) if pointer else None), withdrawn
|
||||
except (ReleaseFeedError, httpx.HTTPError, ValueError):
|
||||
if withdrawn:
|
||||
# A missing/incompatible replacement must not hide a freshly
|
||||
# verified warning about the version already running.
|
||||
return None, True
|
||||
raise
|
||||
|
||||
async def _from_pointer(self, pointer: ReleasePointer, generation: int) -> ReleaseTarget:
|
||||
payload, _ = await self._read(pointer.manifest_url, limit=64 * 1024)
|
||||
manifest = pointer.verify_manifest(payload or b"")
|
||||
try:
|
||||
artifact = manifest.wheel_for(python_version=self.python_version, supported_tags=self.tags)
|
||||
except ValueError as exc:
|
||||
raise ReleaseFeedError("No compatible Preview wheel is available", code="unsupported") from exc
|
||||
# A stable successor in the Preview channel must still be available on PyPI.
|
||||
if not Version(manifest.version).is_prerelease:
|
||||
stable = await self.stable(manifest.version)
|
||||
if stable.artifact != artifact:
|
||||
raise ReleaseFeedError("GitHub and PyPI stable artifacts differ")
|
||||
return ReleaseTarget(version=manifest.version, artifact=artifact, source="github",
|
||||
url=manifest.artifact_url(artifact).split("#", 1)[0],
|
||||
pointer=pointer, catalogue_generation=generation)
|
||||
|
||||
async def revalidate(self, target: ReleaseTarget) -> None:
|
||||
"""Validate the approved target, never replace it with a new latest version."""
|
||||
if target.source == "pypi":
|
||||
current = await self.stable(target.version)
|
||||
else:
|
||||
catalogue = await self.catalogue()
|
||||
if catalogue.generation < target.catalogue_generation:
|
||||
raise ReleaseFeedError("Release catalogue predates the approved target")
|
||||
if target.version in catalogue.withdrawn:
|
||||
raise ReleaseFeedError(f"Release withdrawn: {catalogue.withdrawn[target.version]}")
|
||||
assert target.pointer is not None # Validated by ReleaseTarget.
|
||||
current = await self._from_pointer(target.pointer, catalogue.generation)
|
||||
if (current.artifact, current.url) != (target.artifact, target.url):
|
||||
raise ReleaseFeedError("The approved release artifact has changed")
|
||||
await self._authorize(target)
|
||||
|
||||
async def _authorize(self, target: ReleaseTarget) -> None:
|
||||
"""A matching index checksum is not permission to execute new code.
|
||||
|
||||
Apply equally to PyPI/stable and GitHub/Preview, including revalidation
|
||||
before handoff. Discovery remains possible for older unsigned releases,
|
||||
but they cannot enter an automatic installation transaction.
|
||||
"""
|
||||
base = f"{RELEASE_DOWNLOAD}/v{target.version}/release-manifest.json"
|
||||
payload, _ = await self._read(base, limit=64 * 1024)
|
||||
signature, _ = await self._read(base + ".sigstore.json", limit=256 * 1024)
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.to_thread(verify_release_approval, payload or b"", signature or b""), timeout=30,
|
||||
)
|
||||
except TimeoutError as exc:
|
||||
# The verifier thread can only read/refresh public trust metadata;
|
||||
# it has no installation capability even if its IO finishes later.
|
||||
raise ReleaseFeedError("Release approval verification timed out; keep the current version and retry") from exc
|
||||
manifest = ReleaseManifest.model_validate_json(payload or b"")
|
||||
if manifest.version != target.version or target.artifact not in manifest.artifacts:
|
||||
raise ReleaseFeedError("Release approval does not match the selected package")
|
||||
if target.pointer is not None:
|
||||
target.pointer.verify_manifest(payload or b"")
|
||||
|
||||
async def download(self, target: ReleaseTarget, directory: Path) -> Path:
|
||||
"""Stage one verified wheel. No execution, install, or extraction occurs."""
|
||||
await self.revalidate(target)
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
destination = directory / target.artifact.filename
|
||||
if destination.exists() or destination.is_symlink():
|
||||
_verify_wheel(destination, target)
|
||||
return destination
|
||||
temporary = directory / f".{uuid4().hex}.part"
|
||||
try:
|
||||
async with self._stream(target.url, hosts=_DOWNLOAD_HOSTS) as response:
|
||||
response.raise_for_status()
|
||||
size = 0
|
||||
with temporary.open("xb") as handle:
|
||||
async for chunk in response.aiter_bytes():
|
||||
size += len(chunk)
|
||||
if size > target.artifact.size:
|
||||
raise ReleaseFeedError("Release download exceeds its verified size")
|
||||
handle.write(chunk)
|
||||
_verify_wheel(temporary, target)
|
||||
# Never clobber a file another update already staged.
|
||||
try:
|
||||
destination.hardlink_to(temporary)
|
||||
except FileExistsError:
|
||||
_verify_wheel(destination, target)
|
||||
return destination
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _verify_wheel(path: Path, target: ReleaseTarget) -> None:
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size != target.artifact.size:
|
||||
raise ReleaseFeedError("Staged wheel size or file type does not match")
|
||||
with path.open("rb") as handle:
|
||||
if hashlib.file_digest(handle, "sha256").hexdigest() != target.artifact.sha256:
|
||||
raise ReleaseFeedError("Staged wheel checksum does not match")
|
||||
with ZipFile(path) as wheel:
|
||||
metadata_name = f"nanobot_ai-{target.version}.dist-info/METADATA"
|
||||
names = wheel.namelist()
|
||||
if len(names) != len(set(names)) or any(re.search(r"(^/|\\|(?:^|/)\.\.(?:/|$))", name) for name in names):
|
||||
raise ReleaseFeedError("Invalid wheel member paths")
|
||||
if wheel.getinfo(metadata_name).file_size > 256 * 1024:
|
||||
raise ReleaseFeedError("Wheel metadata exceeds its size limit")
|
||||
metadata = BytesParser().parsebytes(wheel.read(metadata_name))
|
||||
if metadata["Name"] != "nanobot-ai" or metadata["Version"] != target.version:
|
||||
raise ReleaseFeedError("Wheel metadata does not match the approved release")
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Authenticate release approval separately from the download service's hashes.
|
||||
|
||||
The installed verifier owns the trust policy. Neither a feed, a signature bundle,
|
||||
nor an environment variable may choose the signing identity or trust root.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
RELEASE_IDENTITY = (
|
||||
"https://github.com/HKUDS/nanobot/.github/workflows/release-approve.yml@refs/heads/main"
|
||||
)
|
||||
RELEASE_ISSUER = "https://token.actions.githubusercontent.com"
|
||||
|
||||
|
||||
def verify_release_approval(payload: bytes, signature: bytes) -> None:
|
||||
"""Require the official, manually approved workflow's logged signature.
|
||||
|
||||
Sigstore verifies the certificate chain, transparency-log inclusion and
|
||||
artifact signature. Refreshing its production TUF root is fail-closed; do
|
||||
not replace this with an unverified local cache or a root from the release.
|
||||
Imports are lazy so a broken/missing verifier cannot prevent gateway startup
|
||||
or the independent recovery worker from running.
|
||||
"""
|
||||
if not payload or len(payload) > 64 * 1024 or not signature or len(signature) > 256 * 1024:
|
||||
raise ValueError("Release approval is missing or exceeds its size limit")
|
||||
try:
|
||||
from sigstore.models import Bundle
|
||||
from sigstore.verify import Verifier
|
||||
from sigstore.verify.policy import AllOf, GitHubWorkflowTrigger, Identity
|
||||
|
||||
policy = AllOf([
|
||||
Identity(identity=RELEASE_IDENTITY, issuer=RELEASE_ISSUER),
|
||||
GitHubWorkflowTrigger("workflow_dispatch"),
|
||||
])
|
||||
# Reject malformed remote input before refreshing the trust service.
|
||||
# Parsing a bundle grants no authority: the fixed verifier still checks
|
||||
# its certificate, log proof, policy and signature over the exact bytes.
|
||||
bundle = Bundle.from_json(signature)
|
||||
Verifier.production().verify_artifact(payload, bundle, policy)
|
||||
except Exception as exc:
|
||||
# Keep library/network/certificate details out of the public job. A
|
||||
# missing verifier, unavailable trust service or invalid proof all deny
|
||||
# installation; none authorize a checksum-only fallback.
|
||||
raise ValueError("Could not verify the official release approval; the current installation was not changed") from exc
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Release identities shared by packaging and channel-aware update discovery.
|
||||
|
||||
This module validates data and selects artifacts. It never installs packages, trusts
|
||||
arbitrary download URLs, or treats a build manifest as publication approval.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from typing import Annotated, Literal, Self
|
||||
|
||||
from packaging.specifiers import SpecifierSet
|
||||
from packaging.tags import Tag
|
||||
from packaging.utils import parse_wheel_filename
|
||||
from packaging.version import Version
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
Channel = Literal["stable", "preview"]
|
||||
Sha256 = Annotated[str, Field(pattern=r"^[0-9a-f]{64}$")]
|
||||
Commit = Annotated[str, Field(pattern=r"^[0-9a-f]{40}$")]
|
||||
|
||||
# Minimums verified against BOTH Bun and the embedded OpenTUI library.
|
||||
PLATFORMS = {
|
||||
"darwin-arm64": "macosx_13_0_arm64",
|
||||
"darwin-x64": "macosx_13_0_x86_64",
|
||||
"linux-arm64": "manylinux_2_17_aarch64",
|
||||
"linux-x64": "manylinux_2_17_x86_64",
|
||||
"win32-x64": "win_amd64",
|
||||
}
|
||||
RELEASE_DOWNLOAD = "https://github.com/HKUDS/nanobot/releases/download"
|
||||
|
||||
|
||||
def release_version(value: str) -> str:
|
||||
"""Accept canonical versions we publish, not epochs, local builds or refs."""
|
||||
if not re.fullmatch(r"\d+\.\d+\.\d+(?:\.dev\d+|\.post\d+)?", value):
|
||||
raise ValueError("Expected a stable or development release version")
|
||||
if str(Version(value)) != value:
|
||||
raise ValueError("Release version must be canonical")
|
||||
return value
|
||||
|
||||
|
||||
def release_filenames(version: str) -> set[str]:
|
||||
"""The complete upload set, excluding the intermediate universal wheel."""
|
||||
release_version(version)
|
||||
names = {f"nanobot_ai-{version}-py3-none-{platform}.whl" for platform in PLATFORMS.values()}
|
||||
names.add(f"nanobot_ai-{version}.tar.gz")
|
||||
for target in PLATFORMS:
|
||||
asset = f"nanobot-tui-{target}" + (".exe" if target == "win32-x64" else "")
|
||||
names.update((f"{asset}.zip", f"{asset}.zip.sha256"))
|
||||
return names
|
||||
|
||||
|
||||
class ReleaseRecord(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
|
||||
|
||||
|
||||
class ReleaseArtifact(ReleaseRecord):
|
||||
filename: str = Field(pattern=r"^[A-Za-z0-9_.-]+$", max_length=200)
|
||||
size: int = Field(gt=0, le=2 * 1024**3)
|
||||
sha256: Sha256
|
||||
|
||||
|
||||
class ReleaseManifest(ReleaseRecord):
|
||||
schema_version: Literal[1] = 1
|
||||
version: str
|
||||
source_commit: Commit
|
||||
candidate_commit: Commit
|
||||
requires_python: str
|
||||
artifacts: list[ReleaseArtifact] = Field(min_length=16, max_length=16)
|
||||
|
||||
_version = field_validator("version")(release_version)
|
||||
|
||||
@field_validator("requires_python")
|
||||
@classmethod
|
||||
def validate_python(cls, value: str) -> str:
|
||||
if not value or len(value) > 200:
|
||||
raise ValueError("A bounded Python version requirement is required")
|
||||
SpecifierSet(value)
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def complete_artifacts(self) -> Self:
|
||||
if {item.filename for item in self.artifacts} != release_filenames(self.version):
|
||||
raise ValueError("Manifest must contain the complete, matching five-platform release")
|
||||
return self
|
||||
|
||||
def wheel_for(self, *, python_version: str, supported_tags: Iterable[Tag]) -> ReleaseArtifact:
|
||||
"""Select using the target interpreter's tags, never the browser platform."""
|
||||
if not SpecifierSet(self.requires_python).contains(python_version, prereleases=True):
|
||||
raise ValueError(f"Release {self.version} requires Python {self.requires_python}")
|
||||
wheels = {
|
||||
tag: artifact
|
||||
for artifact in self.artifacts if artifact.filename.endswith(".whl")
|
||||
for tag in parse_wheel_filename(artifact.filename)[3]
|
||||
}
|
||||
for tag in supported_tags:
|
||||
if tag in wheels:
|
||||
return wheels[tag]
|
||||
raise ValueError("No compatible release wheel; use the documented source/classic path")
|
||||
|
||||
def artifact_url(self, artifact: ReleaseArtifact) -> str:
|
||||
if artifact not in self.artifacts:
|
||||
raise ValueError("Artifact does not belong to this release")
|
||||
return f"{RELEASE_DOWNLOAD}/v{self.version}/{artifact.filename}#sha256={artifact.sha256}"
|
||||
|
||||
|
||||
class ReleasePointer(ReleaseRecord):
|
||||
version: str
|
||||
candidate_commit: Commit
|
||||
manifest_sha256: Sha256
|
||||
|
||||
_version = field_validator("version")(release_version)
|
||||
|
||||
@property
|
||||
def manifest_url(self) -> str:
|
||||
return f"{RELEASE_DOWNLOAD}/v{self.version}/release-manifest.json"
|
||||
|
||||
def verify_manifest(self, payload: bytes) -> ReleaseManifest:
|
||||
if len(payload) > 64 * 1024 or hashlib.sha256(payload).hexdigest() != self.manifest_sha256:
|
||||
raise ValueError("Release manifest size or checksum mismatch")
|
||||
manifest = ReleaseManifest.model_validate_json(payload)
|
||||
if (manifest.version, manifest.candidate_commit) != (self.version, self.candidate_commit):
|
||||
raise ValueError("Release manifest identity does not match the selected candidate")
|
||||
return manifest
|
||||
|
||||
|
||||
class ReleaseCatalogue(ReleaseRecord):
|
||||
schema_version: Literal[1] = 1
|
||||
generation: int = Field(gt=0)
|
||||
stable: ReleasePointer | None = None
|
||||
preview: ReleasePointer | None = None
|
||||
withdrawn: dict[str, str] = Field(default_factory=dict, max_length=1000)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_channels(self) -> Self:
|
||||
if self.stable and Version(self.stable.version).is_prerelease:
|
||||
raise ValueError("Stable channel cannot contain a prerelease")
|
||||
if self.preview and not Version(self.preview.version).is_devrelease:
|
||||
raise ValueError("Preview pointer must identify a development release")
|
||||
for version, reason in self.withdrawn.items():
|
||||
release_version(version)
|
||||
if not reason.strip() or len(reason) > 2000:
|
||||
raise ValueError("A bounded withdrawal reason is required")
|
||||
return self
|
||||
|
||||
def validate_successor(self, previous: Self) -> None:
|
||||
"""A new index generation cannot rewrite already observed releases."""
|
||||
if self.generation < previous.generation or (self.generation == previous.generation and self != previous):
|
||||
raise ValueError("Release catalogue changed without a newer generation")
|
||||
if not previous.withdrawn.keys() <= self.withdrawn.keys():
|
||||
raise ValueError("Release catalogue cannot reinstate withdrawn versions")
|
||||
for old, new in ((previous.stable, self.stable), (previous.preview, self.preview)):
|
||||
if old is None:
|
||||
continue
|
||||
if new is None:
|
||||
raise ValueError("Release channel cannot erase a published pointer; withdraw the version instead")
|
||||
if Version(new.version) < Version(old.version):
|
||||
raise ValueError("Release channel cannot move to an older version")
|
||||
if new.version == old.version and new != old:
|
||||
raise ValueError("Published version cannot change its commit or manifest")
|
||||
|
||||
def latest(self, channel: Channel, *, minimum_generation: int = 0) -> ReleasePointer | None:
|
||||
if self.generation < minimum_generation:
|
||||
raise ValueError("Release catalogue is older than the last accepted generation")
|
||||
candidates = [self.stable] if channel == "stable" else [self.stable, self.preview]
|
||||
eligible = [item for item in candidates if item and item.version not in self.withdrawn]
|
||||
return max(eligible, key=lambda item: Version(item.version), default=None)
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Event-loop-local task admission during an explicitly requested maintenance window.
|
||||
|
||||
This gate coordinates work in one runtime. It is not an installation/data lock or
|
||||
proof that another process, a channel, or an external store has stopped writing.
|
||||
The update owner must still stop and flush those writers before backup/install.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import contextmanager
|
||||
|
||||
|
||||
class RuntimeMaintenanceError(RuntimeError):
|
||||
"""New work cannot enter a runtime held for maintenance."""
|
||||
|
||||
|
||||
class RuntimeBusyError(RuntimeError):
|
||||
"""Maintenance would interrupt accepted work."""
|
||||
|
||||
|
||||
class RuntimeAdmission:
|
||||
"""Share between the gateway's bus, agent, cron and local trigger intake.
|
||||
|
||||
All methods run on their owning event-loop thread. Checking, counting work
|
||||
and closing admission are synchronous: no task can enter between the idle
|
||||
check and the pause. Do not call this object from an installer worker thread.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._paused = False
|
||||
self._active = 0
|
||||
self._pending_checks: list[Callable[[], bool]] = []
|
||||
self._open = asyncio.Event()
|
||||
self._open.set()
|
||||
|
||||
@property
|
||||
def paused(self) -> bool:
|
||||
return self._paused
|
||||
|
||||
def check(self) -> None:
|
||||
if self._paused:
|
||||
raise RuntimeMaintenanceError(
|
||||
"nanobot is preparing an update. Try again after maintenance finishes."
|
||||
)
|
||||
|
||||
async def wait_until_open(self) -> None:
|
||||
"""Pause scheduler intake without consuming or rescheduling pending work."""
|
||||
while self._paused:
|
||||
await self._open.wait()
|
||||
|
||||
def register_pending_work(self, check: Callable[[], bool]) -> Callable[[], None]:
|
||||
"""Account for an owner's queued/detached work until it is shut down.
|
||||
|
||||
Like activity(), registration and inspection are event-loop-local. The
|
||||
owner removes its check only after closing its writers. Checks must not
|
||||
mutate state or yield, so admission can close without an idle-check gap.
|
||||
"""
|
||||
self.check()
|
||||
self._pending_checks.append(check)
|
||||
registered = True
|
||||
|
||||
def remove() -> None:
|
||||
nonlocal registered
|
||||
if registered:
|
||||
self._pending_checks.remove(check)
|
||||
registered = False
|
||||
|
||||
return remove
|
||||
|
||||
@contextmanager
|
||||
def activity(self) -> Generator[None, None, None]:
|
||||
"""Account for accepted work, including its awaited cleanup."""
|
||||
self.check()
|
||||
self._active += 1
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._active -= 1
|
||||
|
||||
@contextmanager
|
||||
def pause_if_idle(self, has_pending_work: Callable[[], bool]) -> Generator[None, None, None]:
|
||||
"""Refuse busy runtimes without cancelling work or leaving intake closed.
|
||||
|
||||
The owner supplies a synchronous view of queued/detached work which
|
||||
outlives an ``activity`` call. Hold this context through the handoff;
|
||||
releasing it after a refused/aborted update restores prior admission.
|
||||
"""
|
||||
self.check()
|
||||
if self._active or has_pending_work() or any(check() for check in self._pending_checks):
|
||||
raise RuntimeBusyError(
|
||||
"nanobot has pending work. Finish active tasks and retry the update."
|
||||
)
|
||||
with self.pause_before_start():
|
||||
yield
|
||||
|
||||
@contextmanager
|
||||
def pause_before_start(self) -> Generator[None, None, None]:
|
||||
"""Hold a fresh runtime before starting any consumers or external intake.
|
||||
|
||||
Startup may already have reconstructed a durable recovery queue. It must
|
||||
not execute that queue until activation. Running gateways must instead
|
||||
use pause_if_idle, which also checks their owner's pending-work view.
|
||||
"""
|
||||
self.check()
|
||||
if self._active:
|
||||
raise RuntimeBusyError("Runtime work has already started")
|
||||
self._paused = True
|
||||
self._open.clear()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._paused = False
|
||||
self._open.set()
|
||||
@@ -11,6 +11,7 @@ from loguru import logger
|
||||
|
||||
from nanobot.agent.automation_turns import AutomationTurnError
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
|
||||
from nanobot.triggers.local_store import LocalTriggerStore
|
||||
from nanobot.triggers.local_types import LocalTrigger, TriggerDelivery
|
||||
@@ -24,11 +25,14 @@ async def run_local_trigger_queue(
|
||||
is_channel_enabled: Callable[[str], bool],
|
||||
poll_interval_s: float = 0.5,
|
||||
batch_size: int = 20,
|
||||
admission: RuntimeAdmission | None = None,
|
||||
) -> None:
|
||||
"""Poll local trigger deliveries and submit them as session turns."""
|
||||
if submit_turn is None:
|
||||
raise ValueError("run_local_trigger_queue requires submit_turn")
|
||||
gate = admission if admission is not None else RuntimeAdmission()
|
||||
logger.info("Local trigger queue started")
|
||||
await gate.wait_until_open()
|
||||
recovered = store.recover_processing_deliveries()
|
||||
if recovered:
|
||||
logger.warning(
|
||||
@@ -36,91 +40,69 @@ async def run_local_trigger_queue(
|
||||
recovered,
|
||||
)
|
||||
while True:
|
||||
deliveries = store.claim_deliveries(limit=batch_size)
|
||||
if not deliveries:
|
||||
await asyncio.sleep(poll_interval_s)
|
||||
continue
|
||||
|
||||
for delivery in deliveries:
|
||||
try:
|
||||
await _deliver_delivery(
|
||||
store,
|
||||
delivery,
|
||||
submit_turn=submit_turn,
|
||||
await gate.wait_until_open()
|
||||
with gate.activity():
|
||||
deliveries = store.claim_deliveries(limit=batch_size)
|
||||
for delivery in deliveries:
|
||||
await _run_delivery(
|
||||
store, delivery, submit_turn=submit_turn,
|
||||
is_channel_enabled=is_channel_enabled,
|
||||
)
|
||||
store.complete_delivery(delivery)
|
||||
except asyncio.CancelledError as exc:
|
||||
store.retry_delivery(delivery, str(exc) or exc.__class__.__name__)
|
||||
_write_delivery_run_record(
|
||||
store,
|
||||
delivery,
|
||||
status="interrupted",
|
||||
error=str(exc) or exc.__class__.__name__,
|
||||
)
|
||||
raise
|
||||
except _TerminalDeliveryError as exc:
|
||||
store.record_delivery(
|
||||
delivery.trigger_id,
|
||||
status="error",
|
||||
error=str(exc),
|
||||
run_at_ms=delivery.created_at_ms,
|
||||
)
|
||||
_write_delivery_run_record(
|
||||
store,
|
||||
delivery,
|
||||
status="error",
|
||||
error=str(exc),
|
||||
)
|
||||
store.complete_delivery(delivery)
|
||||
logger.warning(
|
||||
"Trigger: dropped delivery {} for {}: {}",
|
||||
delivery.id,
|
||||
delivery.trigger_id,
|
||||
exc,
|
||||
)
|
||||
except AutomationTurnError as exc:
|
||||
error = str(exc) or exc.__class__.__name__
|
||||
store.record_delivery(
|
||||
delivery.trigger_id,
|
||||
status="error",
|
||||
error=error,
|
||||
run_at_ms=delivery.created_at_ms,
|
||||
)
|
||||
_write_delivery_run_record(
|
||||
store,
|
||||
delivery,
|
||||
status="error",
|
||||
error=error,
|
||||
)
|
||||
store.complete_delivery(delivery)
|
||||
logger.warning(
|
||||
"Trigger: delivery {} for {} reached the agent but failed: {}",
|
||||
delivery.id,
|
||||
delivery.trigger_id,
|
||||
error,
|
||||
)
|
||||
except Exception as exc:
|
||||
error = str(exc) or exc.__class__.__name__
|
||||
retried = store.retry_delivery(delivery, error)
|
||||
_write_delivery_run_record(
|
||||
store,
|
||||
delivery,
|
||||
status="retrying" if retried else "error",
|
||||
error=error,
|
||||
)
|
||||
store.record_delivery(
|
||||
delivery.trigger_id,
|
||||
status="error",
|
||||
error=error,
|
||||
run_at_ms=delivery.created_at_ms,
|
||||
)
|
||||
logger.exception(
|
||||
"Trigger: failed delivery {} for {}{}",
|
||||
delivery.id,
|
||||
delivery.trigger_id,
|
||||
"; queued retry" if retried else "; moved to failed queue",
|
||||
)
|
||||
if not deliveries:
|
||||
await asyncio.sleep(poll_interval_s)
|
||||
|
||||
|
||||
async def _run_delivery(
|
||||
store: LocalTriggerStore,
|
||||
delivery: TriggerDelivery,
|
||||
*,
|
||||
submit_turn: Callable[[InboundMessage], Awaitable[OutboundMessage | None]],
|
||||
is_channel_enabled: Callable[[str], bool],
|
||||
) -> None:
|
||||
try:
|
||||
await _deliver_delivery(
|
||||
store, delivery, submit_turn=submit_turn, is_channel_enabled=is_channel_enabled,
|
||||
)
|
||||
store.complete_delivery(delivery)
|
||||
except asyncio.CancelledError as exc:
|
||||
store.retry_delivery(delivery, str(exc) or exc.__class__.__name__)
|
||||
_write_delivery_run_record(
|
||||
store, delivery, status="interrupted", error=str(exc) or exc.__class__.__name__,
|
||||
)
|
||||
raise
|
||||
except _TerminalDeliveryError as exc:
|
||||
store.record_delivery(
|
||||
delivery.trigger_id, status="error", error=str(exc), run_at_ms=delivery.created_at_ms,
|
||||
)
|
||||
_write_delivery_run_record(store, delivery, status="error", error=str(exc))
|
||||
store.complete_delivery(delivery)
|
||||
logger.warning(
|
||||
"Trigger: dropped delivery {} for {}: {}", delivery.id, delivery.trigger_id, exc,
|
||||
)
|
||||
except AutomationTurnError as exc:
|
||||
error = str(exc) or exc.__class__.__name__
|
||||
store.record_delivery(
|
||||
delivery.trigger_id, status="error", error=error, run_at_ms=delivery.created_at_ms,
|
||||
)
|
||||
_write_delivery_run_record(store, delivery, status="error", error=error)
|
||||
store.complete_delivery(delivery)
|
||||
logger.warning(
|
||||
"Trigger: delivery {} for {} reached the agent but failed: {}",
|
||||
delivery.id, delivery.trigger_id, error,
|
||||
)
|
||||
except Exception as exc:
|
||||
error = str(exc) or exc.__class__.__name__
|
||||
retried = store.retry_delivery(delivery, error)
|
||||
_write_delivery_run_record(
|
||||
store, delivery, status="retrying" if retried else "error", error=error,
|
||||
)
|
||||
store.record_delivery(
|
||||
delivery.trigger_id, status="error", error=error, run_at_ms=delivery.created_at_ms,
|
||||
)
|
||||
logger.exception(
|
||||
"Trigger: failed delivery {} for {}{}", delivery.id, delivery.trigger_id,
|
||||
"; queued retry" if retried else "; moved to failed queue",
|
||||
)
|
||||
|
||||
|
||||
class _TerminalDeliveryError(RuntimeError):
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
"""Update the current installation from PyPI or an editable source checkout."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import sysconfig
|
||||
import tempfile
|
||||
import tomllib
|
||||
import urllib.request
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import contextmanager, suppress
|
||||
from importlib.metadata import MetadataPathFinder, PackageNotFoundError, distribution
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
from packaging.version import Version
|
||||
|
||||
from nanobot import __version__
|
||||
from nanobot.bun import bun_environment, ensure_bun
|
||||
from nanobot.installation_lock import (
|
||||
InstallationBusyError,
|
||||
installation_access,
|
||||
installation_id,
|
||||
pending_update_path,
|
||||
)
|
||||
|
||||
_SOURCE_URL = "https://github.com/HKUDS/nanobot.git"
|
||||
|
||||
|
||||
class UpdateError(RuntimeError):
|
||||
"""An update cannot proceed or did not finish successfully."""
|
||||
|
||||
def __init__(self, message: str, *, needs_repair: bool = False) -> None:
|
||||
super().__init__(message)
|
||||
self.needs_repair = needs_repair
|
||||
|
||||
|
||||
class UpdateResult(TypedDict):
|
||||
version: str
|
||||
source: str
|
||||
requires_restart: bool
|
||||
|
||||
|
||||
def _run(
|
||||
command: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
command, cwd=cwd, env=env, capture_output=True, text=True,
|
||||
encoding="utf-8", errors="replace", timeout=900,
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise UpdateError(f"Could not run {Path(command[0]).name}: {exc}") from exc
|
||||
return result
|
||||
|
||||
|
||||
def _checked(command: list[str], *, cwd: Path | None = None) -> str:
|
||||
result = _run(command, cwd=cwd)
|
||||
if result.returncode:
|
||||
raise UpdateError((result.stderr or result.stdout).strip()[-4000:])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def source_checkout() -> Path | None:
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
if (root / "pyproject.toml").is_file() and (root / "tui/package.json").is_file():
|
||||
return root
|
||||
return None
|
||||
|
||||
|
||||
def latest_release() -> str:
|
||||
"""Read the current stable PyPI release; network failures are not 'up to date'."""
|
||||
try:
|
||||
with urllib.request.urlopen("https://pypi.org/pypi/nanobot-ai/json", timeout=15) as response:
|
||||
payload = json.loads(response.read(4 * 1024 * 1024))
|
||||
version = payload["info"]["version"]
|
||||
if not isinstance(version, str) or not version:
|
||||
raise ValueError("missing release version")
|
||||
parsed = Version(version)
|
||||
if parsed.is_prerelease or parsed.is_devrelease:
|
||||
raise ValueError("PyPI returned a prerelease")
|
||||
return str(parsed)
|
||||
except (OSError, ValueError, KeyError, TypeError) as exc:
|
||||
raise UpdateError(f"Could not check PyPI: {exc}") from exc
|
||||
|
||||
|
||||
def update_blocked_reason(*, dev: bool = False) -> str:
|
||||
"""Do not replace files owned by another deployment or package manager."""
|
||||
if Path("/.dockerenv").exists() or os.environ.get("RENDER") == "true":
|
||||
return "This installation is deployed in a container. Rebuild and redeploy its image."
|
||||
prefix = Path(sys.prefix)
|
||||
if (prefix / "uv-receipt.toml").exists():
|
||||
return "Use `uv tool upgrade nanobot-ai` in the gateway's account to preserve its uv tool settings."
|
||||
if (prefix / "pipx_metadata.json").exists():
|
||||
return "Update through pipx in the gateway's account. Review its original constraints and installer options before upgrading; a generic pipx upgrade can discard them."
|
||||
if sys.prefix == sys.base_prefix:
|
||||
return "Use the installer or package manager that owns this Python installation. In-app updates require a virtual environment."
|
||||
if not dev and source_checkout() is not None:
|
||||
return (
|
||||
"This gateway runs from source. Use the source update option to keep its checkout. "
|
||||
"To switch to a release, stop nanobot, install it in a separate environment, "
|
||||
"and launch it outside the checkout."
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def incomplete_update() -> bool:
|
||||
"""A marker survives failure or process termination after mutation begins."""
|
||||
return pending_update_path().exists()
|
||||
|
||||
|
||||
def _mark_installing() -> None:
|
||||
path = pending_update_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8") as marker:
|
||||
marker.write("Installation may be incomplete. Stop nanobot and retry the update.\n")
|
||||
marker.flush()
|
||||
os.fsync(marker.fileno())
|
||||
|
||||
|
||||
def _verify_installation(expected: str, source: str) -> None:
|
||||
# Match normal `python -m nanobot` restart resolution as well as isolated
|
||||
# installed-package resolution. A version from dist-info alone can hide a
|
||||
# checkout shadowing the installed wheel through cwd or PYTHONPATH.
|
||||
probe = (
|
||||
"import json, nanobot; from pathlib import Path; "
|
||||
"print(json.dumps([nanobot.__version__, str(Path(nanobot.__file__).resolve())]))"
|
||||
)
|
||||
installed = json.loads(_checked([sys.executable, "-I", "-c", probe]))
|
||||
restarted = json.loads(_checked([sys.executable, "-c", probe]))
|
||||
if installed[0] != expected:
|
||||
raise UpdateError(f"Installed version is {installed[0]}, expected {expected}. Check the installation environment.")
|
||||
if installed != restarted:
|
||||
raise UpdateError(
|
||||
"The restart would load a different nanobot package. Stop nanobot and restart "
|
||||
"outside the source checkout, without a source directory in PYTHONPATH."
|
||||
)
|
||||
if source != "pypi" and Path(installed[1]).parent != Path(source) / "nanobot":
|
||||
raise UpdateError("The interpreter does not load the updated source checkout. Check the editable installation.")
|
||||
|
||||
|
||||
def _prepare_source(
|
||||
output: Callable[[str], None], *, before_change: Callable[[], None] = lambda: None,
|
||||
) -> Path:
|
||||
git = shutil.which("git")
|
||||
if not git:
|
||||
raise UpdateError("Source updates require Git. Install Git and retry, or use a release update.")
|
||||
root = source_checkout()
|
||||
if root is None:
|
||||
root = Path.home() / ".nanobot" / "src" / installation_id()[:16]
|
||||
root.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not root.exists():
|
||||
output("Downloading nanobot source…")
|
||||
with tempfile.TemporaryDirectory(prefix=".clone-", dir=root.parent) as temporary:
|
||||
candidate = Path(temporary) / "nanobot"
|
||||
_checked([git, "clone", "--depth", "1", "--branch", "main", _SOURCE_URL, str(candidate)])
|
||||
candidate.rename(root)
|
||||
if not (root / ".git").exists():
|
||||
raise UpdateError(f"{root} is not a Git checkout. Update its sources manually.")
|
||||
if _checked([git, "status", "--porcelain"], cwd=root):
|
||||
raise UpdateError(f"Source checkout has local changes: {root}. Commit or move them before updating.")
|
||||
branch = _checked([git, "branch", "--show-current"], cwd=root)
|
||||
if not branch:
|
||||
raise UpdateError("Source checkout has a detached HEAD. Select a branch before updating.")
|
||||
remote_result = _run([git, "config", f"branch.{branch}.remote"], cwd=root)
|
||||
remote = remote_result.stdout.strip()
|
||||
if remote_result.returncode or not remote:
|
||||
raise UpdateError("The source branch has no upstream. Configure its upstream before updating.")
|
||||
output(f"Updating source branch {branch}…")
|
||||
_checked([git, "fetch", "--", remote], cwd=root)
|
||||
if _run([git, "merge-base", "--is-ancestor", "HEAD", "@{upstream}"], cwd=root).returncode:
|
||||
raise UpdateError("The source branch cannot fast-forward to its upstream. Reconcile it manually.")
|
||||
before_change()
|
||||
_checked([git, "merge", "--ff-only", "@{upstream}"], cwd=root)
|
||||
return root
|
||||
|
||||
|
||||
def _install(arguments: list[str], *, upgrade: bool = False) -> None:
|
||||
from nanobot.optional_features import install_packages
|
||||
|
||||
with _release_windows_launchers():
|
||||
result = install_packages(arguments, "nanobot update", upgrade=upgrade, runner=_run)
|
||||
if not result.ok:
|
||||
raise UpdateError(f"Package installation failed: {result.output[-4000:]}")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _release_windows_launchers() -> Generator[None]:
|
||||
"""Windows permits renaming running launchers, but pip cannot overwrite them."""
|
||||
moved: list[tuple[Path, Path]] = []
|
||||
try:
|
||||
if sys.platform == "win32":
|
||||
import gc
|
||||
|
||||
# Metadata discovery can keep the launcher's embedded ZIP open on Windows.
|
||||
importlib.invalidate_caches()
|
||||
MetadataPathFinder().invalidate_caches()
|
||||
gc.collect()
|
||||
scripts = Path(sysconfig.get_path("scripts"))
|
||||
for name in ("nanobot.exe", "nanobot-desktop-tui.exe"):
|
||||
launcher = scripts / name
|
||||
backup = scripts / f".{name}.update-backup"
|
||||
try:
|
||||
if backup.is_file() and not launcher.exists():
|
||||
backup.rename(launcher)
|
||||
else:
|
||||
backup.unlink(missing_ok=True)
|
||||
except PermissionError as exc:
|
||||
raise UpdateError("Restart running nanobot processes before updating again.") from exc
|
||||
if launcher.is_file():
|
||||
try:
|
||||
launcher.rename(backup)
|
||||
except PermissionError as exc:
|
||||
raise UpdateError(
|
||||
"Stop other nanobot processes and retry with `python -m nanobot update`."
|
||||
) from exc
|
||||
moved.append((launcher, backup))
|
||||
yield
|
||||
finally:
|
||||
for launcher, backup in reversed(moved):
|
||||
if not launcher.exists():
|
||||
backup.rename(launcher)
|
||||
else:
|
||||
# An old gateway/console may still hold this file; the next update cleans it.
|
||||
with suppress(PermissionError):
|
||||
backup.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _is_editable() -> bool:
|
||||
try:
|
||||
raw = distribution("nanobot-ai").read_text("direct_url.json")
|
||||
return bool(raw and json.loads(raw).get("dir_info", {}).get("editable"))
|
||||
except (PackageNotFoundError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def _installed_version() -> Version:
|
||||
# Another gateway or CLI process may have changed this shared environment
|
||||
# since __version__ was imported. Read the interpreter's current metadata.
|
||||
probe = (
|
||||
"from importlib.metadata import version, PackageNotFoundError\n"
|
||||
"try: print(version('nanobot-ai'))\n"
|
||||
"except PackageNotFoundError: print('')\n"
|
||||
)
|
||||
return Version(_checked([sys.executable, "-I", "-c", probe]) or __version__)
|
||||
|
||||
|
||||
def update_installation(
|
||||
*, dev: bool = False, allow_downgrade: bool = False, output: Callable[[str], None] = print,
|
||||
) -> UpdateResult:
|
||||
"""Update application files and verify their version in a fresh interpreter."""
|
||||
reason = update_blocked_reason(dev=dev)
|
||||
if reason:
|
||||
raise UpdateError(reason)
|
||||
try:
|
||||
with installation_access(updating=True):
|
||||
if incomplete_update():
|
||||
with pending_update_path().open("rb") as marker:
|
||||
legacy_marker = marker.read(31).startswith(b"Installation may be incomplete.")
|
||||
if not legacy_marker:
|
||||
raise UpdateError(
|
||||
"A saved update job owns this installation. Resume that exact job; "
|
||||
"the legacy updater cannot replace it with a new target.", needs_repair=True,
|
||||
)
|
||||
if dev:
|
||||
bun = ensure_bun(output=output)
|
||||
root = _prepare_source(output, before_change=_mark_installing)
|
||||
output("Preparing TUI dependencies…")
|
||||
with bun_environment(bun) as env:
|
||||
result = _run([bun, "install", "--frozen-lockfile"], cwd=root / "tui", env=env)
|
||||
if result.returncode:
|
||||
raise UpdateError(f"TUI dependencies failed: {(result.stderr or result.stdout)[-4000:]}")
|
||||
output("Building WebUI…")
|
||||
from nanobot.webui.build import build_webui_bundle
|
||||
|
||||
build_webui_bundle(
|
||||
source_dir=root / "webui", dist_dir=root / "nanobot/web/dist",
|
||||
runner=bun, output=output,
|
||||
)
|
||||
output("Synchronizing Python dependencies…")
|
||||
_install(["--editable", str(root)])
|
||||
expected = str(tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]["version"])
|
||||
source = str(root)
|
||||
else:
|
||||
expected = latest_release()
|
||||
installed = _installed_version()
|
||||
current = max(installed, Version(__version__))
|
||||
if Version(expected) < current and not allow_downgrade:
|
||||
raise UpdateError(
|
||||
f"Current version {current} is newer than stable {expected}. "
|
||||
"No files changed. Back up your data before an intentional downgrade, "
|
||||
"then run `nanobot update --allow-downgrade`."
|
||||
)
|
||||
target = f"nanobot-ai=={expected}"
|
||||
editable = _is_editable()
|
||||
repairing = incomplete_update()
|
||||
if Version(expected) == installed and not editable and not repairing:
|
||||
_verify_installation(expected, "pypi")
|
||||
return {
|
||||
"version": expected, "source": "pypi",
|
||||
"requires_restart": installed != Version(__version__),
|
||||
}
|
||||
output(f"Installing nanobot {expected} from PyPI…")
|
||||
_mark_installing()
|
||||
_install([target], upgrade=True)
|
||||
if repairing or (editable and _is_editable()):
|
||||
# Same-version metadata does not prove files survived an interrupted
|
||||
# install. Resolve dependencies above, then replace application files.
|
||||
_install(["--force-reinstall", "--no-deps", target])
|
||||
source = "pypi"
|
||||
output("Verifying the installed version…")
|
||||
_verify_installation(expected, source)
|
||||
pending_update_path().unlink()
|
||||
return {"version": expected, "source": source, "requires_restart": True}
|
||||
except InstallationBusyError as exc:
|
||||
raise UpdateError(str(exc), needs_repair=incomplete_update()) from exc
|
||||
except Exception as exc:
|
||||
if incomplete_update():
|
||||
raise UpdateError(
|
||||
f"{exc}\nInstallation may be incomplete. Stop nanobot and retry the same update "
|
||||
"from its Python environment before restarting. No automatic rollback was performed.",
|
||||
needs_repair=True,
|
||||
) from exc
|
||||
raise
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Private, scoped pre-update snapshots for the standalone update worker.
|
||||
|
||||
Only named nanobot stores are included, never the whole home or user project.
|
||||
The caller must stop writers first; checking a stable inventory detects concurrent
|
||||
changes but is not a substitute for that ownership handoff. This module deliberately
|
||||
does not implement automatic restore or claim to snapshot external services.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Literal, cast
|
||||
from zipfile import ZIP_STORED, ZipFile
|
||||
|
||||
from nanobot.utils.atomic_file import atomic_write_lines
|
||||
|
||||
_MAX_ENTRIES = 100_000
|
||||
_MAX_BYTES = 10 * 1024**3
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BackupSource:
|
||||
path: str
|
||||
|
||||
@classmethod
|
||||
def parse(cls, value: object) -> BackupSource:
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Invalid backup source")
|
||||
path = cast(dict[object, object], value).get("path")
|
||||
if not isinstance(path, str) or not Path(path).is_absolute() or len(path) > 4096 or "\0" in path:
|
||||
raise ValueError("Backup sources must be bounded absolute paths")
|
||||
return cls(path)
|
||||
|
||||
|
||||
def unique_sources(sources: list[BackupSource]) -> tuple[BackupSource, ...]:
|
||||
return tuple(BackupSource(path) for path in sorted({source.path for source in sources}))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Entry:
|
||||
path: str
|
||||
kind: Literal["file", "directory", "missing"]
|
||||
size: int
|
||||
mode: int
|
||||
mtime_ns: int
|
||||
ctime_ns: int
|
||||
device: int
|
||||
inode: int
|
||||
|
||||
|
||||
def _entry(path: Path) -> _Entry:
|
||||
try:
|
||||
info = path.lstat()
|
||||
except FileNotFoundError:
|
||||
return _Entry(str(path), "missing", 0, 0, 0, 0, 0, 0)
|
||||
if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||
raise ValueError("A backup store contains a symlink or reparse point; review its external data before updating")
|
||||
if not stat.S_ISREG(info.st_mode) and not stat.S_ISDIR(info.st_mode):
|
||||
raise ValueError("A backup store contains a special file; stop its owner before updating")
|
||||
if path.resolve() != path:
|
||||
raise ValueError("A backup store has a redirected parent path; review its data location before updating")
|
||||
kind = "directory" if stat.S_ISDIR(info.st_mode) else "file"
|
||||
return _Entry(str(path), kind, info.st_size if kind == "file" else 0, stat.S_IMODE(info.st_mode),
|
||||
info.st_mtime_ns, info.st_ctime_ns, info.st_dev, info.st_ino)
|
||||
|
||||
|
||||
def _inventory(sources: tuple[BackupSource, ...]) -> list[_Entry]:
|
||||
entries: dict[str, _Entry] = {}
|
||||
pending = [Path(source.path) for source in sources]
|
||||
total = 0
|
||||
while pending:
|
||||
path = pending.pop()
|
||||
if str(path) in entries:
|
||||
continue
|
||||
item = _entry(path)
|
||||
entries[item.path] = item
|
||||
total += item.size
|
||||
if len(entries) > _MAX_ENTRIES or total > _MAX_BYTES:
|
||||
raise ValueError("The managed backup exceeds 100,000 entries or 10 GiB; use an explicit maintenance backup")
|
||||
if item.kind == "directory":
|
||||
with os.scandir(path) as children:
|
||||
for child in children:
|
||||
pending.append(Path(child.path))
|
||||
if len(pending) + len(entries) > _MAX_ENTRIES:
|
||||
raise ValueError("The managed backup has too many entries; use an explicit maintenance backup")
|
||||
return sorted(entries.values(), key=lambda entry: entry.path)
|
||||
|
||||
|
||||
def _sources_digest(sources: tuple[BackupSource, ...]) -> str:
|
||||
return hashlib.sha256(json.dumps([asdict(source) for source in sources], sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def _inventory_digest(entries: list[_Entry]) -> str:
|
||||
return hashlib.sha256(json.dumps([asdict(entry) for entry in entries], sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def _file_digest(path: Path) -> str:
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def current_file_hashes(sources: tuple[BackupSource, ...]) -> dict[str, str]:
|
||||
"""Compare user contents with a backup using the same bounded path policy."""
|
||||
entries = _inventory(sources)
|
||||
result = {item.path: _file_digest(Path(item.path)) for item in entries if item.kind == "file"}
|
||||
if _inventory(sources) != entries:
|
||||
raise ValueError("User data changed during recovery verification")
|
||||
return result
|
||||
|
||||
|
||||
def verify_backup(directory: Path, sources: tuple[BackupSource, ...], request_sha256: str, *, unchanged: bool = False) -> Path:
|
||||
"""Verify the original snapshot; before first mutation, require unchanged data."""
|
||||
root = directory / "backup"
|
||||
receipt, archive = root / "receipt.json", root / "data.zip"
|
||||
if root.is_symlink() or receipt.is_symlink() or receipt.stat().st_size > 16 * 1024:
|
||||
raise ValueError("Invalid pre-update backup receipt")
|
||||
raw: object = json.loads(receipt.read_bytes())
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("Invalid pre-update backup receipt")
|
||||
record = cast(dict[str, object], raw)
|
||||
if (record.get("schema_version") != 1 or record.get("request_sha256") != request_sha256 or
|
||||
record.get("sources_sha256") != _sources_digest(sources)):
|
||||
raise ValueError("The pre-update backup belongs to a different update or data scope")
|
||||
info = archive.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or archive.is_symlink() or info.st_size != record.get("archive_size"):
|
||||
raise ValueError("The original pre-update backup is missing or changed; do not replace it with current data")
|
||||
if _file_digest(archive) != record.get("archive_sha256"):
|
||||
raise ValueError("The original pre-update backup checksum changed; installation is blocked")
|
||||
if unchanged and _inventory_digest(_inventory(sources)) != record.get("inventory_sha256"):
|
||||
raise ValueError("Data changed after backup but before installation; prepare a new update plan and preserve this backup")
|
||||
return archive
|
||||
|
||||
|
||||
def ensure_backup(directory: Path, sources: tuple[BackupSource, ...], request_sha256: str, *, mutated: bool) -> Path:
|
||||
"""Commit one complete backup, or retain it unchanged across exact-job retries."""
|
||||
final = directory / "backup"
|
||||
if final.exists() or final.is_symlink():
|
||||
return verify_backup(directory, sources, request_sha256, unchanged=not mutated)
|
||||
if mutated:
|
||||
raise ValueError("The original pre-update backup is missing; repair cannot snapshot already changed data")
|
||||
for source in sources:
|
||||
if directory.resolve().is_relative_to(Path(source.path)):
|
||||
raise ValueError("Backup scope includes the update job itself")
|
||||
entries = _inventory(sources)
|
||||
total = sum(item.size for item in entries)
|
||||
if shutil.disk_usage(directory).free < total + 16 * 1024**2 + len(entries) * 1024:
|
||||
raise ValueError("Not enough space for the required pre-update backup; no packages were changed")
|
||||
# A crash leaves a private incomplete attempt, never a plausible completed
|
||||
# backup. A retry uses a new attempt; no original recovery material is deleted.
|
||||
staging = Path(tempfile.mkdtemp(prefix=".backup-", dir=directory))
|
||||
archive = staging / "data.zip"
|
||||
records: list[dict[str, object]] = []
|
||||
with archive.open("xb") as output:
|
||||
os.chmod(archive, 0o600)
|
||||
with ZipFile(output, "w", compression=ZIP_STORED, allowZip64=True) as bundle:
|
||||
for index, item in enumerate(entries):
|
||||
record: dict[str, object] = {**asdict(item)}
|
||||
if item.kind == "file":
|
||||
path = Path(item.path)
|
||||
if _entry(path) != item:
|
||||
raise ValueError("Data changed while preparing its backup; stop writers and retry")
|
||||
flags = (os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
||||
| getattr(os, "O_BINARY", 0))
|
||||
with os.fdopen(os.open(path, flags), "rb") as source:
|
||||
opened = os.fstat(source.fileno())
|
||||
if not stat.S_ISREG(opened.st_mode) or (opened.st_dev, opened.st_ino) != (item.device, item.inode):
|
||||
raise ValueError("A backup file was replaced while opening it")
|
||||
name, digest, copied = f"files/{index}", hashlib.sha256(), 0
|
||||
with bundle.open(name, "w", force_zip64=True) as target:
|
||||
while chunk := source.read(1024 * 1024):
|
||||
copied += len(chunk)
|
||||
if copied > item.size:
|
||||
raise ValueError("Data grew during backup; stop writers and retry")
|
||||
digest.update(chunk)
|
||||
target.write(chunk)
|
||||
if copied != item.size or _entry(path) != item:
|
||||
raise ValueError("Data changed during backup; stop writers and retry")
|
||||
record.update(member=name, sha256=digest.hexdigest())
|
||||
records.append(record)
|
||||
if _inventory(sources) != entries:
|
||||
raise ValueError("Data changed during backup; stop writers and retry")
|
||||
bundle.writestr("manifest.json", json.dumps({
|
||||
"schema_version": 1, "scope": "named nanobot stores from recorded gateway profiles",
|
||||
"excluded": ["arbitrary project files", "installed integration binaries and caches", "external services and custom stores"],
|
||||
"sources": [asdict(s) for s in sources], "entries": records,
|
||||
}, separators=(",", ":")))
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
record = {"schema_version": 1, "request_sha256": request_sha256, "sources_sha256": _sources_digest(sources),
|
||||
"inventory_sha256": _inventory_digest(entries),
|
||||
"archive_size": archive.stat().st_size, "archive_sha256": _file_digest(archive),
|
||||
"entries": len(entries), "source_bytes": total, "created_at": int(time.time())}
|
||||
atomic_write_lines(staging / "receipt.json", [json.dumps(record, sort_keys=True)])
|
||||
(staging / "receipt.json").chmod(0o600)
|
||||
os.rename(staging, final)
|
||||
# Publish the directory durably; Windows may not permit directory fsync.
|
||||
with suppress(PermissionError):
|
||||
descriptor = os.open(directory, os.O_RDONLY)
|
||||
try:
|
||||
try:
|
||||
os.fsync(descriptor)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EINVAL:
|
||||
raise
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
return final / "data.zip"
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Installation-owned update preference, separate from versions and consent."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.installation_lock import installation_state_dir
|
||||
from nanobot.releases import Channel, ReleaseRecord
|
||||
from nanobot.utils.atomic_file import atomic_write_lines, read_atomic_bytes
|
||||
|
||||
|
||||
class UpdateChannel(ReleaseRecord):
|
||||
schema_version: Literal[1] = 1
|
||||
channel: Channel = "stable"
|
||||
revision: int = Field(default=0, ge=0)
|
||||
|
||||
|
||||
class UpdateChannelRequest(ReleaseRecord):
|
||||
channel: Channel
|
||||
revision: int = Field(ge=0)
|
||||
|
||||
|
||||
def read_update_channel(environment: str | Path | None = None) -> UpdateChannel:
|
||||
path = installation_state_dir(environment) / "channel.json"
|
||||
try:
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid update channel record")
|
||||
return UpdateChannel.model_validate_json(read_atomic_bytes(path, max_bytes=4097))
|
||||
except FileNotFoundError:
|
||||
# Existing installations remain on Stable. A dev version is not consent.
|
||||
return UpdateChannel()
|
||||
|
||||
|
||||
def write_update_channel(selection: UpdateChannel, environment: str | Path | None = None) -> None:
|
||||
"""Caller holds channel.lock and has checked the active job lifecycle."""
|
||||
root = installation_state_dir(environment)
|
||||
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
path = root / "channel.json"
|
||||
atomic_write_lines(path, [selection.model_dump_json()])
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def validate_channel_revision(revision: int | None, environment: str) -> None:
|
||||
if (revision or 0) != read_update_channel(environment).revision:
|
||||
raise ValueError("Update channel changed; review a new update before confirming")
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"handoff_protocols": [1]
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
"""Frozen service recovery for one explicitly confirmed update.
|
||||
|
||||
Keep this module stdlib-only. A program snapshot is not a data backup: recovery
|
||||
never restores user stores. Same-filesystem renames retain both program generations.
|
||||
The caller must hold exclusive installation/data leases before snapshot or restore.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from importlib.metadata import distributions
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from zipfile import ZipFile
|
||||
|
||||
from nanobot.installation_lock import (
|
||||
InstallationBusyError,
|
||||
file_access,
|
||||
installation_access,
|
||||
installation_state_dir,
|
||||
pending_update_path,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.update_worker import EnvironmentSnapshot, WorkerSpec
|
||||
|
||||
|
||||
def _digest(path: Path) -> str:
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def _sync_directory(path: Path) -> None:
|
||||
# Windows does not expose POSIX directory fsync through this interface.
|
||||
if os.name != "nt":
|
||||
descriptor = os.open(path, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(descriptor)
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def _inspect_metadata(spec: WorkerSpec) -> EnvironmentSnapshot:
|
||||
"""Read ownership without executing a possibly broken candidate's site hooks."""
|
||||
from nanobot.update_worker import EnvironmentSnapshot
|
||||
|
||||
root = Path(spec.baseline.environment)
|
||||
sites = [root / "Lib/site-packages"] if os.name == "nt" else list((root / "lib").glob("python*/site-packages"))
|
||||
if len(sites) != 1 or not sites[0].is_dir() or sites[0].is_symlink():
|
||||
raise ValueError("The selected installation's package location changed")
|
||||
items: dict[str, str] = {}
|
||||
versions: dict[str, str] = {}
|
||||
records: dict[str, str] = {}
|
||||
for distribution in distributions(path=[str(sites[0])]):
|
||||
raw_name, version = distribution.metadata["Name"], distribution.version
|
||||
if not raw_name or not version:
|
||||
# Interrupted pip transactions can leave an incomplete dist-info.
|
||||
# Missing targets are allowed by check_environment(repairing=True);
|
||||
# missing unrelated distributions still fail its baseline comparison.
|
||||
continue
|
||||
name = re.sub(r"[-_.]+", "-", raw_name).lower()
|
||||
payload = "\n".join(distribution.read_text(f) or "" for f in ("METADATA", "RECORD", "direct_url.json"))
|
||||
items[name] = hashlib.sha256(payload.encode()).hexdigest()
|
||||
versions[name] = version
|
||||
if name == "nanobot-ai":
|
||||
records = {key: hashlib.sha256((distribution.read_text(key) or "").encode()).hexdigest()
|
||||
for key in ("RECORD", "direct_url.json")}
|
||||
return EnvironmentSnapshot(str(root), spec.baseline.python, spec.baseline.base_python,
|
||||
_digest(root / "pyvenv.cfg"), items, versions, versions.get("nanobot-ai", ""), records,
|
||||
_digest(root / "uv-receipt.toml") if (root / "uv-receipt.toml").exists() else None,
|
||||
_digest(root / "nanobot-install.json") if (root / "nanobot-install.json").exists() else None)
|
||||
|
||||
|
||||
def _tree(root: Path) -> dict[str, tuple[str, str, int]]:
|
||||
"""Hash files and preserve symlinks without following them outside the venv."""
|
||||
result: dict[str, tuple[str, str, int]] = {}
|
||||
for directory, folders, files in os.walk(root, followlinks=False):
|
||||
for name in [*folders, *files]:
|
||||
path = Path(directory) / name
|
||||
info = path.lstat()
|
||||
key = str(path.relative_to(root))
|
||||
mode = stat.S_IMODE(info.st_mode)
|
||||
if path.is_symlink():
|
||||
result[key] = ("link", os.readlink(path), mode)
|
||||
elif getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||
raise ValueError("The program environment contains a redirected directory")
|
||||
elif stat.S_ISDIR(info.st_mode):
|
||||
result[key] = ("directory", "", mode)
|
||||
elif stat.S_ISREG(info.st_mode):
|
||||
result[key] = ("file", _digest(path), mode)
|
||||
else:
|
||||
raise ValueError("The program environment contains a special file; it cannot be preserved safely")
|
||||
return result
|
||||
|
||||
|
||||
def _tree_digest(root: Path) -> str:
|
||||
return hashlib.sha256(json.dumps(_tree(root), sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def _paths(spec: WorkerSpec) -> tuple[Path, Path, Path]:
|
||||
environment = Path(spec.baseline.environment)
|
||||
# No user-supplied restore destination or recursive deletion. The original
|
||||
# venv path remains its identity (and keeps console-script shebangs valid).
|
||||
if environment.is_symlink() or environment.parent == environment or environment == Path.home():
|
||||
raise ValueError("Invalid program restoration destination")
|
||||
return (environment, environment.with_name(f".nanobot-original-{spec.plan_id}"),
|
||||
environment.with_name(f".nanobot-failed-{spec.plan_id}"))
|
||||
|
||||
|
||||
def _copy_program_file(source: str, destination: str) -> str:
|
||||
shutil.copyfile(source, destination)
|
||||
# Windows fsync requires a writable handle. Open it before copystat restores
|
||||
# a package file's read-only flag; keep that handle through metadata sync.
|
||||
with Path(destination).open("rb+") as stream:
|
||||
shutil.copystat(source, destination)
|
||||
os.fsync(stream.fileno())
|
||||
return destination
|
||||
|
||||
|
||||
def preserve_program(directory: Path, spec: WorkerSpec) -> None:
|
||||
from nanobot.update_worker import read_record, write_record
|
||||
|
||||
if not spec.automatic_recovery or spec.uv is not None:
|
||||
return
|
||||
environment, original, _ = _paths(spec)
|
||||
receipt = directory / "program-backup.json"
|
||||
if receipt.exists():
|
||||
record = read_record(receipt)
|
||||
if record.get("request_sha256") != _digest(directory / "request.json") or record.get("sha256") != _tree_digest(original):
|
||||
raise ValueError("The original program snapshot changed")
|
||||
return
|
||||
if original.exists() or original.is_symlink():
|
||||
raise ValueError("An incomplete program snapshot already exists; keep it for diagnosis")
|
||||
# Refuse nested data: a program-only restoration must never move user data.
|
||||
if any(Path(source.path).is_relative_to(environment) and Path(source.path) not in {
|
||||
environment / "pyvenv.cfg", environment / "nanobot-install.json",
|
||||
} for source in spec.backup_sources):
|
||||
raise ValueError("User data is inside the program environment; automatic program restoration is unsafe")
|
||||
size = sum(path.stat().st_size for path in environment.rglob("*") if path.is_file() and not path.is_symlink())
|
||||
if shutil.disk_usage(environment.parent).free < size + 32 * 1024**2:
|
||||
raise ValueError("Not enough space to preserve the original program; no packages were changed")
|
||||
before = _tree_digest(environment)
|
||||
shutil.copytree(environment, original, symlinks=True, copy_function=_copy_program_file)
|
||||
original.chmod(0o700)
|
||||
# File copies are durable; flush directory entries before the receipt.
|
||||
for root, _, _ in os.walk(original, topdown=False, followlinks=False):
|
||||
_sync_directory(Path(root))
|
||||
if _tree_digest(original) != before or _tree_digest(environment) != before:
|
||||
raise ValueError("The program changed during its snapshot; no packages were changed")
|
||||
write_record(receipt, {"plan_id": spec.plan_id, "request_sha256": _digest(directory / "request.json"), "sha256": before})
|
||||
_sync_directory(original.parent)
|
||||
|
||||
|
||||
def require_unchanged_user_data(directory: Path, spec: WorkerSpec) -> None:
|
||||
"""Compare contents, not mtimes; never write a byte to a user store."""
|
||||
from nanobot.update_backup import BackupSource, current_file_hashes, verify_backup
|
||||
|
||||
digest = _digest(directory / "request.json")
|
||||
archive = verify_backup(directory, spec.backup_sources, digest)
|
||||
environment = Path(spec.baseline.environment)
|
||||
profiles = installation_state_dir(spec.baseline.environment) / "profiles"
|
||||
sources = [Path(source.path) for source in spec.backup_sources
|
||||
if not Path(source.path).is_relative_to(environment) and not Path(source.path).is_relative_to(profiles)]
|
||||
with ZipFile(archive) as bundle:
|
||||
manifest = json.loads(bundle.read("manifest.json"))
|
||||
expected = {item["path"]: item["sha256"] for item in manifest["entries"]
|
||||
if item["kind"] == "file" and any(Path(item["path"]).is_relative_to(root) for root in sources)}
|
||||
actual = current_file_hashes(tuple(BackupSource(str(source)) for source in sources))
|
||||
if actual != expected:
|
||||
raise ValueError("User data changed after installation; keep the current program and original backup")
|
||||
|
||||
|
||||
def restore_program(directory: Path, spec: WorkerSpec) -> None:
|
||||
from nanobot.update_worker import read_record, write_record
|
||||
|
||||
if spec.uv is not None:
|
||||
raise ValueError("An external package manager owns this program; automatic downgrade is unavailable")
|
||||
environment, original, failed = _paths(spec)
|
||||
receipt = read_record(directory / "program-backup.json")
|
||||
if receipt.get("plan_id") != spec.plan_id or receipt.get("request_sha256") != _digest(directory / "request.json"):
|
||||
raise ValueError("The original program belongs to a different update")
|
||||
if not original.exists():
|
||||
# A crash after the second rename is a completed restoration, not a
|
||||
# reason to snapshot or replace the environment again.
|
||||
if failed.is_dir() and _tree_digest(environment) == receipt.get("sha256"):
|
||||
write_record(directory / "restoration.json", {"plan_id": spec.plan_id, "state": "restarting"})
|
||||
return
|
||||
raise ValueError("The original program snapshot is unavailable")
|
||||
if original.is_symlink() or _tree_digest(original) != receipt.get("sha256"):
|
||||
raise ValueError("The original program snapshot changed")
|
||||
write_record(directory / "restoration.json", {"plan_id": spec.plan_id, "state": "restoring"})
|
||||
if environment.exists():
|
||||
if failed.exists() or failed.is_symlink():
|
||||
raise ValueError("A failed program generation already exists; refusing to replace it")
|
||||
os.rename(environment, failed)
|
||||
_sync_directory(environment.parent)
|
||||
os.rename(original, environment)
|
||||
_sync_directory(environment.parent)
|
||||
# Journal publication follows renames. Both generations remain recoverable.
|
||||
write_record(directory / "restoration.json", {"plan_id": spec.plan_id, "state": "restarting"})
|
||||
|
||||
|
||||
def _shutdown_committed(spec: WorkerSpec) -> bool:
|
||||
from nanobot.update_worker import read_record
|
||||
|
||||
try:
|
||||
stop = read_record(installation_state_dir(spec.baseline.environment) / "stop.json")
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
return stop.get("plan_id") == spec.plan_id and stop.get("phase") in {"commit", "stopped"}
|
||||
|
||||
|
||||
def restore_service(directory: Path, *, confirmation_id: str | None = None) -> None:
|
||||
from nanobot.update_worker import (
|
||||
JobStatus,
|
||||
Phase,
|
||||
WorkerSpec,
|
||||
check_approval,
|
||||
check_environment,
|
||||
read_record,
|
||||
require_pending_owner,
|
||||
restart_runtime,
|
||||
write_record,
|
||||
)
|
||||
|
||||
spec = WorkerSpec.read(directory)
|
||||
root = installation_state_dir(spec.baseline.environment)
|
||||
with file_access(root / "worker.lock", exclusive=True):
|
||||
status = JobStatus.read(directory)
|
||||
if status.phase in {Phase.SUCCEEDED, Phase.RESTORED, Phase.CANCELLED}:
|
||||
return
|
||||
restoration_path = directory / "restoration.json"
|
||||
if restoration_path.exists():
|
||||
restoration = read_record(restoration_path)
|
||||
if (restoration == {"plan_id": spec.plan_id, "state": "restarting"}
|
||||
and status.phase in {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED}):
|
||||
# Program restoration already committed. Resume only its runtime
|
||||
# handoff, including cleanup after old-version activation.
|
||||
if confirmation_id is not None:
|
||||
check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id, check_expiry=False)
|
||||
restart_runtime(directory, spec)
|
||||
return
|
||||
if restoration not in ({"plan_id": spec.plan_id, "state": "restoring"},
|
||||
{"plan_id": spec.plan_id, "state": "restarting"}):
|
||||
raise ValueError("Invalid original-program restoration journal")
|
||||
# Durable activation can mean the new runtime has accepted tasks. Never
|
||||
# downgrade or roll data back after that point.
|
||||
if (directory / "activation.json").exists():
|
||||
raise ValueError("The new runtime was activated; only same-version repair is safe")
|
||||
check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id, check_expiry=False)
|
||||
if not _shutdown_committed(spec):
|
||||
if not status.mutation_started:
|
||||
status.advance(directory, Phase.HANDOFF_FAILED, "Shutdown was not committed; review the update again", mutation_started=False)
|
||||
return # A refused preflight left the original service running.
|
||||
with file_access(root / "handoff-child.lock", exclusive=True):
|
||||
pass
|
||||
restoring = restoration_path.exists()
|
||||
with spec.mutation_access() as (_, data):
|
||||
require_pending_owner(spec)
|
||||
if not restoring or not status.mutation_started:
|
||||
check_environment(spec, repairing=status.mutation_started, current=_inspect_metadata(spec))
|
||||
if status.mutation_started:
|
||||
require_unchanged_user_data(directory, spec)
|
||||
restore_program(directory, spec)
|
||||
else:
|
||||
write_record(directory / "restoration.json", {"plan_id": spec.plan_id, "state": "restarting"})
|
||||
data.reserve()
|
||||
pending = pending_update_path(spec.baseline.environment)
|
||||
pending.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
write_record(pending, {
|
||||
"schema_version": 2, "job_id": spec.plan_id, "version": spec.baseline.app_version,
|
||||
})
|
||||
status.advance(directory, Phase.RESTARTING, "Restoring the original service without changing user data")
|
||||
restart_runtime(directory, spec)
|
||||
|
||||
|
||||
def supervise(directory: Path, arguments: list[str]) -> None:
|
||||
"""One child execution, one exact-target repair, then safe program restoration."""
|
||||
from nanobot.update_worker import (
|
||||
JobStatus,
|
||||
Phase,
|
||||
WorkerSpec,
|
||||
check_approval,
|
||||
read_record,
|
||||
write_record,
|
||||
)
|
||||
|
||||
spec = WorkerSpec.read(directory)
|
||||
if not spec.automatic_recovery or not spec.restart_profiles:
|
||||
raise ValueError("This job did not prepare automatic service recovery")
|
||||
with file_access(installation_state_dir(spec.baseline.environment) / "supervisor.lock", exclusive=True):
|
||||
journal = directory / "supervision.json"
|
||||
confirmation = arguments[2] if len(arguments) == 3 and arguments[0] == "--confirmed-handoff" else None
|
||||
if journal.exists():
|
||||
previous = read_record(journal)
|
||||
if confirmation is None or previous.get("confirmation_id") == confirmation:
|
||||
return # Duplicate/delayed launch is not another recovery budget.
|
||||
# Validate even the first journal publication: a delayed launcher may
|
||||
# have been replaced before any supervisor acquired this lease.
|
||||
if confirmation is not None:
|
||||
check_approval(directory, spec, handoff=True, confirmation_id=confirmation)
|
||||
write_record(journal, {"plan_id": spec.plan_id, "confirmation_id": confirmation, "started_at": int(time.time())})
|
||||
command = [spec.baseline.base_python, "-I", "-S", str(directory / "worker.pyz")]
|
||||
try:
|
||||
subprocess.run([*command, *arguments], check=False, timeout=1800)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass # Orphan children still own leases; recovery cannot race them.
|
||||
status = JobStatus.read(directory)
|
||||
if status.phase in {Phase.SUCCEEDED, Phase.RESTORED, Phase.CANCELLED}:
|
||||
if status.phase == Phase.SUCCEEDED:
|
||||
_discard_program_snapshot(directory, spec)
|
||||
return
|
||||
if (status.phase == Phase.HANDOFF_FAILED and not status.mutation_started
|
||||
and not _shutdown_committed(spec)):
|
||||
# A busy gateway correctly refused shutdown and retains its runtime
|
||||
# lease. Waiting for that lease would hide the refusal for five minutes.
|
||||
return
|
||||
if confirmation is not None:
|
||||
check_approval(directory, spec, handoff=True, confirmation_id=confirmation, check_expiry=False)
|
||||
# Retry only admitted work. No second stop request, download or release
|
||||
# resolution. Lease-owning orphan children must finish before recovery.
|
||||
deadline = time.monotonic() + 300
|
||||
while time.monotonic() < deadline and not (directory / "activation.json").exists():
|
||||
try:
|
||||
with (installation_access(updating=True, environment=spec.baseline.environment),
|
||||
file_access(installation_state_dir(spec.baseline.environment) / "handoff-child.lock", exclusive=True)):
|
||||
break
|
||||
except (InstallationBusyError, BlockingIOError):
|
||||
time.sleep(0.2)
|
||||
if (directory / "approval.json").exists() and not (directory / "restoration.json").exists():
|
||||
try:
|
||||
subprocess.run([*command, "--recover", str(directory)], check=False, timeout=1800)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
if JobStatus.read(directory).phase == Phase.SUCCEEDED:
|
||||
_discard_program_snapshot(directory, spec)
|
||||
return
|
||||
try:
|
||||
try:
|
||||
restore_service(directory, confirmation_id=confirmation)
|
||||
except OSError:
|
||||
# A transient filesystem error between the two renames must
|
||||
# not leave an absent venv. Replay the journal once, retaining
|
||||
# the same snapshot, ownership checks and recovery budget.
|
||||
restore_service(directory, confirmation_id=confirmation)
|
||||
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError):
|
||||
# Keep fences, snapshots and the exact failure state. A hardware,
|
||||
# ownership or changed-data failure is not permission to discard data.
|
||||
status = JobStatus.read(directory)
|
||||
status.advance(directory, status.phase,
|
||||
"Automatic recovery could not safely finish; original backup and program generations are retained")
|
||||
write_record(journal, {"plan_id": spec.plan_id, "confirmation_id": confirmation, "state": "needs_attention"})
|
||||
|
||||
|
||||
def _discard_program_snapshot(directory: Path, spec: WorkerSpec) -> None:
|
||||
"""Remove only this successful job's redundant program copy, never its data backup."""
|
||||
from nanobot.update_worker import read_record
|
||||
|
||||
_, original, _ = _paths(spec)
|
||||
# Cleanup is not part of gateway readiness. Failed cleanup retains evidence
|
||||
# and must not turn an already usable update into another recovery attempt.
|
||||
with suppress(OSError, ValueError):
|
||||
record = read_record(directory / "program-backup.json")
|
||||
if (not original.is_symlink() and record.get("plan_id") == spec.plan_id
|
||||
and original.is_dir() and _tree_digest(original) == record.get("sha256")):
|
||||
shutil.rmtree(original)
|
||||
_sync_directory(original.parent)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Read-only, installation-bound instructions; never an alternative executor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import platform
|
||||
import shlex
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from packaging.version import Version
|
||||
|
||||
from nanobot.installation_receipt import RECEIPT_NAME
|
||||
from nanobot.releases import ReleaseRecord
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.update_plan import InstallationSnapshot
|
||||
|
||||
Method = Literal["managed", "uv", "pipx", "pip", "source", "container", "system"]
|
||||
|
||||
|
||||
def installation_method(installation: InstallationSnapshot) -> Method:
|
||||
if installation.owner == "venv":
|
||||
return "managed" if RECEIPT_NAME in installation.records else "pip"
|
||||
return installation.owner
|
||||
|
||||
|
||||
def shell_command(arguments: list[str], *, windows: bool, environment: tuple[str, str] | None = None) -> str:
|
||||
"""Bind a manager root without changing the user's persistent shell settings."""
|
||||
if not windows:
|
||||
return shlex.join(["env", "=".join(environment), *arguments] if environment else arguments)
|
||||
def quote(value: str) -> str:
|
||||
return "'" + value.replace("'", "''") + "'"
|
||||
command = "& " + " ".join(quote(value) for value in arguments)
|
||||
if environment:
|
||||
name, value = environment
|
||||
command = (f"& {{ $nanobotPrevious = $env:{name}\n"
|
||||
f" try {{ $env:{name} = {quote(value)}; {command} }}\n"
|
||||
f" finally {{ $env:{name} = $nanobotPrevious }}\n}}")
|
||||
return command
|
||||
|
||||
|
||||
class UpdateGuide(ReleaseRecord):
|
||||
method: Method
|
||||
host: str
|
||||
environment: str
|
||||
shell: Literal["sh", "powershell"]
|
||||
inspect_command: str | None = None
|
||||
update_command: str | None = None
|
||||
verify_command: str | None = None
|
||||
reason: Literal["registry", "preview", "policy", "extras", "manager", "source", "container", "system", "review", "restart"]
|
||||
|
||||
|
||||
def update_guide(installation: InstallationSnapshot, target_version: str, *,
|
||||
extras: list[str] | None, current: bool = True) -> UpdateGuide:
|
||||
"""Only offer commands whose owner and environment have been identified.
|
||||
|
||||
uv retains recorded constraints and settings. Generic pipx upgrades are only
|
||||
offered without recorded constraints or pip options. Neither promises our feed's
|
||||
exact target; the UI explains this and requires checking the running version.
|
||||
"""
|
||||
method = installation_method(installation)
|
||||
windows = os.name == "nt"
|
||||
guide = UpdateGuide(method=method, host=platform.node(), environment=installation.environment,
|
||||
shell="powershell" if windows else "sh", reason="review")
|
||||
if not current or Version(target_version) < Version(installation.installed_version) or any(ord(char) < 32 for value in (installation.python, installation.environment,
|
||||
installation.running_package) for char in value):
|
||||
return guide
|
||||
guide = guide.model_copy(update={"verify_command": shell_command([installation.python, "-I", "-m", "nanobot", "--version"], windows=windows)})
|
||||
if Version(target_version) == Version(installation.installed_version) and method != "container":
|
||||
return guide.model_copy(update={"reason": "restart"})
|
||||
if method == "container":
|
||||
# Container paths/hostname are not the deployment host or service name.
|
||||
return guide.model_copy(update={"reason": "container", "verify_command": None})
|
||||
elif method == "source":
|
||||
root = str(Path(installation.running_package).parent.parent)
|
||||
return guide.model_copy(update={"reason": "source", "inspect_command": shell_command(["git", "-C", root, "status", "--short", "--branch"], windows=windows)})
|
||||
elif method == "system":
|
||||
return guide.model_copy(update={"reason": "system"})
|
||||
elif method in {"uv", "pipx"}:
|
||||
directory = Path(installation.environment)
|
||||
manager = shutil.which(method)
|
||||
policy = installation.manager
|
||||
if not manager or (method == "uv" and directory.name != "nanobot-ai") or (method == "pipx" and (directory.parent.name != "venvs" or not directory.name.startswith("nanobot-ai"))):
|
||||
return guide.model_copy(update={"reason": "manager"})
|
||||
root = ("UV_TOOL_DIR", str(directory.parent)) if method == "uv" else ("PIPX_HOME", str(directory.parent.parent))
|
||||
prefix = [manager, "tool"] if method == "uv" else [manager]
|
||||
guide = guide.model_copy(update={"inspect_command": shell_command([*prefix, "list"], windows=windows, environment=root)})
|
||||
if policy is None or policy.source != "registry" or policy.restriction(target_version):
|
||||
return guide.model_copy(update={"reason": "policy"})
|
||||
elif Version(target_version).is_prerelease:
|
||||
return guide.model_copy(update={"reason": "preview"})
|
||||
else:
|
||||
return guide.model_copy(update={"reason": "registry", "update_command": shell_command([*prefix, "upgrade", directory.name], windows=windows, environment=root)})
|
||||
elif Version(target_version).is_prerelease:
|
||||
return guide.model_copy(update={"reason": "preview"})
|
||||
elif extras is None:
|
||||
# A venv populated with `uv pip` need not contain pip itself. Inspect
|
||||
# metadata with the standard library, without guessing its original extras.
|
||||
inspect = [installation.python, "-I", "-c",
|
||||
"import importlib.metadata,sys; d=importlib.metadata.distribution(sys.argv[1]); "
|
||||
"print(d.metadata[sys.argv[2]], d.version); print(d.locate_file(sys.argv[3]))",
|
||||
"nanobot-ai", "Name", "."]
|
||||
return guide.model_copy(update={"reason": "extras", "inspect_command": shell_command(inspect, windows=windows)})
|
||||
else:
|
||||
requirement = "nanobot-ai" + (f"[{','.join(extras)}]" if extras else "") + f"=={target_version}"
|
||||
return guide.model_copy(update={"reason": "registry", "update_command": shell_command([installation.python, "-I", "-m", "pip", "install", "--upgrade", requirement], windows=windows)})
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Old-runtime preflight for the immutable, detached update owner.
|
||||
|
||||
Entered by the frozen worker only after taking this installation's shared lease.
|
||||
This child must exit before the base-Python parent approves package mutation.
|
||||
No client route calls it, and it never launches an installer itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.data_access import require_no_pending_data_update
|
||||
from nanobot.installation_lock import installation_state_dir
|
||||
from nanobot.release_feed import ReleaseFeed
|
||||
from nanobot.update_plan import UpdatePlan
|
||||
from nanobot.update_stop import stop_reviewed_gateways
|
||||
from nanobot.update_worker import (
|
||||
JobStatus,
|
||||
Phase,
|
||||
WorkerSpec,
|
||||
check_environment,
|
||||
current_environment,
|
||||
)
|
||||
|
||||
|
||||
async def _prepare(directory: Path) -> None:
|
||||
spec = WorkerSpec.read(directory)
|
||||
plan = UpdatePlan.model_validate_json((directory / "plan.json").read_bytes())
|
||||
status = JobStatus.read(directory)
|
||||
if status.phase != Phase.CHECKING or status.mutation_started:
|
||||
raise ValueError("Shutdown preflight requires an unchanged prepared job")
|
||||
try:
|
||||
plan.validate_for(plan.installation)
|
||||
# This process already owns the old runtime's lease, including startup
|
||||
# and atexit. Do not create an unprotected nested interpreter here.
|
||||
check_environment(spec, repairing=False, current=current_environment(uv=spec.uv is not None))
|
||||
async with ReleaseFeed(installation_state_dir(spec.baseline.environment) / "releases") as feed:
|
||||
await feed.revalidate(plan.target)
|
||||
plan.validate_for(plan.installation)
|
||||
require_no_pending_data_update()
|
||||
status.advance(directory, Phase.STOPPING, "Waiting for the reviewed idle gateways to exit normally", mutation_started=False)
|
||||
await stop_reviewed_gateways(directory)
|
||||
except Exception:
|
||||
current = JobStatus.read(directory)
|
||||
message = (
|
||||
"Release or installation revalidation failed; gateway shutdown was not requested"
|
||||
if current.phase == Phase.CHECKING else
|
||||
"Gateway shutdown did not complete; review the saved shutdown state before retrying"
|
||||
)
|
||||
status.advance(directory, Phase.HANDOFF_FAILED, message, mutation_started=False)
|
||||
raise
|
||||
|
||||
|
||||
def prepare_handoff(directory: Path) -> None:
|
||||
"""Revalidate and cooperatively stop; installation remains unapproved."""
|
||||
asyncio.run(_prepare(directory))
|
||||
@@ -0,0 +1,597 @@
|
||||
"""Prepare exact offline jobs and hand them to the standalone installer worker.
|
||||
|
||||
The gateway controller keeps authenticated staging separate from execution consent.
|
||||
The caller owns explicit shutdown/restart selection. A detached worker revalidates,
|
||||
stops reviewed idle gateways, backs up data, installs, and restarts selected runtimes.
|
||||
Confirmed execution is idempotent; managed installs have bounded detached recovery.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
import platform
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from contextlib import nullcontext
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
from uuid import UUID, uuid4
|
||||
from zipfile import ZipFile, ZipInfo
|
||||
|
||||
from packaging.utils import canonicalize_name, parse_wheel_filename
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from nanobot.data_access import data_access
|
||||
from nanobot.installation_lock import (
|
||||
file_access,
|
||||
installation_access,
|
||||
installation_id,
|
||||
installation_state_dir,
|
||||
)
|
||||
from nanobot.installation_receipt import RECEIPT_NAME
|
||||
from nanobot.release_feed import ReleaseFeed
|
||||
from nanobot.releases import Channel, ReleaseRecord, Sha256
|
||||
from nanobot.update_backup import BackupSource, unique_sources
|
||||
from nanobot.update_plan import UpdatePlan
|
||||
from nanobot.update_process import PreparationProcess
|
||||
from nanobot.update_profiles import require_stopped_profiles, validate_profiles
|
||||
from nanobot.update_uv import UVPreparation, prepare_uv
|
||||
from nanobot.update_worker import (
|
||||
ExecutionConfirmation,
|
||||
JobStatus,
|
||||
Phase,
|
||||
StagedWheel,
|
||||
WorkerSpec,
|
||||
check_environment,
|
||||
inspect_environment,
|
||||
inspect_job_environment,
|
||||
read_record,
|
||||
verify_target_handoff,
|
||||
write_record,
|
||||
)
|
||||
from nanobot.utils.atomic_file import atomic_write_lines
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
|
||||
|
||||
class UpdateJobNotFoundError(FileNotFoundError):
|
||||
"""No saved preparation or execution status exists for this installation."""
|
||||
|
||||
|
||||
class UpdateJobView(ReleaseRecord):
|
||||
"""Last durable facts only: not proof of a live worker or authority to retry."""
|
||||
|
||||
id: str
|
||||
installation_id: str
|
||||
host: str
|
||||
previous_version: str
|
||||
target_version: str
|
||||
channel: Channel
|
||||
recorded_phase: Phase
|
||||
attempt: int
|
||||
mutation_started: bool
|
||||
updated_at: int
|
||||
execution_confirmation_id: str | None = None
|
||||
running_version: str = ""
|
||||
recovery_command: str = ""
|
||||
recovery_active: bool = False
|
||||
service_restored: bool = False
|
||||
automatic_recovery: bool = False
|
||||
|
||||
|
||||
def _recovery_command(plan_id: str) -> str:
|
||||
# The installer accepts py or an explicit Python path. Neither guarantees
|
||||
# python/python3 is on PATH after failure. Use the base interpreter outside
|
||||
# the mutable venv, quoted for the operator's platform shell.
|
||||
python: object = getattr(sys, "_base_executable")
|
||||
if not isinstance(python, str):
|
||||
raise ValueError("Recovery needs a known base Python")
|
||||
# The operator's shell may have a different HOME from the gateway.
|
||||
launcher = str(installation_state_dir().parent / "recover.py")
|
||||
if platform.system() == "Windows":
|
||||
quoted = "'" + python.replace("'", "''") + "'"
|
||||
quoted_launcher = "'" + launcher.replace("'", "''") + "'"
|
||||
return f'& {quoted} -I -S {quoted_launcher} {plan_id} --repair'
|
||||
return f'{shlex.quote(python)} -I -S {shlex.quote(launcher)} {plan_id} --repair'
|
||||
|
||||
|
||||
def read_update_job(plan_id: str) -> UpdateJobView:
|
||||
"""Read the journal scoped to this environment path, without probing Python.
|
||||
|
||||
No interpreter probe, network request or runtime lease is required. A failed
|
||||
installation and an active writer must not hide its last recorded state.
|
||||
This does not validate continued release eligibility, worker liveness or
|
||||
that an environment reinstalled at this path is still the reviewed one.
|
||||
"""
|
||||
UpdatePlan.canonical_id(plan_id)
|
||||
directory = installation_state_dir() / "jobs" / plan_id
|
||||
if directory.is_symlink():
|
||||
raise ValueError("Invalid update job directory")
|
||||
try:
|
||||
plan = UpdatePlan.model_validate(read_record(directory / "plan.json"))
|
||||
status = JobStatus.read(directory)
|
||||
except FileNotFoundError as exc:
|
||||
raise UpdateJobNotFoundError("No saved update job is available") from exc
|
||||
if plan.id != plan_id or plan.installation.installation_id != installation_id():
|
||||
raise ValueError("Update job belongs to a different installation or plan")
|
||||
confirmation = ExecutionConfirmation.read(directory)
|
||||
# Local diagnostic messages may contain paths or exception details. Clients
|
||||
# receive typed facts and can localize phases, never raw journal messages.
|
||||
from nanobot import __version__
|
||||
|
||||
recovery_active = False
|
||||
supervision = directory / "supervision.json"
|
||||
recovery_failed = False
|
||||
if supervision.exists():
|
||||
record = read_record(supervision)
|
||||
if record.get("plan_id") == plan_id:
|
||||
recovery_failed = (record.get("state") == "needs_attention"
|
||||
and status.phase not in {Phase.SUCCEEDED, Phase.RESTORED, Phase.CANCELLED})
|
||||
try:
|
||||
with file_access(installation_state_dir() / "supervisor.lock", exclusive=True):
|
||||
pass
|
||||
except BlockingIOError:
|
||||
recovery_active = True
|
||||
|
||||
return UpdateJobView(
|
||||
id=plan_id, installation_id=plan.installation.installation_id, host=platform.node(),
|
||||
previous_version=plan.installation.installed_version, target_version=plan.target.version,
|
||||
# Older clients know FAILED and must not display a rolled-back update
|
||||
# as successful. New clients use the additive service result below.
|
||||
channel=plan.channel, recorded_phase=Phase.FAILED if status.phase == Phase.RESTORED or recovery_failed else status.phase,
|
||||
attempt=status.attempt,
|
||||
mutation_started=status.mutation_started, updated_at=status.updated_at,
|
||||
execution_confirmation_id=confirmation.id if confirmation else None,
|
||||
running_version=__version__,
|
||||
recovery_command=_recovery_command(plan_id),
|
||||
recovery_active=recovery_active,
|
||||
service_restored=status.phase == Phase.RESTORED,
|
||||
automatic_recovery=WorkerSpec.recovery_selected(directory),
|
||||
)
|
||||
|
||||
|
||||
class _Metadata(BaseModel):
|
||||
name: str
|
||||
version: str
|
||||
|
||||
|
||||
class _Hashes(BaseModel):
|
||||
sha256: Sha256
|
||||
|
||||
|
||||
class _Archive(BaseModel):
|
||||
hashes: _Hashes
|
||||
|
||||
|
||||
class _Download(BaseModel):
|
||||
url: str
|
||||
archive_info: _Archive
|
||||
|
||||
|
||||
class _Install(BaseModel):
|
||||
metadata: _Metadata
|
||||
download_info: _Download
|
||||
|
||||
|
||||
class _Report(BaseModel):
|
||||
model_config = ConfigDict(strict=True)
|
||||
version: str
|
||||
install: list[_Install] = Field(max_length=500)
|
||||
|
||||
|
||||
def _pip(process: PreparationProcess, python: str, *arguments: str) -> None:
|
||||
result = process.run(python, ["-m", "pip", "--disable-pip-version-check", "--no-input", *arguments])
|
||||
if result.returncode:
|
||||
# Index URLs and resolver output may contain credentials. Do not put them
|
||||
# in the durable job or the WebUI response.
|
||||
raise ValueError("Could not prepare the pip transaction; check the installation's package-manager configuration")
|
||||
|
||||
|
||||
def _worker_archive(path: Path) -> str:
|
||||
sources = Path(__file__).parent
|
||||
# The frozen worker must not shadow the newly installed application when
|
||||
# handing off to its runtime. Keep only the copied stdlib helpers in this
|
||||
# private namespace; intentional application imports retain `nanobot`.
|
||||
modules = ("update_worker", "update_uv", "update_process", "update_backup", "update_fallback",
|
||||
"update_restart", "data_access", "installation_lock", "utils.atomic_file")
|
||||
with ZipFile(path, "x") as bundle:
|
||||
files = {"__main__.py": b"from _nanobot_update.update_worker import main\nmain()\n",
|
||||
"_nanobot_update/__init__.py": b"", "_nanobot_update/utils/__init__.py": b""}
|
||||
for module in modules:
|
||||
name = module.replace(".", "/") + ".py"
|
||||
source = (sources / name).read_text(encoding="utf-8")
|
||||
for dependency in modules:
|
||||
source = source.replace(f"from nanobot.{dependency} import", f"from _nanobot_update.{dependency} import")
|
||||
files[f"_nanobot_update/{name}"] = source.encode("utf-8")
|
||||
for name, data in files.items():
|
||||
bundle.writestr(ZipInfo(name), data)
|
||||
path.chmod(0o600)
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def _stage_app(plan: UpdatePlan, app_wheel: Path, directory: Path) -> StagedWheel:
|
||||
wheels = directory / "wheels"
|
||||
wheels.mkdir(mode=0o700, exist_ok=True)
|
||||
artifact = plan.target.artifact
|
||||
app = StagedWheel(artifact.filename, "nanobot-ai", plan.target.version, artifact.size, artifact.sha256)
|
||||
destination = wheels / artifact.filename
|
||||
if not destination.exists():
|
||||
shutil.copyfile(app_wheel, destination)
|
||||
verified = app.verify(wheels)
|
||||
with ZipFile(verified) as archive:
|
||||
if plan.restart_profiles:
|
||||
verify_target_handoff(archive)
|
||||
metadata = BytesParser().parsebytes(archive.read(f"nanobot_ai-{app.version}.dist-info/METADATA"))
|
||||
available = {canonicalize_name(extra) for extra in metadata.get_all("Provides-Extra", [])}
|
||||
if not set(plan.extras or []).issubset(available):
|
||||
raise ValueError("The target release does not provide all confirmed extras")
|
||||
return app
|
||||
|
||||
|
||||
def _prepare_wheels(plan: UpdatePlan, app_wheel: Path, directory: Path,
|
||||
process: PreparationProcess) -> tuple[StagedWheel, ...]:
|
||||
app = _stage_app(plan, app_wheel, directory)
|
||||
wheels = directory / "wheels"
|
||||
records = [app]
|
||||
python = plan.installation.python
|
||||
_pip(process, python, "check")
|
||||
with tempfile.TemporaryDirectory(prefix=".resolve-", dir=directory) as temporary:
|
||||
root = Path(temporary)
|
||||
report_path = root / "report.json"
|
||||
extras = f"[{','.join(plan.extras)}]" if plan.extras else ""
|
||||
_pip(process, python, "install", "--dry-run", "--only-binary=:all:", "--upgrade",
|
||||
"--upgrade-strategy", "only-if-needed", "--report", str(report_path),
|
||||
f"nanobot-ai{extras} @ {app_wheel.as_uri()}")
|
||||
if report_path.stat().st_size > 8 * 1024 * 1024:
|
||||
raise ValueError("Package-manager report exceeds its size limit")
|
||||
report = _Report.model_validate_json(report_path.read_bytes())
|
||||
if report.version != "1":
|
||||
raise ValueError("Unsupported pip report version")
|
||||
requirements: list[str] = []
|
||||
dependencies: list[tuple[str, str, str, str]] = []
|
||||
for item in report.install:
|
||||
name = canonicalize_name(item.metadata.name)
|
||||
if name == "nanobot-ai":
|
||||
if (item.metadata.version, item.download_info.archive_info.hashes.sha256) != (app.version, app.sha256):
|
||||
raise ValueError("Resolver changed the approved nanobot target")
|
||||
continue
|
||||
url = item.download_info.url
|
||||
if any(character.isspace() for character in url) or urlsplit(url).scheme not in {"https", "file"}:
|
||||
raise ValueError("An update dependency must be an exact HTTPS or local wheel")
|
||||
filename = Path(unquote(urlsplit(url).path)).name
|
||||
wheel_name, version, _, _ = parse_wheel_filename(filename)
|
||||
if (wheel_name, str(version)) != (name, item.metadata.version) or name == "pip":
|
||||
raise ValueError("Resolver returned an unsupported dependency artifact")
|
||||
digest = item.download_info.archive_info.hashes.sha256
|
||||
requirements.append(f"{name} @ {url} --hash=sha256:{digest}")
|
||||
dependencies.append((filename, name, str(version), digest))
|
||||
if requirements:
|
||||
request = root / "requirements.txt"
|
||||
request.write_text("\n".join(requirements), encoding="utf-8")
|
||||
request.chmod(0o600)
|
||||
downloads = root / "downloads"
|
||||
_pip(process, python, "download", "--no-deps", "--only-binary=:all:", "--require-hashes",
|
||||
"--dest", str(downloads), "--requirement", str(request))
|
||||
for filename, name, version, digest in dependencies:
|
||||
path = downloads / filename
|
||||
record = StagedWheel(filename, name, version, path.stat().st_size, digest)
|
||||
record.verify(downloads)
|
||||
shutil.copyfile(path, wheels / filename)
|
||||
records.append(record)
|
||||
return tuple(records)
|
||||
|
||||
|
||||
def _prepare_transaction(plan: UpdatePlan, app_wheel: Path, directory: Path,
|
||||
process: PreparationProcess) -> tuple[tuple[StagedWheel, ...], UVPreparation | None]:
|
||||
if plan.installation.owner != "uv":
|
||||
return _prepare_wheels(plan, app_wheel, directory, process), None
|
||||
executable = shutil.which("uv")
|
||||
if executable is None:
|
||||
raise ValueError("The installation's uv manager is not available")
|
||||
app = _stage_app(plan, app_wheel, directory)
|
||||
prepared = prepare_uv(environment=plan.installation.environment, python=plan.installation.python,
|
||||
receipt_sha256=plan.installation.records["uv-receipt.toml"],
|
||||
app_wheel=directory / "wheels" / app.filename, version=plan.target.version,
|
||||
extras=plan.extras or [], directory=directory, executable=executable, process=process)
|
||||
return (app,), prepared
|
||||
|
||||
|
||||
def validate_preparation(plan: UpdatePlan) -> None:
|
||||
"""Check the supported preparation contract, without touching the environment."""
|
||||
if plan.installation.owner not in {"venv", "uv"} or plan.extras is None:
|
||||
raise ValueError("The worker requires a supported dedicated environment and explicitly confirmed extras")
|
||||
if plan.installation.owner == "uv" and (os.name != "posix" or plan.installation.manager is None):
|
||||
raise ValueError("This uv installation needs its owner's external update workflow")
|
||||
if plan.owner_restriction:
|
||||
raise ValueError(plan.owner_restriction)
|
||||
if plan.action != "upgrade":
|
||||
raise ValueError("This executor prepares upgrades only; no-op, restart and downgrade need their own review")
|
||||
plan.validate_for(plan.installation)
|
||||
|
||||
|
||||
async def prepare_job(plan: UpdatePlan, feed: ReleaseFeed) -> Path:
|
||||
"""Stage a supported job without granting execution or changing installed files."""
|
||||
validate_preparation(plan)
|
||||
native_uv = plan.installation.owner == "uv"
|
||||
root = installation_state_dir(plan.installation.environment)
|
||||
# A stable stdlib-only entrypoint survives missing application dependencies.
|
||||
# It selects the immutable per-job worker, not code in site-packages.
|
||||
recovery = root.parent / "recover.py"
|
||||
source = Path(__file__).with_name("update_recovery.py").read_text()
|
||||
if recovery.exists() and (recovery.is_symlink() or not recovery.read_text().startswith(
|
||||
'\"\"\"nanobot standalone recovery launcher, protocol 1.')):
|
||||
raise ValueError("The recovery launcher path is already owned by another file")
|
||||
atomic_write_lines(recovery, source.splitlines())
|
||||
recovery.chmod(0o600)
|
||||
with (file_access(root / "channel.lock", exclusive=False),
|
||||
installation_access(environment=plan.installation.environment), file_access(root / "prepare.lock", exclusive=True)):
|
||||
validate_preparation(plan)
|
||||
directory = root / "jobs" / plan.id
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
if (directory / "request.json").exists():
|
||||
spec = WorkerSpec.read(directory)
|
||||
saved = (directory / "plan.json").read_bytes()
|
||||
if (UpdatePlan.model_validate_json(saved) != plan
|
||||
or spec.plan_sha256 != hashlib.sha256(saved).hexdigest()):
|
||||
raise ValueError("This job already belongs to another approved plan")
|
||||
return directory
|
||||
if (directory / "status.json").exists() and JobStatus.read(directory).phase == Phase.PREPARING:
|
||||
# A crashed preparer may have left a native child writing staging.
|
||||
# Absence of its Python task/lease is not proof that child exited.
|
||||
raise ValueError("A previous preparation did not settle; inspect this job before retrying or cleaning it up")
|
||||
plan_path = directory / "plan.json"
|
||||
if plan_path.exists() and UpdatePlan.model_validate_json(plan_path.read_bytes()) != plan:
|
||||
raise ValueError("This preparation already belongs to another reviewed plan")
|
||||
if not plan_path.exists():
|
||||
atomic_write_lines(plan_path, [plan.model_dump_json()])
|
||||
plan_path.chmod(0o600)
|
||||
# An orphan native command retains this installation-wide lease. Never
|
||||
# replace its archive or begin another preparation while it is active.
|
||||
with file_access(root / "prepare-native.lock", exclusive=True):
|
||||
archive = directory / "worker.pyz"
|
||||
archive.unlink(missing_ok=True) # No committed request exists above.
|
||||
_worker_archive(archive)
|
||||
process = PreparationProcess.create(directory, plan.installation.environment)
|
||||
JobStatus(plan.id, Phase.PREPARING, 0, False,
|
||||
"Checking the installation and preparing the exact package", int(time.time())).save(directory)
|
||||
try:
|
||||
return await _prepare_inputs(plan, feed, root, directory, process, native_uv=native_uv)
|
||||
except asyncio.CancelledError:
|
||||
JobStatus(plan.id, Phase.PREPARATION_FAILED, 0, False,
|
||||
"Preparation cancelled after its workers exited; no installation was started",
|
||||
int(time.time())).save(directory)
|
||||
raise
|
||||
except Exception as exc:
|
||||
# Resolver/network exceptions can contain index credentials or paths.
|
||||
JobStatus(plan.id, Phase.PREPARATION_FAILED, 0, False,
|
||||
f"Preparation failed ({type(exc).__name__}); no installation was started",
|
||||
int(time.time())).save(directory)
|
||||
raise
|
||||
finally:
|
||||
process.close()
|
||||
|
||||
|
||||
async def _prepare_inputs(plan: UpdatePlan, feed: ReleaseFeed, root: Path, directory: Path,
|
||||
process: PreparationProcess, *, native_uv: bool) -> Path:
|
||||
baseline = await shield_and_drain(asyncio.to_thread(inspect_environment, plan.installation.python, uv=native_uv, process=process))
|
||||
if (baseline.environment, baseline.python, baseline.app_version, baseline.receipt_sha) != (
|
||||
plan.installation.environment, plan.installation.python, plan.installation.installed_version,
|
||||
plan.installation.records.get("pyvenv.cfg"),
|
||||
) or any(plan.installation.records.get(name) != digest for name, digest in baseline.app_records.items()):
|
||||
raise ValueError("The installation changed since this plan was prepared")
|
||||
if native_uv and baseline.manager_receipt_sha != plan.installation.records.get("uv-receipt.toml"):
|
||||
raise ValueError("The uv installation settings changed since this plan was prepared")
|
||||
if baseline.installer_receipt_sha != plan.installation.records.get(RECEIPT_NAME):
|
||||
raise ValueError("The installer selection changed since this plan was prepared")
|
||||
validate_profiles(plan.profiles, plan.installation.environment)
|
||||
JobStatus(plan.id, Phase.PREPARING, 0, False,
|
||||
"Downloading and verifying the reviewed package", int(time.time())).save(directory)
|
||||
app_wheel = await feed.download(plan.target, root / "downloads")
|
||||
JobStatus(plan.id, Phase.PREPARING, 0, False,
|
||||
"Preparing dependencies without changing the installation", int(time.time())).save(directory)
|
||||
records, uv = await shield_and_drain(asyncio.to_thread(_prepare_transaction, plan, app_wheel, directory, process))
|
||||
current = await shield_and_drain(asyncio.to_thread(inspect_environment, plan.installation.python, uv=native_uv, process=process))
|
||||
if current != baseline:
|
||||
raise ValueError("Installation changed while preparing the update")
|
||||
plan.validate_for(plan.installation)
|
||||
plan_path = directory / "plan.json"
|
||||
archive = directory / "worker.pyz"
|
||||
sources = [BackupSource(str(Path(baseline.environment) / "pyvenv.cfg"))]
|
||||
if native_uv:
|
||||
sources.append(BackupSource(str(Path(baseline.environment) / "uv-receipt.toml")))
|
||||
if baseline.installer_receipt_sha is not None:
|
||||
sources.append(BackupSource(str(Path(baseline.environment) / RECEIPT_NAME)))
|
||||
for profile in plan.profiles:
|
||||
receipt = profile.receipt
|
||||
sources.extend(BackupSource.parse({"path": str(path)}) for path in receipt.data_paths)
|
||||
sources.append(BackupSource(str(root / "profiles" / f"{receipt.id}.json")))
|
||||
spec = WorkerSpec(plan.id, hashlib.sha256(plan_path.read_bytes()).hexdigest(), hashlib.sha256(archive.read_bytes()).hexdigest(),
|
||||
baseline, plan.target.version, records, unique_sources(sources), tuple(plan.restart_profiles), uv,
|
||||
automatic_recovery=bool(plan.restart_profiles) and baseline.installer_receipt_sha is not None)
|
||||
for path in [archive, *(directory / "wheels" / item.filename for item in records)]:
|
||||
path.chmod(0o600)
|
||||
with path.open("r+b") as stream:
|
||||
os.fsync(stream.fileno())
|
||||
JobStatus(plan.id, Phase.READY, 0, False, "Files prepared; not installed", int(time.time())).save(directory)
|
||||
# The immutable request is the commit record: its presence means every
|
||||
# input and the initial status were flushed successfully.
|
||||
spec.save(directory)
|
||||
return directory
|
||||
|
||||
|
||||
def settle_interrupted_preparation(directory: Path) -> JobStatus:
|
||||
"""Revoke an abandoned, uncommitted preparation after its real child exits.
|
||||
|
||||
Internal recovery only: no install, directory deletion or automatic retry.
|
||||
A record from the older parent-only lease scheme cannot establish this proof.
|
||||
"""
|
||||
directory = directory.resolve()
|
||||
process = PreparationProcess.load(directory)
|
||||
root = installation_state_dir(process.environment)
|
||||
with file_access(root / "prepare.lock", exclusive=True), file_access(root / "prepare-native.lock", exclusive=True):
|
||||
if PreparationProcess.load(directory) != process:
|
||||
raise ValueError("The preparation generation changed")
|
||||
status = JobStatus.read(directory)
|
||||
if status.phase != Phase.PREPARING or (directory / "request.json").exists() or status.mutation_started:
|
||||
raise ValueError("Only an uncommitted preparation can be settled")
|
||||
process.close()
|
||||
status = JobStatus(directory.name, Phase.PREPARATION_FAILED, 0, False,
|
||||
"Interrupted preparation stopped; no installation was started", int(time.time()))
|
||||
status.save(directory)
|
||||
return status
|
||||
|
||||
|
||||
async def start_job(directory: Path, feed: ReleaseFeed, *, repair: bool = False) -> subprocess.Popen[bytes]:
|
||||
"""Approve the exact staged job and start its detached worker.
|
||||
|
||||
Not called by a client route yet. The caller must quiesce/stop old runtimes;
|
||||
the worker rechecks their leases before installation. Only explicitly saved
|
||||
background participants may be restarted, never an external supervisor.
|
||||
"""
|
||||
spec = WorkerSpec.read(directory)
|
||||
plan = UpdatePlan.model_validate_json((directory / "plan.json").read_bytes())
|
||||
runtime_phases = {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED}
|
||||
if JobStatus.read(directory).phase not in runtime_phases:
|
||||
await feed.revalidate(plan.target)
|
||||
with (file_access(installation_state_dir(spec.baseline.environment) / "channel.lock", exclusive=False),
|
||||
file_access(installation_state_dir(spec.baseline.environment) / "worker.lock", exclusive=True)):
|
||||
state = JobStatus.read(directory)
|
||||
if state.phase in {Phase.INSTALLED, Phase.CANCELLED, Phase.SUCCEEDED, Phase.RESTORED}:
|
||||
raise ValueError("This job is already finished; it cannot be started again")
|
||||
restarting = state.phase in runtime_phases
|
||||
if state.mutation_started and not repair:
|
||||
raise ValueError("This interrupted job requires an explicit repair confirmation")
|
||||
if repair and not state.mutation_started:
|
||||
raise ValueError("Repair is only available after this job began replacing files")
|
||||
current = await shield_and_drain(asyncio.to_thread(inspect_job_environment, directory, spec))
|
||||
with (installation_access(updating=not restarting, allow_incomplete=restarting,
|
||||
environment=spec.baseline.environment),
|
||||
nullcontext() if state.phase == Phase.FINALIZING else
|
||||
data_access((source.path for source in spec.backup_sources), updating=not restarting, job_id=spec.plan_id)):
|
||||
check_environment(spec, repairing=state.mutation_started, current=current)
|
||||
if not restarting:
|
||||
require_stopped_profiles(plan.profiles, spec.baseline.environment)
|
||||
spec.verify_inputs(directory)
|
||||
now = int(time.time())
|
||||
if not repair:
|
||||
plan.validate_for(plan.installation, now=now)
|
||||
write_record(directory / "approval.json", {
|
||||
"plan_id": spec.plan_id, "request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
|
||||
"created_at": now, "expires_at": now + 900 if repair else min(plan.expires_at, now + 900),
|
||||
})
|
||||
return _spawn_worker(directory, spec)
|
||||
|
||||
|
||||
def start_handoff(directory: Path, *, once: bool = False) -> subprocess.Popen[bytes] | None:
|
||||
"""Confirm an exact prepared plan and detach before the requesting gateway exits.
|
||||
|
||||
Unlike start_job (already-stopped installations/repair), release revalidation
|
||||
and cooperative shutdown run independently of the caller. No installation
|
||||
approval is written until that child exits and exclusive leases are held.
|
||||
With once=True, persist one confirmation and never launch again for a repeated
|
||||
request. A missing response, failed launch or failed job is not retry authority.
|
||||
"""
|
||||
return _start_handoff(directory, once=once)
|
||||
|
||||
|
||||
def retry_handoff(directory: Path, previous_confirmation_id: str) -> subprocess.Popen[bytes] | None:
|
||||
"""Consume explicit recovery consent for one unmodified handoff generation.
|
||||
|
||||
A stale predecessor is a read, not another retry. A live owner, surviving
|
||||
preflight child, expired plan or package mutation requires a different action.
|
||||
"""
|
||||
if UUID(previous_confirmation_id).hex != previous_confirmation_id:
|
||||
raise ValueError("Invalid previous execution confirmation")
|
||||
return _start_handoff(directory, once=True, previous_confirmation_id=previous_confirmation_id)
|
||||
|
||||
|
||||
def _start_handoff(directory: Path, *, once: bool,
|
||||
previous_confirmation_id: str | None = None) -> subprocess.Popen[bytes] | None:
|
||||
spec = WorkerSpec.read(directory)
|
||||
plan = UpdatePlan.model_validate_json((directory / "plan.json").read_bytes())
|
||||
root = installation_state_dir(spec.baseline.environment)
|
||||
|
||||
def already_confirmed() -> bool:
|
||||
current = ExecutionConfirmation.read(directory)
|
||||
if previous_confirmation_id is not None:
|
||||
if current is None:
|
||||
raise ValueError("No execution confirmation is available to retry")
|
||||
return current.id != previous_confirmation_id
|
||||
return once and current is not None
|
||||
|
||||
if already_confirmed():
|
||||
return None
|
||||
confirmation = None
|
||||
with (file_access(root / "supervisor.lock", exclusive=True) if spec.automatic_recovery else nullcontext(),
|
||||
file_access(root / "channel.lock", exclusive=False),
|
||||
file_access(root / "worker.lock", exclusive=True),
|
||||
file_access(root / "handoff-child.lock", exclusive=True),
|
||||
installation_access(environment=spec.baseline.environment)):
|
||||
state = JobStatus.read(directory)
|
||||
if already_confirmed():
|
||||
return None
|
||||
if once and previous_confirmation_id is None and state.phase != Phase.READY:
|
||||
raise ValueError("Only a ready job can receive its first execution confirmation")
|
||||
if state.mutation_started or state.phase not in {
|
||||
Phase.READY, Phase.CHECKING, Phase.STOPPING, Phase.HANDOFF_FAILED,
|
||||
}:
|
||||
raise ValueError("Shutdown handoff requires an unmodified prepared job")
|
||||
now = int(time.time())
|
||||
plan.validate_for(plan.installation, now=now)
|
||||
spec.verify_inputs(directory)
|
||||
approval: dict[str, object] = {
|
||||
"plan_id": spec.plan_id, "request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
|
||||
"created_at": now, "expires_at": min(plan.expires_at, now + 900),
|
||||
}
|
||||
if once:
|
||||
confirmation = ExecutionConfirmation(
|
||||
uuid4().hex, spec.plan_id, hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
|
||||
now, min(plan.expires_at, now + 900),
|
||||
)
|
||||
# Persist before any launch. If the requester dies here, repeated
|
||||
# submissions read this record; recovery needs explicit new consent.
|
||||
confirmation.save(directory)
|
||||
approval["confirmation_id"] = confirmation.id
|
||||
# Both owner leases are held. Revoking the old confirmation first
|
||||
# makes its delayed launchers harmless, even across a crash here.
|
||||
(directory / "confirmation-claimed.json").unlink(missing_ok=True)
|
||||
write_record(directory / "handoff-approval.json", approval)
|
||||
(directory / "approval.json").unlink(missing_ok=True)
|
||||
JobStatus(spec.plan_id, Phase.CHECKING, state.attempt, False,
|
||||
"Starting an independent update handoff", now).save(directory)
|
||||
# Release the ownership lease before spawning: a fast child must be able to
|
||||
# take it immediately. Duplicate launches still serialize in run_job.
|
||||
try:
|
||||
return _spawn_worker(directory, spec, handoff=True, confirmation_id=confirmation.id if confirmation else None)
|
||||
except OSError:
|
||||
with file_access(root / "worker.lock", exclusive=True):
|
||||
state = JobStatus.read(directory)
|
||||
current = ExecutionConfirmation.read(directory)
|
||||
if (state.phase == Phase.CHECKING
|
||||
and (confirmation is None or current == confirmation)):
|
||||
JobStatus(spec.plan_id, Phase.HANDOFF_FAILED, state.attempt, False,
|
||||
"Could not start the independent update process; no shutdown was requested",
|
||||
int(time.time())).save(directory)
|
||||
raise
|
||||
|
||||
|
||||
def _spawn_worker(directory: Path, spec: WorkerSpec, *, handoff: bool = False,
|
||||
confirmation_id: str | None = None) -> subprocess.Popen[bytes]:
|
||||
command = [spec.baseline.base_python, "-I", "-S", str(directory / "worker.pyz")]
|
||||
if spec.automatic_recovery:
|
||||
command.extend(["--supervise", str(directory)])
|
||||
if confirmation_id is not None:
|
||||
command.extend(["--confirmed-handoff", str(directory), confirmation_id])
|
||||
else:
|
||||
command.extend(["--handoff", str(directory)] if handoff else [str(directory)])
|
||||
if os.name == "nt":
|
||||
return subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
cwd=directory, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS)
|
||||
return subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
cwd=directory, start_new_session=True)
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Read package-manager intent without changing its receipt or exposing source URLs.
|
||||
|
||||
These facts supplement an installation-bound update plan. They do not authorize an
|
||||
installer: the owning manager still resolves its full settings and dependencies.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from packaging.requirements import InvalidRequirement, Requirement
|
||||
from packaging.specifiers import SpecifierSet
|
||||
from packaging.utils import canonicalize_name
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from nanobot.releases import ReleaseRecord, Sha256
|
||||
|
||||
Source = Literal["registry", "artifact", "source", "unrecognized"]
|
||||
|
||||
|
||||
def _source(url: str | None) -> Source:
|
||||
if url is None:
|
||||
return "registry"
|
||||
parsed = urlsplit(url)
|
||||
return "artifact" if parsed.scheme in {"https", "http", "file"} and parsed.path.endswith(".whl") else "source"
|
||||
|
||||
|
||||
class ManagerPolicy(ReleaseRecord):
|
||||
"""Credential-free summary; the receipt hash binds the complete private record."""
|
||||
|
||||
manager: Literal["uv", "pipx"]
|
||||
backend: Literal["uv", "pip"]
|
||||
extras: list[str] | None
|
||||
version_constraint: str = Field(default="", max_length=1000)
|
||||
source: Source
|
||||
pinned: bool = False
|
||||
locked: bool = False
|
||||
injected_packages: list[str] = Field(default_factory=list, max_length=500)
|
||||
custom_pip_args: bool = False
|
||||
|
||||
@field_validator("version_constraint")
|
||||
@classmethod
|
||||
def valid_constraint(cls, value: str) -> str:
|
||||
SpecifierSet(value)
|
||||
return value
|
||||
|
||||
@field_validator("extras", "injected_packages")
|
||||
@classmethod
|
||||
def normalized_names(cls, value: list[str] | None) -> list[str] | None:
|
||||
if value is not None and (len(value) > 500 or value != sorted(set(value)) or any(
|
||||
canonicalize_name(name, validate=True) != name for name in value
|
||||
)):
|
||||
raise ValueError("Expected unique normalized package or extra names")
|
||||
return value
|
||||
|
||||
def restriction(self, version: str) -> str | None:
|
||||
"""Why this target requires owner intervention, not permission to execute it."""
|
||||
if self.pinned:
|
||||
return "The package is pinned by its installation owner. Review that pin before updating."
|
||||
if self.locked:
|
||||
return "The environment uses an owner-managed lock file. Update through that lock workflow."
|
||||
if self.manager == "pipx" and (self.version_constraint or self.custom_pip_args):
|
||||
return "This pipx installation has constraints or installer options. Review them with its owner; a generic pipx upgrade can discard those settings."
|
||||
if self.manager == "uv" and self.source == "artifact":
|
||||
return "This uv tool is bound to a wheel URL. Change its source through the installation owner's workflow."
|
||||
if self.source in {"source", "unrecognized"} or self.extras is None:
|
||||
return "The recorded installation source needs manual review by its owner."
|
||||
if not SpecifierSet(self.version_constraint).contains(version, prereleases=True):
|
||||
return "This version is outside the installation's recorded version constraints."
|
||||
return None
|
||||
|
||||
|
||||
class _UVRequirement(BaseModel):
|
||||
model_config = ConfigDict(extra="allow", strict=True)
|
||||
name: str
|
||||
extras: list[str] = Field(default_factory=list)
|
||||
specifier: str = ""
|
||||
url: str | None = None
|
||||
index: str | None = None
|
||||
marker: str | None = None
|
||||
|
||||
|
||||
class _UVTool(BaseModel):
|
||||
model_config = ConfigDict(strict=True)
|
||||
requirements: list[_UVRequirement] = Field(min_length=1, max_length=500)
|
||||
|
||||
|
||||
class _UVReceipt(BaseModel):
|
||||
tool: _UVTool
|
||||
|
||||
|
||||
class _PipxPackage(BaseModel):
|
||||
model_config = ConfigDict(strict=True)
|
||||
package: str
|
||||
package_or_url: str
|
||||
pinned: bool = False
|
||||
lock_file: str | dict[str, str] | None = None
|
||||
pip_args: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class _PipxReceipt(BaseModel):
|
||||
model_config = ConfigDict(strict=True)
|
||||
pipx_metadata_version: str
|
||||
main_package: _PipxPackage
|
||||
injected_packages: dict[str, _PipxPackage] = Field(default_factory=dict, max_length=500)
|
||||
backend: Literal["pip", "uv"] = "pip"
|
||||
|
||||
|
||||
def read_manager_policy(environment: Path, manager: Literal["uv", "pipx"], expected_sha: Sha256) -> ManagerPolicy:
|
||||
"""Read the exact receipt observed by the fresh interpreter, without rewriting it."""
|
||||
path = environment / ("uv-receipt.toml" if manager == "uv" else "pipx_metadata.json")
|
||||
try:
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise ValueError("Invalid package-manager receipt")
|
||||
with path.open("rb") as stream:
|
||||
raw = stream.read(1024 * 1024 + 1)
|
||||
if len(raw) > 1024 * 1024 or hashlib.sha256(raw).hexdigest() != expected_sha:
|
||||
raise ValueError("Package-manager receipt changed or exceeds its size limit")
|
||||
if manager == "uv":
|
||||
receipt = _UVReceipt.model_validate(tomllib.loads(raw.decode("utf-8")))
|
||||
main = [item for item in receipt.tool.requirements if canonicalize_name(item.name) == "nanobot-ai"]
|
||||
if len(main) != 1:
|
||||
raise ValueError("Ambiguous managed package")
|
||||
requirement = main[0]
|
||||
source = "unrecognized" if requirement.model_extra or requirement.marker else _source(requirement.url)
|
||||
return ManagerPolicy(
|
||||
manager=manager, backend="uv", source=source,
|
||||
extras=sorted({canonicalize_name(extra, validate=True) for extra in requirement.extras}),
|
||||
version_constraint=requirement.specifier,
|
||||
injected_packages=sorted({canonicalize_name(item.name, validate=True)
|
||||
for item in receipt.tool.requirements if item is not requirement}),
|
||||
)
|
||||
pipx = _PipxReceipt.model_validate_json(raw)
|
||||
# The fields used here have matching semantics in receipts produced by
|
||||
# pipx 1.7.1 (0.5) and 1.17.13 (0.12). Reading an older supported receipt
|
||||
# must not require upgrading pipx or migrating its private metadata.
|
||||
if pipx.pipx_metadata_version not in {"0.5", "0.12"}:
|
||||
raise ValueError("Unknown pipx receipt schema")
|
||||
if canonicalize_name(pipx.main_package.package) != "nanobot-ai":
|
||||
raise ValueError("Receipt belongs to another package")
|
||||
try:
|
||||
requested = Requirement(pipx.main_package.package_or_url)
|
||||
except InvalidRequirement:
|
||||
requested = None
|
||||
if requested is not None and canonicalize_name(requested.name) != "nanobot-ai":
|
||||
raise ValueError("Receipt names a different package")
|
||||
return ManagerPolicy(
|
||||
manager=manager, backend=pipx.backend,
|
||||
source="unrecognized" if requested is None or requested.marker else (
|
||||
"source" if "--editable" in pipx.main_package.pip_args or "-e" in pipx.main_package.pip_args else (
|
||||
_source(requested.url)
|
||||
)
|
||||
),
|
||||
extras=sorted({canonicalize_name(extra, validate=True) for extra in requested.extras})
|
||||
if requested is not None else None,
|
||||
version_constraint=str(requested.specifier) if requested is not None else "",
|
||||
pinned=pipx.main_package.pinned, locked=pipx.main_package.lock_file is not None,
|
||||
custom_pip_args=bool(pipx.main_package.pip_args),
|
||||
injected_packages=sorted({canonicalize_name(name, validate=True) for name in pipx.injected_packages}),
|
||||
)
|
||||
except (OSError, ValueError, TypeError):
|
||||
# Parse errors can embed credential-bearing URLs; never relay their text.
|
||||
raise ValueError("Could not verify package-manager settings; inspect this installation before updating") from None
|
||||
@@ -0,0 +1,460 @@
|
||||
"""Installation-bound, expiring release plans shared by update entrypoints.
|
||||
|
||||
Planning never invokes an installer or changes the running gateway. The approved
|
||||
record is immutable; an executor must revalidate it before changing any package files.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from filelock import FileLock
|
||||
from packaging.version import Version
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
|
||||
import nanobot
|
||||
from nanobot.installation_lock import installation_access, installation_id, installation_state_dir
|
||||
from nanobot.installation_receipt import RECEIPT_NAME, managed_extras
|
||||
from nanobot.release_feed import ReleaseFeed, ReleaseTarget
|
||||
from nanobot.releases import Channel, ReleaseRecord, Sha256
|
||||
from nanobot.update_channel import read_update_channel, validate_channel_revision
|
||||
from nanobot.update_guidance import UpdateGuide, update_guide
|
||||
from nanobot.update_manager import ManagerPolicy, read_manager_policy
|
||||
from nanobot.update_process import inspect_python_environment
|
||||
from nanobot.update_profiles import (
|
||||
ObservedProfile,
|
||||
ProfileReceipt,
|
||||
inspect_profiles,
|
||||
validate_profiles,
|
||||
)
|
||||
from nanobot.update_uv import UV_TRANSACTION_VERSION
|
||||
from nanobot.utils.atomic_file import atomic_write_lines
|
||||
|
||||
Owner = Literal["venv", "uv", "pipx", "source", "container", "system"]
|
||||
|
||||
|
||||
def _managed_background(profile: ProfileReceipt, environment: str) -> bool:
|
||||
return (profile.environment == environment and profile.launch_mode == "background"
|
||||
and profile.launch is not None and profile.launch.lifetime == "explicit")
|
||||
|
||||
# Read fresh metadata using this installation's Python, not an executable from PATH
|
||||
# or this long-lived gateway's cached importlib.metadata state. No config is loaded.
|
||||
_PROBE = """
|
||||
import hashlib, json, sys, nanobot
|
||||
from pathlib import Path
|
||||
from importlib.metadata import distribution
|
||||
d = distribution('nanobot-ai')
|
||||
prefix = Path(sys.prefix).resolve()
|
||||
records = {}
|
||||
for name in ('pyvenv.cfg', 'uv-receipt.toml', 'pipx_metadata.json', 'nanobot-install.json'):
|
||||
path = prefix / name
|
||||
if path.is_file():
|
||||
records[name] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
records['RECORD'] = hashlib.sha256((d.read_text('RECORD') or '').encode()).hexdigest()
|
||||
records['direct_url.json'] = hashlib.sha256((d.read_text('direct_url.json') or '').encode()).hexdigest()
|
||||
print(json.dumps(dict(environment=str(prefix), python=str(Path(sys.executable).absolute()),
|
||||
installed_version=d.version, package_path=str(Path(nanobot.__file__).resolve()),
|
||||
records=records)))
|
||||
"""
|
||||
|
||||
|
||||
class _Probe(ReleaseRecord):
|
||||
environment: str
|
||||
python: str
|
||||
installed_version: str
|
||||
package_path: str
|
||||
records: dict[str, Sha256]
|
||||
|
||||
|
||||
class InstallationSnapshot(_Probe):
|
||||
running_version: str
|
||||
running_package: str
|
||||
owner: Owner
|
||||
manager: ManagerPolicy | None = None
|
||||
manager_version: str | None = Field(default=None, max_length=64)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def matching_manager(self) -> InstallationSnapshot:
|
||||
if self.manager is not None and self.manager.manager != self.owner:
|
||||
raise ValueError("Package-manager settings must belong to this installation owner")
|
||||
return self
|
||||
|
||||
@field_validator("installed_version", "running_version")
|
||||
@classmethod
|
||||
def valid_version(cls, value: str) -> str:
|
||||
Version(value)
|
||||
return value
|
||||
|
||||
@property
|
||||
def installation_id(self) -> str:
|
||||
return installation_id(self.environment)
|
||||
|
||||
@property
|
||||
def fingerprint(self) -> str:
|
||||
payload = json.dumps(self.model_dump(mode="json"), sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(payload.encode()).hexdigest()
|
||||
|
||||
|
||||
def inspect_installation() -> InstallationSnapshot:
|
||||
probe = inspect_python_environment(sys.executable, str(Path(sys.prefix).resolve()), _PROBE, timeout=10)
|
||||
probe.check_returncode()
|
||||
fresh = _Probe.model_validate_json(probe.stdout)
|
||||
if Path(fresh.environment) != Path(sys.prefix).resolve():
|
||||
raise RuntimeError("The update interpreter belongs to a different installation")
|
||||
root = Path(nanobot.__file__).resolve().parent.parent
|
||||
owner: Owner = "venv"
|
||||
if Path("/.dockerenv").exists() or os.environ.get("RENDER") == "true":
|
||||
owner = "container"
|
||||
elif (root / "pyproject.toml").is_file() and (root / "tui/package.json").is_file():
|
||||
owner = "source"
|
||||
elif "uv-receipt.toml" in fresh.records:
|
||||
owner = "uv"
|
||||
elif "pipx_metadata.json" in fresh.records:
|
||||
owner = "pipx"
|
||||
elif sys.prefix == sys.base_prefix:
|
||||
owner = "system"
|
||||
manager = None
|
||||
manager_version = None
|
||||
if owner == "uv" or owner == "pipx":
|
||||
receipt = "uv-receipt.toml" if owner == "uv" else "pipx_metadata.json"
|
||||
manager = read_manager_policy(Path(fresh.environment), owner, fresh.records[receipt])
|
||||
if owner == "uv" and (executable := shutil.which("uv")):
|
||||
try:
|
||||
result = subprocess.run([executable, "--version"], capture_output=True, text=True, timeout=5)
|
||||
parts = result.stdout.split()
|
||||
if result.returncode == 0 and len(parts) >= 2 and parts[0] == "uv" and len(parts[1]) <= 64:
|
||||
manager_version = parts[1]
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass # Unknown manager capability requires its external workflow.
|
||||
return InstallationSnapshot(**fresh.model_dump(), running_version=nanobot.__version__,
|
||||
running_package=str(Path(nanobot.__file__).resolve()), owner=owner, manager=manager,
|
||||
manager_version=manager_version)
|
||||
|
||||
|
||||
class UpdatePlan(ReleaseRecord):
|
||||
schema_version: Literal[1] = 1
|
||||
id: str
|
||||
installation: InstallationSnapshot
|
||||
channel: Channel
|
||||
channel_revision: int | None = Field(default=None, ge=0)
|
||||
target: ReleaseTarget
|
||||
extras: list[str] | None = None
|
||||
profiles: list[ObservedProfile] = Field(default_factory=list, max_length=1024)
|
||||
# Explicit consent to stop exact running instances, separate from restart.
|
||||
stop_profiles: list[str] = Field(default_factory=list, max_length=1024)
|
||||
# Inventory alone is not authority to start a previously stopped instance.
|
||||
restart_profiles: list[str] = Field(default_factory=list, max_length=1024)
|
||||
created_at: int = Field(ge=0)
|
||||
expires_at: int = Field(gt=0)
|
||||
|
||||
@field_validator("id")
|
||||
@classmethod
|
||||
def canonical_id(cls, value: str) -> str:
|
||||
if str(UUID(value)) != value:
|
||||
raise ValueError("Invalid update plan identifier")
|
||||
return value
|
||||
|
||||
@field_validator("extras")
|
||||
@classmethod
|
||||
def explicit_extras(cls, value: list[str] | None) -> list[str] | None:
|
||||
import re
|
||||
|
||||
if value is not None and (len(value) > 50 or len(value) != len(set(value)) or any(
|
||||
not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", extra) for extra in value
|
||||
)):
|
||||
raise ValueError("Extras must be explicit, unique normalized names")
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def valid_plan(self) -> UpdatePlan:
|
||||
if not self.created_at < self.expires_at <= self.created_at + 15 * 60:
|
||||
raise ValueError("Update plan must expire within fifteen minutes")
|
||||
if self.channel == "stable" and Version(self.target.version).is_prerelease:
|
||||
raise ValueError("A stable plan cannot install a preview")
|
||||
if self.installation.manager is not None and self.extras != self.installation.manager.extras:
|
||||
raise ValueError("An update must preserve the installation owner's recorded extras")
|
||||
profiles = {item.receipt.id: item.receipt for item in self.profiles}
|
||||
if len(set(self.stop_profiles)) != len(self.stop_profiles):
|
||||
raise ValueError("Shutdown participants must be unique")
|
||||
for participant in self.stop_profiles:
|
||||
profile = profiles.get(participant)
|
||||
if (profile is None or not _managed_background(profile, self.installation.environment)
|
||||
or profile.stop_protocol != 1
|
||||
or not any(item.receipt.id == participant and item.state == "running" for item in self.profiles)):
|
||||
raise ValueError("Shutdown requires a reviewed running gateway with cooperative stop support")
|
||||
if len(set(self.restart_profiles)) != len(self.restart_profiles):
|
||||
raise ValueError("Restart participants must be unique")
|
||||
for participant in self.restart_profiles:
|
||||
profile = profiles.get(participant)
|
||||
if (profile is None or not _managed_background(profile, self.installation.environment)
|
||||
or not profile.port):
|
||||
raise ValueError("Restart requires a reviewed, explicitly managed background gateway")
|
||||
return self
|
||||
|
||||
@property
|
||||
def action(self) -> Literal["upgrade", "downgrade", "restart", "none"]:
|
||||
target = Version(self.target.version)
|
||||
installed = Version(self.installation.installed_version)
|
||||
running = Version(self.installation.running_version)
|
||||
if target < max(installed, running):
|
||||
return "downgrade"
|
||||
if target > installed:
|
||||
return "upgrade"
|
||||
if running != installed:
|
||||
return "restart"
|
||||
return "none"
|
||||
|
||||
@property
|
||||
def owner_restriction(self) -> str | None:
|
||||
manager = self.installation.manager
|
||||
return manager.restriction(self.target.version) if manager is not None else None
|
||||
|
||||
@property
|
||||
def can_restart_inline(self) -> bool:
|
||||
"""The review includes this gateway and every confirmed running peer."""
|
||||
running = {item.receipt.id for item in self.profiles if item.state == "running"}
|
||||
return (not any(item.state == "unconfirmed" for item in self.profiles)
|
||||
and any(item.state == "running" and item.receipt.pid == os.getpid() for item in self.profiles)
|
||||
and running == set(self.stop_profiles) == set(self.restart_profiles))
|
||||
|
||||
def validate_for(self, installation: InstallationSnapshot, *, now: int | None = None) -> None:
|
||||
validate_channel_revision(self.channel_revision, self.installation.environment)
|
||||
checked_at = int(time.time()) if now is None else now
|
||||
if checked_at < self.created_at or checked_at >= self.expires_at:
|
||||
raise ValueError("Update plan expired; check again before confirming")
|
||||
if self.installation.fingerprint != installation.fingerprint:
|
||||
raise ValueError("Installation changed since this plan; check again before confirming")
|
||||
|
||||
|
||||
class UpdatePlanNotFoundError(FileNotFoundError):
|
||||
"""The requested saved plan is absent, not an installation-probe failure."""
|
||||
|
||||
|
||||
class UpdatePlans:
|
||||
"""Persist plans outside replaceable package files, with a small caller Interface."""
|
||||
|
||||
def __init__(self, directory: Path) -> None:
|
||||
self.directory = directory
|
||||
|
||||
def save(self, plan: UpdatePlan) -> UpdatePlan:
|
||||
encoded = plan.model_dump_json()
|
||||
if len(encoded.encode("utf-8")) + 1 > 1024 * 1024:
|
||||
raise ValueError("Update plan exceeds its size limit")
|
||||
self.directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
path = self.directory / f"{plan.id}.json"
|
||||
with FileLock(str(self.directory / "plans.lock"), timeout=5):
|
||||
if path.exists():
|
||||
if self.load(plan.id) != plan:
|
||||
raise ValueError("An approved update plan cannot be replaced")
|
||||
return plan
|
||||
atomic_write_lines(path, [encoded])
|
||||
path.chmod(0o600)
|
||||
return plan
|
||||
|
||||
def load(self, plan_id: str) -> UpdatePlan:
|
||||
UpdatePlan.canonical_id(plan_id)
|
||||
path = self.directory / f"{plan_id}.json"
|
||||
try:
|
||||
if path.is_symlink() or path.stat().st_size > 1024 * 1024:
|
||||
raise ValueError("Invalid saved update plan")
|
||||
encoded = path.read_bytes()
|
||||
except FileNotFoundError as exc:
|
||||
raise UpdatePlanNotFoundError("The saved update plan is no longer available") from exc
|
||||
plan = UpdatePlan.model_validate_json(encoded)
|
||||
if plan.id != plan_id:
|
||||
raise ValueError("Saved update plan identity differs")
|
||||
return plan
|
||||
|
||||
async def prepare(self, installation: InstallationSnapshot, channel: Channel, feed: ReleaseFeed,
|
||||
*, now: int | None = None, restart_running: bool = False,
|
||||
extras: list[str] | None = None, channel_revision: int | None = None) -> UpdatePlan:
|
||||
target = await feed.latest(channel)
|
||||
created_at = int(time.time()) if now is None else now
|
||||
profiles = inspect_profiles(installation.environment)
|
||||
if installation.manager is not None:
|
||||
if extras is not None and extras != installation.manager.extras:
|
||||
raise ValueError("The plan cannot change the installation owner's recorded extras")
|
||||
extras = installation.manager.extras
|
||||
elif installation.owner == "venv" and RECEIPT_NAME in installation.records:
|
||||
recorded_extras = managed_extras(installation.environment, installation.records[RECEIPT_NAME])
|
||||
if extras is not None and extras != recorded_extras:
|
||||
raise ValueError("The plan cannot change the installer's recorded extras")
|
||||
extras = recorded_extras
|
||||
participants: list[str] = []
|
||||
if restart_running:
|
||||
for profile in profiles:
|
||||
if profile.state == "running":
|
||||
if (not _managed_background(profile.receipt, installation.environment) or not profile.receipt.port
|
||||
or profile.receipt.stop_protocol != 1):
|
||||
# Review must still explain an external owner's workflow.
|
||||
# Such a plan is ineligible for inline execution below.
|
||||
continue
|
||||
participants.append(profile.receipt.id)
|
||||
plan = UpdatePlan(id=str(uuid4()), installation=installation, channel=channel, target=target, extras=extras, profiles=profiles,
|
||||
channel_revision=channel_revision,
|
||||
stop_profiles=participants, restart_profiles=participants,
|
||||
created_at=created_at, expires_at=created_at + 15 * 60)
|
||||
return self.save(plan)
|
||||
|
||||
async def revalidate(self, plan_id: str, installation: InstallationSnapshot, feed: ReleaseFeed,
|
||||
*, now: int | None = None) -> UpdatePlan:
|
||||
plan = self.load(plan_id)
|
||||
plan.validate_for(installation, now=now)
|
||||
validate_profiles(plan.profiles, installation.environment)
|
||||
await feed.revalidate(plan.target)
|
||||
# Release discovery can yield to a profile restart or a long network wait.
|
||||
plan.validate_for(installation, now=now)
|
||||
validate_profiles(plan.profiles, installation.environment)
|
||||
return plan
|
||||
|
||||
|
||||
class UpdatePlanRequest(ReleaseRecord):
|
||||
"""An intended change to review, never installation/shutdown permission."""
|
||||
|
||||
channel: Channel | None = None
|
||||
restart_running: bool = False
|
||||
extras: list[str] | None = None
|
||||
|
||||
@field_validator("extras")
|
||||
@classmethod
|
||||
def explicit_extras(cls, value: list[str] | None) -> list[str] | None:
|
||||
return UpdatePlan.explicit_extras(value)
|
||||
|
||||
|
||||
class ProfileReview(ReleaseRecord):
|
||||
id: str
|
||||
workspace: str
|
||||
reviewed_state: Literal["running", "stopped", "unconfirmed"]
|
||||
stop: bool
|
||||
restart: bool
|
||||
|
||||
|
||||
class UpdatePlanReview(ReleaseRecord):
|
||||
"""Client-safe facts, not execution approval or fresh release eligibility.
|
||||
|
||||
Validity describes the locally observed installation and review lifetime.
|
||||
Reading a review never re-resolves its target or checks the release feed.
|
||||
"""
|
||||
|
||||
id: str
|
||||
installation_id: str
|
||||
host: str
|
||||
owner: Owner
|
||||
running_version: str
|
||||
installed_version: str
|
||||
target_version: str
|
||||
channel: Channel
|
||||
action: Literal["upgrade", "downgrade", "restart", "none"]
|
||||
created_at: int
|
||||
expires_at: int
|
||||
validity: Literal["current", "expired", "installation_changed", "profiles_changed", "channel_changed"]
|
||||
artifact_size: int
|
||||
extras: list[str] | None
|
||||
owner_restriction: str | None
|
||||
profiles: list[ProfileReview]
|
||||
execution_blocked_reason: str | None = None
|
||||
automatic_recovery: bool = False
|
||||
guide: UpdateGuide | None = None
|
||||
|
||||
|
||||
def review_plan(plan: UpdatePlan, installation: InstallationSnapshot, *, now: int | None = None,
|
||||
profiles: list[ObservedProfile] | None = None) -> UpdatePlanReview:
|
||||
checked_at = int(time.time()) if now is None else now
|
||||
validity: Literal["current", "expired", "installation_changed", "profiles_changed", "channel_changed"] = "current"
|
||||
if (plan.channel_revision or 0) != read_update_channel(plan.installation.environment).revision:
|
||||
validity = "channel_changed"
|
||||
elif plan.installation.fingerprint != installation.fingerprint:
|
||||
validity = "installation_changed"
|
||||
elif not plan.created_at <= checked_at < plan.expires_at:
|
||||
validity = "expired"
|
||||
elif profiles is not None and profiles != plan.profiles:
|
||||
validity = "profiles_changed"
|
||||
return UpdatePlanReview(
|
||||
id=plan.id, installation_id=plan.installation.installation_id, host=platform.node(),
|
||||
owner=plan.installation.owner, running_version=installation.running_version,
|
||||
installed_version=installation.installed_version, target_version=plan.target.version,
|
||||
channel=plan.channel, action=plan.action, created_at=plan.created_at, expires_at=plan.expires_at,
|
||||
validity=validity, artifact_size=plan.target.artifact.size, extras=plan.extras,
|
||||
owner_restriction=plan.owner_restriction, execution_blocked_reason=inline_update_blocked_reason(plan, validity),
|
||||
automatic_recovery=bool(plan.restart_profiles) and RECEIPT_NAME in plan.installation.records,
|
||||
guide=update_guide(installation, plan.target.version, extras=plan.extras, current=validity == "current"),
|
||||
profiles=[ProfileReview(
|
||||
id=item.receipt.id, workspace=item.receipt.workspace, reviewed_state=item.state,
|
||||
stop=item.receipt.id in plan.stop_profiles, restart=item.receipt.id in plan.restart_profiles,
|
||||
) for item in plan.profiles],
|
||||
)
|
||||
|
||||
|
||||
def inline_update_blocked_reason(plan: UpdatePlan, validity: str = "current") -> str | None:
|
||||
"""Eligibility is not approval: preparation and handoff recheck these facts."""
|
||||
if validity != "current":
|
||||
return "review_changed"
|
||||
if plan.action != "upgrade":
|
||||
return "not_upgrade"
|
||||
if plan.installation.owner not in {"venv", "uv"}:
|
||||
return "installation_owner"
|
||||
if plan.installation.owner == "uv" and (os.name != "posix"
|
||||
or plan.installation.manager_version != UV_TRANSACTION_VERSION):
|
||||
return "installation_owner"
|
||||
if plan.extras is None or plan.owner_restriction:
|
||||
return "installation_policy"
|
||||
if not plan.can_restart_inline:
|
||||
return "external_restart"
|
||||
return None
|
||||
|
||||
|
||||
def inspect_update_installation() -> InstallationSnapshot:
|
||||
# Keep the complete snapshot (including owner receipt parsing) protected
|
||||
# after request cancellation. The native child also holds its own lease,
|
||||
# so loss of this process cannot leave site/import/exit cleanup unprotected.
|
||||
with installation_access():
|
||||
return inspect_installation()
|
||||
|
||||
|
||||
async def preview_release_update(channel: Channel | None = None, *, restart_running: bool = False,
|
||||
extras: list[str] | None = None) -> UpdatePlan:
|
||||
"""Build a read-only installation plan for CLI and future gateway handoff."""
|
||||
with installation_access():
|
||||
installation = await asyncio.to_thread(inspect_update_installation)
|
||||
directory = installation_state_dir(installation.environment)
|
||||
selection = read_update_channel(installation.environment)
|
||||
async with ReleaseFeed(directory / "releases") as feed:
|
||||
plan = await UpdatePlans(directory / "plans").prepare(
|
||||
installation, channel or selection.channel, feed, restart_running=restart_running, extras=extras,
|
||||
channel_revision=selection.revision,
|
||||
)
|
||||
# External package managers do not participate in our lease. Discovery
|
||||
# can be slow: do not return a freshly valid review of a replaced install.
|
||||
plan.validate_for(await asyncio.to_thread(inspect_update_installation))
|
||||
return plan
|
||||
|
||||
|
||||
async def read_release_plan(plan_id: str) -> UpdatePlanReview:
|
||||
"""Recover the exact review after refresh; do not query a newer release."""
|
||||
UpdatePlan.canonical_id(plan_id)
|
||||
with installation_access():
|
||||
installation = await asyncio.to_thread(inspect_update_installation)
|
||||
plan = UpdatePlans(installation_state_dir(installation.environment) / "plans").load(plan_id)
|
||||
return review_plan(plan, installation, profiles=inspect_profiles(installation.environment))
|
||||
|
||||
|
||||
def describe_plan(plan: UpdatePlan) -> str:
|
||||
"""No promised install command until the owner/lifecycle executor is available."""
|
||||
return json.dumps({
|
||||
**plan.model_dump(mode="json"), "action": plan.action,
|
||||
"installation_id": plan.installation.installation_id,
|
||||
"owner_restriction": plan.owner_restriction,
|
||||
"profile_notice": "Known profiles only; this does not prove all runtimes or supervisors are accounted for.",
|
||||
"notice": "Plan only. No packages were changed or processes restarted.",
|
||||
}, indent=2)
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Process-owned leases and protected startup for frozen updater children.
|
||||
|
||||
Copied into the frozen worker; keep this module standard-library only. Commands
|
||||
come from the preparer's implementation, never from a client or release record.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Literal, cast
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from nanobot.installation_lock import (
|
||||
InstallationBusyError,
|
||||
file_access,
|
||||
installation_access,
|
||||
installation_state_dir,
|
||||
)
|
||||
from nanobot.utils.atomic_file import atomic_write_lines, io_path
|
||||
|
||||
# This stack belongs only to the single-use frozen child. Do not close it on a
|
||||
# function return/SystemExit: pip/site atexit cleanup must still hold the leases.
|
||||
# Module teardown and process exit release them after Python's exit callbacks.
|
||||
child_leases = ExitStack()
|
||||
|
||||
|
||||
def initialize_runtime(python: str, environment: str) -> None:
|
||||
"""Initialize the target's site only after the caller acquired its own leases."""
|
||||
if not sys.flags.isolated or not sys.flags.no_site:
|
||||
raise ValueError("An update child must start with isolated, deferred site initialization")
|
||||
if Path(sys.executable).absolute() != Path(python).absolute():
|
||||
raise ValueError("Update child is using a different Python interpreter")
|
||||
import site
|
||||
|
||||
site.main()
|
||||
if Path(sys.prefix).resolve() != Path(environment).resolve():
|
||||
raise ValueError("Update child is using a different installation")
|
||||
|
||||
|
||||
_INSPECTION_BOOTSTRAP = """
|
||||
import json, sys, types
|
||||
from contextlib import ExitStack
|
||||
from pathlib import Path
|
||||
request = json.load(sys.stdin)
|
||||
atomic = types.ModuleType('_nanobot_inspection_atomic')
|
||||
sys.modules[atomic.__name__] = atomic
|
||||
exec(compile(request['atomic'], '<inspection atomic I/O>', 'exec'), atomic.__dict__)
|
||||
locking = types.ModuleType('_nanobot_inspection_lock')
|
||||
sys.modules[locking.__name__] = locking
|
||||
exec(compile(request['locking'], '<inspection leases>', 'exec'), locking.__dict__)
|
||||
leases = ExitStack()
|
||||
try:
|
||||
leases.enter_context(locking.installation_access(environment=request['environment'],
|
||||
allow_incomplete=request['allow_incomplete']))
|
||||
except locking.InstallationBusyError:
|
||||
raise SystemExit(11) from None
|
||||
exec(compile(request['startup'], '<inspection startup>', 'exec'))
|
||||
initialize_runtime(request['python'], request['environment'])
|
||||
sys.argv = ['-c', *request['arguments']]
|
||||
exec(compile(request['probe'], '<installation inspection>', 'exec'), {'__name__': '__main__'})
|
||||
"""
|
||||
|
||||
|
||||
def inspect_python_environment(python: str, environment: str, probe: str, *,
|
||||
arguments: tuple[str, ...] = (), timeout: int = 15,
|
||||
allow_incomplete: bool = False) -> subprocess.CompletedProcess[str]:
|
||||
"""Run a first-party read probe with child-owned startup/exit protection.
|
||||
|
||||
Planning has no staged worker yet. Freeze the existing stdlib lease and
|
||||
startup implementations while holding the parent lease, then pass them over
|
||||
stdin to an isolated child. No mutable package code runs before its lease;
|
||||
the global child stack survives probe return and atexit after caller loss.
|
||||
This is not an installer or a command interface for clients/release records.
|
||||
"""
|
||||
import inspect
|
||||
|
||||
with installation_access(environment=environment, allow_incomplete=allow_incomplete):
|
||||
# Lease acquisition needs the same frozen I/O helper as the worker. The
|
||||
# child must not import either helper from the target before its lease.
|
||||
atomic_module = io_path.__module__
|
||||
locking = inspect.getsource(sys.modules[installation_access.__module__]).replace(
|
||||
f"from {atomic_module} import io_path", "from _nanobot_inspection_atomic import io_path",
|
||||
)
|
||||
request = json.dumps(dict(
|
||||
atomic=inspect.getsource(sys.modules[atomic_module]), locking=locking,
|
||||
startup=inspect.getsource(initialize_runtime), python=python, environment=environment,
|
||||
probe=probe, arguments=arguments, allow_incomplete=allow_incomplete,
|
||||
))
|
||||
result = subprocess.run([python, "-I", "-S", "-c", _INSPECTION_BOOTSTRAP], input=request,
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
if result.returncode == 11:
|
||||
raise InstallationBusyError("This installation is being updated; try checking again when it finishes")
|
||||
return result
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PreparationProcess:
|
||||
directory: Path
|
||||
environment: str
|
||||
generation: str
|
||||
active: bool = True
|
||||
|
||||
@classmethod
|
||||
def create(cls, directory: Path, environment: str) -> PreparationProcess:
|
||||
"""Called with the parent and native preparation leases held."""
|
||||
result = cls(directory.resolve(), str(Path(environment).resolve()), uuid4().hex)
|
||||
result._save(active=True)
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def load(cls, directory: Path) -> PreparationProcess:
|
||||
path = directory / "preparation.json"
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid preparation identity")
|
||||
with path.open("rb") as stream:
|
||||
value = json.loads(stream.read(16_385))
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Invalid preparation identity")
|
||||
record = cast(dict[str, object], value)
|
||||
if (type(record.get("active")) is not bool or not isinstance(record.get("environment"), str)
|
||||
or not isinstance(record.get("generation"), str)):
|
||||
raise ValueError("Invalid preparation identity")
|
||||
environment, generation = cast(str, record["environment"]), cast(str, record["generation"])
|
||||
if (UUID(generation).hex != generation or not Path(environment).is_absolute()
|
||||
or directory != installation_state_dir(environment).resolve() / "jobs" / str(UUID(directory.name))):
|
||||
raise ValueError("Preparation belongs to another installation")
|
||||
return cls(directory, environment, generation, cast(bool, record["active"]))
|
||||
|
||||
def _save(self, *, active: bool) -> None:
|
||||
path = self.directory / "preparation.json"
|
||||
atomic_write_lines(path, [json.dumps(dict(environment=self.environment,
|
||||
generation=self.generation, active=active))])
|
||||
path.chmod(0o600)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Revoke late children only after the actual native command has exited."""
|
||||
self._save(active=False)
|
||||
|
||||
def run(self, executable: str, arguments: list[str], *, kind: Literal["python", "native"] = "python",
|
||||
timeout: int = 900, env: dict[str, str] | None = None,
|
||||
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
# Python commands run in their intended interpreter. Native uv uses the
|
||||
# base interpreter only to acquire leases, then replaces that same PID.
|
||||
base: object = getattr(sys, "_base_executable")
|
||||
if not isinstance(base, str):
|
||||
raise ValueError("Preparation needs a known base Python")
|
||||
bootstrap = executable if kind == "python" else base
|
||||
request = json.dumps(dict(generation=self.generation, kind=kind,
|
||||
executable=executable, arguments=arguments))
|
||||
# -S prevents site/.pth code in the mutable environment from running
|
||||
# before this child has acquired its own leases.
|
||||
return subprocess.run([bootstrap, "-I", "-S", str(self.directory / "worker.pyz"),
|
||||
"--prepare-native", str(self.directory)], input=request,
|
||||
capture_output=True, text=True, timeout=timeout, env=env, cwd=cwd)
|
||||
|
||||
|
||||
def run_preparation_child(directory: Path) -> None:
|
||||
"""Acquire our own leases before reading mutable packages or staging files."""
|
||||
encoded = sys.stdin.read(1024 * 1024 + 1)
|
||||
if len(encoded) > 1024 * 1024:
|
||||
raise ValueError("Preparation command exceeds its size limit")
|
||||
value = json.loads(encoded)
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Invalid preparation command")
|
||||
request = cast(dict[str, object], value)
|
||||
kind, executable, arguments = request.get("kind"), request.get("executable"), request.get("arguments")
|
||||
if (not isinstance(kind, str) or kind not in {"python", "native"} or not isinstance(executable, str)
|
||||
or not Path(executable).is_absolute() or not isinstance(arguments, list)
|
||||
or not arguments):
|
||||
raise ValueError("Invalid preparation command")
|
||||
if not all(isinstance(item, str) for item in cast(list[object], arguments)):
|
||||
raise ValueError("Invalid preparation arguments")
|
||||
args = cast(list[str], arguments)
|
||||
identity = PreparationProcess.load(directory)
|
||||
native = child_leases.enter_context(file_access(
|
||||
installation_state_dir(identity.environment) / "prepare-native.lock", exclusive=True))
|
||||
installation = child_leases.enter_context(installation_access(environment=identity.environment))
|
||||
# Recovery/retry holds native.lock while revoking the generation. Check
|
||||
# again inside the lease: a delayed child cannot use a replacement job.
|
||||
if (not identity.active or PreparationProcess.load(directory) != identity
|
||||
or request.get("generation") != identity.generation):
|
||||
raise ValueError("The preparation generation changed")
|
||||
if kind == "native":
|
||||
if os.name != "posix":
|
||||
raise ValueError("Native preparation needs a verified exec handoff on this platform")
|
||||
with native.inherit_for_exec(), installation.inherit_for_exec():
|
||||
os.execve(executable, [executable, *args], os.environ)
|
||||
if len(args) < 2 or not (args[:1] == ["-c"] or args[:2] == ["-m", "pip"]):
|
||||
raise ValueError("Unsupported preparation command")
|
||||
# Use the same Python path on POSIX and Windows; byte-range leases cannot
|
||||
# transfer through exec on Windows. Site startup and atexit stay protected.
|
||||
sys.argv = ["pip" if args[0] == "-m" else "-c", *args[2:]]
|
||||
# uv also probes its disposable prepared venv. The job's leases protect
|
||||
# both that staging area and the live installation; they are not necessarily
|
||||
# the environment whose Python this particular probe is running.
|
||||
initialize_runtime(executable, str(Path(executable).parent.parent))
|
||||
if args[0] == "-m":
|
||||
runpy.run_module("pip", run_name="__main__")
|
||||
else:
|
||||
exec(compile(args[1], "<update preparation probe>", "exec"), {"__name__": "__main__"})
|
||||
@@ -0,0 +1,285 @@
|
||||
"""Installation-scoped inventory of gateway profiles, not process-control authority.
|
||||
|
||||
Receipts survive shutdown so a stopped profile's durable data is not forgotten by
|
||||
an update plan. Liveness is checked against the existing process identity, never a
|
||||
PID alone. This inventory cannot discover pre-receipt or other-account runtimes;
|
||||
the installation lease and an explicit process-owner handoff are still required.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from uuid import uuid4
|
||||
|
||||
from filelock import FileLock
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
import nanobot
|
||||
from nanobot.config.home import get_home_path
|
||||
from nanobot.data_access import DataStartupGrant, profile_data_access, profile_data_paths
|
||||
from nanobot.gateway.runtime import (
|
||||
GatewayHealthIdentity,
|
||||
GatewayInstance,
|
||||
GatewayRuntime,
|
||||
GatewayRuntimePaths,
|
||||
GatewayStartOptions,
|
||||
)
|
||||
from nanobot.installation_lock import installation_state_dir
|
||||
from nanobot.utils.atomic_file import atomic_write_lines, read_atomic_bytes
|
||||
|
||||
|
||||
class ProfileLaunch(BaseModel):
|
||||
"""Original selectors, not inferred arguments or an executable shell command."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
|
||||
|
||||
home: str | None
|
||||
config_path: str | None
|
||||
workspace: str | None
|
||||
working_directory: str
|
||||
verbose: bool
|
||||
lifetime: Literal["explicit", "on_demand"]
|
||||
|
||||
@field_validator("home", "config_path", "workspace", "working_directory")
|
||||
@classmethod
|
||||
def bounded_path(cls, value: str | None) -> str | None:
|
||||
if value is not None and (not Path(value).is_absolute() or len(value) > 4096 or "\0" in value):
|
||||
raise ValueError("Launch selectors must be bounded absolute paths")
|
||||
return value
|
||||
|
||||
def options(self, *, port: int) -> GatewayStartOptions:
|
||||
return GatewayStartOptions(home=self.home, config_path=self.config_path,
|
||||
workspace=self.workspace, port=port, verbose=self.verbose)
|
||||
|
||||
|
||||
class ProfileReceipt(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
|
||||
|
||||
schema_version: Literal[1] = 1
|
||||
id: str = Field(pattern=r"^[0-9a-f]{64}$")
|
||||
run_id: str = Field(pattern=r"^[0-9a-f]{32}$")
|
||||
environment: str
|
||||
python: str
|
||||
package: str
|
||||
version: str
|
||||
home: str
|
||||
data_dir: str
|
||||
config: str
|
||||
workspace: str
|
||||
state_path: str
|
||||
log_path: str
|
||||
port: int = Field(ge=0, le=65535)
|
||||
launch_mode: Literal["foreground", "background", "unknown"]
|
||||
pid: int = Field(gt=0)
|
||||
process_identity: str | int | None
|
||||
active: bool
|
||||
# Older receipts remain useful data inventory, but cannot prove launch intent.
|
||||
launch: ProfileLaunch | None = None
|
||||
stop_protocol: Literal[1] | None = None
|
||||
update_job_id: str | None = Field(default=None, pattern=r"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$")
|
||||
|
||||
@field_validator("environment", "python", "package", "home", "data_dir", "config", "workspace", "state_path", "log_path")
|
||||
@classmethod
|
||||
def absolute_path(cls, value: str) -> str:
|
||||
if not Path(value).is_absolute() or len(value) > 4096 or "\0" in value:
|
||||
raise ValueError("Profile paths must be bounded absolute paths")
|
||||
return value
|
||||
|
||||
@property
|
||||
def health_identity(self) -> GatewayHealthIdentity:
|
||||
return GatewayHealthIdentity(self.id, self.run_id, self.version)
|
||||
|
||||
@property
|
||||
def runtime_paths(self) -> GatewayRuntimePaths:
|
||||
state, log = Path(self.state_path), Path(self.log_path)
|
||||
return GatewayRuntimePaths(run_dir=state.parent, logs_dir=log.parent, state_path=state, log_path=log)
|
||||
|
||||
@property
|
||||
def data_paths(self) -> tuple[Path, ...]:
|
||||
# Preserve individual store paths: leases and backups must reject links,
|
||||
# not resolve them into additional read/write authority.
|
||||
return profile_data_paths(home=Path(self.home), data_dir=Path(self.data_dir),
|
||||
config=Path(self.config), workspace=Path(self.workspace))
|
||||
|
||||
|
||||
class ObservedProfile(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
|
||||
receipt: ProfileReceipt
|
||||
state: Literal["running", "stopped", "unconfirmed"]
|
||||
|
||||
|
||||
class _RuntimeClaim(BaseModel):
|
||||
model_config = ConfigDict(strict=True)
|
||||
pid: int = Field(gt=0)
|
||||
identity: str | int | None = None
|
||||
stable_identity: str | int | None = None
|
||||
|
||||
|
||||
def _observe(receipt: ProfileReceipt) -> Literal["running", "stopped", "unconfirmed"]:
|
||||
state_path = Path(receipt.state_path)
|
||||
runtime = GatewayRuntime(paths=receipt.runtime_paths)
|
||||
try:
|
||||
if state_path.is_symlink() or state_path.stat().st_size > 32 * 1024:
|
||||
return "unconfirmed"
|
||||
claim = _RuntimeClaim.model_validate_json(read_atomic_bytes(state_path))
|
||||
except FileNotFoundError:
|
||||
claim = None
|
||||
except (OSError, ValueError):
|
||||
return "unconfirmed"
|
||||
if claim is not None and runtime.process_is_running(claim.pid):
|
||||
identity = claim.stable_identity if claim.stable_identity is not None else claim.identity
|
||||
if identity is None:
|
||||
return "unconfirmed"
|
||||
match = runtime.process_identity_match(identity, claim.pid)
|
||||
if match == "unknown":
|
||||
return "unconfirmed"
|
||||
if match == "match":
|
||||
# The profile may now be used by a different installation. Its old
|
||||
# inactive receipt does not grant a right to back up/restore live data.
|
||||
if claim.pid != receipt.pid:
|
||||
return "unconfirmed"
|
||||
if receipt.process_identity is None:
|
||||
return "unconfirmed"
|
||||
own_match = runtime.process_identity_match(receipt.process_identity, receipt.pid)
|
||||
if own_match != "match":
|
||||
return "unconfirmed"
|
||||
return "running" if receipt.active else "stopped"
|
||||
if receipt.active and runtime.process_is_running(receipt.pid):
|
||||
match = (runtime.process_identity_match(receipt.process_identity, receipt.pid)
|
||||
if receipt.process_identity is not None else "unknown")
|
||||
if match != "mismatch":
|
||||
return "unconfirmed" # Live process, but its runtime claim disappeared.
|
||||
return "stopped"
|
||||
|
||||
|
||||
def _profile_id(state_path: str) -> str:
|
||||
return hashlib.sha256(os.fsencode(Path(state_path).resolve())).hexdigest()
|
||||
|
||||
|
||||
def _save(directory: Path, receipt: ProfileReceipt) -> None:
|
||||
path = directory / f"{receipt.id}.json"
|
||||
atomic_write_lines(path, [receipt.model_dump_json()])
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def record_gateway_profile(instance: GatewayInstance, runtime: GatewayRuntime, *,
|
||||
data_dir: Path, workspace: Path, port: int,
|
||||
verbose: bool = False,
|
||||
grant: DataStartupGrant | None = None,
|
||||
cooperative_stop: bool = False) -> Generator[ProfileReceipt]:
|
||||
"""Record an already-claimed gateway and retain its profile after shutdown."""
|
||||
state_path = str(instance.paths.state_path.resolve())
|
||||
directory = installation_state_dir() / "profiles"
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
status = runtime.status()
|
||||
if not status.running or status.pid != os.getpid():
|
||||
raise ValueError("Only the gateway that claimed this runtime may record its profile")
|
||||
options = instance.start_options(port=port, verbose=verbose)
|
||||
receipt = ProfileReceipt(
|
||||
id=_profile_id(state_path), run_id=uuid4().hex,
|
||||
environment=str(Path(sys.prefix).resolve()), python=str(Path(sys.executable).absolute()),
|
||||
package=str(Path(nanobot.__file__).resolve()), version=nanobot.__version__,
|
||||
home=str(get_home_path().resolve()), data_dir=str(data_dir.resolve()),
|
||||
config=str(instance.config_path.resolve()), workspace=str(workspace.resolve()),
|
||||
state_path=state_path, log_path=str(instance.paths.log_path.resolve()), port=port,
|
||||
launch_mode=status.launch_mode, pid=os.getpid(),
|
||||
process_identity=runtime.process_identity(os.getpid()), active=True,
|
||||
update_job_id=grant.job_id if grant else None,
|
||||
stop_protocol=1 if cooperative_stop else None,
|
||||
launch=ProfileLaunch(home=options.home, config_path=options.config_path,
|
||||
workspace=options.workspace, working_directory=str(Path.cwd().resolve()),
|
||||
verbose=options.verbose, lifetime=status.lifetime),
|
||||
)
|
||||
if grant is not None and grant.participant != receipt.id:
|
||||
raise ValueError("Startup grant belongs to a different gateway instance")
|
||||
with profile_data_access(home=Path(receipt.home), data_dir=Path(receipt.data_dir),
|
||||
config=Path(receipt.config), workspace=Path(receipt.workspace), grant=grant):
|
||||
with FileLock(str(directory / "profiles.lock"), timeout=5):
|
||||
_save(directory, receipt)
|
||||
try:
|
||||
yield receipt
|
||||
finally:
|
||||
with FileLock(str(directory / "profiles.lock"), timeout=5):
|
||||
# Persist the inactive receipt before releasing the data leases.
|
||||
# A receipt alone does not prove every external writer has stopped.
|
||||
_save(directory, receipt.model_copy(update={"active": False}))
|
||||
|
||||
|
||||
def inspect_profiles(environment: str) -> list[ObservedProfile]:
|
||||
"""Read known profiles without writing their runtime files or contacting hosts."""
|
||||
directory = installation_state_dir(environment) / "profiles"
|
||||
if not directory.exists():
|
||||
return []
|
||||
profiles: list[ObservedProfile] = []
|
||||
with FileLock(str(directory / "profiles.lock"), timeout=5):
|
||||
for path in sorted(directory.glob("*.json")):
|
||||
if len(profiles) >= 1024 or path.is_symlink() or path.stat().st_size > 32 * 1024:
|
||||
raise ValueError("Invalid installation profile inventory")
|
||||
receipt = ProfileReceipt.model_validate_json(read_atomic_bytes(path))
|
||||
if (receipt.environment != str(Path(environment).resolve()) or
|
||||
receipt.id != path.stem or receipt.id != _profile_id(receipt.state_path)):
|
||||
raise ValueError("Profile receipt belongs to a different installation or instance")
|
||||
profiles.append(ObservedProfile(receipt=receipt, state=_observe(receipt)))
|
||||
return profiles
|
||||
|
||||
|
||||
def validate_profiles(expected: list[ObservedProfile], environment: str) -> None:
|
||||
"""Before confirming a plan, reject a newly started/reconfigured profile."""
|
||||
if inspect_profiles(environment) != expected:
|
||||
raise ValueError("Gateway profiles changed since this plan; check again before confirming")
|
||||
|
||||
|
||||
def require_stopped_profiles(expected: list[ObservedProfile], environment: str) -> None:
|
||||
"""Allow the reviewed gateways to exit, not a replacement or an unknown owner."""
|
||||
current = inspect_profiles(environment)
|
||||
# A graceful exit only changes `active`; a restart/reconfiguration creates a
|
||||
# new run_id and needs a new plan even if the file paths are unchanged.
|
||||
before = [item.receipt.model_dump(exclude={"active"}) for item in expected]
|
||||
after = [item.receipt.model_dump(exclude={"active"}) for item in current]
|
||||
if before != after:
|
||||
raise ValueError("Gateway profiles changed since this plan; check again before confirming")
|
||||
if any(item.state != "stopped" for item in current):
|
||||
raise ValueError("A reviewed gateway profile is still in use or its process owner is unconfirmed")
|
||||
|
||||
|
||||
def validate_restart_identity(previous: ProfileReceipt, current: ProfileReceipt, *,
|
||||
version: str, job_id: str | None = None) -> None:
|
||||
"""Validate a new claim without mistaking it for running/healthy evidence."""
|
||||
if previous.launch is None:
|
||||
raise ValueError("The original gateway launch identity is unknown")
|
||||
changing = {"run_id", "pid", "process_identity", "version", "active", "update_job_id", "stop_protocol"}
|
||||
if (current.model_dump(exclude=changing) != previous.model_dump(exclude=changing)
|
||||
or current.version != version or current.run_id == previous.run_id
|
||||
or current.process_identity == previous.process_identity or current.update_job_id != job_id):
|
||||
raise ValueError("The restarted gateway differs from the reviewed instance or target version")
|
||||
|
||||
|
||||
def verify_restarted_profile(previous: ProfileReceipt, *, version: str,
|
||||
job_id: str | None = None, maintenance: bool | None = None) -> ProfileReceipt:
|
||||
"""Verify a fresh run of the reviewed local profile; never start/stop it.
|
||||
|
||||
Call under the update owner's lifecycle/maintenance handoff. A receipt or an
|
||||
HTTP 200 alone is insufficient, and this does not grant restart authority.
|
||||
"""
|
||||
observed = next((item for item in inspect_profiles(previous.environment)
|
||||
if item.receipt.id == previous.id), None)
|
||||
if observed is None or observed.state != "running":
|
||||
raise ValueError("The updated gateway is not running with a verified process identity")
|
||||
current = observed.receipt
|
||||
validate_restart_identity(previous, current, version=version, job_id=job_id)
|
||||
runtime = GatewayRuntime(paths=current.runtime_paths)
|
||||
if not runtime.verify_ready(current.health_identity, maintenance=maintenance):
|
||||
raise ValueError("Gateway readiness did not confirm the updated instance, run and version")
|
||||
# Re-read the receipt as well: a new claim can precede its new receipt.
|
||||
final = next((item for item in inspect_profiles(previous.environment)
|
||||
if item.receipt.id == previous.id), None)
|
||||
if final != observed:
|
||||
raise ValueError("The gateway changed during restart verification")
|
||||
return current
|
||||
@@ -0,0 +1,68 @@
|
||||
"""nanobot standalone recovery launcher, protocol 1.
|
||||
|
||||
Copied outside the installed package before an update. Uses only the standard
|
||||
library and delegates to the exact saved worker, never imports a broken nanobot.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Inspect or resume a saved nanobot update; never install latest")
|
||||
parser.add_argument("job", help="Saved update ID shown in the WebUI")
|
||||
parser.add_argument("--repair", action="store_true", help="Review and resume this exact offline update")
|
||||
parser.add_argument("--yes", action="store_true", help="Confirm the reviewed exact repair without a prompt")
|
||||
args = parser.parse_args()
|
||||
if str(UUID(args.job)) != args.job:
|
||||
parser.error("Use the complete saved update ID")
|
||||
if args.yes and not args.repair:
|
||||
parser.error("--yes requires --repair")
|
||||
# This launcher is staged beside the installation journals. Preserve that
|
||||
# gateway's HOME for the frozen worker's job binding, locks and restarts,
|
||||
# even when the operator invokes the command from their ordinary terminal.
|
||||
root = Path(__file__).resolve().parent
|
||||
worker_env = dict(os.environ, HOME=str(root.parent.parent), USERPROFILE=str(root.parent.parent))
|
||||
matches = [path for path in root.glob(f"*/jobs/{args.job}") if path.is_dir() and not path.is_symlink()]
|
||||
if len(matches) != 1:
|
||||
parser.error("No unique saved job exists for this OS account. Keep the original update directory.")
|
||||
directory = matches[0]
|
||||
request_path = directory / "request.json"
|
||||
if request_path.is_symlink() or request_path.stat().st_size > 16 * 1024 * 1024:
|
||||
parser.error("Invalid saved update request")
|
||||
request = json.loads(request_path.read_bytes())
|
||||
worker = directory / "worker.pyz"
|
||||
if (worker.is_symlink() or worker.stat().st_size > 2 * 1024 * 1024
|
||||
or hashlib.sha256(worker.read_bytes()).hexdigest() != request["worker_sha256"]):
|
||||
parser.error("The saved worker changed. Preserve the backup; do not run another installation over it.")
|
||||
python = request["baseline"]["base_python"]
|
||||
if not Path(python).is_absolute() or not Path(python).is_file():
|
||||
parser.error("The original base Python is missing. Restore it before repairing this environment.")
|
||||
command = [python, "-I", "-S", str(worker)]
|
||||
# The frozen worker validates the full request, directory and plan binding.
|
||||
result = subprocess.run([*command, "--status", str(directory)], env=worker_env,
|
||||
check=True, capture_output=True, text=True)
|
||||
status = json.loads(result.stdout)
|
||||
print(f"Update {args.job}: {status['phase']}")
|
||||
print(f"Version: {request['baseline']['app_version']} -> {request['version']}")
|
||||
print(f"Environment: {request['baseline']['environment']}")
|
||||
print(f"Saved files and backup: {directory}")
|
||||
if not args.repair:
|
||||
print("Inspection only. Add --repair to review and resume this exact job.")
|
||||
return
|
||||
print("Repair reuses verified saved files and the original backup. It does not download a new release or roll back data.")
|
||||
if not args.yes and input("Resume this exact update? [y/N] ").strip().lower() not in {"y", "yes"}:
|
||||
print("No changes made.")
|
||||
return
|
||||
raise SystemExit(subprocess.call([*command, "--recover", str(directory)], env=worker_env))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Post-install handoff to reviewed, explicitly managed background gateways.
|
||||
|
||||
Entered through the frozen worker while holding a shared installation lease. The
|
||||
coordinator grants scoped data initialization, verifies all parked runtimes, then
|
||||
durably authorizes those exact run identities to accept work. It never reinstalls
|
||||
packages, kills another owner, or invents launch options from resolved paths.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import asdict, dataclass, replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import nanobot
|
||||
from nanobot.data_access import (
|
||||
DataStartupGrant,
|
||||
data_access,
|
||||
finish_data_handoff,
|
||||
)
|
||||
from nanobot.gateway.runtime import GatewayHealthIdentity, GatewayRuntime
|
||||
from nanobot.installation_lock import pending_update_path
|
||||
from nanobot.update_plan import UpdatePlan
|
||||
from nanobot.update_profiles import (
|
||||
ProfileReceipt,
|
||||
inspect_profiles,
|
||||
validate_restart_identity,
|
||||
verify_restarted_profile,
|
||||
)
|
||||
from nanobot.update_worker import JobStatus, Phase, WorkerSpec, read_record, write_record
|
||||
|
||||
_TOKEN_ENV = "NANOBOT_UPDATE_STARTUP_TOKEN"
|
||||
_HANDOFF_PHASES = {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED, Phase.SUCCEEDED, Phase.RESTORED}
|
||||
|
||||
|
||||
def _read_plan(directory: Path) -> tuple[WorkerSpec, UpdatePlan]:
|
||||
spec = WorkerSpec.read(directory)
|
||||
if (directory / "restoration.json").exists():
|
||||
restoration = read_record(directory / "restoration.json")
|
||||
if restoration != {"plan_id": spec.plan_id, "state": "restarting"}:
|
||||
raise ValueError("The original program restoration has not completed")
|
||||
spec = replace(spec, version=spec.baseline.app_version)
|
||||
plan = UpdatePlan.model_validate_json((directory / "plan.json").read_bytes())
|
||||
if (Path(sys.prefix).resolve() != Path(spec.baseline.environment)
|
||||
or nanobot.__version__ != spec.version or plan.id != spec.plan_id
|
||||
or tuple(plan.restart_profiles) != spec.restart_profiles or not spec.restart_profiles):
|
||||
raise ValueError("Runtime handoff does not match the approved installation and target")
|
||||
return spec, plan
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GatewayStartup:
|
||||
directory: Path
|
||||
previous: ProfileReceipt
|
||||
grant: DataStartupGrant
|
||||
|
||||
def validate_installation(self) -> None:
|
||||
spec, plan = _read_plan(self.directory)
|
||||
pending = read_record(pending_update_path())
|
||||
selected = {item.receipt.id: item.receipt for item in plan.profiles}
|
||||
if (pending.get("job_id") != self.grant.job_id or pending.get("version") != spec.version
|
||||
or spec.plan_id != self.grant.job_id or self.grant.participant != self.previous.id
|
||||
or self.previous.id not in spec.restart_profiles
|
||||
or selected.get(self.previous.id) != self.previous
|
||||
or JobStatus.read(self.directory).phase not in {Phase.RESTARTING, Phase.ACTIVATING}):
|
||||
raise ValueError("This gateway has no current protected-startup handoff")
|
||||
|
||||
def validate_profile(self, current: ProfileReceipt) -> None:
|
||||
validate_restart_identity(self.previous, current, version=nanobot.__version__, job_id=self.grant.job_id)
|
||||
|
||||
async def wait_for_activation(self, identity: GatewayHealthIdentity) -> None:
|
||||
"""An approval for an earlier attempt/run cannot activate this process."""
|
||||
deadline = time.monotonic() + 240
|
||||
while time.monotonic() < deadline:
|
||||
status = JobStatus.read(self.directory)
|
||||
if status.phase not in {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.SUCCEEDED, Phase.RESTORED}:
|
||||
raise ValueError("Update handoff stopped before gateway activation")
|
||||
try:
|
||||
decision = read_record(self.directory / "activation.json")
|
||||
except FileNotFoundError:
|
||||
decision = {}
|
||||
if (status.phase in {Phase.ACTIVATING, Phase.FINALIZING, Phase.SUCCEEDED, Phase.RESTORED}
|
||||
and decision.get("plan_id") == self.grant.job_id
|
||||
and decision.get(self.previous.id) == asdict(identity)):
|
||||
return
|
||||
await asyncio.sleep(0.1)
|
||||
raise TimeoutError("Gateway activation was not verified in time")
|
||||
|
||||
|
||||
def run_gateway(directory: Path, participant: str) -> None:
|
||||
# Remove the bearer before configuration, channels, MCP or tools can inherit it.
|
||||
token = os.environ.pop(_TOKEN_ENV, "")
|
||||
spec, plan = _read_plan(directory)
|
||||
previous = next(item.receipt for item in plan.profiles if item.receipt.id == participant)
|
||||
startup = GatewayStartup(directory, previous, DataStartupGrant(spec.plan_id, participant, token))
|
||||
startup.validate_installation()
|
||||
launch = previous.launch
|
||||
if launch is None:
|
||||
raise ValueError("Original gateway launch selectors are unavailable")
|
||||
|
||||
from nanobot.cli.entry import configure_windows_console
|
||||
from nanobot.cli.gateway_runtime import _run_gateway
|
||||
from nanobot.cli.process_identity import set_cli_process_identity
|
||||
from nanobot.cli.runtime_config import _load_runtime_config
|
||||
from nanobot.config.home import set_home_path
|
||||
from nanobot.config.loader import get_config_path
|
||||
from nanobot.gateway.runtime import GatewayInstance
|
||||
from nanobot.utils.log_config import configure_console_logging
|
||||
from nanobot.utils.rotating_output import configure_background_output_from_env
|
||||
|
||||
configure_background_output_from_env()
|
||||
set_cli_process_identity(["gateway"])
|
||||
configure_windows_console()
|
||||
configure_console_logging(sys.stderr, level="DEBUG" if launch.verbose else "INFO")
|
||||
if Path.cwd().resolve() != Path(launch.working_directory):
|
||||
raise ValueError("Gateway restart used a different working directory")
|
||||
set_home_path(Path(launch.home) if launch.home else None)
|
||||
config = _load_runtime_config(launch.config_path, launch.workspace)
|
||||
instance = GatewayInstance.resolve(config_path=get_config_path(), workspace=launch.workspace)
|
||||
_run_gateway(config, port=previous.port, verbose=launch.verbose, gateway_instance=instance,
|
||||
update_startup=startup)
|
||||
|
||||
|
||||
def _start_gateway(directory: Path, previous: ProfileReceipt, grant: DataStartupGrant) -> None:
|
||||
launch = previous.launch
|
||||
if launch is None:
|
||||
raise ValueError("Original gateway launch selectors are unavailable")
|
||||
|
||||
def spawn(_command: list[str], **kwargs: Any) -> subprocess.Popen[bytes] | subprocess.Popen[str]:
|
||||
# Preserve the existing runtime's detached-process and rotating-log setup.
|
||||
kwargs["env"] = {**kwargs["env"], _TOKEN_ENV: grant.token}
|
||||
return subprocess.Popen([previous.python, "-I", "-S", str(directory / "worker.pyz"),
|
||||
"--gateway", str(directory), previous.id],
|
||||
cwd=launch.working_directory, text=False, **kwargs)
|
||||
|
||||
runtime = GatewayRuntime(paths=previous.runtime_paths,
|
||||
python_executable=previous.python, popen=spawn)
|
||||
result = runtime.start_background(launch.options(port=previous.port))
|
||||
if not result.ok:
|
||||
raise ValueError("The reviewed gateway could not start; inspect its existing runtime log")
|
||||
|
||||
|
||||
def _wait_verified(profiles: list[ProfileReceipt], spec: WorkerSpec, *,
|
||||
maintenance: bool | None, deadline: float) -> list[ProfileReceipt]:
|
||||
while True:
|
||||
try:
|
||||
return [verify_restarted_profile(profile, version=spec.version, job_id=spec.plan_id,
|
||||
maintenance=maintenance) for profile in profiles]
|
||||
except ValueError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError("The reviewed gateways did not confirm target-version readiness in time") from None
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
def run_restarts(directory: Path) -> None:
|
||||
"""Resume only this job's startup/activation; never rerun its pip transaction."""
|
||||
spec, plan = _read_plan(directory)
|
||||
status = JobStatus.read(directory)
|
||||
if status.phase not in _HANDOFF_PHASES:
|
||||
raise ValueError("Package verification has not handed off to gateway restart")
|
||||
profiles = [item.receipt for item in plan.profiles if item.receipt.id in spec.restart_profiles]
|
||||
deadline = time.monotonic() + 120
|
||||
pending = pending_update_path()
|
||||
restored = (directory / "restoration.json").exists()
|
||||
final_phase = Phase.RESTORED if restored else Phase.SUCCEEDED
|
||||
final_message = ("The original service is running; the update was not installed and user data was not restored"
|
||||
if restored else "The reviewed gateways are running the verified target version")
|
||||
if status.phase in {Phase.SUCCEEDED, Phase.RESTORED}:
|
||||
# Completed jobs are history, not authority to relaunch stopped gateways.
|
||||
return
|
||||
if pending.exists() and read_record(pending).get("job_id") != spec.plan_id:
|
||||
raise ValueError("The installation is reserved by another update")
|
||||
if status.phase == Phase.FINALIZING:
|
||||
# Verification was durably committed before either fence was cleared.
|
||||
# Do not rerun or reactivate applications to recover only this cleanup.
|
||||
finish_data_handoff((item.path for item in spec.backup_sources), job_id=spec.plan_id)
|
||||
pending.unlink(missing_ok=True)
|
||||
status.advance(directory, final_phase, final_message)
|
||||
return
|
||||
if not pending.exists():
|
||||
raise ValueError("The runtime handoff no longer owns an installation fence")
|
||||
|
||||
with data_access((item.path for item in spec.backup_sources), job_id=spec.plan_id) as data:
|
||||
observed = {item.receipt.id: item for item in inspect_profiles(spec.baseline.environment)}
|
||||
if set(observed) != {item.receipt.id for item in plan.profiles}:
|
||||
raise ValueError("Gateway inventory changed during the update")
|
||||
# Do not start or ignore a newly changed, unreviewed runtime.
|
||||
for item in plan.profiles:
|
||||
current = observed[item.receipt.id]
|
||||
previous = item.receipt
|
||||
unchanged = (current.receipt.model_dump(exclude={"active"})
|
||||
== previous.model_dump(exclude={"active"}))
|
||||
if previous.id not in spec.restart_profiles:
|
||||
if not unchanged or current.state != "stopped":
|
||||
raise ValueError("An unselected gateway changed during the update")
|
||||
elif current.state == "unconfirmed":
|
||||
raise ValueError("The restart participant's process owner is unconfirmed")
|
||||
elif not unchanged:
|
||||
# A failed, parked candidate may have recorded its run before
|
||||
# exiting. Its stopped receipt is history, not launch authority.
|
||||
version = plan.target.version if restored and current.state == "stopped" else spec.version
|
||||
validate_restart_identity(previous, current.receipt, version=version, job_id=spec.plan_id)
|
||||
elif current.state != "stopped":
|
||||
raise ValueError("An original gateway is still running")
|
||||
|
||||
status.advance(directory, Phase.RESTARTING, "Starting the reviewed gateways with task intake closed", mutation_started=True)
|
||||
for previous in profiles:
|
||||
if observed[previous.id].state == "stopped":
|
||||
grant = data.grant_profile_startup(
|
||||
previous.id, home=Path(previous.home), data_dir=Path(previous.data_dir),
|
||||
config=Path(previous.config), workspace=Path(previous.workspace),
|
||||
)
|
||||
_start_gateway(directory, previous, grant)
|
||||
|
||||
# A resumed activation can include already active runs; their durable
|
||||
# job identity still has to match. A fresh handoff must prove intake shut.
|
||||
resuming_activation = (directory / "activation.json").exists()
|
||||
parked = _wait_verified(profiles, spec, maintenance=None if resuming_activation else True, deadline=deadline)
|
||||
status.advance(directory, Phase.ACTIVATING, "Verified runtime identities; enabling the reviewed gateways", mutation_started=True)
|
||||
write_record(directory / "activation.json", {
|
||||
"plan_id": spec.plan_id, **{item.id: asdict(item.health_identity) for item in parked},
|
||||
})
|
||||
_wait_verified(profiles, spec, maintenance=False, deadline=deadline)
|
||||
status.advance(directory, Phase.FINALIZING, "Verified running gateways; completing maintenance cleanup", mutation_started=True)
|
||||
# Clearing data first retains the installation fence if either operation
|
||||
# fails. Active participants continue holding their own shared leases.
|
||||
data.release_reservation()
|
||||
pending.unlink()
|
||||
status.advance(directory, final_phase, final_message)
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Own exact-plan staging and execution consent independently of a client.
|
||||
|
||||
Staging does not grant installation consent. Each explicit execution confirmation
|
||||
can launch its detached owner once; repeating an ID reads the durable record.
|
||||
No phase automatically retries work. Clients do not own installer lifetimes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import ExitStack
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, field_validator
|
||||
|
||||
from nanobot.installation_lock import (
|
||||
file_access,
|
||||
installation_access,
|
||||
installation_id,
|
||||
installation_state_dir,
|
||||
pending_update_path,
|
||||
)
|
||||
from nanobot.release_feed import ReleaseFeed
|
||||
from nanobot.releases import ReleaseRecord
|
||||
from nanobot.update_channel import (
|
||||
UpdateChannel,
|
||||
UpdateChannelRequest,
|
||||
read_update_channel,
|
||||
write_update_channel,
|
||||
)
|
||||
from nanobot.update_jobs import (
|
||||
UpdateJobNotFoundError,
|
||||
UpdateJobView,
|
||||
prepare_job,
|
||||
read_update_job,
|
||||
retry_handoff,
|
||||
settle_interrupted_preparation,
|
||||
start_handoff,
|
||||
validate_preparation,
|
||||
)
|
||||
from nanobot.update_plan import UpdatePlan, UpdatePlans
|
||||
from nanobot.update_worker import JobStatus, Phase, read_record
|
||||
from nanobot.utils.atomic_file import atomic_write_lines
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
|
||||
|
||||
class UpdateJobRequest(ReleaseRecord):
|
||||
id: str
|
||||
|
||||
@field_validator("id")
|
||||
@classmethod
|
||||
def canonical_id(cls, value: str) -> str:
|
||||
return UpdatePlan.canonical_id(value)
|
||||
|
||||
|
||||
class UpdateExecutionRequest(UpdateJobRequest):
|
||||
confirm_restart: bool
|
||||
|
||||
@field_validator("confirm_restart")
|
||||
@classmethod
|
||||
def explicit_restart(cls, value: bool) -> bool:
|
||||
if not value:
|
||||
raise ValueError("Confirm the reviewed shutdown and restart before updating")
|
||||
return value
|
||||
|
||||
|
||||
class UpdateRetryRequest(UpdateExecutionRequest):
|
||||
previous_confirmation_id: str = Field(pattern=r"^[0-9a-f]{32}$")
|
||||
|
||||
|
||||
class UpdateJobService:
|
||||
def __init__(self) -> None:
|
||||
self._task: asyncio.Task[None] | None = None
|
||||
self._closing = False
|
||||
self._reapers: set[asyncio.Task[None]] = set()
|
||||
|
||||
def has_pending_work(self) -> bool:
|
||||
return self._task is not None and not self._task.done()
|
||||
|
||||
def change_channel(self, request: UpdateChannelRequest) -> UpdateChannel:
|
||||
"""Change subscription only; retire inactive staged jobs, never rollback."""
|
||||
from nanobot.update_stop import settle_uncommitted_handoff
|
||||
|
||||
root = installation_state_dir()
|
||||
with (file_access(root / "channel.lock", exclusive=True),
|
||||
file_access(root / "preparation-controller.lock", exclusive=True),
|
||||
installation_access(allow_incomplete=True)):
|
||||
current = read_update_channel()
|
||||
if request.revision != current.revision:
|
||||
raise ValueError("Update channel changed in another client; check again")
|
||||
if request.channel == current.channel:
|
||||
return current
|
||||
if self._closing or pending_update_path().exists():
|
||||
raise ValueError("Recover the current update before changing channels")
|
||||
staged: list[Path] = []
|
||||
for path in (root / "jobs").glob("*/status.json"):
|
||||
state = JobStatus.read(path.parent)
|
||||
if state.phase in {Phase.SUCCEEDED, Phase.RESTORED, Phase.CANCELLED, Phase.PREPARATION_FAILED}:
|
||||
continue
|
||||
if state.phase not in {Phase.READY, Phase.HANDOFF_FAILED} or state.mutation_started:
|
||||
raise ValueError("Finish or recover the current update before changing channels")
|
||||
staged.append(path.parent)
|
||||
# Existing settlement checks real worker leases, shutdown commit and
|
||||
# install admission. Changing preference cannot discard pending work.
|
||||
for directory in staged:
|
||||
settle_uncommitted_handoff(directory)
|
||||
selected = UpdateChannel(channel=request.channel, revision=current.revision + 1)
|
||||
write_update_channel(selected)
|
||||
return selected
|
||||
|
||||
def prepare(self, plan_id: str) -> UpdateJobView:
|
||||
"""Acknowledge one durable staging request; never install or restart."""
|
||||
if self._closing:
|
||||
raise RuntimeError("The update service is shutting down")
|
||||
loop = asyncio.get_running_loop()
|
||||
root = installation_state_dir()
|
||||
plan = UpdatePlans(root / "plans").load(plan_id)
|
||||
if plan.installation.installation_id != installation_id():
|
||||
raise ValueError("The plan belongs to another installation")
|
||||
try:
|
||||
return read_update_job(plan_id)
|
||||
except UpdateJobNotFoundError:
|
||||
pass
|
||||
# Acquire synchronously before acknowledging or starting a task. Another
|
||||
# profile may return this job's journal, but cannot start competing work.
|
||||
leases = ExitStack()
|
||||
try:
|
||||
leases.enter_context(file_access(root / "channel.lock", exclusive=False))
|
||||
leases.enter_context(file_access(root / "preparation-controller.lock", exclusive=True))
|
||||
leases.enter_context(installation_access())
|
||||
validate_preparation(plan)
|
||||
directory = root / "jobs" / plan_id
|
||||
if directory.is_symlink():
|
||||
raise ValueError("Invalid update job directory")
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
plan_path = directory / "plan.json"
|
||||
if plan_path.exists():
|
||||
if UpdatePlan.model_validate(read_record(plan_path)) != plan:
|
||||
raise ValueError("The job belongs to another plan")
|
||||
else:
|
||||
atomic_write_lines(plan_path, [plan.model_dump_json()])
|
||||
plan_path.chmod(0o600)
|
||||
# Recheck after taking the lease: a second process might have
|
||||
# finished between the first lookup and acquisition.
|
||||
if (directory / "status.json").exists():
|
||||
return read_update_job(plan_id)
|
||||
JobStatus(plan_id, Phase.PREPARATION_REQUESTED, 0, False,
|
||||
"Preparation requested; no installation approved", int(time.time())).save(directory)
|
||||
result = read_update_job(plan_id)
|
||||
owned = leases.pop_all()
|
||||
self._task = loop.create_task(self._prepare(plan, owned), name="nanobot-update-prepare")
|
||||
# Also release if loop shutdown cancels before the coroutine enters.
|
||||
self._task.add_done_callback(lambda _: owned.close())
|
||||
return result
|
||||
finally:
|
||||
leases.close()
|
||||
|
||||
async def _prepare(self, plan: UpdatePlan, leases: ExitStack) -> None:
|
||||
root = installation_state_dir()
|
||||
directory = root / "jobs" / plan.id
|
||||
with leases:
|
||||
try:
|
||||
async with ReleaseFeed(root / "releases") as feed:
|
||||
# Revalidate the reviewed target, never resolve `latest`.
|
||||
# prepare_job probes the actual environment under native
|
||||
# child-owned leases before downloads or dependency work.
|
||||
await feed.revalidate(plan.target)
|
||||
await prepare_job(plan, feed)
|
||||
except (Exception, asyncio.CancelledError) as exc:
|
||||
# Raw errors can include private index URLs. Cancellation is
|
||||
# recorded only after prepare_job has settled native work.
|
||||
# A cancellation while closing the HTTP client cannot undo the
|
||||
# durable staging commit which prepare_job already completed.
|
||||
if not (directory / "request.json").exists():
|
||||
JobStatus(plan.id, Phase.PREPARATION_FAILED, 0, False,
|
||||
f"Preparation stopped ({type(exc).__name__}); no installation was started",
|
||||
int(time.time())).save(directory)
|
||||
|
||||
def settle(self, plan_id: str) -> UpdateJobView:
|
||||
"""Settle inactive work before a new review; never retry or install."""
|
||||
job = read_update_job(plan_id)
|
||||
root = installation_state_dir()
|
||||
directory = root / "jobs" / plan_id
|
||||
with file_access(root / "preparation-controller.lock", exclusive=True):
|
||||
if job.recorded_phase == Phase.PREPARATION_REQUESTED:
|
||||
# No native child can start before PREPARING is persisted.
|
||||
with file_access(root / "prepare.lock", exclusive=True):
|
||||
state = JobStatus.read(directory)
|
||||
if state.phase != Phase.PREPARATION_REQUESTED or state.mutation_started or (directory / "request.json").exists():
|
||||
raise ValueError("The preparation state changed")
|
||||
JobStatus(plan_id, Phase.PREPARATION_FAILED, 0, False,
|
||||
"Interrupted request settled; no installation was started", int(time.time())).save(directory)
|
||||
elif job.recorded_phase == Phase.PREPARING:
|
||||
settle_interrupted_preparation(directory)
|
||||
elif job.recorded_phase in {Phase.READY, Phase.HANDOFF_FAILED, Phase.CANCELLED}:
|
||||
from nanobot.update_stop import settle_uncommitted_handoff
|
||||
|
||||
settle_uncommitted_handoff(directory)
|
||||
else:
|
||||
raise ValueError("Only an interrupted preparation or uncommitted handoff can be settled")
|
||||
return read_update_job(plan_id)
|
||||
|
||||
async def execute(self, plan_id: str, *, previous_confirmation_id: str | None = None) -> UpdateJobView:
|
||||
"""Confirm once, or explicitly retry the supplied previous confirmation.
|
||||
|
||||
Repeating either request reads the durable result; it cannot launch twice.
|
||||
|
||||
This handoff does not count itself as pending runtime work: its detached
|
||||
owner must be able to stop the requesting gateway. All unrelated work
|
||||
still participates in the cooperative idle-admission check.
|
||||
"""
|
||||
if self._closing:
|
||||
raise RuntimeError("The update service is shutting down")
|
||||
job = read_update_job(plan_id)
|
||||
if previous_confirmation_id is not None:
|
||||
if job.execution_confirmation_id is None:
|
||||
raise ValueError("No execution confirmation is available to retry")
|
||||
if job.execution_confirmation_id != previous_confirmation_id:
|
||||
return job
|
||||
elif job.execution_confirmation_id is not None:
|
||||
return job
|
||||
directory = installation_state_dir() / "jobs" / plan_id
|
||||
plan = UpdatePlan.model_validate(read_record(directory / "plan.json"))
|
||||
if not plan.can_restart_inline:
|
||||
raise ValueError("Inline updates require reviewed shutdown and restart of this gateway and every running peer")
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
def launch() -> None:
|
||||
process = (start_handoff(directory, once=True) if previous_confirmation_id is None
|
||||
else retry_handoff(directory, previous_confirmation_id))
|
||||
if process is not None:
|
||||
# Transfer the child even if cancellation means the HTTP caller
|
||||
# will never receive the thread's return value.
|
||||
loop.call_soon_threadsafe(self._track_worker, process)
|
||||
|
||||
try:
|
||||
await shield_and_drain(asyncio.to_thread(launch))
|
||||
except (OSError, RuntimeError):
|
||||
# The launcher may have failed after persisting consent, or another
|
||||
# tab may already own the worker. Return durable facts, not a retry.
|
||||
latest = read_update_job(plan_id)
|
||||
if latest.execution_confirmation_id in {None, previous_confirmation_id}:
|
||||
raise
|
||||
return read_update_job(plan_id)
|
||||
|
||||
def _track_worker(self, process: subprocess.Popen[bytes]) -> None:
|
||||
reaper = asyncio.create_task(self._reap(process), name="nanobot-update-reap")
|
||||
self._reapers.add(reaper)
|
||||
reaper.add_done_callback(self._reapers.discard)
|
||||
|
||||
@staticmethod
|
||||
async def _reap(process: subprocess.Popen[bytes]) -> None:
|
||||
# Do not put process.wait in the default thread pool: gateway shutdown
|
||||
# would join that thread while this child is waiting for the gateway.
|
||||
while process.poll() is None:
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
async def close(self) -> None:
|
||||
self._closing = True
|
||||
if self._task is not None:
|
||||
# Browser requests never own this task. Shutdown must also wait for
|
||||
# the real preparation, not release ownership on cancellation.
|
||||
while not self._task.done():
|
||||
try:
|
||||
await asyncio.shield(self._task)
|
||||
except asyncio.CancelledError:
|
||||
continue
|
||||
self._task.result()
|
||||
for reaper in self._reapers:
|
||||
reaper.cancel()
|
||||
await asyncio.gather(*self._reapers, return_exceptions=True)
|
||||
@@ -0,0 +1,301 @@
|
||||
"""Cooperative pre-install shutdown of explicitly reviewed gateway runs.
|
||||
|
||||
The private local mailbox carries identities, never commands or arbitrary paths.
|
||||
Preparation is reversible: every participant must hold its idle admission gate
|
||||
before the coordinator commits normal shutdown. A committed stop is not an
|
||||
installation approval, and the installer must still acquire exclusive leases.
|
||||
Only a detached update owner runs this protocol, never a request awaiting its own exit.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from contextlib import AbstractContextManager, ExitStack
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from uuid import uuid4
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from nanobot.gateway.runtime import GatewayRuntime
|
||||
from nanobot.installation_lock import file_access, installation_access, installation_state_dir
|
||||
from nanobot.runtime_admission import RuntimeBusyError, RuntimeMaintenanceError
|
||||
from nanobot.update_plan import UpdatePlan
|
||||
from nanobot.update_profiles import ProfileReceipt, require_stopped_profiles, validate_profiles
|
||||
from nanobot.update_worker import JobStatus, Phase, WorkerSpec, read_record, write_record
|
||||
from nanobot.utils.atomic_file import io_path, read_atomic_bytes
|
||||
|
||||
_POLL_SECONDS = 0.1
|
||||
|
||||
|
||||
class _Request(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
|
||||
|
||||
plan_id: str = Field(pattern=r"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$")
|
||||
attempt: str = Field(pattern=r"^[0-9a-f]{32}$")
|
||||
phase: Literal["prepare", "commit", "abort", "stopped"]
|
||||
# Monotonic timestamps coordinate processes on this host, not other hosts.
|
||||
deadline: float = Field(gt=0, allow_inf_nan=False)
|
||||
|
||||
|
||||
class _Reply(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
|
||||
|
||||
attempt: str = Field(pattern=r"^[0-9a-f]{32}$")
|
||||
run_id: str = Field(pattern=r"^[0-9a-f]{32}$")
|
||||
state: Literal["ready", "busy", "released", "stopping", "refused"]
|
||||
|
||||
|
||||
def _request_path(environment: str) -> Path:
|
||||
return installation_state_dir(environment) / "stop.json"
|
||||
|
||||
|
||||
def _read_request(environment: str) -> _Request | None:
|
||||
try:
|
||||
return _Request.model_validate(read_record(_request_path(environment), max_bytes=2048))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
|
||||
def _job(environment: str, identifier: str) -> tuple[Path, UpdatePlan]:
|
||||
directory = installation_state_dir(environment) / "jobs" / identifier
|
||||
spec = WorkerSpec.read(directory)
|
||||
plan = UpdatePlan.model_validate_json(read_atomic_bytes(directory / "plan.json"))
|
||||
status = JobStatus.read(directory)
|
||||
if (spec.baseline.environment != environment or plan.installation.environment != environment
|
||||
or spec.plan_id != plan.id or tuple(plan.restart_profiles) != spec.restart_profiles
|
||||
or spec.version != plan.target.version
|
||||
or status.phase not in {Phase.READY, Phase.CHECKING, Phase.STOPPING} or status.mutation_started):
|
||||
raise ValueError("Gateway shutdown requires an unchanged, prepared update job")
|
||||
return directory, plan
|
||||
|
||||
|
||||
def _reply(directory: Path, request: _Request, profile: ProfileReceipt,
|
||||
state: Literal["ready", "busy", "released", "stopping", "refused"]) -> None:
|
||||
path = directory / "stop-replies" / f"{profile.id}.json"
|
||||
io_path(path.parent).mkdir(exist_ok=True, mode=0o700)
|
||||
write_record(path, _Reply(attempt=request.attempt, run_id=profile.run_id, state=state).model_dump())
|
||||
|
||||
|
||||
def _coordinator_present(environment: str) -> bool:
|
||||
try:
|
||||
with file_access(installation_state_dir(environment) / "stop.lock", exclusive=True):
|
||||
return False
|
||||
except BlockingIOError:
|
||||
return True
|
||||
|
||||
|
||||
async def watch_gateway_stop(
|
||||
profile: ProfileReceipt,
|
||||
maintenance: Callable[[], AbstractContextManager[None]],
|
||||
shutdown_event: asyncio.Event,
|
||||
shutdown_gate: ExitStack,
|
||||
) -> None:
|
||||
"""Serve this run's mailbox on the same event loop as task admission.
|
||||
|
||||
The runtime must retain shutdown_gate until its consumers and cleanup finish.
|
||||
Cancellation before commit restores intake; after commit the outer runtime
|
||||
owns the gate, so cancelling this watcher cannot reopen task intake.
|
||||
"""
|
||||
seen: str | None = None
|
||||
while not shutdown_event.is_set():
|
||||
try:
|
||||
request = _read_request(profile.environment)
|
||||
if request is not None and request.attempt != seen:
|
||||
seen = request.attempt
|
||||
if (request.phase == "prepare" and time.monotonic() < request.deadline
|
||||
and _coordinator_present(profile.environment)):
|
||||
await _prepare_gateway_stop(profile, request, maintenance, shutdown_event, shutdown_gate)
|
||||
except (OSError, ValueError):
|
||||
# A malformed/stale local record must not crash an otherwise healthy
|
||||
# gateway. The coordinator times out; it never treats silence as ready.
|
||||
pass
|
||||
await asyncio.sleep(_POLL_SECONDS)
|
||||
|
||||
|
||||
async def _prepare_gateway_stop(
|
||||
profile: ProfileReceipt,
|
||||
request: _Request,
|
||||
maintenance: Callable[[], AbstractContextManager[None]],
|
||||
shutdown_event: asyncio.Event,
|
||||
shutdown_gate: ExitStack,
|
||||
) -> None:
|
||||
directory, plan = _job(profile.environment, request.plan_id)
|
||||
selected = next((item for item in plan.profiles if item.receipt.id == profile.id), None)
|
||||
if profile.id not in plan.stop_profiles:
|
||||
return
|
||||
if selected is None or selected.receipt != profile or selected.state != "running":
|
||||
_reply(directory, request, profile, "refused")
|
||||
return
|
||||
plan.validate_for(plan.installation)
|
||||
committed = False
|
||||
with ExitStack() as gate:
|
||||
try:
|
||||
gate.enter_context(maintenance())
|
||||
except (RuntimeBusyError, RuntimeMaintenanceError):
|
||||
_reply(directory, request, profile, "busy")
|
||||
return
|
||||
try:
|
||||
_reply(directory, request, profile, "ready")
|
||||
while not shutdown_event.is_set():
|
||||
current = _read_request(profile.environment)
|
||||
if (current is None or current.plan_id != request.plan_id
|
||||
or current.attempt != request.attempt or current.phase not in {"prepare", "commit"}):
|
||||
return
|
||||
if current.phase == "commit":
|
||||
# Commit is durable and irrevocable even if its coordinator
|
||||
# exits. Only a prepared run can accept it; startup replay
|
||||
# or a new run identity cannot enter this branch.
|
||||
shutdown_gate.enter_context(gate.pop_all())
|
||||
committed = True
|
||||
shutdown_event.set()
|
||||
_reply(directory, request, profile, "stopping")
|
||||
return
|
||||
if not _coordinator_present(profile.environment):
|
||||
# The owner may have committed just before exiting. Read
|
||||
# once more after observing its released lease, rather than
|
||||
# undoing that durable decision from an earlier prepare read.
|
||||
latest = _read_request(profile.environment)
|
||||
if (latest is not None and latest.attempt == request.attempt
|
||||
and latest.plan_id == request.plan_id and latest.phase == "commit"):
|
||||
continue
|
||||
return
|
||||
# While its lease remains held, the coordinator owns the
|
||||
# deadline decision. Independently expiring a ready participant
|
||||
# could reopen intake between the ready check and commit.
|
||||
await asyncio.sleep(_POLL_SECONDS)
|
||||
finally:
|
||||
if not committed:
|
||||
# Release before publishing the acknowledgement. A failed write
|
||||
# cannot keep task intake closed after refusal/cancellation.
|
||||
gate.close()
|
||||
_reply(directory, request, profile, "released")
|
||||
|
||||
|
||||
async def stop_reviewed_gateways(directory: Path, *, timeout: float = 30) -> None:
|
||||
"""Stop only the plan's selected runs, or abort before any stop is committed.
|
||||
|
||||
Call from the detached update owner, not a gateway request awaiting its own
|
||||
shutdown. Cancellation before commit aborts all holds. After commit, callers
|
||||
must report/recover the saved handoff rather than promise that nobody stopped.
|
||||
The caller revalidates release eligibility and installation identity before
|
||||
requesting shutdown. This operation neither approves nor launches installation.
|
||||
"""
|
||||
if not 0 < timeout <= 120:
|
||||
raise ValueError("Shutdown timeout must be between zero and 120 seconds")
|
||||
spec = WorkerSpec.read(directory)
|
||||
environment = spec.baseline.environment
|
||||
root = installation_state_dir(environment)
|
||||
# The detached parent owns worker.lock. This coordinator owns the stop
|
||||
# mailbox and a runtime lease instead, also protecting standalone callers
|
||||
# and an orphan child when its parent exits before the handoff completes.
|
||||
with (installation_access(environment=environment), file_access(root / "stop.lock", exclusive=True),
|
||||
file_access(root / "prepare.lock", exclusive=True), file_access(root / "prepare-native.lock", exclusive=True)):
|
||||
_, plan = _job(environment, spec.plan_id)
|
||||
participants = [item.receipt for item in plan.profiles if item.receipt.id in plan.stop_profiles]
|
||||
if any(item.pid == os.getpid() for item in participants):
|
||||
raise ValueError("The shutdown coordinator must run outside the selected gateways")
|
||||
previous = _read_request(environment)
|
||||
resuming = previous is not None and previous.plan_id == plan.id and previous.phase in {"commit", "stopped"}
|
||||
if previous is not None and previous.phase == "commit" and not resuming:
|
||||
raise ValueError("A committed gateway shutdown needs to be resolved before another handoff")
|
||||
if not resuming:
|
||||
plan.validate_for(plan.installation)
|
||||
# Refuse missing/changed staged inputs before disturbing a running
|
||||
# gateway. Installation will independently recheck them after exit.
|
||||
await asyncio.to_thread(spec.verify_inputs, directory)
|
||||
plan.validate_for(plan.installation)
|
||||
validate_profiles(plan.profiles, environment)
|
||||
if any(item.state == "unconfirmed" or
|
||||
(item.state == "running" and item.receipt.id not in plan.stop_profiles)
|
||||
for item in plan.profiles):
|
||||
raise ValueError("Every running gateway must have a confirmed shutdown selection")
|
||||
request = _Request(plan_id=plan.id, attempt=uuid4().hex, phase="prepare",
|
||||
deadline=time.monotonic() + timeout)
|
||||
write_record(_request_path(environment), request.model_dump())
|
||||
try:
|
||||
while True:
|
||||
ready: set[str] = set()
|
||||
for profile in participants:
|
||||
path = directory / "stop-replies" / f"{profile.id}.json"
|
||||
try:
|
||||
reply = _Reply.model_validate(read_record(path, max_bytes=2048))
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
if reply.attempt != request.attempt:
|
||||
continue
|
||||
if reply.run_id != profile.run_id:
|
||||
raise ValueError("A selected gateway run changed; no stop was committed")
|
||||
if reply.state != "ready":
|
||||
raise ValueError("A selected gateway is busy or refused shutdown; no stop was committed")
|
||||
ready.add(profile.id)
|
||||
if len(ready) == len(participants):
|
||||
plan.validate_for(plan.installation)
|
||||
validate_profiles(plan.profiles, environment)
|
||||
if time.monotonic() >= request.deadline:
|
||||
raise TimeoutError("Gateway shutdown preparation expired")
|
||||
write_record(_request_path(environment), request.model_copy(update={"phase": "commit"}).model_dump())
|
||||
break
|
||||
if time.monotonic() >= request.deadline:
|
||||
raise TimeoutError("Gateways did not prepare shutdown in time; no stop was committed")
|
||||
await asyncio.sleep(_POLL_SECONDS)
|
||||
finally:
|
||||
# Atomic replacement may have succeeded even if its directory
|
||||
# fsync failed. Never overwrite an observable commit with abort.
|
||||
decision = _read_request(environment)
|
||||
if decision is not None and decision.attempt == request.attempt and decision.phase == "prepare":
|
||||
write_record(_request_path(environment), request.model_copy(update={"phase": "abort"}).model_dump())
|
||||
|
||||
# A receipt becomes inactive before its outer process/lease finishes.
|
||||
# Require actual process exit too, and leave lock acquisition to the
|
||||
# installer: neither an acknowledgement nor inventory grants that lock.
|
||||
deadline = time.monotonic() + timeout
|
||||
reviewed_runs = [item.receipt for item in plan.profiles]
|
||||
while True:
|
||||
try:
|
||||
require_stopped_profiles(plan.profiles, environment)
|
||||
runtime = GatewayRuntime()
|
||||
if all(not runtime.process_is_running(item.pid) or (
|
||||
item.process_identity is not None
|
||||
and runtime.process_identity_match(item.process_identity, item.pid) == "mismatch"
|
||||
) for item in reviewed_runs):
|
||||
completed = _read_request(environment)
|
||||
if completed is not None and completed.plan_id == plan.id:
|
||||
write_record(_request_path(environment), completed.model_copy(update={"phase": "stopped"}).model_dump())
|
||||
return
|
||||
except ValueError:
|
||||
pass
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("Shutdown was committed but process exit is not confirmed; no package files were changed")
|
||||
await asyncio.sleep(_POLL_SECONDS)
|
||||
|
||||
|
||||
def settle_uncommitted_handoff(directory: Path) -> JobStatus:
|
||||
"""Retire a prepared/failed handoff without undoing a committed shutdown.
|
||||
|
||||
The requesting gateway can remain running. No worker, orphan preflight or
|
||||
stop coordinator may still own the old job. Keep its files and confirmation
|
||||
for diagnosis; CANCELLED prevents a delayed launcher from using that consent.
|
||||
"""
|
||||
spec = WorkerSpec.read(directory)
|
||||
root = installation_state_dir(spec.baseline.environment)
|
||||
with (file_access(root / "worker.lock", exclusive=True),
|
||||
file_access(root / "handoff-child.lock", exclusive=True),
|
||||
file_access(root / "stop.lock", exclusive=True),
|
||||
installation_access(environment=spec.baseline.environment)):
|
||||
status = JobStatus.read(directory)
|
||||
if status.mutation_started or status.phase not in {Phase.READY, Phase.HANDOFF_FAILED, Phase.CANCELLED}:
|
||||
raise ValueError("Only an unmodified, inactive handoff can be settled")
|
||||
request = _read_request(spec.baseline.environment)
|
||||
if request is not None and request.plan_id == spec.plan_id and request.phase in {"commit", "stopped"}:
|
||||
raise ValueError("Shutdown was committed; recover the saved update before starting another")
|
||||
if (directory / "approval.json").exists():
|
||||
raise ValueError("Installation was admitted; recover the saved update before starting another")
|
||||
if status.phase != Phase.CANCELLED:
|
||||
status = JobStatus(spec.plan_id, Phase.CANCELLED, status.attempt, False,
|
||||
"Previous handoff settled; review a new plan before updating", int(time.time()))
|
||||
status.save(directory)
|
||||
return status
|
||||
@@ -0,0 +1,354 @@
|
||||
"""Private uv tool preparation; cache copies never change the owner's saved policy.
|
||||
|
||||
Keep this module stdlib-only: its verification/copy operations also run from the
|
||||
frozen update worker after the installed application has stopped.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
import tomllib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
from nanobot.update_process import PreparationProcess
|
||||
|
||||
# Cache/receipt and exec-lease behavior must be exercised before expanding this
|
||||
# internal native route to another manager release. Unsupported versions use
|
||||
# the installation owner's workflow; they are never downgraded automatically.
|
||||
UV_TRANSACTION_VERSION = "0.11.16"
|
||||
_TRANSPORT_SETTINGS = {"UV_HTTP_TIMEOUT", "UV_HTTP_RETRIES", "UV_SYSTEM_CERTS", "UV_NATIVE_TLS"}
|
||||
|
||||
|
||||
def _receipt_only_policy() -> None:
|
||||
"""Refuse external resolver policy that this receipt-bound plan has not frozen."""
|
||||
locations = {"UV_TOOL_DIR", "UV_TOOL_BIN_DIR", "UV_CACHE_DIR", "UV_NO_CONFIG"}
|
||||
for key in os.environ:
|
||||
if (key.startswith("UV_") and key not in locations | _TRANSPORT_SETTINGS
|
||||
and not (key.startswith("UV_INDEX_") and key.endswith(("_USERNAME", "_PASSWORD")))):
|
||||
raise ValueError("External uv settings require the installation owner's update workflow")
|
||||
if os.environ.get("UV_NO_CONFIG", "").lower() in {"1", "true"}:
|
||||
return
|
||||
roots = [Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"), Path("/etc")]
|
||||
roots.extend(Path(value) for value in os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg").split(":") if value)
|
||||
if any((root / "uv/uv.toml").exists() for root in roots):
|
||||
raise ValueError("External uv configuration requires the installation owner's update workflow")
|
||||
|
||||
|
||||
def _record(value: object) -> dict[str, object]:
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Invalid uv preparation record")
|
||||
data = cast(dict[object, object], value)
|
||||
if not all(isinstance(key, str) for key in data):
|
||||
raise ValueError("Invalid uv preparation record")
|
||||
return cast(dict[str, object], data)
|
||||
|
||||
|
||||
def _text(value: object) -> str:
|
||||
if not isinstance(value, str) or not value or len(value) > 16_384:
|
||||
raise ValueError("Invalid uv preparation value")
|
||||
return value
|
||||
|
||||
|
||||
def _hash_file(path: Path) -> str:
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def _toml(value: object) -> str:
|
||||
"""Re-encode parsed receipt settings, leaving their semantics to uv itself."""
|
||||
if isinstance(value, (str, bool)) or type(value) is int:
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
if isinstance(value, list):
|
||||
return "[" + ", ".join(_toml(item) for item in cast(list[object], value)) + "]"
|
||||
if isinstance(value, dict):
|
||||
items = _record(cast(dict[object, object], value))
|
||||
return "{ " + ", ".join(f"{json.dumps(key)} = {_toml(item)}" for key, item in items.items()) + " }"
|
||||
raise ValueError("Unsupported uv receipt setting; use the installation owner")
|
||||
|
||||
|
||||
def _requirement(value: object) -> str:
|
||||
item = _record(value)
|
||||
if item.keys() - {"name", "extras", "specifier", "url", "marker"}:
|
||||
raise ValueError("This uv requirement needs its owner's update workflow")
|
||||
name = _text(item.get("name"))
|
||||
extras = item.get("extras", [])
|
||||
if not isinstance(extras, list):
|
||||
raise ValueError("Invalid uv requirement extras")
|
||||
extra_values = cast(list[object], extras)
|
||||
if (not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", name)
|
||||
or not all(isinstance(extra, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", extra)
|
||||
for extra in extra_values)):
|
||||
raise ValueError("Invalid uv requirement identity")
|
||||
suffix = "[" + ",".join(cast(list[str], extras)) + "]" if extras else ""
|
||||
url = item.get("url")
|
||||
if url is not None:
|
||||
# Source/editable installs can run build children; they are not a wheel
|
||||
# transaction and must not be quietly converted into one.
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
parsed = urlsplit(_text(url))
|
||||
if parsed.scheme not in {"https", "http", "file"} or not parsed.path.endswith(".whl"):
|
||||
raise ValueError("Source requirements need the uv owner's update workflow")
|
||||
suffix += " @ " + _text(url)
|
||||
elif item.get("specifier"):
|
||||
suffix += _text(item["specifier"])
|
||||
if item.get("marker"):
|
||||
suffix += " ; " + _text(item["marker"])
|
||||
return name + suffix
|
||||
|
||||
|
||||
def uv_environment(*, tools: Path, binaries: Path, cache: Path) -> dict[str, str]:
|
||||
"""Use frozen receipt policy, retaining credentials and transport settings only."""
|
||||
env = {key: value for key, value in os.environ.items() if not key.upper().startswith(("UV_", "PIP_", "PIPX_"))
|
||||
or key in _TRANSPORT_SETTINGS or (key.startswith("UV_INDEX_") and key.endswith(("_USERNAME", "_PASSWORD")))}
|
||||
env.update(UV_TOOL_DIR=str(tools), UV_TOOL_BIN_DIR=str(binaries), UV_CACHE_DIR=str(cache),
|
||||
UV_NO_PROGRESS="1", UV_PYTHON_DOWNLOADS="never", PYTHONDONTWRITEBYTECODE="1")
|
||||
return env
|
||||
|
||||
|
||||
def _run(process: PreparationProcess, executable: str, arguments: list[str], *, env: dict[str, str], cwd: Path) -> str:
|
||||
result = process.run(executable, arguments, kind="native", env=env, cwd=cwd)
|
||||
if result.returncode:
|
||||
# Index URLs, raw resolver messages and TOML parse diagnostics may carry
|
||||
# credentials. The public job stores a stage, not these raw strings.
|
||||
raise ValueError("Could not prepare the uv transaction; inspect the installation's manager settings")
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def cache_digest(source: Path, *, copy_to: Path | None = None) -> str:
|
||||
"""Seal/copy a private cache without its absolute internal symlink locations.
|
||||
|
||||
uv writes its working cache during apply. A fresh verified copy keeps both the
|
||||
original preparation and interrupted-update retries bound to the same inputs.
|
||||
No shared uv cache is read, moved, rewritten or cleared by this operation.
|
||||
"""
|
||||
root = source.resolve(strict=True)
|
||||
if source.is_symlink() or not root.is_dir():
|
||||
raise ValueError("Invalid private uv cache")
|
||||
if copy_to is not None:
|
||||
copy_to.mkdir(mode=0o700) # Never merge into an existing apply cache.
|
||||
digest = hashlib.sha256()
|
||||
count, size = 0, 0
|
||||
for current, directories, files in os.walk(root, followlinks=False):
|
||||
directories.sort()
|
||||
files.sort()
|
||||
for name in sorted(directories + files):
|
||||
path = Path(current) / name
|
||||
relative = path.relative_to(root)
|
||||
mode = path.lstat().st_mode
|
||||
output = copy_to / relative if copy_to is not None else None
|
||||
count += 1
|
||||
if count > 200_000:
|
||||
raise ValueError("Private uv cache exceeds its entry limit")
|
||||
if stat.S_ISLNK(mode):
|
||||
target = path.resolve(strict=True)
|
||||
if not target.is_relative_to(root):
|
||||
raise ValueError("Private uv cache links outside its preparation")
|
||||
target_name = target.relative_to(root).as_posix()
|
||||
entry = [relative.as_posix(), "link", target_name]
|
||||
if output is not None and copy_to is not None:
|
||||
output.symlink_to(os.path.relpath(copy_to / target_name, output.parent),
|
||||
target_is_directory=target.is_dir())
|
||||
elif stat.S_ISDIR(mode):
|
||||
entry = [relative.as_posix(), "directory"]
|
||||
if output is not None:
|
||||
output.mkdir(mode=0o700)
|
||||
elif stat.S_ISREG(mode):
|
||||
size += path.stat().st_size
|
||||
if size > 4 * 1024**3:
|
||||
raise ValueError("Private uv cache exceeds its size limit")
|
||||
entry = [relative.as_posix(), "file", str(mode & 0o111), _hash_file(path)]
|
||||
if output is not None:
|
||||
shutil.copyfile(path, output)
|
||||
output.chmod(0o600 | (mode & 0o111))
|
||||
else:
|
||||
raise ValueError("Private uv cache contains an unsupported file type")
|
||||
digest.update((json.dumps(entry, separators=(",", ":")) + "\n").encode())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _versions(process: PreparationProcess, python: str, *, prepared: bool = False) -> dict[str, str]:
|
||||
result = process.run(python, ["-c",
|
||||
"import json,re; from importlib.metadata import distributions; "
|
||||
"print(json.dumps({re.sub(r'[-_.]+','-',d.metadata['Name']).lower():"
|
||||
"[d.version,json.loads(d.read_text('direct_url.json') or '{}')] for d in distributions()}))"],
|
||||
timeout=30)
|
||||
if result.returncode:
|
||||
raise ValueError("Could not inspect the prepared uv environment")
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
versions: dict[str, str] = {}
|
||||
for name, value in _record(json.loads(result.stdout)).items():
|
||||
if not isinstance(value, list):
|
||||
raise ValueError("Invalid prepared distribution record")
|
||||
fields = cast(list[object], value)
|
||||
if len(fields) != 2:
|
||||
raise ValueError("Invalid prepared distribution record")
|
||||
versions[name] = _text(fields[0])
|
||||
direct = _record(fields[1])
|
||||
if prepared and direct and name != "nanobot-ai":
|
||||
parsed = urlsplit(_text(direct.get("url")))
|
||||
if parsed.scheme not in {"https", "http"} or not parsed.path.endswith(".whl"):
|
||||
raise ValueError("Local or source dependencies need the uv owner's update workflow")
|
||||
return versions
|
||||
|
||||
|
||||
def _remote_location(value: object) -> None:
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
if isinstance(value, list):
|
||||
for item in cast(list[object], value):
|
||||
_remote_location(item)
|
||||
elif isinstance(value, dict):
|
||||
_remote_location(_record(cast(dict[object, object], value)).get("url"))
|
||||
elif urlsplit(_text(value)).scheme not in {"https", "http"}:
|
||||
# --offline still reads local indexes/find-links. Such a directory can
|
||||
# change the resolved target after preparation even with a sealed cache.
|
||||
raise ValueError("Local package sources need their owner's update workflow")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UVPreparation:
|
||||
executable: str
|
||||
executable_sha256: str
|
||||
manager_version: str
|
||||
receipt_sha256: str
|
||||
cache: str
|
||||
cache_sha256: str
|
||||
binaries: str
|
||||
versions: dict[str, str]
|
||||
|
||||
@classmethod
|
||||
def parse(cls, value: object) -> UVPreparation:
|
||||
data = _record(value)
|
||||
result = cls(_text(data["executable"]), _text(data["executable_sha256"]), _text(data["manager_version"]),
|
||||
_text(data["receipt_sha256"]), _text(data["cache"]), _text(data["cache_sha256"]),
|
||||
_text(data["binaries"]),
|
||||
{name: _text(version) for name, version in _record(data["versions"]).items()})
|
||||
if any(not re.fullmatch(r"[0-9a-f]{64}", item) for item in (
|
||||
result.executable_sha256, result.receipt_sha256, result.cache_sha256,
|
||||
)) or len(result.versions) > 500 or not all(
|
||||
Path(path).is_absolute() for path in (result.executable, result.binaries)
|
||||
):
|
||||
raise ValueError("Invalid uv preparation identity")
|
||||
cache = Path(result.cache)
|
||||
if (cache.is_absolute() or ".." in cache.parts or len(cache.parts) != 2
|
||||
or not cache.parts[0].startswith(".uv-prepare-") or cache.parts[1] != "cache"):
|
||||
raise ValueError("Invalid private uv cache location")
|
||||
return result
|
||||
|
||||
def verify(self, environment: str, directory: Path) -> None:
|
||||
_receipt_only_policy()
|
||||
if _hash_file(Path(self.executable)) != self.executable_sha256:
|
||||
raise ValueError("The uv executable changed since preparation")
|
||||
receipt = Path(environment) / "uv-receipt.toml"
|
||||
if receipt.is_symlink() or _hash_file(receipt) != self.receipt_sha256:
|
||||
raise ValueError("The uv installation settings changed since preparation")
|
||||
cache = directory / self.cache
|
||||
if not cache.resolve().is_relative_to(directory.resolve()) or cache_digest(cache) != self.cache_sha256:
|
||||
raise ValueError("The prepared uv cache changed")
|
||||
|
||||
def working_cache(self, directory: Path) -> Path:
|
||||
attempt = Path(tempfile.mkdtemp(prefix=".uv-apply-", dir=directory)) / "cache"
|
||||
if (cache_digest(directory / self.cache, copy_to=attempt) != self.cache_sha256
|
||||
or cache_digest(attempt) != self.cache_sha256):
|
||||
raise ValueError("The copied uv transaction does not match its preparation")
|
||||
return attempt
|
||||
|
||||
|
||||
def prepare_uv(*, environment: str, python: str, receipt_sha256: str, app_wheel: Path,
|
||||
version: str, extras: list[str], directory: Path, executable: str,
|
||||
process: PreparationProcess) -> UVPreparation:
|
||||
"""Resolve in a separate tool home; never change the user's tool or receipt."""
|
||||
_receipt_only_policy()
|
||||
if Path(environment).resolve().name != "nanobot-ai":
|
||||
raise ValueError("This tool layout needs the uv owner's update workflow")
|
||||
executable = str(Path(executable).resolve(strict=True))
|
||||
with Path(executable).open("rb") as stream:
|
||||
magic = stream.read(4)
|
||||
if (Path(executable).is_relative_to(Path(environment).resolve())
|
||||
or magic not in {b"\x7fELF", b"\xcf\xfa\xed\xfe", b"\xfe\xed\xfa\xcf",
|
||||
b"\xca\xfe\xba\xbe", b"\xbe\xba\xfe\xca",
|
||||
b"\xca\xfe\xba\xbf", b"\xbf\xba\xfe\xca"}):
|
||||
raise ValueError("The uv updater needs a native manager outside the environment being replaced")
|
||||
manager_sha = _hash_file(Path(executable))
|
||||
receipt_path = Path(environment) / "uv-receipt.toml"
|
||||
with receipt_path.open("rb") as stream:
|
||||
raw = stream.read(1024**2 + 1)
|
||||
if receipt_path.is_symlink() or len(raw) > 1024**2 or hashlib.sha256(raw).hexdigest() != receipt_sha256:
|
||||
raise ValueError("The uv receipt changed before preparation")
|
||||
try:
|
||||
receipt = _record(tomllib.loads(raw.decode()))
|
||||
tool = _record(receipt["tool"])
|
||||
if receipt.keys() != {"tool"} or tool.keys() - {"requirements", "python", "entrypoints", "options"}:
|
||||
raise ValueError("Unsupported receipt fields")
|
||||
requirements = tool["requirements"]
|
||||
entries = tool["entrypoints"]
|
||||
options = _record(tool.get("options", {}))
|
||||
if not isinstance(requirements, list) or not isinstance(entries, list):
|
||||
raise ValueError("Invalid receipt collections")
|
||||
injected: list[str] = []
|
||||
main = 0
|
||||
for item in cast(list[object], requirements):
|
||||
requirement = _record(item)
|
||||
rendered = _requirement(item)
|
||||
if re.sub(r"[-_.]+", "-", _text(requirement["name"])).lower() == "nanobot-ai":
|
||||
main += 1
|
||||
else:
|
||||
injected.extend(["--with", rendered])
|
||||
paths = [_text(_record(entry)["install-path"]) for entry in cast(list[object], entries)]
|
||||
parents = {str(Path(path).parent) for path in paths}
|
||||
if main != 1 or len(parents) != 1 or not all(Path(path).is_absolute() for path in paths):
|
||||
raise ValueError("Ambiguous tool ownership")
|
||||
if (options.get("compile-bytecode") or options.get("no-binary") or options.get("no-binary-package")
|
||||
or options.get("link-mode") == "symlink" or options.get("keyring-provider") == "subprocess"):
|
||||
raise ValueError("This policy requires a different native lifecycle")
|
||||
for name in ("index", "index-url", "default-index", "extra-index-url", "find-links"):
|
||||
if name in options:
|
||||
_remote_location(options[name])
|
||||
binaries = parents.pop()
|
||||
encoded_options = "\n".join(f"{json.dumps(key)} = {_toml(value)}" for key, value in options.items())
|
||||
except (ValueError, KeyError, TypeError):
|
||||
raise ValueError("These uv settings need the installation owner's update workflow") from None
|
||||
before = _versions(process, python)
|
||||
# Unique attempts prevent an orphan preparing process from writing a cache
|
||||
# reused by a subsequent request after its parent exits.
|
||||
staging = Path(tempfile.mkdtemp(prefix=".uv-prepare-", dir=directory))
|
||||
cache = staging / "cache"
|
||||
config = staging / "uv.toml"
|
||||
config.write_text(encoded_options, encoding="utf-8")
|
||||
config.chmod(0o600)
|
||||
env = uv_environment(tools=staging / "tools", binaries=staging / "bin", cache=cache)
|
||||
manager_version = _run(process, executable, ["--version"], env=env, cwd=staging)
|
||||
if manager_version.split()[:2] != ["uv", UV_TRANSACTION_VERSION]:
|
||||
raise ValueError("This uv version needs the installation owner's update workflow")
|
||||
target = "nanobot-ai" + (f"[{','.join(extras)}]" if extras else "") + " @ " + app_wheel.as_uri()
|
||||
# --no-build is private to this disposable receipt. Supplying it to the real
|
||||
# tool upgrade would permanently change the user's stored options.
|
||||
_run(process, executable, ["tool", "install", "--config-file", str(config), "--python", python,
|
||||
"--no-build", *injected, target], env=env, cwd=staging)
|
||||
prepared_python = staging / "tools/nanobot-ai" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
||||
versions = _versions(process, str(prepared_python), prepared=True)
|
||||
if versions.get("nanobot-ai") != version:
|
||||
raise ValueError("uv resolved a different application version")
|
||||
if _versions(process, python) != before or receipt_path.read_bytes() != raw:
|
||||
raise ValueError("The original uv installation changed during preparation")
|
||||
for source_cache in cache.glob("sdists-*"):
|
||||
if any(path.is_file() and path.stat().st_size for path in source_cache.rglob("*")):
|
||||
raise ValueError("Source-built dependencies cannot enter the offline uv transaction")
|
||||
for path in cache.rglob("*"):
|
||||
if path.is_file() and not path.is_symlink():
|
||||
with path.open("r+b") as stream:
|
||||
os.fsync(stream.fileno())
|
||||
result = UVPreparation(executable, manager_sha, manager_version, receipt_sha256,
|
||||
cache.relative_to(directory).as_posix(), cache_digest(cache), binaries, versions)
|
||||
result.verify(environment, directory)
|
||||
return result
|
||||
@@ -0,0 +1,957 @@
|
||||
"""Standalone, offline installer worker for an already prepared update.
|
||||
|
||||
This file and its stdlib-only helpers are copied to an immutable zipapp outside
|
||||
site-packages before mutation. The coordinator uses the base Python. Its installer and
|
||||
verification children own their runtime leases, so coordinator loss cannot release a
|
||||
lease while they are still using the installation. Only lease-protected child entrypoints
|
||||
import the installed nanobot runtime for shutdown, verification or restart.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import asdict, dataclass
|
||||
from email.parser import BytesParser
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
from uuid import UUID, uuid4
|
||||
from zipfile import ZipFile
|
||||
|
||||
from nanobot.data_access import DataLease, data_access
|
||||
from nanobot.installation_lock import (
|
||||
FileLease,
|
||||
InstallationBusyError,
|
||||
file_access,
|
||||
installation_access,
|
||||
installation_state_dir,
|
||||
pending_update_path,
|
||||
)
|
||||
from nanobot.update_backup import BackupSource, ensure_backup, verify_backup
|
||||
from nanobot.update_process import (
|
||||
PreparationProcess,
|
||||
child_leases,
|
||||
initialize_runtime,
|
||||
inspect_python_environment,
|
||||
run_preparation_child,
|
||||
)
|
||||
from nanobot.update_uv import UVPreparation, uv_environment
|
||||
from nanobot.utils.atomic_file import atomic_write_lines, io_path, read_atomic_bytes
|
||||
|
||||
_REQUEST_SCHEMA_VERSION = 4
|
||||
_MAX_REQUEST_BYTES = 16 * 1024 * 1024
|
||||
_HANDOFF_PROTOCOL = 1
|
||||
|
||||
_PROBE = """
|
||||
import hashlib, json, re, sys
|
||||
from pathlib import Path
|
||||
from importlib.metadata import distributions, distribution, PackageNotFoundError
|
||||
root = Path(sys.prefix).resolve()
|
||||
cfg = root / 'pyvenv.cfg'
|
||||
if sys.prefix == sys.base_prefix or not cfg.is_file():
|
||||
raise SystemExit('A dedicated virtual environment is required')
|
||||
owners = [name for name in ('uv-receipt.toml', 'pipx_metadata.json') if (root / name).exists()]
|
||||
if owners != (['uv-receipt.toml'] if manager == 'uv' else []):
|
||||
raise SystemExit('This environment belongs to another package manager')
|
||||
if 'include-system-site-packages = true' in cfg.read_text().lower():
|
||||
raise SystemExit('Shared system packages are not supported by this worker')
|
||||
items, versions = {}, {}
|
||||
for d in distributions():
|
||||
name = re.sub(r'[-_.]+', '-', d.metadata['Name']).lower()
|
||||
payload = '\\n'.join(d.read_text(f) or '' for f in ('METADATA', 'RECORD', 'direct_url.json'))
|
||||
items[name] = hashlib.sha256(payload.encode()).hexdigest()
|
||||
versions[name] = d.version
|
||||
try:
|
||||
app = distribution('nanobot-ai')
|
||||
app_version = app.version
|
||||
app_records = {name: hashlib.sha256((app.read_text(name) or '').encode()).hexdigest()
|
||||
for name in ('RECORD', 'direct_url.json')}
|
||||
except PackageNotFoundError:
|
||||
app_version, app_records = '', {}
|
||||
snapshot = dict(environment=str(root), python=str(Path(sys.executable).absolute()),
|
||||
base_python=str(Path(sys._base_executable).resolve()),
|
||||
receipt_sha=hashlib.sha256(cfg.read_bytes()).hexdigest(), distributions=items, versions=versions,
|
||||
app_version=app_version, app_records=app_records,
|
||||
installer_receipt_sha=hashlib.sha256((root / 'nanobot-install.json').read_bytes()).hexdigest()
|
||||
if (root / 'nanobot-install.json').is_file() else None,
|
||||
manager_receipt_sha=hashlib.sha256((root / owners[0]).read_bytes()).hexdigest() if owners else None)
|
||||
"""
|
||||
|
||||
|
||||
def _object(value: object) -> dict[str, object]:
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Expected a JSON object")
|
||||
data = cast(dict[object, object], value)
|
||||
if not all(isinstance(key, str) for key in data):
|
||||
raise ValueError("Expected string record keys")
|
||||
return cast(dict[str, object], data)
|
||||
|
||||
|
||||
def _text(value: object) -> str:
|
||||
if not isinstance(value, str) or not value or len(value) > 4096:
|
||||
raise ValueError("Expected a bounded nonempty string")
|
||||
return value
|
||||
|
||||
|
||||
def _sha(value: object) -> str:
|
||||
text = _text(value)
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", text):
|
||||
raise ValueError("Invalid checksum")
|
||||
return text
|
||||
|
||||
|
||||
def _integer(value: object) -> int:
|
||||
if type(value) is not int or value < 0:
|
||||
raise ValueError("Expected a nonnegative integer")
|
||||
return value
|
||||
|
||||
|
||||
def read_record(path: Path, *, max_bytes: int = 1024 * 1024) -> dict[str, object]:
|
||||
path = io_path(path)
|
||||
if path.is_symlink():
|
||||
raise ValueError("Invalid update record")
|
||||
data = read_atomic_bytes(path, max_bytes=max_bytes + 1)
|
||||
if len(data) > max_bytes:
|
||||
raise ValueError("Update record exceeds its size limit")
|
||||
return _object(json.loads(data))
|
||||
|
||||
|
||||
def write_record(path: Path, record: object, *, max_bytes: int = 1024 * 1024) -> None:
|
||||
encoded = json.dumps(record, sort_keys=True, separators=(",", ":"))
|
||||
if len(encoded.encode("utf-8")) + 1 > max_bytes:
|
||||
raise ValueError("Update record exceeds its size limit")
|
||||
atomic_write_lines(path, [encoded])
|
||||
io_path(path).chmod(0o600)
|
||||
|
||||
|
||||
def verify_target_handoff(wheel: ZipFile) -> None:
|
||||
"""Read the target's declared restart contract without executing its code.
|
||||
|
||||
Protocol 1 covers request schema 4, protected -I -S gateway startup, scoped
|
||||
data grants and exact-run activation. A matching package version or Python
|
||||
filename does not establish that contract. See docs/releasing.md.
|
||||
"""
|
||||
message = ("This release cannot use this updater's protected restart. "
|
||||
"Use the installation owner's external update procedure instead.")
|
||||
try:
|
||||
wheel.getinfo("nanobot/update_restart.py")
|
||||
entry = wheel.getinfo("nanobot/update_contract.json")
|
||||
if entry.file_size > 4096:
|
||||
raise ValueError(message)
|
||||
record = _object(json.loads(wheel.read(entry)))
|
||||
except (KeyError, ValueError, UnicodeError) as exc:
|
||||
raise ValueError(message) from exc
|
||||
protocols = record.get("handoff_protocols")
|
||||
if (type(record.get("schema_version")) is not int or record["schema_version"] != 1
|
||||
or not isinstance(protocols, list)):
|
||||
raise ValueError(message)
|
||||
values = cast(list[object], protocols)
|
||||
if (not 1 <= len(values) <= 32 or not all(type(value) is int and value > 0 for value in values)
|
||||
or _HANDOFF_PROTOCOL not in values):
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EnvironmentSnapshot:
|
||||
environment: str
|
||||
python: str
|
||||
base_python: str
|
||||
receipt_sha: str
|
||||
distributions: dict[str, str]
|
||||
versions: dict[str, str]
|
||||
app_version: str
|
||||
app_records: dict[str, str]
|
||||
manager_receipt_sha: str | None = None
|
||||
installer_receipt_sha: str | None = None
|
||||
|
||||
@classmethod
|
||||
def parse(cls, value: object) -> EnvironmentSnapshot:
|
||||
data = _object(value)
|
||||
version = data["app_version"]
|
||||
if not isinstance(version, str):
|
||||
raise ValueError("Invalid installed version")
|
||||
return cls(_text(data["environment"]), _text(data["python"]), _text(data["base_python"]),
|
||||
_sha(data["receipt_sha"]), {name: _sha(digest) for name, digest in
|
||||
_object(data["distributions"]).items()},
|
||||
{name: _text(value) for name, value in _object(data["versions"]).items()}, version,
|
||||
{name: _sha(digest) for name, digest in _object(data["app_records"]).items()},
|
||||
_sha(data["manager_receipt_sha"]) if data.get("manager_receipt_sha") is not None else None,
|
||||
_sha(data["installer_receipt_sha"]) if data.get("installer_receipt_sha") is not None else None)
|
||||
|
||||
|
||||
def inspect_environment(python: str, *, uv: bool = False, process: PreparationProcess | None = None) -> EnvironmentSnapshot:
|
||||
# Raw metadata diagnostics may inspect an interrupted installation, but
|
||||
# never run concurrently with a package writer. Preparation is stricter.
|
||||
probe = "manager = __import__('sys').argv[1]\n" + _PROBE + "\nprint(json.dumps(snapshot))\n"
|
||||
arguments = ["-c", probe, "uv" if uv else "pip"]
|
||||
result = (process.run(python, arguments, timeout=15) if process is not None else
|
||||
inspect_python_environment(python, str(Path(python).parent.parent.resolve()), probe,
|
||||
arguments=("uv" if uv else "pip",), allow_incomplete=True))
|
||||
if result.returncode:
|
||||
raise ValueError("Could not verify the selected package environment; use its installation owner")
|
||||
return EnvironmentSnapshot.parse(json.loads(result.stdout))
|
||||
|
||||
|
||||
def current_environment(*, uv: bool = False) -> EnvironmentSnapshot:
|
||||
"""Inspect in an already initialized, lease-owning target child, without a grandchild."""
|
||||
scope: dict[str, object] = {"manager": "uv" if uv else "pip"}
|
||||
exec(compile(_PROBE, "<update environment probe>", "exec"), scope)
|
||||
return EnvironmentSnapshot.parse(scope["snapshot"])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StagedWheel:
|
||||
filename: str
|
||||
name: str
|
||||
version: str
|
||||
size: int
|
||||
sha256: str
|
||||
|
||||
@classmethod
|
||||
def parse(cls, value: object) -> StagedWheel:
|
||||
data = _object(value)
|
||||
filename, name = _text(data["filename"]), _text(data["name"])
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.-]+\.whl", filename) or not re.fullmatch(r"[a-z0-9-]+", name):
|
||||
raise ValueError("Invalid staged wheel name")
|
||||
if name == "pip":
|
||||
raise ValueError("An application update cannot replace its installer")
|
||||
return cls(filename, name, _text(data["version"]), _integer(data["size"]), _sha(data["sha256"]))
|
||||
|
||||
def verify(self, directory: Path) -> Path:
|
||||
path = directory / self.filename
|
||||
if path.is_symlink() or path.stat().st_size != self.size:
|
||||
raise ValueError("Staged wheel size or file type changed")
|
||||
with path.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != self.sha256:
|
||||
raise ValueError("Staged wheel checksum changed")
|
||||
with ZipFile(path) as wheel:
|
||||
names = wheel.namelist()
|
||||
if len(names) != len(set(names)) or any(re.search(r"(^[A-Za-z]:|^/|\\|(?:^|/)\.\.(?:/|$))", name) for name in names):
|
||||
raise ValueError("Invalid wheel paths")
|
||||
metadata = [item for item in wheel.infolist() if item.filename.endswith(".dist-info/METADATA")]
|
||||
if len(metadata) != 1 or metadata[0].file_size > 256 * 1024:
|
||||
raise ValueError("Invalid wheel metadata")
|
||||
parsed = BytesParser().parsebytes(wheel.read(metadata[0]))
|
||||
name = re.sub(r"[-_.]+", "-", str(parsed["Name"])).lower()
|
||||
if (name, parsed["Version"]) != (self.name, self.version):
|
||||
raise ValueError("Staged wheel identity changed")
|
||||
return path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkerSpec:
|
||||
plan_id: str
|
||||
plan_sha256: str
|
||||
worker_sha256: str
|
||||
baseline: EnvironmentSnapshot
|
||||
version: str
|
||||
wheels: tuple[StagedWheel, ...]
|
||||
backup_sources: tuple[BackupSource, ...]
|
||||
restart_profiles: tuple[str, ...] = ()
|
||||
uv: UVPreparation | None = None
|
||||
automatic_recovery: bool = False
|
||||
|
||||
@staticmethod
|
||||
def recovery_selected(directory: Path) -> bool:
|
||||
"""Read the frozen selection for status, without probing damaged inputs."""
|
||||
try:
|
||||
data = read_record(directory / "request.json", max_bytes=_MAX_REQUEST_BYTES)
|
||||
except FileNotFoundError:
|
||||
return False # Preparation has not committed a worker request.
|
||||
if data.get("plan_id") != directory.name:
|
||||
raise ValueError("Update job identity mismatch")
|
||||
return data.get("automatic_recovery") is True
|
||||
|
||||
@classmethod
|
||||
def read(cls, directory: Path) -> WorkerSpec:
|
||||
data = read_record(directory / "request.json", max_bytes=_MAX_REQUEST_BYTES)
|
||||
if data.get("schema_version") != _REQUEST_SCHEMA_VERSION:
|
||||
raise ValueError("Unsupported update worker request")
|
||||
plan_id = _text(data["plan_id"])
|
||||
if str(UUID(plan_id)) != plan_id or directory.name != plan_id:
|
||||
raise ValueError("Update job identity mismatch")
|
||||
raw_wheels = data["wheels"]
|
||||
if not isinstance(raw_wheels, list):
|
||||
raise ValueError("Invalid update wheel set")
|
||||
wheel_values = cast(list[object], raw_wheels)
|
||||
if not 1 <= len(wheel_values) <= 500:
|
||||
raise ValueError("Invalid update wheel set")
|
||||
wheels = tuple(StagedWheel.parse(value) for value in wheel_values)
|
||||
raw_sources = data.get("backup_sources")
|
||||
if not isinstance(raw_sources, list):
|
||||
raise ValueError("Invalid backup scope")
|
||||
source_values = cast(list[object], raw_sources)
|
||||
if not 1 <= len(source_values) <= 40_000:
|
||||
raise ValueError("Invalid backup scope")
|
||||
sources = tuple(BackupSource.parse(value) for value in source_values)
|
||||
participants = data.get("restart_profiles")
|
||||
if not isinstance(participants, list):
|
||||
raise ValueError("Invalid restart participants")
|
||||
restart_profiles = tuple(_sha(value) for value in cast(list[object], participants))
|
||||
if len(restart_profiles) > 1024 or len(set(restart_profiles)) != len(restart_profiles):
|
||||
raise ValueError("Invalid restart participants")
|
||||
automatic_recovery = data.get("automatic_recovery", False)
|
||||
if type(automatic_recovery) is not bool:
|
||||
raise ValueError("Invalid automatic recovery selection")
|
||||
spec = cls(plan_id, _sha(data["plan_sha256"]), _sha(data["worker_sha256"]), EnvironmentSnapshot.parse(data["baseline"]),
|
||||
_text(data["version"]), wheels, sources, restart_profiles,
|
||||
UVPreparation.parse(data["uv"]) if data.get("uv") is not None else None,
|
||||
automatic_recovery)
|
||||
if (spec.uv is None) != (spec.baseline.manager_receipt_sha is None):
|
||||
raise ValueError("Installer preparation does not match the environment owner")
|
||||
if spec.uv is not None and (spec.uv.receipt_sha256 != spec.baseline.manager_receipt_sha
|
||||
or spec.uv.versions.get("nanobot-ai") != spec.version):
|
||||
raise ValueError("The uv preparation does not match the approved installation or target")
|
||||
if directory.resolve() != (installation_state_dir(spec.baseline.environment) / "jobs" / plan_id).resolve():
|
||||
raise ValueError("Update job is outside its installation state directory")
|
||||
if len({wheel.name for wheel in wheels}) != len(wheels):
|
||||
raise ValueError("Duplicate staged distributions")
|
||||
if [(wheel.name, wheel.version) for wheel in wheels if wheel.name == "nanobot-ai"] != [("nanobot-ai", spec.version)]:
|
||||
raise ValueError("Missing exact nanobot target")
|
||||
if hashlib.sha256((directory / "plan.json").read_bytes()).hexdigest() != spec.plan_sha256:
|
||||
raise ValueError("The approved plan changed")
|
||||
if hashlib.sha256((directory / "worker.pyz").read_bytes()).hexdigest() != spec.worker_sha256:
|
||||
raise ValueError("The staged update worker changed")
|
||||
return spec
|
||||
|
||||
def save(self, directory: Path) -> None:
|
||||
# Expanded profile stores may exceed the small journal/approval limit.
|
||||
# Keep the writer and standalone reader on the same bounded contract.
|
||||
write_record(directory / "request.json", {"schema_version": _REQUEST_SCHEMA_VERSION, **asdict(self)},
|
||||
max_bytes=_MAX_REQUEST_BYTES)
|
||||
|
||||
def verify_inputs(self, directory: Path) -> None:
|
||||
for wheel in self.wheels:
|
||||
path = wheel.verify(directory / "wheels")
|
||||
if self.restart_profiles and wheel.name == "nanobot-ai":
|
||||
with ZipFile(path) as archive:
|
||||
verify_target_handoff(archive)
|
||||
if self.uv is not None:
|
||||
self.uv.verify(self.baseline.environment, directory)
|
||||
|
||||
@contextmanager
|
||||
def mutation_access(self) -> Generator[tuple[FileLease, DataLease]]:
|
||||
"""Hold this job's installation and data leases, in acquisition order."""
|
||||
with (installation_access(updating=True, environment=self.baseline.environment) as installation,
|
||||
data_access((source.path for source in self.backup_sources), updating=True, job_id=self.plan_id) as data):
|
||||
yield installation, data
|
||||
|
||||
|
||||
class Phase(str, Enum):
|
||||
PREPARATION_REQUESTED = "preparation_requested"
|
||||
PREPARING = "preparing"
|
||||
PREPARATION_FAILED = "preparation_failed"
|
||||
READY = "ready"
|
||||
CHECKING = "checking"
|
||||
STOPPING = "stopping"
|
||||
HANDOFF_FAILED = "handoff_failed"
|
||||
BACKING_UP = "backing_up"
|
||||
INSTALLING = "installing"
|
||||
VERIFYING = "verifying"
|
||||
INSTALLED = "installed"
|
||||
RESTARTING = "restarting"
|
||||
ACTIVATING = "activating"
|
||||
FINALIZING = "finalizing"
|
||||
RESTART_FAILED = "restart_failed"
|
||||
SUCCEEDED = "succeeded"
|
||||
FAILED = "failed"
|
||||
CANCELLED = "cancelled"
|
||||
RESTORED = "restored"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JobStatus:
|
||||
plan_id: str
|
||||
phase: Phase
|
||||
attempt: int
|
||||
mutation_started: bool
|
||||
message: str
|
||||
updated_at: int
|
||||
|
||||
@classmethod
|
||||
def read(cls, directory: Path) -> JobStatus:
|
||||
value = read_record(directory / "status.json")
|
||||
mutated = value["mutation_started"]
|
||||
if type(mutated) is not bool or value["plan_id"] != directory.name:
|
||||
raise ValueError("Invalid update status")
|
||||
return cls(directory.name, Phase(value["phase"]), _integer(value["attempt"]), mutated,
|
||||
_text(value["message"]), _integer(value["updated_at"]))
|
||||
|
||||
def save(self, directory: Path) -> None:
|
||||
write_record(directory / "status.json", asdict(self))
|
||||
|
||||
def advance(self, directory: Path, phase: Phase, message: str, *,
|
||||
mutation_started: bool | None = None, attempt: int | None = None) -> JobStatus:
|
||||
"""Publish a phase without reconstructing the job's execution history."""
|
||||
status = JobStatus(self.plan_id, phase, self.attempt if attempt is None else attempt,
|
||||
self.mutation_started if mutation_started is None else mutation_started,
|
||||
message, int(time.time()))
|
||||
status.save(directory)
|
||||
return status
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExecutionConfirmation:
|
||||
"""One durable user confirmation; not proof that a worker is currently alive."""
|
||||
|
||||
id: str
|
||||
plan_id: str
|
||||
request_sha256: str
|
||||
created_at: int
|
||||
expires_at: int
|
||||
|
||||
@classmethod
|
||||
def read(cls, directory: Path) -> ExecutionConfirmation | None:
|
||||
try:
|
||||
value = read_record(directory / "confirmation.json", max_bytes=2048)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
identifier, plan_id = _text(value["id"]), _text(value["plan_id"])
|
||||
if UUID(identifier).hex != identifier or str(UUID(plan_id)) != plan_id or plan_id != directory.name:
|
||||
raise ValueError("Invalid execution confirmation identity")
|
||||
created, expires = _integer(value["created_at"]), _integer(value["expires_at"])
|
||||
if not created < expires <= created + 900:
|
||||
raise ValueError("Invalid execution confirmation lifetime")
|
||||
return cls(identifier, plan_id, _sha(value["request_sha256"]), created, expires)
|
||||
|
||||
def save(self, directory: Path) -> None:
|
||||
write_record(directory / "confirmation.json", asdict(self), max_bytes=2048)
|
||||
|
||||
|
||||
def check_approval(directory: Path, spec: WorkerSpec, *, handoff: bool = False,
|
||||
confirmation_id: str | None = None, check_expiry: bool = True) -> dict[str, object]:
|
||||
approval = read_record(directory / ("handoff-approval.json" if handoff else "approval.json"))
|
||||
now = int(time.time())
|
||||
created, expires = _integer(approval["created_at"]), _integer(approval["expires_at"])
|
||||
if not created < expires <= created + 900 or (check_expiry and not created <= now < expires):
|
||||
raise ValueError("Update approval expired; review this exact job again before retrying")
|
||||
digest = hashlib.sha256((directory / "request.json").read_bytes()).hexdigest()
|
||||
if approval.get("request_sha256") != digest or approval.get("plan_id") != spec.plan_id:
|
||||
raise ValueError("Update approval does not match this job")
|
||||
if confirmation_id is not None:
|
||||
confirmation = ExecutionConfirmation.read(directory)
|
||||
if (confirmation is None or confirmation.id != confirmation_id
|
||||
or approval.get("confirmation_id") != confirmation_id
|
||||
or confirmation.request_sha256 != digest or confirmation.plan_id != spec.plan_id
|
||||
or (confirmation.created_at, confirmation.expires_at) != (created, expires)):
|
||||
raise ValueError("Execution confirmation was replaced or revoked")
|
||||
return approval
|
||||
|
||||
|
||||
def _prepare_handoff_child(directory: Path, confirmation_id: str | None = None) -> None:
|
||||
spec = WorkerSpec.read(directory)
|
||||
# The child imports the old application, but keeps a shared lease until it
|
||||
# actually exits. Parent loss cannot allow another installer to replace its
|
||||
# imports. The base-Python parent waits for this exit before changing files.
|
||||
child_leases.enter_context(file_access(
|
||||
installation_state_dir(spec.baseline.environment) / "handoff-child.lock", exclusive=True))
|
||||
child_leases.enter_context(installation_access(environment=spec.baseline.environment))
|
||||
check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id)
|
||||
initialize_runtime(spec.baseline.python, spec.baseline.environment)
|
||||
from nanobot.update_handoff import prepare_handoff
|
||||
|
||||
prepare_handoff(directory)
|
||||
|
||||
|
||||
def _handoff(directory: Path, spec: WorkerSpec, confirmation_id: str | None = None) -> None:
|
||||
status = JobStatus.read(directory)
|
||||
check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id)
|
||||
status.advance(directory, Phase.CHECKING, "Rechecking the exact release and installation before shutdown", mutation_started=False)
|
||||
subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
|
||||
"--prepare-handoff", str(directory), *([confirmation_id] if confirmation_id else [])], check=True, timeout=300,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
approval = check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id)
|
||||
current = inspect_job_environment(directory, spec)
|
||||
with spec.mutation_access():
|
||||
check_environment(spec, repairing=False, current=current)
|
||||
spec.verify_inputs(directory)
|
||||
# Stopping a process did not grant installation authority. Only successful
|
||||
# preflight, child exit and exclusive installation/data leases get here.
|
||||
write_record(directory / "approval.json", approval)
|
||||
|
||||
|
||||
def check_environment(spec: WorkerSpec, *, repairing: bool, current: EnvironmentSnapshot) -> None:
|
||||
if current.installer_receipt_sha != spec.baseline.installer_receipt_sha:
|
||||
raise ValueError("Installer selection changed outside this update")
|
||||
if (current.environment, current.python, current.base_python, current.receipt_sha, current.manager_receipt_sha) != (
|
||||
spec.baseline.environment, spec.baseline.python, spec.baseline.base_python, spec.baseline.receipt_sha,
|
||||
spec.baseline.manager_receipt_sha,
|
||||
):
|
||||
raise ValueError("Installation ownership or interpreter changed")
|
||||
changed: set[str] = {wheel.name for wheel in spec.wheels} if repairing else set()
|
||||
targets = {wheel.name: wheel.version for wheel in spec.wheels}
|
||||
if spec.uv is not None:
|
||||
targets = spec.uv.versions
|
||||
if repairing:
|
||||
changed = set(spec.baseline.versions) | set(targets)
|
||||
before = {name: digest for name, digest in spec.baseline.distributions.items() if name not in changed}
|
||||
after = {name: digest for name, digest in current.distributions.items() if name not in changed}
|
||||
if before != after:
|
||||
raise ValueError("The package environment changed outside this update; review it before continuing")
|
||||
if repairing:
|
||||
for name in changed:
|
||||
if current.versions.get(name) not in {None, spec.baseline.versions.get(name), targets.get(name)}:
|
||||
raise ValueError("Another update changed a target package; repair cannot overwrite its version")
|
||||
|
||||
|
||||
def require_pending_owner(spec: WorkerSpec) -> None:
|
||||
pending = pending_update_path(spec.baseline.environment)
|
||||
if pending.exists() and read_record(pending).get("job_id") != spec.plan_id:
|
||||
raise ValueError("Another incomplete update owns this installation")
|
||||
|
||||
|
||||
def inspect_job_environment(directory: Path, spec: WorkerSpec) -> EnvironmentSnapshot:
|
||||
"""Inspect a staged job without borrowing its caller's runtime/data leases.
|
||||
|
||||
Call with the worker lease held, but not exclusive runtime/data leases. The
|
||||
child owns those while loading site and retains them through exit cleanup.
|
||||
The caller still checks the snapshot under its final admission leases, and
|
||||
the installer repeats that check in-process immediately before mutation.
|
||||
"""
|
||||
result = subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
|
||||
"--inspect", str(directory)], capture_output=True, text=True, timeout=15)
|
||||
if result.returncode == 11:
|
||||
raise InstallationBusyError("The update's installation or data is in use; wait for its current owner")
|
||||
if result.returncode:
|
||||
raise ValueError("Could not verify the selected package environment; use its installation owner")
|
||||
return EnvironmentSnapshot.parse(json.loads(result.stdout))
|
||||
|
||||
|
||||
def _inspection_child(directory: Path) -> None:
|
||||
spec = WorkerSpec.read(directory)
|
||||
status = JobStatus.read(directory)
|
||||
restarting = status.phase in {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED}
|
||||
child_leases.enter_context(installation_access(
|
||||
updating=not restarting, allow_incomplete=restarting, environment=spec.baseline.environment))
|
||||
# Finalization can already have released the data reservation while the
|
||||
# verified gateway is serving requests. It only needs the runtime read lease.
|
||||
if status.phase != Phase.FINALIZING:
|
||||
child_leases.enter_context(data_access(
|
||||
(source.path for source in spec.backup_sources), updating=not restarting, job_id=spec.plan_id))
|
||||
require_pending_owner(spec)
|
||||
initialize_runtime(spec.baseline.python, spec.baseline.environment)
|
||||
print(json.dumps(asdict(current_environment(uv=spec.uv is not None))))
|
||||
|
||||
|
||||
def _installer_child(directory: Path, confirmation_id: str | None = None) -> None:
|
||||
spec = WorkerSpec.read(directory)
|
||||
installation, data = child_leases.enter_context(spec.mutation_access())
|
||||
status = JobStatus.read(directory)
|
||||
if status.phase in {Phase.INSTALLED, Phase.CANCELLED, Phase.RESTARTING,
|
||||
Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED, Phase.SUCCEEDED, Phase.RESTORED}:
|
||||
raise ValueError("This update job is already finished")
|
||||
check_approval(directory, spec, confirmation_id=confirmation_id)
|
||||
require_pending_owner(spec)
|
||||
initialize_runtime(spec.baseline.python, spec.baseline.environment)
|
||||
check_environment(spec, repairing=status.mutation_started, current=current_environment(uv=spec.uv is not None))
|
||||
spec.verify_inputs(directory)
|
||||
wheels = [str(directory / "wheels" / wheel.filename) for wheel in spec.wheels]
|
||||
uv_cache = None
|
||||
if spec.uv is not None:
|
||||
if os.name != "posix":
|
||||
raise ValueError("Native uv lease handoff is not available on this platform")
|
||||
uv_cache = spec.uv.working_cache(directory)
|
||||
verify_backup(directory, spec.backup_sources, hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
|
||||
unchanged=not status.mutation_started)
|
||||
pending = pending_update_path()
|
||||
pending.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
data.reserve()
|
||||
write_record(pending, {"schema_version": 2, "job_id": spec.plan_id, "version": spec.version})
|
||||
status.advance(directory, Phase.INSTALLING, "Installing the verified package files",
|
||||
mutation_started=True, attempt=status.attempt + 1)
|
||||
if spec.uv is not None and uv_cache is not None:
|
||||
# Exact-wheel override is one operation, not a rewrite of the saved
|
||||
# requirement. Even --no-build would persist in the user's receipt.
|
||||
plan = read_record(directory / "plan.json", max_bytes=_MAX_REQUEST_BYTES)
|
||||
extras = plan.get("extras")
|
||||
if not isinstance(extras, list):
|
||||
raise ValueError("Invalid approved uv extras")
|
||||
extra_values = cast(list[object], extras)
|
||||
if not all(isinstance(extra, str) and re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", extra)
|
||||
for extra in extra_values):
|
||||
raise ValueError("Invalid approved uv extras")
|
||||
suffix = "[" + ",".join(cast(list[str], extra_values)) + "]" if extras else ""
|
||||
app = next(wheel for wheel in spec.wheels if wheel.name == "nanobot-ai")
|
||||
target = "nanobot-ai" + suffix + " @ " + (directory / "wheels" / app.filename).as_uri()
|
||||
env = uv_environment(tools=Path(spec.baseline.environment).parent,
|
||||
binaries=Path(spec.uv.binaries), cache=uv_cache)
|
||||
arguments = [spec.uv.executable, "tool", "upgrade", "--no-config", "--offline", "--reinstall", target]
|
||||
with installation.inherit_for_exec(), data.inherit_for_exec():
|
||||
os.execve(spec.uv.executable, arguments, env)
|
||||
# Keep pip in this lease-owning process on every platform. Inherited Windows
|
||||
# handles cannot transfer byte-range locks; a POSIX wrapper can also die
|
||||
# before a spawned installer. Only verified local wheels are accepted, so
|
||||
# no build child can outlive it. A separate protected child verifies afterwards.
|
||||
arguments = ["--disable-pip-version-check", "--no-input", "install",
|
||||
"--no-index", "--no-deps", "--only-binary=:all:", "--no-compile",
|
||||
"--force-reinstall", *wheels]
|
||||
# A dedicated CLI, ending in pip's SystemExit; no application or second pip
|
||||
# call runs afterwards. Process-owned leases remain held during atexit.
|
||||
sys.argv = ["pip", *arguments]
|
||||
runpy.run_module("pip", run_name="__main__")
|
||||
|
||||
|
||||
def _verify(spec: WorkerSpec, directory: Path) -> None:
|
||||
# The coordinator must not hold the runtime/data leases here: this child
|
||||
# acquires its own before site/imports and keeps them through dependency
|
||||
# checks and atexit, even if the coordinator disappears.
|
||||
verification_id = uuid4().hex
|
||||
env = {key: value for key, value in os.environ.items() if not key.upper().startswith("PIP_")}
|
||||
env["PIP_CONFIG_FILE"] = os.devnull
|
||||
result = subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
|
||||
"--verify", str(directory), verification_id], timeout=90,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
|
||||
if result.returncode == 10:
|
||||
raise ValueError("The installed nanobot package does not import")
|
||||
if result.returncode:
|
||||
raise ValueError("Installed package or dependency verification failed")
|
||||
try:
|
||||
checkpoint = read_record(directory / "verification.json", max_bytes=2048)
|
||||
except (OSError, ValueError) as exc:
|
||||
raise ValueError("Installed package verification did not finish") from exc
|
||||
if checkpoint.get("id") != verification_id:
|
||||
raise ValueError("Installed package verification did not finish")
|
||||
|
||||
|
||||
def _verification_child(directory: Path, verification_id: str) -> None:
|
||||
if UUID(verification_id).hex != verification_id:
|
||||
raise ValueError("Invalid verification identity")
|
||||
spec = WorkerSpec.read(directory)
|
||||
installation, data = child_leases.enter_context(spec.mutation_access())
|
||||
status = JobStatus.read(directory)
|
||||
if not status.mutation_started or status.phase not in {Phase.VERIFYING, Phase.INSTALLED}:
|
||||
raise ValueError("This job is not awaiting installed-package verification")
|
||||
if read_record(pending_update_path(spec.baseline.environment)).get("job_id") != spec.plan_id:
|
||||
raise ValueError("This job no longer owns installed-package verification")
|
||||
spec.verify_inputs(directory)
|
||||
initialize_runtime(spec.baseline.python, spec.baseline.environment)
|
||||
try:
|
||||
import nanobot
|
||||
except Exception:
|
||||
# A dedicated exit code preserves an actionable diagnosis without
|
||||
# persisting arbitrary import exceptions, paths or package output.
|
||||
raise SystemExit(10) from None
|
||||
package = Path(nanobot.__file__).resolve()
|
||||
if nanobot.__version__ != spec.version or not package.is_relative_to(spec.baseline.environment):
|
||||
raise ValueError("Installed package version or location differs from the approved target")
|
||||
app = next(wheel for wheel in spec.wheels if wheel.name == "nanobot-ai")
|
||||
with ZipFile(directory / "wheels" / app.filename) as wheel:
|
||||
for item in wheel.infolist():
|
||||
if item.is_dir() or not item.filename.startswith("nanobot/"):
|
||||
continue
|
||||
installed = package.parent.parent / item.filename
|
||||
if not installed.is_file() or installed.is_symlink():
|
||||
raise ValueError("An installed application file is missing")
|
||||
with installed.open("rb") as actual, wheel.open(item) as expected:
|
||||
digest = hashlib.sha256()
|
||||
while chunk := expected.read(1024 * 1024):
|
||||
digest.update(chunk)
|
||||
if hashlib.file_digest(actual, "sha256").digest() != digest.digest():
|
||||
raise ValueError("Installed application files differ from the verified wheel")
|
||||
if spec.uv is not None:
|
||||
current = current_environment(uv=True)
|
||||
if (current.environment, current.python, current.base_python, current.receipt_sha) != (
|
||||
spec.baseline.environment, spec.baseline.python, spec.baseline.base_python, spec.baseline.receipt_sha,
|
||||
):
|
||||
raise ValueError("uv changed the prepared interpreter or environment ownership")
|
||||
if current.versions != spec.uv.versions:
|
||||
raise ValueError("The installed uv dependencies differ from the prepared transaction")
|
||||
if os.name != "posix":
|
||||
raise ValueError("Native uv lease handoff is not available on this platform")
|
||||
command = [spec.uv.executable, "pip", "check", "--no-config", "--no-cache", "--offline", "--python", spec.baseline.python]
|
||||
env = uv_environment(tools=Path(spec.baseline.environment).parent,
|
||||
binaries=Path(spec.uv.binaries), cache=directory / ".uv-check-cache")
|
||||
# This checkpoint plus the native command's successful exit proves the
|
||||
# verification path ran. Exit 0 from site/import hooks alone does not.
|
||||
write_record(directory / "verification.json", {"id": verification_id}, max_bytes=2048)
|
||||
with installation.inherit_for_exec(), data.inherit_for_exec():
|
||||
os.execve(spec.uv.executable, command, env)
|
||||
# Like installation, pip check runs in the same process that owns the
|
||||
# leases, not in an unprotected subprocess of a protected wrapper.
|
||||
sys.argv = ["pip", "check"]
|
||||
try:
|
||||
runpy.run_module("pip", run_name="__main__")
|
||||
except SystemExit as exc:
|
||||
if exc.code not in {None, 0}:
|
||||
raise
|
||||
write_record(directory / "verification.json", {"id": verification_id}, max_bytes=2048)
|
||||
|
||||
|
||||
def _approve_recovery(directory: Path, spec: WorkerSpec, status: JobStatus) -> None:
|
||||
"""Fresh local consent resumes only a previously admitted, immutable job.
|
||||
|
||||
Never repeats shutdown or resolves a release. Before mutation, the original
|
||||
handoff must already have admitted this worker (approval.json). After mutation
|
||||
the same installation/data reservation and backup remain authoritative.
|
||||
"""
|
||||
if status.phase in {Phase.CANCELLED, Phase.PREPARATION_FAILED, Phase.PREPARING, Phase.PREPARATION_REQUESTED}:
|
||||
raise ValueError("This job cannot be repaired; no installation was admitted")
|
||||
check_approval(directory, spec, check_expiry=False)
|
||||
spec.verify_inputs(directory)
|
||||
current = inspect_job_environment(directory, spec)
|
||||
check_environment(spec, repairing=status.mutation_started, current=current)
|
||||
if status.mutation_started:
|
||||
verify_backup(directory, spec.backup_sources,
|
||||
hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(), unchanged=False)
|
||||
now = int(time.time())
|
||||
write_record(directory / "approval.json", {
|
||||
"plan_id": spec.plan_id,
|
||||
"request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
|
||||
"created_at": now, "expires_at": now + 900,
|
||||
})
|
||||
|
||||
|
||||
def run_job(directory: Path, *, handoff: bool = False, confirmation_id: str | None = None,
|
||||
recover: bool = False) -> JobStatus:
|
||||
"""Execute one approved offline job. 'installed' does not mean restarted."""
|
||||
spec = WorkerSpec.read(directory)
|
||||
root = installation_state_dir(spec.baseline.environment)
|
||||
with file_access(root / "worker.lock", exclusive=True):
|
||||
if recover and (handoff or confirmation_id is not None):
|
||||
raise ValueError("Repair cannot initiate a second shutdown handoff")
|
||||
if confirmation_id is not None:
|
||||
if not handoff:
|
||||
raise ValueError("A confirmation only starts the reviewed shutdown handoff")
|
||||
confirmation = ExecutionConfirmation.read(directory)
|
||||
if confirmation is None or confirmation.id != confirmation_id:
|
||||
raise ValueError("This execution confirmation is no longer current")
|
||||
claimed = directory / "confirmation-claimed.json"
|
||||
if claimed.exists():
|
||||
if read_record(claimed, max_bytes=2048).get("id") != confirmation_id:
|
||||
raise ValueError("Another execution confirmation owns this job")
|
||||
# A duplicate or delayed launcher is history, not a retry, even
|
||||
# if the first worker exited before updating its journal.
|
||||
return JobStatus.read(directory)
|
||||
check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id)
|
||||
write_record(claimed, {"id": confirmation_id}, max_bytes=2048)
|
||||
if handoff:
|
||||
# An orphan preflight child may still own the old runtime. Refuse a
|
||||
# competing handoff without rewriting its durable progress.
|
||||
with file_access(root / "handoff-child.lock", exclusive=True):
|
||||
pass
|
||||
status = JobStatus.read(directory)
|
||||
if status.phase == Phase.RESTORED:
|
||||
raise ValueError("This update was settled by service recovery; review a new update instead")
|
||||
if status.phase == Phase.CANCELLED:
|
||||
raise ValueError("This update job was cancelled")
|
||||
if recover:
|
||||
with file_access(root / "handoff-child.lock", exclusive=True):
|
||||
if status.phase == Phase.SUCCEEDED:
|
||||
return status
|
||||
_approve_recovery(directory, spec, status)
|
||||
if handoff and (status.mutation_started or status.phase not in {
|
||||
Phase.READY, Phase.CHECKING, Phase.STOPPING, Phase.HANDOFF_FAILED,
|
||||
}):
|
||||
raise ValueError("Shutdown handoff requires an unmodified prepared job")
|
||||
try:
|
||||
if handoff:
|
||||
spec.verify_inputs(directory)
|
||||
_handoff(directory, spec, confirmation_id)
|
||||
if status.phase in {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED, Phase.SUCCEEDED}:
|
||||
return restart_runtime(directory, spec, confirmation_id)
|
||||
if status.phase == Phase.INSTALLED:
|
||||
# Recover a crash after saving the result but before removing
|
||||
# the startup fence. Verification owns independent leases.
|
||||
with spec.mutation_access():
|
||||
require_pending_owner(spec)
|
||||
needs_verification = pending_update_path(spec.baseline.environment).exists()
|
||||
if needs_verification:
|
||||
_verify(spec, directory)
|
||||
with spec.mutation_access() as (_, data):
|
||||
require_pending_owner(spec)
|
||||
pending_update_path(spec.baseline.environment).unlink(missing_ok=True)
|
||||
data.release_reservation()
|
||||
return status
|
||||
check_approval(directory, spec, confirmation_id=confirmation_id)
|
||||
current = inspect_job_environment(directory, spec)
|
||||
with spec.mutation_access() as (_, data):
|
||||
require_pending_owner(spec)
|
||||
check_approval(directory, spec, confirmation_id=confirmation_id)
|
||||
check_environment(spec, repairing=status.mutation_started, current=current)
|
||||
spec.verify_inputs(directory)
|
||||
if not status.mutation_started:
|
||||
from nanobot.update_fallback import preserve_program
|
||||
|
||||
preserve_program(directory, spec)
|
||||
status.advance(directory, Phase.BACKING_UP, "Preserving the original scoped data backup")
|
||||
ensure_backup(directory, spec.backup_sources,
|
||||
hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
|
||||
mutated=status.mutation_started)
|
||||
# Block shared-data writers too, including a different Python
|
||||
# installation, across handoff and interrupted-job recovery.
|
||||
data.reserve()
|
||||
pending = pending_update_path(spec.baseline.environment)
|
||||
pending.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
write_record(pending, {"schema_version": 2, "job_id": spec.plan_id, "version": spec.version})
|
||||
env = {key: value for key, value in os.environ.items() if not key.upper().startswith("PIP_")}
|
||||
env["PIP_CONFIG_FILE"] = os.devnull
|
||||
subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
|
||||
"--install", str(directory), *([confirmation_id] if confirmation_id else [])], check=True, timeout=900,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
|
||||
with spec.mutation_access():
|
||||
status = JobStatus.read(directory)
|
||||
status.advance(directory, Phase.VERIFYING, "Checking the installed package and dependencies", mutation_started=True)
|
||||
_verify(spec, directory)
|
||||
with spec.mutation_access() as (_, data):
|
||||
require_pending_owner(spec)
|
||||
status = status.advance(directory, Phase.RESTARTING if spec.restart_profiles else Phase.INSTALLED,
|
||||
"Files installed and checked; running gateway not yet verified", mutation_started=True)
|
||||
if not spec.restart_profiles:
|
||||
pending_update_path(spec.baseline.environment).unlink()
|
||||
data.release_reservation()
|
||||
return status
|
||||
return restart_runtime(directory, spec, confirmation_id)
|
||||
except InstallationBusyError:
|
||||
# An orphan pip child may still be alive. Do not turn its ongoing
|
||||
# installation into a terminal failure or overwrite its journal.
|
||||
current = JobStatus.read(directory)
|
||||
if handoff and current.phase in {Phase.CHECKING, Phase.STOPPING} and not current.mutation_started:
|
||||
current.advance(directory, Phase.HANDOFF_FAILED,
|
||||
"Update handoff could not acquire exclusive access; no package files were changed", mutation_started=False)
|
||||
raise
|
||||
except Exception as exc:
|
||||
status = JobStatus.read(directory)
|
||||
if status.phase in {Phase.FINALIZING, Phase.SUCCEEDED}:
|
||||
# Runtime success was durably verified. Retry only final cleanup,
|
||||
# never demote it to a restart or package-repair transaction.
|
||||
raise
|
||||
# Do not persist arbitrary package-manager output, URLs or credentials.
|
||||
message = str(exc) if isinstance(exc, (ValueError, InstallationBusyError)) else f"Update failed ({type(exc).__name__})"
|
||||
handoff_failed = status.phase in {Phase.CHECKING, Phase.STOPPING, Phase.HANDOFF_FAILED}
|
||||
if handoff_failed:
|
||||
# The old runtime may already have exited. Never imply that a
|
||||
# pre-install failure undoes a durable shutdown commitment.
|
||||
message = (status.message if status.phase == Phase.HANDOFF_FAILED else
|
||||
"Update handoff did not finish; review the saved shutdown state before retrying")
|
||||
phase = Phase.HANDOFF_FAILED if handoff_failed else (
|
||||
Phase.RESTART_FAILED if status.phase in {
|
||||
Phase.RESTARTING, Phase.ACTIVATING, Phase.RESTART_FAILED,
|
||||
} else Phase.FAILED
|
||||
)
|
||||
status.advance(directory, phase, message[:1000])
|
||||
if not status.mutation_started and not handoff_failed:
|
||||
with spec.mutation_access() as (_, data):
|
||||
require_pending_owner(spec)
|
||||
pending_update_path(spec.baseline.environment).unlink(missing_ok=True)
|
||||
data.release_reservation()
|
||||
raise
|
||||
|
||||
|
||||
def restart_runtime(directory: Path, spec: WorkerSpec, confirmation_id: str | None = None) -> JobStatus:
|
||||
# Use the target Python, but enter through frozen stdlib code so its shared
|
||||
# installation lease is held before importing the mutable target runtime.
|
||||
subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
|
||||
"--restart", str(directory), *([confirmation_id] if confirmation_id else [])], check=True, timeout=300,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
result = JobStatus.read(directory)
|
||||
if result.phase not in {Phase.SUCCEEDED, Phase.RESTORED}:
|
||||
raise ValueError("Runtime handoff did not verify the updated gateways")
|
||||
return result
|
||||
|
||||
|
||||
def _runtime_child(directory: Path, participant: str | None = None, confirmation_id: str | None = None) -> None:
|
||||
spec = WorkerSpec.read(directory)
|
||||
if not spec.restart_profiles or (participant is not None and participant not in spec.restart_profiles):
|
||||
raise ValueError("This gateway is not a reviewed restart participant")
|
||||
child_leases.enter_context(installation_access(allow_incomplete=True, environment=spec.baseline.environment))
|
||||
require_pending_owner(spec)
|
||||
if confirmation_id is not None:
|
||||
# Completion can take longer than consent's launch window. Bind the
|
||||
# identity, without treating elapsed time as a reason to reinstall.
|
||||
check_approval(directory, spec, confirmation_id=confirmation_id, check_expiry=False)
|
||||
initialize_runtime(spec.baseline.python, spec.baseline.environment)
|
||||
# Deliberately import the installed application, not a frozen stub.
|
||||
if (directory / "restoration.json").exists():
|
||||
# Recovery uses the original frozen restart implementation. An older
|
||||
# installed package need not understand the newer recovery journal.
|
||||
from .update_restart import run_gateway, run_restarts
|
||||
else:
|
||||
import importlib
|
||||
|
||||
restart = importlib.import_module("nanobot.update_restart")
|
||||
run_gateway, run_restarts = restart.run_gateway, restart.run_restarts
|
||||
|
||||
if participant is None:
|
||||
run_restarts(directory)
|
||||
else:
|
||||
run_gateway(directory, participant)
|
||||
|
||||
|
||||
def cancel_job(directory: Path) -> JobStatus:
|
||||
"""Cancel only a stopped, unmodified job; never terminate an installer."""
|
||||
spec = WorkerSpec.read(directory)
|
||||
with file_access(installation_state_dir(spec.baseline.environment) / "worker.lock", exclusive=True):
|
||||
with spec.mutation_access() as (_, data):
|
||||
status = JobStatus.read(directory)
|
||||
if status.mutation_started:
|
||||
raise ValueError("Installation has begun; this job needs verification or repair, not cancellation")
|
||||
require_pending_owner(spec)
|
||||
pending_update_path(spec.baseline.environment).unlink(missing_ok=True)
|
||||
data.release_reservation()
|
||||
status = status.advance(directory, Phase.CANCELLED, "Cancelled; installed files were not changed", mutation_started=False)
|
||||
(directory / "approval.json").unlink(missing_ok=True)
|
||||
return status
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) >= 4 and sys.argv[1] == "--supervise":
|
||||
from nanobot.update_fallback import supervise
|
||||
|
||||
supervise(Path(sys.argv[2]).resolve(), sys.argv[3:])
|
||||
return
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--inspect":
|
||||
try:
|
||||
_inspection_child(Path(sys.argv[2]).resolve())
|
||||
except InstallationBusyError:
|
||||
raise SystemExit(11) from None
|
||||
return
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--prepare-native":
|
||||
run_preparation_child(Path(sys.argv[2]).resolve())
|
||||
return
|
||||
if len(sys.argv) in {3, 4} and sys.argv[1] == "--prepare-handoff":
|
||||
_prepare_handoff_child(Path(sys.argv[2]).resolve(), sys.argv[3] if len(sys.argv) == 4 else None)
|
||||
return
|
||||
if len(sys.argv) in {3, 4} and sys.argv[1] == "--restart":
|
||||
_runtime_child(Path(sys.argv[2]).resolve(), confirmation_id=sys.argv[3] if len(sys.argv) == 4 else None)
|
||||
return
|
||||
if len(sys.argv) == 4 and sys.argv[1] == "--gateway":
|
||||
_runtime_child(Path(sys.argv[2]).resolve(), sys.argv[3])
|
||||
return
|
||||
if len(sys.argv) in {3, 4} and sys.argv[1] == "--install":
|
||||
_installer_child(Path(sys.argv[2]).resolve(), sys.argv[3] if len(sys.argv) == 4 else None)
|
||||
return
|
||||
if len(sys.argv) == 4 and sys.argv[1] == "--verify":
|
||||
_verification_child(Path(sys.argv[2]).resolve(), sys.argv[3])
|
||||
return
|
||||
if len(sys.argv) == 3 and sys.argv[1] in {"--status", "--cancel"}:
|
||||
directory = Path(sys.argv[2]).resolve()
|
||||
WorkerSpec.read(directory)
|
||||
status = cancel_job(directory) if sys.argv[1] == "--cancel" else JobStatus.read(directory)
|
||||
print(json.dumps(asdict(status)))
|
||||
return
|
||||
recover = len(sys.argv) == 3 and sys.argv[1] == "--recover"
|
||||
handoff = len(sys.argv) == 3 and sys.argv[1] == "--handoff"
|
||||
confirmed = len(sys.argv) == 4 and sys.argv[1] == "--confirmed-handoff"
|
||||
if len(sys.argv) != 2 and not handoff and not confirmed and not recover:
|
||||
raise SystemExit("Use this worker with its exact saved job directory")
|
||||
directory = Path(sys.argv[2] if handoff or confirmed or recover else sys.argv[1]).resolve()
|
||||
try:
|
||||
result = run_job(directory, handoff=handoff or confirmed, confirmation_id=sys.argv[3] if confirmed else None,
|
||||
recover=recover)
|
||||
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc:
|
||||
print(f"Update did not finish: {type(exc).__name__}. Consult the saved job status.", file=sys.stderr)
|
||||
raise SystemExit(1) from exc
|
||||
print(json.dumps(asdict(result)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Standard-library atomic record replacement, also used by the update worker."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import os
|
||||
import uuid
|
||||
from collections.abc import Iterable
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO
|
||||
|
||||
|
||||
def io_path(path: Path) -> Path:
|
||||
"""Use Windows' extended namespace for I/O, without changing stored identities."""
|
||||
if os.name != "nt":
|
||||
return path
|
||||
name = str(path)
|
||||
if name.startswith(("\\\\?\\", "\\\\.\\")):
|
||||
return path
|
||||
# Extended paths bypass Win32 normalization and must be absolute. Normalize
|
||||
# ordinary relative paths, separators and dot segments before adding a prefix.
|
||||
name = os.path.abspath(name)
|
||||
if name.startswith("\\\\"):
|
||||
return Path("\\\\?\\UNC\\" + name[2:])
|
||||
return Path("\\\\?\\" + name)
|
||||
|
||||
|
||||
def _open_snapshot(path: Path) -> BinaryIO:
|
||||
"""Read one inode without preventing its atomic replacement on Windows."""
|
||||
if os.name != "nt":
|
||||
return path.open("rb")
|
||||
import ctypes
|
||||
import msvcrt
|
||||
from ctypes import wintypes
|
||||
|
||||
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
create = kernel.CreateFileW
|
||||
create.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
|
||||
wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
|
||||
create.restype = wintypes.HANDLE
|
||||
close = kernel.CloseHandle
|
||||
close.argtypes = [wintypes.HANDLE]
|
||||
close.restype = wintypes.BOOL
|
||||
# GENERIC_READ; FILE_SHARE_READ | WRITE | DELETE; OPEN_EXISTING.
|
||||
# Python's normal open omits SHARE_DELETE. Pair this handle with the POSIX
|
||||
# rename below so a short status poll cannot block journal commits.
|
||||
handle = create(str(io_path(path)), 0x80000000, 1 | 2 | 4, None, 3, 0x80, None)
|
||||
if handle == wintypes.HANDLE(-1).value:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
try:
|
||||
descriptor = msvcrt.open_osfhandle(handle, os.O_RDONLY | os.O_BINARY)
|
||||
except BaseException:
|
||||
close(handle)
|
||||
raise
|
||||
# open_osfhandle transfers handle ownership to the file descriptor.
|
||||
return os.fdopen(descriptor, "rb")
|
||||
|
||||
|
||||
def replace_atomic(source: Path, destination: Path) -> None:
|
||||
"""Publish a new inode while existing snapshot readers retain the old one."""
|
||||
if os.name != "nt":
|
||||
os.replace(source, destination)
|
||||
return
|
||||
source, destination = io_path(source), io_path(destination)
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
class RenameInfo(ctypes.Structure):
|
||||
_fields_ = [("Flags", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE),
|
||||
("FileNameLength", wintypes.DWORD), ("FileName", wintypes.WCHAR * 1)]
|
||||
|
||||
# MoveFileExW (Python's os.replace) rejects an open destination even when
|
||||
# readers share DELETE. FileRenameInfoEx provides atomic POSIX replacement
|
||||
# on modern Windows: old readers keep their snapshot, new readers see this
|
||||
# commit. Do not unlink first or fall back to copying a partially written file.
|
||||
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
create = kernel.CreateFileW
|
||||
create.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
|
||||
wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
|
||||
create.restype = wintypes.HANDLE
|
||||
rename = kernel.SetFileInformationByHandle
|
||||
rename.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD]
|
||||
rename.restype = wintypes.BOOL
|
||||
close = kernel.CloseHandle
|
||||
close.argtypes = [wintypes.HANDLE]
|
||||
close.restype = wintypes.BOOL
|
||||
# DELETE | SYNCHRONIZE; share READ | WRITE | DELETE; OPEN_EXISTING.
|
||||
handle = create(str(source), 0x10000 | 0x100000, 1 | 2 | 4, None, 3, 0x80, None)
|
||||
if handle == wintypes.HANDLE(-1).value:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
unsupported = False
|
||||
try:
|
||||
name = str(destination).encode("utf-16-le")
|
||||
buffer = ctypes.create_string_buffer(ctypes.sizeof(RenameInfo) + len(name))
|
||||
info = RenameInfo.from_buffer(buffer)
|
||||
info.Flags = 1 | 2 # REPLACE_IF_EXISTS | POSIX_SEMANTICS (not IGNORE_READONLY).
|
||||
info.FileNameLength = len(name)
|
||||
ctypes.memmove(ctypes.addressof(buffer) + RenameInfo.FileName.offset, name, len(name))
|
||||
if not rename(handle, 22, buffer, len(buffer)): # FileRenameInfoEx
|
||||
error = ctypes.get_last_error()
|
||||
# Older Windows/filesystems can lack this information class. Keep
|
||||
# their existing atomic rename behavior, never a delete/copy gap.
|
||||
# Sharing/permission errors are not treated as missing capability.
|
||||
if error not in (1, 50, 87): # INVALID_FUNCTION, NOT_SUPPORTED, INVALID_PARAMETER
|
||||
raise ctypes.WinError(error)
|
||||
unsupported = True
|
||||
finally:
|
||||
close(handle)
|
||||
if unsupported:
|
||||
os.replace(source, destination)
|
||||
|
||||
|
||||
def read_atomic_bytes(path: Path, *, max_bytes: int = -1) -> bytes:
|
||||
"""Read a snapshot while permitting writers to atomically publish the next."""
|
||||
with _open_snapshot(path) as stream:
|
||||
return stream.read(max_bytes)
|
||||
|
||||
|
||||
def _fsync_directory_after_replace(directory: Path) -> None:
|
||||
"""Fsync a directory, ignoring only unsupported platforms/filesystems."""
|
||||
with suppress(PermissionError):
|
||||
fd = os.open(str(directory), os.O_RDONLY)
|
||||
try:
|
||||
try:
|
||||
os.fsync(fd)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EINVAL:
|
||||
raise
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def atomic_write_text(path: Path, content: str) -> None:
|
||||
"""Create parent directories and durably replace exact UTF-8 text."""
|
||||
path = io_path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
with open(tmp, "x", encoding="utf-8") as handle:
|
||||
handle.write(content)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
replace_atomic(tmp, path)
|
||||
_fsync_directory_after_replace(path.parent)
|
||||
finally:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def atomic_write_lines(path: Path, lines: Iterable[str], *, fsync: bool = True) -> None:
|
||||
"""Replace serialized records, optionally syncing both file and directory.
|
||||
|
||||
A unique sibling is flushed before replacement and cleaned on every failure.
|
||||
Directory fsync tolerates Windows permission errors and unsupported filesystems,
|
||||
but propagates other I/O failures. Existing callers retain their durability choice.
|
||||
"""
|
||||
path = io_path(path)
|
||||
tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
# Stable bytes across platforms: callers hash records and bound their
|
||||
# encoded size, so Windows newline translation would break the contract.
|
||||
with open(tmp, "x", encoding="utf-8", newline="\n") as handle:
|
||||
for line in lines:
|
||||
handle.write(line if line.endswith("\n") else f"{line}\n")
|
||||
if fsync:
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
replace_atomic(tmp, path)
|
||||
if fsync:
|
||||
_fsync_directory_after_replace(path.parent)
|
||||
finally:
|
||||
if tmp.exists():
|
||||
tmp.unlink(missing_ok=True)
|
||||
@@ -3,14 +3,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Iterable
|
||||
from contextlib import suppress
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -19,6 +15,8 @@ from typing import TYPE_CHECKING, Any, TypeVar, cast, overload
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.utils.atomic_file import atomic_write_lines as atomic_write_lines
|
||||
from nanobot.utils.atomic_file import atomic_write_text as atomic_write_text
|
||||
from nanobot.utils.file_io import ensure_dir as ensure_dir
|
||||
from nanobot.utils.file_io import write_text_atomic as _write_text_atomic
|
||||
from nanobot.utils.token_encoding import get_token_encoding as _get_token_encoding
|
||||
@@ -554,67 +552,6 @@ def _cleanup_tool_result_buckets(root: Path, current_bucket: Path) -> None:
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
|
||||
|
||||
def atomic_write_text(path: Path, content: str) -> None:
|
||||
"""Create parent directories and durably replace *path* with UTF-8 text."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
with open(tmp_path, "w", encoding="utf-8") as handle:
|
||||
handle.write(content)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(tmp_path, path)
|
||||
_fsync_directory_after_replace(path.parent)
|
||||
except BaseException:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def atomic_write_lines(path: Path, lines: Iterable[str], *, fsync: bool = True) -> None:
|
||||
"""Atomically replace *path* with already-serialized record lines.
|
||||
|
||||
Each item is one record. A trailing newline is added when the item does
|
||||
not already end with one. The bytes are written to a uniquely named temp
|
||||
file in the same directory, then published with ``os.replace``.
|
||||
|
||||
``fsync=True`` (the default) flushes and fsyncs the file before the
|
||||
replace, then fsyncs the parent directory. ``fsync=False`` skips both,
|
||||
which session saves use when the caller does not ask for durability.
|
||||
Directory fsync suppresses ``PermissionError`` (Windows cannot open a
|
||||
directory this way) and ``EINVAL`` (filesystems that reject directory
|
||||
fsync). Any other directory fsync error propagates. The temp file is
|
||||
removed on every ``BaseException``.
|
||||
"""
|
||||
tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
with open(tmp, "x", encoding="utf-8") as handle:
|
||||
for line in lines:
|
||||
handle.write(line if line.endswith("\n") else f"{line}\n")
|
||||
if fsync:
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(tmp, path)
|
||||
if fsync:
|
||||
_fsync_directory_after_replace(path.parent)
|
||||
finally:
|
||||
if tmp.exists():
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _fsync_directory_after_replace(directory: Path) -> None:
|
||||
"""Fsync *directory* after a replace, ignoring unsupported platforms."""
|
||||
with suppress(PermissionError):
|
||||
fd = os.open(str(directory), os.O_RDONLY)
|
||||
try:
|
||||
try:
|
||||
os.fsync(fd)
|
||||
except OSError as exc:
|
||||
if exc.errno != errno.EINVAL:
|
||||
raise
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def maybe_persist_tool_result(
|
||||
workspace: Path | None,
|
||||
session_key: str | None,
|
||||
|
||||
+18
-10
@@ -6,11 +6,13 @@ import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from collections.abc import Callable, Mapping
|
||||
from contextlib import suppress
|
||||
from contextlib import nullcontext, suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
from nanobot.bun import BunUnavailableError, bun_environment, ensure_bun
|
||||
|
||||
BuildMode = Literal["auto", "prompt", "warn", "skip"]
|
||||
|
||||
_SOURCE_TOP_LEVEL_FILES = (
|
||||
@@ -194,21 +196,20 @@ def build_webui_bundle(
|
||||
) -> WebUIBundleStatus:
|
||||
"""Install frontend dependencies and build the WebUI bundle."""
|
||||
resolved_source = source_dir or default_webui_source_dir()
|
||||
command_runner = runner or pick_webui_build_runner()
|
||||
if command_runner is None:
|
||||
raise WebUIBuildError(
|
||||
"neither `bun` nor `npm` is available on PATH; install one or run "
|
||||
"`cd webui && bun run build` manually"
|
||||
)
|
||||
try:
|
||||
command_runner = runner or pick_webui_build_runner() or ensure_bun(output=output or print)
|
||||
except BunUnavailableError as exc:
|
||||
raise WebUIBuildError(str(exc)) from exc
|
||||
using_bun = Path(command_runner).stem.lower() == "bun"
|
||||
|
||||
_emit(output, f"Building bundled WebUI with `{command_runner}`...")
|
||||
_run_frontend_command(
|
||||
[command_runner, "install"],
|
||||
[command_runner, "install", *(["--frozen-lockfile"] if using_bun else [])],
|
||||
cwd=resolved_source,
|
||||
subprocess_run=subprocess_run,
|
||||
)
|
||||
_run_frontend_command(
|
||||
[command_runner, "run", "build"],
|
||||
[command_runner, *(["--bun"] if using_bun else []), "run", "build"],
|
||||
cwd=resolved_source,
|
||||
subprocess_run=subprocess_run,
|
||||
)
|
||||
@@ -281,13 +282,20 @@ def _run_frontend_command(
|
||||
subprocess_run: Callable[..., subprocess.CompletedProcess[Any]],
|
||||
) -> None:
|
||||
try:
|
||||
subprocess_run(command, cwd=cwd, check=True)
|
||||
environment = (
|
||||
bun_environment(command[0])
|
||||
if Path(command[0]).stem.lower() == "bun" else nullcontext(os.environ.copy())
|
||||
)
|
||||
with environment as env:
|
||||
subprocess_run(command, cwd=cwd, check=True, env=env, timeout=900)
|
||||
except subprocess.CalledProcessError as exc:
|
||||
raise WebUIBuildError(
|
||||
f"command failed ({exc.returncode}): {' '.join(command)}"
|
||||
) from exc
|
||||
except OSError as exc:
|
||||
raise WebUIBuildError(f"command failed: {' '.join(command)} ({exc})") from exc
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise WebUIBuildError(f"command timed out: {' '.join(command)}") from exc
|
||||
|
||||
|
||||
def _display_source_path(status: WebUIBundleStatus) -> str:
|
||||
|
||||
@@ -18,6 +18,14 @@ SUBAGENT_EVENTS_CAPABILITY = "webui.subagents.events.v1"
|
||||
SUBAGENT_HISTORY_CAPABILITY = "webui.subagents.history.v1"
|
||||
AUTOMATION_CHAT_CAPABILITY = "webui.automation-chat.v1"
|
||||
BINARY_ATTACHMENTS_CAPABILITY = "webui.attachments.binary.v1"
|
||||
UPDATE_PLAN_CAPABILITY = "webui.update-plans.v1"
|
||||
UPDATE_JOB_CAPABILITY = "webui.update-jobs.read.v1"
|
||||
UPDATE_PREPARATION_CAPABILITY = "webui.update-jobs.prepare.v1"
|
||||
UPDATE_EXECUTION_CAPABILITY = "webui.update-jobs.execute.v1"
|
||||
UPDATE_RETRY_CAPABILITY = "webui.update-jobs.retry-handoff.v1"
|
||||
UPDATE_SETTLE_HANDOFF_CAPABILITY = "webui.update-jobs.settle-handoff.v1"
|
||||
UPDATE_FLOW_CAPABILITY = "webui.update-flow.v1"
|
||||
UPDATE_CHANNEL_CAPABILITY = "webui.update-channels.v1"
|
||||
PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1"
|
||||
|
||||
|
||||
@@ -35,7 +43,10 @@ def webui_contract() -> dict[str, object]:
|
||||
"capabilities": [
|
||||
CORE_CAPABILITY, SUBAGENT_CAPABILITY, SUBAGENT_EVENTS_CAPABILITY,
|
||||
SUBAGENT_HISTORY_CAPABILITY, AUTOMATION_CHAT_CAPABILITY,
|
||||
BINARY_ATTACHMENTS_CAPABILITY, PROMPT_NAVIGATION_CAPABILITY,
|
||||
BINARY_ATTACHMENTS_CAPABILITY, UPDATE_PLAN_CAPABILITY,
|
||||
UPDATE_JOB_CAPABILITY, UPDATE_PREPARATION_CAPABILITY, UPDATE_EXECUTION_CAPABILITY,
|
||||
UPDATE_RETRY_CAPABILITY, UPDATE_SETTLE_HANDOFF_CAPABILITY, UPDATE_FLOW_CAPABILITY, UPDATE_CHANNEL_CAPABILITY,
|
||||
PROMPT_NAVIGATION_CAPABILITY,
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -4,11 +4,13 @@ from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
from collections.abc import Callable
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
from websockets.http11 import Request as WsRequest
|
||||
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.webui.gateway_tokens import GatewayTokenStore
|
||||
from nanobot.webui.http_utils import (
|
||||
is_trusted_proxy_authenticated_request,
|
||||
@@ -57,6 +59,10 @@ class WebUIGatewayEndpoint:
|
||||
is_allowed: Callable[[str], bool],
|
||||
) -> Any:
|
||||
"""Route one listener request to a WS handshake or the HTTP application."""
|
||||
try:
|
||||
self._http.bus.admission.check()
|
||||
except RuntimeMaintenanceError:
|
||||
return connection.respond(HTTPStatus.SERVICE_UNAVAILABLE, "Gateway update is being verified. Retry shortly.\n")
|
||||
got, query = parse_request_path(request.path)
|
||||
expected_ws = normalize_config_path(self._config.path)
|
||||
if got == expected_ws and is_websocket_upgrade(request):
|
||||
|
||||
@@ -16,6 +16,7 @@ from nanobot.agent.tools.mcp import MCPConnection, connect_mcp_servers
|
||||
from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH, MCPOAuthHandlers
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.security.network import validate_url_target
|
||||
from nanobot.webui.http_utils import is_loopback_host
|
||||
|
||||
@@ -100,9 +101,36 @@ def prepare_mcp_oauth_redirect_uri(redirect_uri: str) -> tuple[str, bool]:
|
||||
class McpOAuthManager:
|
||||
"""Own short-lived browser flows while the gateway process is running."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, admission: RuntimeAdmission) -> None:
|
||||
self._admission = admission
|
||||
self._flows: dict[str, _McpOAuthFlow] = {}
|
||||
self._states: dict[str, str] = {}
|
||||
self._tasks: set[asyncio.Task[bool]] = set()
|
||||
self._cleanup_tasks: set[asyncio.Task[None]] = set()
|
||||
self._remove_pending_work: Callable[[], None] | None = None
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Join authorization work after the owner has stopped request intake."""
|
||||
tasks = tuple(self._tasks)
|
||||
for task in tasks:
|
||||
if not task.done() and not task.cancelling():
|
||||
task.cancel()
|
||||
if tasks:
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
if self._cleanup_tasks:
|
||||
await asyncio.shield(asyncio.gather(*tuple(self._cleanup_tasks)))
|
||||
self._flows.clear()
|
||||
self._states.clear()
|
||||
if self._remove_pending_work is not None:
|
||||
self._remove_pending_work()
|
||||
self._remove_pending_work = None
|
||||
|
||||
def _flow_finished(self, task: asyncio.Task[bool]) -> None:
|
||||
self._tasks.discard(task)
|
||||
# An expired flow no longer has a status consumer, but still owns its
|
||||
# task until connection cleanup finishes. Observe any terminal error.
|
||||
if not task.cancelled():
|
||||
task.exception()
|
||||
|
||||
async def start(
|
||||
self,
|
||||
@@ -113,9 +141,15 @@ class McpOAuthManager:
|
||||
reload_mcp: McpReload,
|
||||
reset_credentials: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
self._admission.check()
|
||||
self._prune()
|
||||
redirect_uri, manual_callback = prepare_mcp_oauth_redirect_uri(redirect_uri)
|
||||
await self._cancel_name(name)
|
||||
self._admission.check()
|
||||
if self._remove_pending_work is None:
|
||||
self._remove_pending_work = self._admission.register_pending_work(
|
||||
lambda: bool(self._tasks or self._cleanup_tasks),
|
||||
)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
now = time.monotonic()
|
||||
@@ -139,6 +173,8 @@ class McpOAuthManager:
|
||||
self._connect_and_reload(flow, handlers, reload_mcp),
|
||||
name=f"mcp-oauth:{name}",
|
||||
)
|
||||
self._tasks.add(flow.task)
|
||||
flow.task.add_done_callback(self._flow_finished)
|
||||
|
||||
ready_waiter = asyncio.create_task(flow.authorization_ready.wait())
|
||||
try:
|
||||
@@ -287,11 +323,21 @@ class McpOAuthManager:
|
||||
flow.error = "MCP authorization timed out."
|
||||
raise _OAuthCallbackError(flow.error) from exc
|
||||
|
||||
@staticmethod
|
||||
async def _close_connections(connections: dict[str, MCPConnection]) -> None:
|
||||
for connection in connections.values():
|
||||
with suppress(Exception):
|
||||
await connection.aclose()
|
||||
async def _close_connections(self, connections: dict[str, MCPConnection]) -> None:
|
||||
if not connections:
|
||||
return
|
||||
|
||||
async def close_all() -> None:
|
||||
for connection in connections.values():
|
||||
with suppress(Exception):
|
||||
await connection.aclose()
|
||||
|
||||
# Cancelling/expiring the browser flow must not interrupt a transport
|
||||
# close already in progress. Keep ownership until it actually finishes.
|
||||
cleanup = asyncio.create_task(close_all(), name="mcp-oauth-cleanup")
|
||||
self._cleanup_tasks.add(cleanup)
|
||||
cleanup.add_done_callback(self._cleanup_tasks.discard)
|
||||
await asyncio.shield(cleanup)
|
||||
|
||||
async def _connect(
|
||||
self, flow: _McpOAuthFlow, handlers: MCPOAuthHandlers
|
||||
@@ -406,7 +452,8 @@ class McpOAuthManager:
|
||||
self._states.pop(flow.state, None)
|
||||
task = flow.task
|
||||
if task is not None and not task.done():
|
||||
task.cancel()
|
||||
if not task.cancelling():
|
||||
task.cancel()
|
||||
with suppress(BaseException):
|
||||
await task
|
||||
|
||||
@@ -417,7 +464,7 @@ class McpOAuthManager:
|
||||
continue
|
||||
if flow.state:
|
||||
self._states.pop(flow.state, None)
|
||||
if flow.task is not None and not flow.task.done():
|
||||
if flow.task is not None and not flow.task.done() and not flow.task.cancelling():
|
||||
flow.task.cancel()
|
||||
callback_result = flow.callback_result
|
||||
if callback_result is not None and not callback_result.done():
|
||||
|
||||
@@ -49,6 +49,7 @@ from nanobot.providers.registry import (
|
||||
)
|
||||
from nanobot.providers.request_overrides import isolate_request_overrides
|
||||
from nanobot.providers.routing import resolve_automatic_model_api, resolve_model_api
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.webui import request_settings
|
||||
from nanobot.webui.settings_contracts import (
|
||||
QueryParams,
|
||||
@@ -1724,7 +1725,7 @@ def login_oauth_provider(
|
||||
|
||||
if spec.name == "openai_codex":
|
||||
try:
|
||||
from nanobot.providers.openai_codex_oauth import start_openai_codex_oauth_login
|
||||
from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthLoginFlow
|
||||
except ImportError:
|
||||
raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None
|
||||
|
||||
@@ -1741,19 +1742,21 @@ def login_oauth_provider(
|
||||
if remote_browser_value is not None
|
||||
else False
|
||||
)
|
||||
flow = OpenAICodexOAuthLoginFlow(
|
||||
proxy=proxy,
|
||||
timeout_s=_WEBUI_OAUTH_TIMEOUT_S,
|
||||
open_browser=not remote_browser,
|
||||
)
|
||||
flow_id = secrets.token_urlsafe(24)
|
||||
try:
|
||||
flow = start_openai_codex_oauth_login(
|
||||
proxy=proxy,
|
||||
timeout_s=_WEBUI_OAUTH_TIMEOUT_S,
|
||||
open_browser=not remote_browser,
|
||||
)
|
||||
oauth_flows.register(spec.name, flow_id, flow)
|
||||
flow.start()
|
||||
except Exception as exc:
|
||||
oauth_flows.remove(spec.name, flow_id, flow)
|
||||
raise WebUISettingsError(
|
||||
f"OpenAI Codex OAuth login failed: {exc}",
|
||||
status=502,
|
||||
) from exc
|
||||
flow_id = secrets.token_urlsafe(24)
|
||||
oauth_flows.register(spec.name, flow_id, flow)
|
||||
return {
|
||||
"status": "authorization_required",
|
||||
"provider": spec.name,
|
||||
@@ -1776,8 +1779,8 @@ def login_oauth_provider(
|
||||
flow_id = secrets.token_urlsafe(24)
|
||||
# Own the flow before network I/O, so logout/replacement also cancels a
|
||||
# login that is still waiting for GitHub to return its device prompt.
|
||||
oauth_flows.register(spec.name, flow_id, copilot_flow)
|
||||
try:
|
||||
oauth_flows.register(spec.name, flow_id, copilot_flow)
|
||||
copilot_flow.start()
|
||||
except Exception:
|
||||
oauth_flows.remove(spec.name, flow_id, copilot_flow)
|
||||
@@ -1793,7 +1796,7 @@ def login_oauth_provider(
|
||||
}
|
||||
|
||||
if spec.name == "xai_grok":
|
||||
from nanobot.providers.xai_oauth import start_xai_oauth_login
|
||||
from nanobot.providers.xai_oauth import create_xai_oauth_login
|
||||
|
||||
try:
|
||||
proxy = resolve_config_env_vars(
|
||||
@@ -1803,14 +1806,19 @@ def login_oauth_provider(
|
||||
except ValueError as exc:
|
||||
raise WebUISettingsError(str(exc), status=400) from exc
|
||||
try:
|
||||
flow = start_xai_oauth_login(
|
||||
flow = create_xai_oauth_login(
|
||||
proxy=proxy,
|
||||
timeout_s=_WEBUI_OAUTH_TIMEOUT_S,
|
||||
)
|
||||
except Exception as exc:
|
||||
raise WebUISettingsError(f"xAI OAuth login failed: {exc}", status=502) from exc
|
||||
flow_id = secrets.token_urlsafe(24)
|
||||
oauth_flows.register(spec.name, flow_id, flow)
|
||||
try:
|
||||
oauth_flows.register(spec.name, flow_id, flow)
|
||||
flow.start()
|
||||
except Exception as exc:
|
||||
oauth_flows.remove(spec.name, flow_id, flow)
|
||||
raise WebUISettingsError(f"xAI OAuth login failed: {exc}", status=502) from exc
|
||||
return {
|
||||
"status": "authorization_required",
|
||||
"provider": spec.name,
|
||||
@@ -1850,25 +1858,14 @@ def complete_oauth_provider(
|
||||
|
||||
try:
|
||||
if spec.name == "openai_codex":
|
||||
from nanobot.providers.openai_codex_oauth import (
|
||||
OpenAICodexOAuthInputError,
|
||||
complete_openai_codex_oauth_login,
|
||||
)
|
||||
from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthInputError
|
||||
|
||||
try:
|
||||
token = complete_openai_codex_oauth_login(flow, authorization_response)
|
||||
token = flow.complete(authorization_response)
|
||||
except OpenAICodexOAuthInputError as exc:
|
||||
raise WebUISettingsError(str(exc), status=400) from exc
|
||||
elif spec.name == "github_copilot":
|
||||
from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow
|
||||
|
||||
if not isinstance(flow, GitHubCopilotOAuthFlow):
|
||||
raise WebUISettingsError("Invalid GitHub sign-in session. Start again.")
|
||||
token = flow.complete()
|
||||
else:
|
||||
from nanobot.providers.xai_oauth import complete_xai_oauth_login
|
||||
|
||||
token = complete_xai_oauth_login(flow, authorization_response)
|
||||
token = flow.complete(authorization_response)
|
||||
except WebUISettingsError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
@@ -1941,9 +1938,26 @@ def logout_oauth_provider(
|
||||
class ModelSettingsHandler:
|
||||
"""Handle model/provider commands after transport authentication and decoding."""
|
||||
|
||||
def __init__(self, settings: WebUISettingsServices, logger: Any) -> None:
|
||||
def __init__(
|
||||
self, settings: WebUISettingsServices, logger: Any, admission: RuntimeAdmission,
|
||||
) -> None:
|
||||
self.settings = settings
|
||||
self.logger = logger
|
||||
self._admission = admission
|
||||
self._remove_pending_work: Callable[[], None] | None = None
|
||||
self._close_task: asyncio.Task[None] | None = None
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Keep the registry owned even if its shutdown awaiter is cancelled."""
|
||||
if self._close_task is None or self._close_task.done():
|
||||
self._close_task = asyncio.create_task(asyncio.to_thread(self.settings.oauth_flows.close))
|
||||
self._close_task.add_done_callback(
|
||||
lambda task: task.exception() if not task.cancelled() else None,
|
||||
)
|
||||
await asyncio.shield(self._close_task)
|
||||
if self._remove_pending_work is not None:
|
||||
self._remove_pending_work()
|
||||
self._remove_pending_work = None
|
||||
|
||||
def _refresh_runtime_config(self) -> None:
|
||||
"""Make a successful model-settings mutation visible to live clients now."""
|
||||
@@ -1956,6 +1970,12 @@ class ModelSettingsHandler:
|
||||
request: SettingsRequest,
|
||||
operations: ModelSettingsOperations,
|
||||
) -> SettingsRouteResult:
|
||||
if action in {"oauth-login", "oauth-complete", "oauth-logout"}:
|
||||
self._admission.check()
|
||||
if self._remove_pending_work is None:
|
||||
self._remove_pending_work = self._admission.register_pending_work(
|
||||
lambda: self.settings.oauth_flows.has_pending_work,
|
||||
)
|
||||
try:
|
||||
if action == "agent-update":
|
||||
payload = await asyncio.to_thread(
|
||||
|
||||
@@ -146,6 +146,14 @@ _SYSTEM_ROUTES = {
|
||||
"/api/settings/pairing/deny": "pairing-deny",
|
||||
"/api/settings/mcp-presets": "mcp-list",
|
||||
"/api/settings/version-check": "version-check",
|
||||
"/api/settings/nanobot-update/channel": "update-channel",
|
||||
"/api/settings/nanobot-update/plan": "update-plan-read",
|
||||
"/api/settings/nanobot-update/plan/create": "update-plan-create",
|
||||
"/api/settings/nanobot-update/job": "update-job-read",
|
||||
"/api/settings/nanobot-update/job/prepare": "update-job-prepare",
|
||||
"/api/settings/nanobot-update/job/settle": "update-job-settle",
|
||||
"/api/settings/nanobot-update/job/execute": "update-job-execute",
|
||||
"/api/settings/nanobot-update/job/retry": "update-job-retry",
|
||||
**{
|
||||
path: f"mcp-{action}"
|
||||
for path, action in _MCP_PRESET_ACTIONS_BY_PATH.items()
|
||||
@@ -153,6 +161,12 @@ _SYSTEM_ROUTES = {
|
||||
}
|
||||
|
||||
_SETTINGS_MUTATION_PATHS = frozenset({
|
||||
"/api/settings/nanobot-update/channel",
|
||||
"/api/settings/nanobot-update/plan/create",
|
||||
"/api/settings/nanobot-update/job/prepare",
|
||||
"/api/settings/nanobot-update/job/settle",
|
||||
"/api/settings/nanobot-update/job/execute",
|
||||
"/api/settings/nanobot-update/job/retry",
|
||||
"/api/settings/runtime-config/update",
|
||||
"/api/settings/update",
|
||||
"/api/settings/model-configurations/create",
|
||||
@@ -251,19 +265,21 @@ class WebUISettingsRouter:
|
||||
self._mcp_reload = mcp_reload
|
||||
self._image_generation_reload = image_generation_reload
|
||||
self._mcp_oauth_redirect_uri = mcp_oauth_redirect_uri
|
||||
self._mcp_oauth = McpOAuthManager()
|
||||
self._mcp_oauth = McpOAuthManager(bus.admission)
|
||||
self._restart_sections: set[str] = set()
|
||||
self._restart_baselines: dict[str, dict[str, Any]] = {}
|
||||
self._restart_changes: dict[str, str] = {}
|
||||
self._models = model_domain.ModelSettingsHandler(settings, logger)
|
||||
self._models = model_domain.ModelSettingsHandler(settings, logger, bus.admission)
|
||||
self._capabilities = capability_domain.CapabilitySettingsHandler(
|
||||
settings,
|
||||
logger,
|
||||
)
|
||||
self._system = system_domain.SystemSettingsHandler(settings, logger)
|
||||
self._system = system_domain.SystemSettingsHandler(settings, logger, bus.admission)
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Release state owned by settings domains."""
|
||||
await self._mcp_oauth.close()
|
||||
await self._models.close()
|
||||
await self._system.close()
|
||||
|
||||
async def dispatch(
|
||||
@@ -303,6 +319,8 @@ class WebUISettingsRouter:
|
||||
return await asyncio.to_thread(self._handle_settings_usage)
|
||||
|
||||
domain, action = route
|
||||
if action.startswith("update-") and self._runtime_surface == "native":
|
||||
return self._error_response(409, "Update this installation through Nanobot Desktop.")
|
||||
restart_before = (
|
||||
await asyncio.to_thread(self._restart_values, action)
|
||||
if action in {"runtime-config-update", "image-update", "web-search-update"}
|
||||
@@ -318,6 +336,14 @@ class WebUISettingsRouter:
|
||||
"features-enable",
|
||||
"channel-configure",
|
||||
"channel-connect",
|
||||
"update-channel",
|
||||
"version-check",
|
||||
"update-plan-create",
|
||||
"update-plan-read",
|
||||
"update-job-prepare",
|
||||
"update-job-settle",
|
||||
"update-job-execute",
|
||||
"update-job-retry",
|
||||
}
|
||||
),
|
||||
)
|
||||
@@ -362,7 +388,12 @@ class WebUISettingsRouter:
|
||||
self._restart_changes[action] = result.restart_section
|
||||
# Reversible changes are tracked separately from installation and reload failures.
|
||||
result.payload["requires_restart"] = False
|
||||
return self._render_result(result)
|
||||
response = self._render_result(result)
|
||||
if action.startswith("update-") or action == "version-check":
|
||||
# A saved review is immutable, but its local validity and permission
|
||||
# are not. Never reuse a cached success after an installation changes.
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
def _restart_values(self, action: str) -> dict[str, Any]:
|
||||
config = self.settings.config.load()
|
||||
|
||||
@@ -6,7 +6,7 @@ import threading
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, TypeVar
|
||||
from typing import Any, Protocol, TypeVar
|
||||
|
||||
from filelock import FileLock
|
||||
|
||||
@@ -46,30 +46,90 @@ class WebUISettingsConfig:
|
||||
return operation(self.path)
|
||||
|
||||
|
||||
class WebUIOAuthToken(Protocol):
|
||||
@property
|
||||
def access(self) -> str: ...
|
||||
|
||||
|
||||
class WebUIOAuthFlow(Protocol):
|
||||
"""Provider flow whose cancellation and actual worker exit are separate."""
|
||||
|
||||
@property
|
||||
def expired(self) -> bool: ...
|
||||
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
"""A nonblocking observation of live workers, including cleanup."""
|
||||
...
|
||||
|
||||
def complete(self, response: str | None = None, /) -> WebUIOAuthToken | None: ...
|
||||
def cancel(self) -> None: ...
|
||||
def wait_closed(self) -> None:
|
||||
"""Return only after the cancelled flow's workers have actually exited."""
|
||||
...
|
||||
|
||||
|
||||
class WebUIOAuthFlowRegistry:
|
||||
"""Bounded, thread-safe OAuth flows owned by one gateway instance."""
|
||||
"""Bounded, thread-safe OAuth ownership, including removed flows still stopping."""
|
||||
|
||||
def __init__(self, *, max_flows: int = _WEBUI_OAUTH_MAX_FLOWS) -> None:
|
||||
if max_flows < 1:
|
||||
raise ValueError("max_flows must be at least one")
|
||||
self._max_flows = max_flows
|
||||
self._flows: dict[str, tuple[str, Any]] = {}
|
||||
self._flows: dict[str, tuple[str, WebUIOAuthFlow]] = {}
|
||||
self._retiring: dict[int, tuple[str, WebUIOAuthFlow]] = {}
|
||||
self._cancelling: set[int] = set()
|
||||
self._lock = threading.Lock()
|
||||
self._closed = False
|
||||
self._closing = False
|
||||
|
||||
def register(self, provider_name: str, flow_id: str, flow: Any) -> None:
|
||||
discarded: list[Any] = []
|
||||
@property
|
||||
def has_pending_work(self) -> bool:
|
||||
with self._lock:
|
||||
for existing_id, (_provider_name, existing) in list(self._flows.items()):
|
||||
if existing.expired:
|
||||
discarded.append(self._flows.pop(existing_id)[1])
|
||||
while len(self._flows) >= self._max_flows:
|
||||
oldest_id = next(iter(self._flows))
|
||||
discarded.append(self._flows.pop(oldest_id)[1])
|
||||
self._flows[flow_id] = (provider_name, flow)
|
||||
for existing in discarded:
|
||||
existing.cancel()
|
||||
return self._closing or bool(self._cancelling) or any(
|
||||
flow.has_pending_work
|
||||
for _provider, flow in (*self._flows.values(), *self._retiring.values())
|
||||
)
|
||||
|
||||
def get(self, provider_name: str, flow_id: str) -> Any | None:
|
||||
def _retire_locked(self, flow_id: str, *, cancel: bool = True) -> WebUIOAuthFlow:
|
||||
registered = self._flows.pop(flow_id)
|
||||
self._retiring[id(registered[1])] = registered
|
||||
if cancel:
|
||||
self._cancelling.add(id(registered[1]))
|
||||
return registered[1]
|
||||
|
||||
def _cancel(self, flow: WebUIOAuthFlow) -> None:
|
||||
flow.cancel()
|
||||
with self._lock:
|
||||
self._cancelling.discard(id(flow))
|
||||
|
||||
def register(self, provider_name: str, flow_id: str, flow: WebUIOAuthFlow) -> None:
|
||||
"""Register before start; reject capacity rather than losing a live worker."""
|
||||
discarded: list[WebUIOAuthFlow] = []
|
||||
with self._lock:
|
||||
if self._closed:
|
||||
raise RuntimeError("OAuth sign-in is closing. Reconnect before starting again.")
|
||||
for existing_id, (_provider_name, existing) in list(self._flows.items()):
|
||||
if existing.expired or existing_id == flow_id:
|
||||
discarded.append(self._retire_locked(existing_id))
|
||||
if len(self._flows) >= self._max_flows:
|
||||
oldest_id = next(iter(self._flows))
|
||||
discarded.append(self._retire_locked(oldest_id))
|
||||
# Never hold the registry lock while a provider waits for its commit lock.
|
||||
for existing in discarded:
|
||||
self._cancel(existing)
|
||||
with self._lock:
|
||||
self._retiring = {
|
||||
key: value for key, value in self._retiring.items()
|
||||
if key in self._cancelling or value[1].has_pending_work
|
||||
}
|
||||
if self._closed:
|
||||
raise RuntimeError("OAuth sign-in is closing. Reconnect before starting again.")
|
||||
if len(self._flows) + len(self._retiring) >= self._max_flows:
|
||||
raise RuntimeError("Previous sign-ins are still stopping. Try again shortly.")
|
||||
self._flows[flow_id] = (provider_name, flow)
|
||||
|
||||
def get(self, provider_name: str, flow_id: str) -> WebUIOAuthFlow | None:
|
||||
with self._lock:
|
||||
registered = self._flows.get(flow_id)
|
||||
if registered is None or registered[0] != provider_name:
|
||||
@@ -77,15 +137,15 @@ class WebUIOAuthFlowRegistry:
|
||||
flow = registered[1]
|
||||
if not flow.expired:
|
||||
return flow
|
||||
self._flows.pop(flow_id, None)
|
||||
flow.cancel()
|
||||
self._retire_locked(flow_id)
|
||||
self._cancel(flow)
|
||||
return None
|
||||
|
||||
def remove(
|
||||
self,
|
||||
provider_name: str,
|
||||
flow_id: str,
|
||||
flow: Any,
|
||||
flow: WebUIOAuthFlow,
|
||||
*,
|
||||
cancel: bool = True,
|
||||
) -> None:
|
||||
@@ -96,9 +156,9 @@ class WebUIOAuthFlowRegistry:
|
||||
and registered[0] == provider_name
|
||||
and registered[1] is flow
|
||||
):
|
||||
self._flows.pop(flow_id)
|
||||
self._retire_locked(flow_id, cancel=cancel)
|
||||
if cancel:
|
||||
flow.cancel()
|
||||
self._cancel(flow)
|
||||
|
||||
def clear(self, provider_name: str) -> None:
|
||||
with self._lock:
|
||||
@@ -107,9 +167,29 @@ class WebUIOAuthFlowRegistry:
|
||||
for flow_id, (registered_provider, _flow) in self._flows.items()
|
||||
if registered_provider == provider_name
|
||||
]
|
||||
flows = [self._flows.pop(flow_id)[1] for flow_id in flow_ids]
|
||||
for flow_id in flow_ids:
|
||||
self._retire_locked(flow_id)
|
||||
flows = [
|
||||
flow for provider, flow in self._retiring.values() if provider == provider_name
|
||||
]
|
||||
for flow in flows:
|
||||
flow.cancel()
|
||||
self._cancel(flow)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Cancel and join all owned workers; failure retains ownership for retry."""
|
||||
with self._lock:
|
||||
self._closed = True
|
||||
self._closing = True
|
||||
for flow_id in tuple(self._flows):
|
||||
self._retire_locked(flow_id)
|
||||
flows = [flow for _provider, flow in self._retiring.values()]
|
||||
for flow in flows:
|
||||
self._cancel(flow)
|
||||
for flow in flows:
|
||||
flow.wait_closed()
|
||||
with self._lock:
|
||||
self._retiring.clear()
|
||||
self._closing = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -7,6 +7,7 @@ import inspect
|
||||
import json
|
||||
import platform
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass
|
||||
@@ -14,11 +15,13 @@ from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TypedDict, cast
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import httpx
|
||||
from pydantic import ValidationError
|
||||
from pydantic.alias_generators import to_snake
|
||||
|
||||
from nanobot.build_info import COMMIT
|
||||
from nanobot.channels._setup import channel_setup_spec
|
||||
from nanobot.channels.connect import ChannelConnectError
|
||||
from nanobot.channels.connect import ChannelConnectError, ChannelConnector, ManagedChannelConnector
|
||||
from nanobot.channels.contracts import (
|
||||
RouteFieldType,
|
||||
channel_instance_config,
|
||||
@@ -27,7 +30,26 @@ from nanobot.channels.contracts import (
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.llm_usage import llm_usage_payload
|
||||
from nanobot.optional_features import OptionalFeatureError, with_channel_runtime_status
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.security.workspace_access import workspace_sandbox_status
|
||||
from nanobot.update_channel import UpdateChannelRequest
|
||||
from nanobot.update_guidance import installation_method
|
||||
from nanobot.update_jobs import UpdateJobNotFoundError, read_update_job
|
||||
from nanobot.update_plan import (
|
||||
UpdatePlan,
|
||||
UpdatePlanNotFoundError,
|
||||
UpdatePlanRequest,
|
||||
inspect_update_installation,
|
||||
preview_release_update,
|
||||
read_release_plan,
|
||||
review_plan,
|
||||
)
|
||||
from nanobot.update_service import (
|
||||
UpdateExecutionRequest,
|
||||
UpdateJobRequest,
|
||||
UpdateJobService,
|
||||
UpdateRetryRequest,
|
||||
)
|
||||
from nanobot.webui.settings_capabilities import network_safety_payload
|
||||
from nanobot.webui.settings_contracts import (
|
||||
QueryParams,
|
||||
@@ -40,9 +62,10 @@ from nanobot.webui.settings_contracts import (
|
||||
from nanobot.webui.settings_runtime import runtime_config_payload
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
from nanobot.webui.settings_services import WebUISettingsServices
|
||||
|
||||
LoadChannelPlugin = Callable[[str], Any]
|
||||
LoadChannelPlugin = Callable[[str], "ChannelPlugin"]
|
||||
ListPendingPairings = Callable[[], Iterable[dict[str, Any]]]
|
||||
SettingsOperation = Callable[..., Any]
|
||||
|
||||
@@ -424,28 +447,53 @@ def pairing_payload(
|
||||
class SystemSettingsHandler:
|
||||
"""Handle channel and system commands behind a transport-neutral request DTO."""
|
||||
|
||||
def __init__(self, settings: WebUISettingsServices, logger: Any) -> None:
|
||||
def __init__(
|
||||
self, settings: WebUISettingsServices, logger: Any, admission: RuntimeAdmission,
|
||||
) -> None:
|
||||
self.settings = settings
|
||||
self.logger = logger
|
||||
self._channel_connectors: dict[str, Any] = {}
|
||||
self._admission = admission
|
||||
self._channel_connectors: dict[str, ChannelConnector] = {}
|
||||
self._remove_pending_work: Callable[[], None] | None = None
|
||||
self._closing_connectors = False
|
||||
self._update_jobs = UpdateJobService()
|
||||
self._remove_update_work: Callable[[], None] | None = None
|
||||
|
||||
def _has_pending_connectors(self) -> bool:
|
||||
return self._closing_connectors or any(
|
||||
not isinstance(connector, ManagedChannelConnector) or connector.has_pending_work
|
||||
for connector in self._channel_connectors.values()
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Release channel-owned setup sessions during gateway shutdown."""
|
||||
await self._update_jobs.close()
|
||||
if self._remove_update_work is not None:
|
||||
self._remove_update_work()
|
||||
self._remove_update_work = None
|
||||
connectors = tuple(self._channel_connectors.items())
|
||||
self._channel_connectors.clear()
|
||||
for channel_name, connector in connectors:
|
||||
close = getattr(connector, "close", None)
|
||||
if not callable(close):
|
||||
continue
|
||||
try:
|
||||
result = close()
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
except Exception:
|
||||
self.logger.exception(
|
||||
"failed to close {} WebUI connector",
|
||||
channel_name,
|
||||
)
|
||||
self._closing_connectors = True
|
||||
try:
|
||||
for channel_name, connector in connectors:
|
||||
close = getattr(connector, "close", None)
|
||||
if not callable(close):
|
||||
continue
|
||||
try:
|
||||
result = close()
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
if isinstance(connector, ManagedChannelConnector) and not connector.has_pending_work:
|
||||
del self._channel_connectors[channel_name]
|
||||
except Exception:
|
||||
self.logger.exception(
|
||||
"failed to close {} WebUI connector",
|
||||
channel_name,
|
||||
)
|
||||
if not self._channel_connectors and self._remove_pending_work is not None:
|
||||
self._remove_pending_work()
|
||||
self._remove_pending_work = None
|
||||
finally:
|
||||
self._closing_connectors = False
|
||||
|
||||
async def handle(
|
||||
self,
|
||||
@@ -516,9 +564,122 @@ class SystemSettingsHandler:
|
||||
operations,
|
||||
)
|
||||
if action == "version-check":
|
||||
return await self._version_check(operations)
|
||||
return await self._version_check(request, operations)
|
||||
if action == "update-channel":
|
||||
if not self.allow_feature_package_install(request):
|
||||
return SettingsRouteResult.failure(403, "Changing update channels requires package-install permission.")
|
||||
try:
|
||||
options = UpdateChannelRequest.model_validate(request.payload or {})
|
||||
except (ValidationError, ValueError):
|
||||
return SettingsRouteResult.failure(400, "Invalid update channel request")
|
||||
try:
|
||||
self._admission.check()
|
||||
selection = self._update_jobs.change_channel(options)
|
||||
except (RuntimeError, ValueError, OSError, KeyError) as exc:
|
||||
self.logger.warning("could not change update channel ({})", type(exc).__name__)
|
||||
return SettingsRouteResult.failure(409, "Could not change channels. Finish or recover any pending update, then check again.")
|
||||
return SettingsRouteResult.success({"channel": selection.channel, "revision": selection.revision})
|
||||
if action in {"update-plan-create", "update-plan-read"}:
|
||||
return await self._update_plan(request, create=action == "update-plan-create")
|
||||
if action == "update-job-read":
|
||||
return await self._update_job(request)
|
||||
if action in {"update-job-prepare", "update-job-settle"}:
|
||||
return self._update_job_action(request, prepare=action == "update-job-prepare")
|
||||
if action in {"update-job-execute", "update-job-retry"}:
|
||||
return await self._execute_update_job(request, retry=action == "update-job-retry")
|
||||
return SettingsRouteResult.failure(404, "unknown settings action")
|
||||
|
||||
async def _execute_update_job(self, request: SettingsRequest, *, retry: bool) -> SettingsRouteResult:
|
||||
if not self.allow_feature_package_install(request):
|
||||
return SettingsRouteResult.failure(
|
||||
403, "Updating from a remote WebUI is disabled. Use localhost or enable remote package installation.",
|
||||
)
|
||||
try:
|
||||
options = (UpdateRetryRequest if retry else UpdateExecutionRequest).model_validate(request.payload or {})
|
||||
except (ValidationError, ValueError):
|
||||
return SettingsRouteResult.failure(400, "Confirm the saved update plan and its gateway restart.")
|
||||
try:
|
||||
self._admission.check()
|
||||
job = await self._update_jobs.execute(
|
||||
options.id, previous_confirmation_id=options.previous_confirmation_id if isinstance(options, UpdateRetryRequest) else None,
|
||||
)
|
||||
except UpdateJobNotFoundError:
|
||||
return SettingsRouteResult.failure(404, "No saved update job is available. Review and prepare the update first.")
|
||||
except (RuntimeError, ValueError, OSError, KeyError) as exc:
|
||||
self.logger.warning("could not confirm an update handoff ({})", type(exc).__name__)
|
||||
return SettingsRouteResult.failure(409, "Could not confirm this update. Read its saved state before starting a new review.")
|
||||
return SettingsRouteResult.success({"job": job.model_dump(mode="json")})
|
||||
|
||||
def _update_job_action(self, request: SettingsRequest, *, prepare: bool) -> SettingsRouteResult:
|
||||
if not self.allow_feature_package_install(request):
|
||||
return SettingsRouteResult.failure(
|
||||
403, "Preparing updates from a remote WebUI is disabled. Use localhost or enable remote package installation.",
|
||||
)
|
||||
try:
|
||||
options = UpdateJobRequest.model_validate(request.payload or {})
|
||||
except (ValidationError, ValueError):
|
||||
return SettingsRouteResult.failure(400, "Invalid update job request")
|
||||
try:
|
||||
self._admission.check()
|
||||
if prepare:
|
||||
if self._remove_update_work is None:
|
||||
self._remove_update_work = self._admission.register_pending_work(self._update_jobs.has_pending_work)
|
||||
job = self._update_jobs.prepare(options.id)
|
||||
else:
|
||||
job = self._update_jobs.settle(options.id)
|
||||
except (UpdatePlanNotFoundError, UpdateJobNotFoundError):
|
||||
return SettingsRouteResult.failure(404, "This saved update is no longer available. Check again.")
|
||||
except (RuntimeError, ValueError, OSError, KeyError) as exc:
|
||||
self.logger.warning("could not accept an update preparation action ({})", type(exc).__name__)
|
||||
return SettingsRouteResult.failure(409, "Could not accept this preparation action. Read the saved update state before trying again.")
|
||||
return SettingsRouteResult.success({"job": job.model_dump(mode="json")})
|
||||
|
||||
async def _update_job(self, request: SettingsRequest) -> SettingsRouteResult:
|
||||
plan_id = query_first(request.query, "id") or ""
|
||||
try:
|
||||
UpdatePlan.canonical_id(plan_id)
|
||||
except ValueError:
|
||||
return SettingsRouteResult.failure(400, "Invalid update job identifier")
|
||||
try:
|
||||
job = await asyncio.to_thread(read_update_job, plan_id)
|
||||
except UpdateJobNotFoundError:
|
||||
return SettingsRouteResult.failure(404, "No saved update job is available for this installation.")
|
||||
except (ValueError, OSError, KeyError) as exc:
|
||||
self.logger.warning("could not read the gateway's update job ({})", type(exc).__name__)
|
||||
return SettingsRouteResult.failure(409, "Could not read this update's saved state. No recovery action was started.")
|
||||
return SettingsRouteResult.success({"job": job.model_dump(mode="json")})
|
||||
|
||||
async def _update_plan(self, request: SettingsRequest, *, create: bool) -> SettingsRouteResult:
|
||||
plan_id = query_first(request.query, "id") or ""
|
||||
try:
|
||||
options = UpdatePlanRequest.model_validate(request.payload or {}) if create else None
|
||||
if options is None:
|
||||
UpdatePlan.canonical_id(plan_id)
|
||||
except (ValidationError, ValueError):
|
||||
return SettingsRouteResult.failure(400, "Invalid update plan request")
|
||||
try:
|
||||
if options is not None:
|
||||
plan = await preview_release_update(
|
||||
options.channel, restart_running=options.restart_running, extras=options.extras,
|
||||
)
|
||||
review = review_plan(plan, plan.installation)
|
||||
else:
|
||||
review = await read_release_plan(plan_id)
|
||||
except UpdatePlanNotFoundError:
|
||||
return SettingsRouteResult.failure(404, "The update plan is no longer available. Check again.")
|
||||
except (RuntimeError, ValueError, OSError, subprocess.SubprocessError, httpx.HTTPError) as exc:
|
||||
# A parser/subprocess error may contain local configuration or source
|
||||
# credentials. Neither belongs in a remote response.
|
||||
self.logger.warning("could not inspect the gateway's update plan ({})", type(exc).__name__)
|
||||
return SettingsRouteResult.failure(409, "Could not verify an update plan for this installation. No update was started.")
|
||||
return SettingsRouteResult.success({
|
||||
"plan": review.model_dump(mode="json"),
|
||||
"installation_allowed": self.allow_feature_package_install(request),
|
||||
# This exact review is consumed by the durable preparation/handoff
|
||||
# routes, never by the legacy unbound latest-release mutation.
|
||||
"execution_available": review.execution_blocked_reason is None,
|
||||
})
|
||||
|
||||
async def _cli_apps(
|
||||
self,
|
||||
request: SettingsRequest,
|
||||
@@ -883,10 +1044,15 @@ class SystemSettingsHandler:
|
||||
action: str,
|
||||
operations: SystemSettingsOperations,
|
||||
) -> SettingsRouteResult:
|
||||
self._admission.check()
|
||||
try:
|
||||
connector = self._channel_connectors.get(channel_name)
|
||||
if connector is None:
|
||||
plugin = operations.load_channel_plugin(channel_name)
|
||||
if self._remove_pending_work is None:
|
||||
self._remove_pending_work = self._admission.register_pending_work(
|
||||
self._has_pending_connectors,
|
||||
)
|
||||
connector = plugin.load_connector()
|
||||
self._channel_connectors[channel_name] = connector
|
||||
except ImportError:
|
||||
@@ -1055,11 +1221,25 @@ class SystemSettingsHandler:
|
||||
|
||||
async def _version_check(
|
||||
self,
|
||||
request: SettingsRequest,
|
||||
operations: SystemSettingsOperations,
|
||||
) -> SettingsRouteResult:
|
||||
try:
|
||||
update_info = await asyncio.to_thread(operations.check_for_update)
|
||||
except Exception:
|
||||
self.logger.exception("version check failed")
|
||||
except Exception as exc:
|
||||
self.logger.warning("version check failed ({})", type(exc).__name__)
|
||||
return SettingsRouteResult.failure(500, "version check failed")
|
||||
return SettingsRouteResult.success({"updateAvailable": update_info})
|
||||
if query_first(request.query, "channel_status") == "1":
|
||||
try:
|
||||
method = installation_method(await asyncio.to_thread(inspect_update_installation))
|
||||
except (RuntimeError, ValueError, OSError, subprocess.SubprocessError):
|
||||
method = None # Unknown owner must not imply one-click eligibility.
|
||||
return SettingsRouteResult.success({
|
||||
**update_info, "can_change_channel": self.allow_feature_package_install(request),
|
||||
"installation_method": method,
|
||||
})
|
||||
# An older client cannot interpret waiting/withdrawn/unavailable states.
|
||||
# Report a failure rather than converting them to its green "up to date".
|
||||
if update_info["releaseStatus"]["state"] not in {"available", "current", "ahead"}:
|
||||
return SettingsRouteResult.failure(409, "No verified update result is available. Open this gateway's current WebUI to check its release channel.")
|
||||
return SettingsRouteResult.success({"updateAvailable": update_info["updateAvailable"]})
|
||||
@@ -1,58 +1,57 @@
|
||||
"""On-demand version checker for nanobot-ai releases.
|
||||
|
||||
Checks PyPI for newer versions when explicitly requested (no background polling).
|
||||
"""
|
||||
"""Channel-aware discovery using the same verified feed as update planning."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from packaging.version import InvalidVersion, Version
|
||||
from packaging.version import Version
|
||||
|
||||
from nanobot import __version__
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_PYPI_URL = "https://pypi.org/pypi/nanobot-ai/json"
|
||||
_CACHE_TTL_S = 300 # 5 minutes cache to avoid hammering PyPI
|
||||
|
||||
_cache: tuple[float, str | None] = (0.0, None)
|
||||
import nanobot
|
||||
from nanobot.installation_lock import installation_state_dir
|
||||
from nanobot.release_feed import ReleaseFeed, ReleaseFeedError
|
||||
from nanobot.update_channel import read_update_channel
|
||||
|
||||
|
||||
def check_for_update() -> dict[str, Any] | None:
|
||||
"""Check PyPI for a newer version. Returns update info dict or None if up-to-date.
|
||||
|
||||
Uses a short cache to avoid repeated requests within the TTL window.
|
||||
This is a blocking call — invoke from a thread or background task.
|
||||
"""
|
||||
global _cache
|
||||
now = time.monotonic()
|
||||
cached_at, cached_val = _cache
|
||||
if now - cached_at < _CACHE_TTL_S and cached_val is not None:
|
||||
latest = cached_val
|
||||
else:
|
||||
try:
|
||||
resp = httpx.get(_PYPI_URL, timeout=5.0, follow_redirects=True)
|
||||
resp.raise_for_status()
|
||||
latest = resp.json().get("info", {}).get("version")
|
||||
except Exception:
|
||||
logger.debug("PyPI version check failed", exc_info=True)
|
||||
return None
|
||||
_cache = (now, latest)
|
||||
|
||||
if not isinstance(latest, str) or not latest:
|
||||
return None
|
||||
try:
|
||||
if Version(latest) <= Version(__version__):
|
||||
return None
|
||||
except InvalidVersion:
|
||||
logger.debug("PyPI returned an invalid nanobot version: %r", latest)
|
||||
return None
|
||||
return {
|
||||
"currentVersion": __version__,
|
||||
"latestVersion": latest,
|
||||
"pypiUrl": "https://pypi.org/project/nanobot-ai/",
|
||||
async def _check() -> dict[str, Any]:
|
||||
selection = read_update_channel()
|
||||
current = nanobot.__version__
|
||||
status: dict[str, Any] = {
|
||||
"channel": selection.channel, "revision": selection.revision,
|
||||
"currentVersion": current, "state": "unavailable",
|
||||
}
|
||||
result: dict[str, Any] = {"updateAvailable": None, "releaseStatus": status}
|
||||
try:
|
||||
async with ReleaseFeed(installation_state_dir() / "releases") as feed:
|
||||
target, withdrawn = await feed.discover(selection.channel, current)
|
||||
if target is not None and Version(target.version) > Version(current):
|
||||
result["updateAvailable"] = {
|
||||
"currentVersion": current, "latestVersion": target.version,
|
||||
"releaseUrl": f"https://github.com/HKUDS/nanobot/releases/tag/v{target.version}",
|
||||
}
|
||||
status["state"] = "available"
|
||||
elif target is not None:
|
||||
status["state"] = (
|
||||
"waiting_stable" if selection.channel == "stable" and Version(current).is_prerelease
|
||||
else "ahead" if Version(current) > Version(target.version) else "current"
|
||||
)
|
||||
if withdrawn:
|
||||
status["state"] = "withdrawn"
|
||||
except ReleaseFeedError as exc:
|
||||
# This concerns the candidate, not necessarily the installed version.
|
||||
status["state"] = "unavailable" if exc.code == "withdrawn" else exc.code
|
||||
except (httpx.HTTPError, ValueError, OSError):
|
||||
status["state"] = "unavailable"
|
||||
if read_update_channel() != selection:
|
||||
raise ValueError("Update channel changed while checking; check again")
|
||||
return result
|
||||
|
||||
|
||||
def check_for_update() -> dict[str, Any]:
|
||||
"""Blocking settings adapter. Every check is fresh and never installs.
|
||||
|
||||
The feed's ETag cache guards generations, not availability. Older clients
|
||||
still read updateAvailable; channel status is additive.
|
||||
"""
|
||||
return asyncio.run(_check())
|
||||
@@ -32,6 +32,7 @@ from nanobot.command.builtin import builtin_command_palette
|
||||
from nanobot.cron.binding import CronBindingError, binding_revision
|
||||
from nanobot.cron.session_turns import is_bound_cron_job
|
||||
from nanobot.cron.types import CronJob, CronSchedule
|
||||
from nanobot.runtime_admission import RuntimeMaintenanceError
|
||||
from nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeError
|
||||
from nanobot.session.display_history import HistoryReader
|
||||
from nanobot.session.manager import SessionManager
|
||||
@@ -222,6 +223,12 @@ _WEBUI_MUTATION_PATHS = {
|
||||
"settings.cli_app.test": "/api/settings/cli-apps/test",
|
||||
"settings.feature.enable": "/api/settings/nanobot-features/enable",
|
||||
"settings.feature.disable": "/api/settings/nanobot-features/disable",
|
||||
"settings.nanobot.update.channel": "/api/settings/nanobot-update/channel",
|
||||
"settings.nanobot.update.plan": "/api/settings/nanobot-update/plan/create",
|
||||
"settings.nanobot.update.prepare": "/api/settings/nanobot-update/job/prepare",
|
||||
"settings.nanobot.update.settle": "/api/settings/nanobot-update/job/settle",
|
||||
"settings.nanobot.update.execute": "/api/settings/nanobot-update/job/execute",
|
||||
"settings.nanobot.update.retry": "/api/settings/nanobot-update/job/retry",
|
||||
"settings.channel.validate": "/api/settings/channels/validate",
|
||||
"settings.channel.configure": "/api/settings/channels/configure",
|
||||
"settings.pairing.approve": "/api/settings/pairing/approve",
|
||||
@@ -479,8 +486,11 @@ class GatewayHTTPHandler:
|
||||
405,
|
||||
"WebUI mutations require an authenticated WebSocket",
|
||||
)
|
||||
response = await self._dispatch_resolved(connection, request, got)
|
||||
with self.bus.admission.activity():
|
||||
response = await self._dispatch_resolved(connection, request, got)
|
||||
return response
|
||||
except RuntimeMaintenanceError:
|
||||
return _http_error(503, "Gateway update is being verified. Retry shortly.")
|
||||
finally:
|
||||
self._log_slow_http(got, response, started)
|
||||
|
||||
@@ -511,7 +521,13 @@ class GatewayHTTPHandler:
|
||||
setattr(request, "_nanobot_trusted_proxy_authenticated", True)
|
||||
setattr(request, _WEBUI_MUTATION_REQUEST_ATTR, True)
|
||||
setattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, dict(payload))
|
||||
response = await self._dispatch_resolved(connection, request, path)
|
||||
try:
|
||||
# WebUI mutation tasks already survive a disconnected browser. Keep
|
||||
# their async/threaded writes busy until that operation really ends.
|
||||
with self.bus.admission.activity():
|
||||
response = await self._dispatch_resolved(connection, request, path)
|
||||
except RuntimeMaintenanceError:
|
||||
return _http_error(503, "Gateway update is being verified. Retry shortly.")
|
||||
if isinstance(response, Response):
|
||||
return response
|
||||
return _http_error(404, "WebUI mutation action not found")
|
||||
|
||||
Loaded 100 of 216 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user