Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: Enhance grid launch with MCP support and validation

Dev jacob331b5db4ab3b
diff --git a/cli/pnpm-lock.yaml b/cli/pnpm-lock.yaml
index d44f90a84..50f3cc7e8 100644
--- a/cli/pnpm-lock.yaml
+++ b/cli/pnpm-lock.yaml
@@ -23,6 +23,9 @@ importers:
dotenv:
specifier: ^17.2.3
version: 17.4.2
+ werift:
+ specifier: 0.24.4
+ version: 0.24.4
ws:
specifier: ^8.18.0
version: 8.21.3
@@ -363,9 +366,20 @@ packages:
cpu: [x64]
os: [win32]
+ resolution: {integrity: sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==}
+ engines: {node: '>= 8'}
+
+ resolution: {integrity: sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==}
+ engines: {node: '>= 8'}
+
'@jridgewell/[email protected]':
resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}
+ '@leichtgewicht/[email protected]':
+ resolution: {integrity: sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==}
+
resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==}
engines: {node: ^14.21.3 || >=16}
@@ -381,6 +395,53 @@ packages:
'@oxc-project/[email protected]':
resolution: {integrity: sha512-Nm4s/jB+4FpFsPhWGEC4h7rzksesmtnMXomo6rCMcg/b8zLQuOziRgkCS1fxDCXOlJB/6Q8oABOZ/OP6RIPj9A==}
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-cben7oxmQsUGZqotus7yt0srYdncOT6RNWcTQ77T2RFOXejYVYkXadrfePdRcrVpO9K95IRLKKglG2k38jKXuw==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-xd4YN4vpRjkDAQWVfZZkeu12IEND7DOpkqaHSIHxZl1uggUNa9Ju0QxY2jHvDAS9pP0zhRBytg8ifsnGo3V0jw==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-JJXefFshRAuVAjWQo/39bkg1ywc1VaiO44S8RRC+Ykvf/u2KDmYffoDb0ZBPCR5uJy4AGKQhl8mX+Q8ShcWaXQ==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-khuGzHTzNzk4GDlIBEILyIs6Lce0yn0ZBdoI9v93kmNncfZRhD+AQ5ODFqdhvoE8cMJF/JMTQ8yA+t1D14kqCw==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-duRdotlUx9eDZe6QrQpQKl61RbWykCHBCkKayP8V8XdEFwlKHZ8qGGDMyS6Pye7OX7nLFttTTpRkJeet78ckwQ==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-kaL4cNxBpdQE2dKlyZBqz4ygCrwffO+8wfoxTEqM1Z8RadvCeELBRzcv0dzM8aY9azHMwODO5nxU65zXmhToOQ==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-pZ96eD1PptovcWQ/GSmuNFXd/7EQJNlKfDaNCyE2rx3W0v6QFelkzquVqRSRyyDXXCYD69ZXJDzZ8GhIiQzKoA==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-ehQXbpQaQYycgu8OrvigwSPTFfVRcu0ECNYCWw+yzBp02Lw5paRqzzhUpfOgO2K38+WfFZuEz/0RPtam5g0OMg==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-CxhBo/RdEbMMob7T31ZdQjGuoyRFLVwrDzTn25bihzBasRg9kRm/0IxIPvhgQtcK/9dNcO1XQL2fuPugwELL0Q==}
+ engines: {node: '>=14'}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==}
+ engines: {node: '>=20.0.0'}
+
'@rolldown/[email protected]':
resolution: {integrity: sha512-EypzgnYCwyVY4NDHKzGmNJT5b+XaQEBniHxsMdeIQLB/tcCzZnhqrzHpZFbX9iaxx+5RiB8caATBtfvZP7zVxQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -480,6 +541,10 @@ packages:
'@rolldown/[email protected]':
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
+ '@shinyoshiaki/[email protected]':
+ resolution: {integrity: sha512-7HDb/fQAop2bCmvDIzU5+69i+UJaFgIVp99h1VzK1mpg1JwSODOkjbqD7ilTYnqlnadF8C4XjpwpepxDsGY6+w==}
+ engines: {node: '>=6'}
+
'@standard-schema/[email protected]':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
@@ -489,6 +554,12 @@ packages:
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==}
+
resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}
@@ -527,10 +598,20 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==}
+ resolution: {integrity: sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==}
+ engines: {node: '>=12.0.0'}
+
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
+
+ resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}
+
resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
engines: {node: '>=18'}
@@ -542,10 +623,23 @@ packages:
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+ resolution: {integrity: sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==}
+ engines: {node: '>=6.0'}
+ peerDependencies:
+ supports-color: '*'
+ peerDependenciesMeta:
+ supports-color:
+ optional: true
+
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}
engines: {node: '>=12'}
@@ -584,6 +678,23 @@ packages:
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
+ resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==}
+
+ resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}
+
+ resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==}
+
+ resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
engines: {node: '>= 12.0.0'}
@@ -661,6 +772,16 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-Sb/vI8frRiDPbPUwl3hz0n69NSe9yt4Nydcv5yxi8Rdgk0BgnujEGjZqE+uCTehFbafcqIu6gDAok8ln98dcqg==}
+
+ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
+
+ resolution: {integrity: sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==}
+ hasBin: true
+
resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -684,10 +805,20 @@ packages:
resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==}
engines: {node: ^10 || ^12 || >=14}
+ resolution: {integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==}
+
+ resolution: {integrity: sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==}
+ engines: {node: '>=16.0.0'}
+
resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==}
engines: {node: '>= 14.18.0'}
+ resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==}
+
resolution: {integrity: sha512-g0EtLvBjTUB7jhyV0S/TCup3v/XSVl45vUIGbOGU4QPiyjTenCe4mKuFvW9fEgYmS2Fo42AUssRmNuMziXdrig==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -706,6 +837,9 @@ packages:
resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}
+ resolution: {integrity: sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==}
+
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
@@ -721,11 +855,24 @@ packages:
resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==}
engines: {node: '>=14.0.0'}
+ resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==}
+
+ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
+
resolution: {integrity: sha512-BL5MGkRln6aDYhb0xbQlEAGw743BaZYWdbWtdJOBriYJboKgUUYCadFp2/FpBBZquBC/ezNBn7wMMPx7FDZUDw==}
engines: {node: '>=18.0.0'}
hasBin: true
+ resolution: {integrity: sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==}
+ engines: {node: '>= 6.0.0'}
+
+ resolution: {integrity: sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==}
+
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
engines: {node: '>=14.17'}
@@ -818,6 +965,10 @@ packages:
jsdom:
optional: true
+ resolution: {integrity: sha512-NoROZ11L/ZqAB5ombCB4VBuVNdIZfwI493zlxlIX7BlwfWRy55eDJdtWMC2VX35yBXFaWwA8NtYbmJ8qWtVk9Q==}
+ engines: {node: '>=16'}
+
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
engines: {node: '>=8'}
@@ -996,8 +1147,17 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@fidm/[email protected]': {}
+
+ dependencies:
+ '@fidm/asn1': 1.0.4
+ tweetnacl: 1.0.3
+
'@jridgewell/[email protected]': {}
+ '@leichtgewicht/[email protected]': {}
+
'@noble/[email protected]': {}
@@ -1008,6 +1168,100 @@ snapshots:
'@oxc-project/[email protected]': {}
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/asn1-x509': 2.9.4
+ '@peculiar/asn1-x509-attr': 2.9.4
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/asn1-x509': 2.9.4
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/asn1-x509': 2.9.4
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.9.4
+ '@peculiar/asn1-pkcs8': 2.9.4
+ '@peculiar/asn1-rsa': 2.9.4
+ '@peculiar/asn1-schema': 2.9.4
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/asn1-x509': 2.9.4
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.9.4
+ '@peculiar/asn1-pfx': 2.9.4
+ '@peculiar/asn1-pkcs8': 2.9.4
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/asn1-x509': 2.9.4
+ '@peculiar/asn1-x509-attr': 2.9.4
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/asn1-x509': 2.9.4
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/utils': 2.0.3
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/asn1-x509': 2.9.4
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/utils': 2.0.3
+ asn1js: 3.0.10
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.9.4
+ '@peculiar/asn1-csr': 2.9.4
+ '@peculiar/asn1-ecc': 2.9.4
+ '@peculiar/asn1-pkcs9': 2.9.4
+ '@peculiar/asn1-rsa': 2.9.4
+ '@peculiar/asn1-schema': 2.9.4
+ '@peculiar/asn1-x509': 2.9.4
+ pvtsutils: 1.3.6
+ reflect-metadata: 0.2.2
+ tslib: 2.8.1
+ tsyringe: 4.10.0
+
'@rolldown/[email protected]':
optional: true
@@ -1055,6 +1309,11 @@ snapshots:
'@rolldown/[email protected]': {}
+ '@shinyoshiaki/[email protected]':
+ dependencies:
+ generate-function: 2.3.1
+ is-plain-object: 2.0.4
+
'@standard-schema/[email protected]': {}
@@ -1064,6 +1323,12 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/dom-webcodecs': 0.1.13
+
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
@@ -1115,8 +1380,21 @@ snapshots:
convert-source-map: 2.0.0
tinyrainbow: 3.1.1
+ dependencies:
+ pvtsutils: 1.3.6
+ pvutils: 1.2.0
+ tslib: 2.8.1
+
+
+ dependencies:
+ base64-js: 1.5.1
+ ieee754: 1.2.1
+
@@ -1125,8 +1403,16 @@ snapshots:
+ dependencies:
+ ms: 2.1.3
+
+ dependencies:
+ '@leichtgewicht/ip-codec': 2.0.5
+
@@ -1202,6 +1488,20 @@ snapshots:
optional: true
+ dependencies:
+ is-property: 1.0.2
+
+
+ dependencies:
+ isobject: 3.0.1
+
+
+
optional: true
@@ -1255,6 +1555,18 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.6.0
+ dependencies:
+ '@types/dom-mediacapture-transform': 0.1.12
+ '@types/dom-webcodecs': 0.1.13
+
+
+ dependencies:
+ dns-packet: 5.6.1
+ thunky: 1.1.0
+
@@ -1271,8 +1583,16 @@ snapshots:
picocolors: 1.1.1
source-map-js: 1.2.1
+ dependencies:
+ tslib: 2.8.1
+
+
+
dependencies:
'@oxc-project/types': 0.148.0
@@ -1302,6 +1622,8 @@ snapshots:
+
@@ -1313,12 +1635,22 @@ snapshots:
+
+
dependencies:
esbuild: 0.28.2
optionalDependencies:
fsevents: 2.3.3
+ dependencies:
+ tslib: 1.14.1
+
+
@@ -1363,6 +1695,20 @@ snapshots:
transitivePeerDependencies:
- msw
+ dependencies:
+ '@fidm/x509': 1.2.1
+ '@noble/curves': 1.9.7
+ '@peculiar/x509': 1.14.3
+ '@shinyoshiaki/binary-data': 0.6.1
+ buffer: 6.0.3
+ debug: 4.4.0
+ mediabunny: 1.55.7
+ multicast-dns: 7.2.5
+ tweetnacl: 1.0.3
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
siginfo: 2.0.0
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index f25287096..15bd3ec18 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -48,7 +48,8 @@ import { ENGINE_CLI_COMMANDS, ENGINES, engineBin } from './lib/engineBin.js'
import type { AgentEngine } from './engines/types.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'
-import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames } from './lib/gridLaunch.js'
+import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, gridEnvVarNames, type GridEngineLaunch } from './lib/gridLaunch.js'
+import { HERMES_SYSTEM_MANAGED_DIR } from './lib/gridWebMcp.js'
import { writeGridConfigDir } from './lib/gridConfigDir.js'
import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
@@ -63,6 +64,7 @@ import {
clearPaneRemainOnExit,
resolvePaneEngineProcess,
resolvePaneRootProcess,
+ tmuxPaneEnvironment,
tmuxPaneProcessTree,
tmuxPaneState,
type TmuxPaneState,
@@ -152,7 +154,7 @@ import {
lastCommandCodeTurnText,
} from './engines/commandcode/normalizer.js'
import { probeGatewayRuntime } from './lib/gatewayRuntime.js'
-import { probeGridAssignment } from './lib/gridAssignment.js'
+import { gridAssignmentFromEnv, probeGridAssignment, sameGridAssignment } from './lib/gridAssignment.js'
import { agentFrame, type AgentFrame } from './lib/agentFrame.js'
import { SessionInputController } from './lib/sessionInput.js'
import { adaptSlashCommand } from './lib/goalCommand.js'
@@ -2307,6 +2309,10 @@ async function runForeground(session: AuthSession): Promise<void> {
},
onObserved: async (observed, current) => {
const wasDormant = !current.active
+ // Read BEFORE the update, because the update is what overwrites it. `undefined` means the probe
+ // could not look, which never counts as a move — see `probeGridAssignment`'s three answers.
+ const gridMoved = observed.grid !== undefined
+ && !sameGridAssignment(current.grid ?? null, observed.grid)
registry.updateRuntimes(current.agentId, observed.runtimes, observed.primaryRuntimeKey)
registry.updateProcessIdentity(current.agentId, observed.processIdentity, observed.gateway, observed.grid)
await bindObservedAgent(observed)
@@ -2319,7 +2325,17 @@ async function runForeground(session: AuthSession): Promise<void> {
}
syncRecapPool()
announceSession(active)
+ return
}
+ // An agent that was already awake changed grid under us. Nobody was told: this branch wrote the
+ // new assignment into the registry and stopped, so the app went on drawing the old one until
+ // its own 60s reconciliation tick happened to notice — a minute of an agent's header naming a
+ // grid it had left. The retarget path has always announced (it is the same fact, arriving by a
+ // different door); this is the door an engine's own `exec` comes through, which is what an
+ // install-then-launch does the moment the install finishes.
+ if (!gridMoved) return
+ const refreshed = registry.byAgent(current.agentId)
+ if (refreshed) announceSession(refreshed)
},
onDormant: (agent, reason) => {
if (!agent.active) return
@@ -3011,6 +3027,25 @@ async function runForeground(session: AuthSession): Promise<void> {
* The freshly-exec'd engine process may not be visible to `ps` the instant tmux returns, so one probe
* pass can miss it — retry `triggerHint` a few times with backoff before giving up.
*/
+ /**
+ * The config directory a grid launch should actually be given on THIS machine, or none.
+ *
+ * Only Hermes can lose one. Its web tools ride a managed-scope overlay, and `HERMES_MANAGED_DIR`
+ * REPLACES `/etc/hermes` rather than adding to it — so on a machine where an administrator pinned
+ * Hermes settings there, writing ours would take their policy away for as long as the agent runs.
+ * The agent still launches on the grid; it launches without web tools, which is the smaller loss
+ * and the one that can be said out loud.
+ *
+ * Here rather than in the contract because it is a fact about the machine: a `build()` that
+ * stats the filesystem answers differently on two of them, and its spec would follow.
+ */
+ const gridConfigDirFor = (engine: AgentEngine, launch: GridEngineLaunch): GridEngineLaunch['configDir'] => {
+ if (!launch.configDir || engine !== 'hermes' || !existsSync(HERMES_SYSTEM_MANAGED_DIR)) return launch.configDir
+ console.warn(`[grid] ${engine} starts without web tools · ${HERMES_SYSTEM_MANAGED_DIR} pins this `
+ + `machine's Hermes settings, and the overlay carrying the web tools would replace it`)
+ return undefined
+ }
+
backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid }) => {
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
try {
@@ -3043,8 +3078,9 @@ async function runForeground(session: AuthSession): Promise<void> {
gridLaunch = { env: { ...built.launch.env }, args: built.launch.args }
// An engine whose provider lives in a file gets a directory this daemon owns, never the
// user's own dotfiles. The label is unique per creation, so two agents never share one.
- if (built.launch.configDir) {
- const { envVar, files, pointAt } = built.launch.configDir
+ const createConfigDir = gridConfigDirFor(engine, built.launch)
+ if (createConfigDir) {
+ const { envVar, files, pointAt } = createConfigDir
try {
const dir = await writeGridConfigDir(label, files)
// Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.
@@ -3169,17 +3205,22 @@ async function runForeground(session: AuthSession): Promise<void> {
// `routeAgent` branch in registry.ts, which matches on terminal route exactly while an agent has
// no engine session bound. Same agentId, same tile, no flicker.
const placeholder = await resolvePaneRootProcess(spawned.runtime.paneId)
- // The grid, READ off the shell that is about to become the engine — not declared.
+ // The grid, read from TMUX rather than from the shell running the installer.
//
- // That shell already carries everything the launch set, because `tmux new-session -e` put it
- // there before anything ran: it is the same environment the engine will inherit, in a process
- // that exists now. So the ordinary probe answers, and it answers truthfully.
+ // Reading the shell was the obvious move and it does not work on macOS: `ps` refuses to print
+ // the environment of an Apple platform binary, and the pane's own `/bin/zsh` is one. It refuses
+ // by exiting 0 with argv alone, so the probe came back "this agent is on no grid" — a finding,
+ // from a read that never happened — and the app said "own login" over an agent already pointed
+ // at a grid, for the whole length of the install. Linux never showed it: `/proc/<pid>/environ`
+ // answers for any process of your own.
//
- // Skipping this was a real bug, not a purity win. An install runs for a minute, and for that
- // whole minute the app said "own login" over an agent that had already been pointed at a grid
- // — the one moment the user is watching, and the one answer they were owed.
- const placeholderGrid = placeholder
- ? await probeGridAssignment(placeholder, engine, argv.join(' '))
+ // tmux holds the same fact and will say it. `new-session -e` wrote this environment before
+ // anything ran, and it is what the engine inherits at exec — so this is the launch's own
+ // routing, read back, not a note we wrote about what we intended. Discovery replaces it with
+ // the process's answer the moment there is a process anyone is allowed to read.
+ const paneEnv = await tmuxPaneEnvironment(spawned.runtime.paneId)
+ const placeholderGrid = paneEnv
+ ? await gridAssignmentFromEnv(engine, paneEnv, argv.join(' '))
: undefined
const opened = placeholder
? registry.openProcessAgent({
@@ -3435,10 +3476,11 @@ async function runForeground(session: AuthSession): Promise<void> {
const release = acquireTerminalControl(session.agentId)
if (!release) return { ok: false, error: 'AGENT_BUSY' }
const gridEnv: Record<string, string> = built && built.ok ? { ...built.launch.env } : {}
- if (built && built.ok && built.launch.configDir) {
+ const retargetConfigDir = built && built.ok ? gridConfigDirFor(session.engine, built.launch) : undefined
+ if (retargetConfigDir) {
// Keyed on the agent, so moving the same agent between grids rewrites one directory rather
// than leaving a trail of them.
- const { envVar, files, pointAt } = built.launch.configDir
+ const { envVar, files, pointAt } = retargetConfigDir
try {
const dir = await writeGridConfigDir(session.agentId, files)
// Same split as create: a directory for Pi, the file itself for OpenCode.
diff --git a/cli/src/lib/gridAssignment.spec.ts b/cli/src/lib/gridAssignment.spec.ts
index fa63d1e3a..14beaa280 100644
--- a/cli/src/lib/gridAssignment.spec.ts
+++ b/cli/src/lib/gridAssignment.spec.ts
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { assignmentMatches, classifyGridAssignment, probeGridAssignment, readOpencodeGridAssignment, readPiGridAssignment } from './gridAssignment.js'
import { buildGridEngineLaunch, gridCapableEngines, type GridLaunchOverride } from './gridLaunch.js'
+import type { AgentEngine } from '../engines/types.js'
import { clearProcessEnvCache, parsePsEnviron } from './processEnv.js'
const NETWORK_ID = 'grid-3378218621364f16'
@@ -18,6 +19,12 @@ const OVERRIDE: GridLaunchOverride = {
model: 'GLM-4.7-Flash',
}
+/** The same launch with the grid's web tools wired in — see `gridLaunch`'s MCP section. */
+const WITH_MCP: GridLaunchOverride = {
+ ...OVERRIDE,
+ mcpUrl: 'https://api-grid.autonomous.ai/v1/grid/web-mcp/',
+}
+
describe('classifyGridAssignment', () => {
it('reads back what every supported engine was actually launched with', () => {
// The point of the round trip: the probe and the launcher must use the SAME knob per engine, or
@@ -287,3 +294,51 @@ describe('a failed read is not a finding', () => {
expect(classifyGridAssignment('claude', { PATH: '/usr/bin' })).not.toBeUndefined()
})
})
+
+describe('web tools do not disturb the probe', () => {
+ // Wiring MCP adds argv to Codex and a key to OpenCode's config file, and both are things the probe
+ // parses. An agent that IS on a grid reporting as being on none gets pointlessly restarted, so the
+ // round trips above are repeated against the shape a launch with web tools produces.
+ const dirs: string[] = []
+ afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ })
+
+ const classify = (engine: AgentEngine, override: GridLaunchOverride) => {
+ const built = buildGridEngineLaunch(engine, override)
+ if (!built.ok) throw new Error(`${engine}: ${built.detail}`)
+ return classifyGridAssignment(engine, built.launch.env, built.launch.args.join(' '))
+ }
+
+ it('reads a process back identically with the MCP argv in the way', () => {
+ for (const engine of gridCapableEngines()) {
+ if (engine === 'pi' || engine === 'opencode') continue
+ // Compared against the same engine launched WITHOUT web tools rather than a literal, so this
+ // states the invariant — wiring MCP changes nothing the probe reads — in a form that survives
+ // an engine changing which URL shape it wants.
+ expect(classify(engine, WITH_MCP), engine).toEqual(classify(engine, OVERRIDE))
+ expect(classify(engine, WITH_MCP)?.model, engine).toBe('GLM-4.7-Flash')
+ }
+ })
+
+ it('never reads the control plane as the place an agent is running', () => {
+ // Codex is the one at risk: its endpoint comes out of argv, which now also carries
+ // `mcp_servers.grid_web.url=…`. Reading that as the endpoint would report an agent as running on
+ // the control plane, and the app would offer to move it off a grid it is already on.
+ expect(classify('codex', WITH_MCP)?.baseUrl).toBe(RELAY_V1)
+ })
+
+ it("reads OpenCode's config back with the server declared beside the provider", async () => {
+ const built = buildGridEngineLaunch('opencode', WITH_MCP)
+ if (!built.ok) throw new Error(built.detail)
+ const dir = mkdtempSync(join(tmpdir(), 'opencode-grid-mcp-'))
+ dirs.push(dir)
+ for (const file of built.launch.configDir!.files) {
+ writeFileSync(join(dir, file.name), file.content)
+ }
+ const assignment = await readOpencodeGridAssignment({
+ [built.launch.configDir!.envVar]: join(dir, built.launch.configDir!.pointAt!),
+ })
+ expect(assignment).toEqual({ baseUrl: RELAY_V1, model: 'GLM-4.7-Flash' })
+ })
+})
diff --git a/cli/src/lib/gridAssignment.ts b/cli/src/lib/gridAssignment.ts
index 23dc9dece..25dbc9e80 100644
--- a/cli/src/lib/gridAssignment.ts
+++ b/cli/src/lib/gridAssignment.ts
@@ -214,10 +214,40 @@ export async function probeGridAssignment(
): Promise<GridAssignment | null | undefined> {
const processEnv = await readProcessEnv(identity)
if (!processEnv) return undefined
- // The two engines whose provider lives in a file this daemon wrote, rather than in a variable.
- if (engine === 'pi') return await readPiGridAssignment(processEnv, args)
- if (engine === 'opencode') return await readOpencodeGridAssignment(processEnv)
- return classifyGridAssignment(engine, processEnv, args)
+ return await gridAssignmentFromEnv(engine, processEnv, args)
+}
+
+/**
+ * The same classification, over an environment the caller already holds.
+ *
+ * Split out for the one window where no readable process exists yet: between `tmux new-session` and
+ * the engine's `exec`, the pane belongs to `/bin/zsh`, whose environment macOS will not show to
+ * `ps` at all. `tmuxPaneEnvironment` can still say what that pane was given, and this turns it into
+ * the same answer by the same rules — including the two engines whose provider lives in a file
+ * rather than a variable, which is precisely the part a caller would get wrong on its own.
+ *
+ * There is no `undefined` here: the caller decided it could look, and did. Only [probeGridAssignment]
+ * distinguishes "could not read the process".
+ */
+export async function gridAssignmentFromEnv(
+ engine: AgentEngine,
+ env: Record<string, string>,
+ args = '',
+): Promise<GridAssignment | null> {
+ if (engine === 'pi') return await readPiGridAssignment(env, args)
+ if (engine === 'opencode') return await readOpencodeGridAssignment(env)
+ return classifyGridAssignment(engine, env, args)
+}
+
+/**
+ * Do these two describe the same assignment?
+ *
+ * `undefined` is not compared here and must not reach this: it means the probe could not look, which
+ * is never evidence that anything moved. Callers guard on it before asking.
+ */
+export function sameGridAssignment(a: GridAssignment | null, b: GridAssignment | null): boolean {
+ if (a === null || b === null) return a === b
+ return a.baseUrl === b.baseUrl && (a.model ?? null) === (b.model ?? null)
}
/** Is this agent already where `networkId` is served, on `model`? */
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index afae1fdd8..1059800a5 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -12,6 +12,7 @@ import {
type GridLaunchOverride,
} from './gridLaunch.js'
import { ENGINES, type AgentEngine } from '../engines/types.js'
+import { buildEngineLaunchArgv } from './engineLaunch.js'
/** The shape the desktop actually sends, with values read off the live control plane. */
const WIRE = {
@@ -25,6 +26,9 @@ const RELAY = 'https://grid.autonomous.ai/grid-3378218621364f16/relay'
const OVERRIDE: GridLaunchOverride = { ...WIRE }
const WITH_MODEL: GridLaunchOverride = { ...WIRE, model: 'GLM-4.7-Flash' }
+/** The control plane's web-tools mount, trailing slash and all — see `GridLaunchOverride.mcpUrl`. */
+const MCP_URL = 'https://api-grid.autonomous.ai/v1/grid/web-mcp/'
+const WITH_MCP: GridLaunchOverride = { ...WITH_MODEL, mcpUrl: MCP_URL }
function launchOf(engine: AgentEngine, override = WITH_MODEL) {
const built = buildGridEngineLaunch(engine, override)
@@ -113,12 +117,19 @@ describe('the launch each engine gets', () => {
expect(launch.args).toContain('GLM-4.7-Flash')
})
- it('uses the OpenAI-compatible pair for Hermes, which honours the endpoint it is given', () => {
- expect(launchOf('hermes').env).toEqual({
+ it('uses the OpenAI-compatible pair for Hermes, with the model on the command line too', () => {
+ const launch = launchOf('hermes')
+ expect(launch.env).toEqual({
OPENAI_BASE_URL: RELAY_V1,
OPENAI_API_KEY: WIRE.apiKey,
HERMES_INFERENCE_MODEL: 'GLM-4.7-Flash',
})
+ // The variable alone was measured to decide nothing: the pane this daemon opens is hermes'
+ // INTERACTIVE CLI, which reads its model from `-m` then config.yaml and from no environment
+ // tier — and a grid move relaunches it as `hermes --resume <id>`, which puts the model stored
+ // on the session row back unless argv carried an explicit `-m`. The pill read GLM-4.7-Flash
+ // out of the environment while the pane ran the config's DeepSeek-V4-Flash-0731.
+ expect(launch.args).toEqual(['-m', 'GLM-4.7-Flash'])
})
it('does NOT use that pair for opencode, which would not honour it', () => {
@@ -190,6 +201,7 @@ describe('the launch each engine gets', () => {
it('leaves the model to the engine when the user picked none', () => {
expect(launchOf('claude', OVERRIDE).env).not.toHaveProperty('ANTHROPIC_MODEL')
expect(launchOf('hermes', OVERRIDE).env).not.toHaveProperty('HERMES_INFERENCE_MODEL')
+ expect(launchOf('hermes', OVERRIDE).args).toEqual([])
expect(launchOf('grok', OVERRIDE).args).toEqual([])
expect(launchOf('codex', OVERRIDE).args).not.toContain('-m')
})
@@ -238,8 +250,21 @@ describe('gridEnvVarNames', () => {
// an engine's contract gained a variable, and the symptom would be a "cleared" agent still running
// on the grid it was supposedly moved off.
it('names every variable claude is launched with', () => {
+ // GRID_API_KEY among them: the probe asks for a launch with web tools, and moving an agent to
+ // another grid has to take the old grid's MCP credential out of the pane with everything else.
expect(gridEnvVarNames('claude').sort())
- .toEqual(['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL'])
+ .toEqual(['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL', 'GRID_API_KEY'])
+ })
+
+ it("names the scope Hermes' web tools are written into", () => {
+ // Cleared on a retarget like every other variable here. It points at a directory holding one
+ // grid's credential reference; an agent moved to another grid must not keep reading it.
+ expect(gridEnvVarNames('hermes')).toContain('HERMES_MANAGED_DIR')
+ })
+
+ it("names codex's MCP header variable, which no other engine uses", () => {
+ expect(gridEnvVarNames('codex')).toContain('GRID_MCP_AUTHORIZATION')
+ expect(gridEnvVarNames('claude')).not.toContain('GRID_MCP_AUTHORIZATION')
})
it('includes the config-dir pointer for an engine that uses one', () => {
@@ -384,3 +409,121 @@ describe('opencode declares the grid as a provider', () => {
expect(launch().configDir!.pointAt).toBe('opencode.json')
})
})
+
+describe('web tools (grid ADR 0041)', () => {
+ const claudeMcpJson = (override = WITH_MCP) => {
+ const args = launchOf('claude', override).args
+ const at = args.indexOf('--mcp-config')
+ expect(at, 'claude was not given --mcp-config').toBeGreaterThanOrEqual(0)
+ return JSON.parse(args[at + 1] as string)
+ }
+ const codexArg = (key: string, override = WITH_MCP): string | undefined => {
+ const args = launchOf('codex', override).args
+ return args.find((arg) => arg.startsWith(`${key}=`))
+ }
+ const opencodeConfig = (override = WITH_MCP) =>
+ JSON.parse(launchOf('opencode', override).configDir!.files[0]!.content)
+
+ it('accepts the desktop payload carrying an MCP url', () => {
+ expect(parseGridLaunchOverride({ ...WIRE, mcpUrl: MCP_URL }))
+ .toEqual({ state: 'ok', override: { ...OVERRIDE, mcpUrl: MCP_URL } })
+ })
+
+ it('refuses an mcpUrl that is not an http(s) address', () => {
+ for (const mcpUrl of ['api-grid.autonomous.ai/v1/grid/web-mcp/', 'file:///etc/passwd', '']) {
+ expect(parseGridLaunchOverride({ ...WIRE, mcpUrl }).state, mcpUrl).toBe('invalid')
+ }
+ })
+
+ it('hands Claude Code the server as a --mcp-config JSON string', () => {
+ expect(claudeMcpJson().mcpServers['grid-web'])
+ .toEqual({ type: 'http', url: MCP_URL, headers: { Authorization: 'Bearer ${GRID_API_KEY}' } })
+ })
+
+ it('leaves the user their own MCP servers', () => {
+ // --strict-mcp-config would drop every server they configured for themselves. A grid adds web
+ // tools; it does not take an agent's own tools away.
+ expect(launchOf('claude', WITH_MCP).args).not.toContain('--strict-mcp-config')
+ })
+
+ it("points Codex at it through env_http_headers, which carries the WHOLE header value", () => {
+ expect(codexArg('mcp_servers.grid_web.url')).toBe(`mcp_servers.grid_web.url="${MCP_URL}"`)
+ expect(codexArg('mcp_servers.grid_web.env_http_headers.Authorization'))
+ .toBe('mcp_servers.grid_web.env_http_headers.Authorization="GRID_MCP_AUTHORIZATION"')
+ // Bearer included — `bearer_token_env_var` takes a bare token, this one does not, and ADR 0041
+ // D-d calls confusing the two a silent 401.
+ expect(launchOf('codex', WITH_MCP).env.GRID_MCP_AUTHORIZATION).toBe(`Bearer ${WIRE.apiKey}`)
+ })
+
+ it('declares it in the config file opencode already gets', () => {
+ expect(opencodeConfig().mcp['grid-web'])
+ .toEqual({
+ type: 'remote',
+ url: MCP_URL,
+ enabled: true,
+ headers: { Authorization: 'Bearer {env:GRID_API_KEY}' },
+ })
+ })
+
+ it('gives Hermes a managed-scope overlay, since it takes no flag for MCP', () => {
+ const dir = launchOf('hermes', WITH_MCP).configDir
+ expect(dir?.envVar).toBe('HERMES_MANAGED_DIR')
+ // The directory itself, like Pi — Hermes reads `config.yaml` out of the scope it is handed.
+ expect(dir?.pointAt).toBeUndefined()
+ const file = dir?.files.find((f) => f.name === 'config.yaml')
+ expect(file, 'hermes was given no config.yaml').toBeDefined()
+ // Emitted as JSON on purpose: it is a subset of YAML, and Hermes parses this with a YAML loader.
+ expect(JSON.parse(file!.content)).toEqual({
+ mcp_servers: {
+ 'grid-web': {
+ url: MCP_URL,
+ headers: { Authorization: 'Bearer ${GRID_API_KEY}' },
+ },
+ },
+ })
+ })
+
+ it("merges into the user's Hermes config rather than replacing it", () => {
+ // `_deep_merge` recurses dict-over-dict, so pinning one server under `mcp_servers` keeps every
+ // server they configured for themselves. Nothing outside that key may appear here — a second
+ // top-level key would pin a setting of theirs that nobody asked us to pin.
+ const file = launchOf('hermes', WITH_MCP).configDir!.files[0]!
+ expect(Object.keys(JSON.parse(file.content))).toEqual(['mcp_servers'])
+ })
+
+ it('never writes the key to disk or to an argv', () => {
+ for (const engine of ['claude', 'codex', 'opencode', 'hermes'] as const) {
+ const launch = launchOf(engine, WITH_MCP)
+ for (const arg of launch.args) expect(arg, `${engine} argv`).not.toContain(WIRE.apiKey)
+ for (const file of launch.configDir?.files ?? []) {
+ expect(file.content, `${engine} ${file.name}`).not.toContain(WIRE.apiKey)
+ }
+ // It reaches the engine the one way this module allows.
+ expect(Object.values(launch.env).some((value) => value.includes(WIRE.apiKey))).toBe(true)
+ }
+ })
+
+ it('survives the interactive-shell wrapper the pane actually launches through', () => {
+ // The one that would be catastrophic to get wrong. An engine is started as
+ // `zsh -lic 'unset …; exec "$@"' harness-engine <engine> …`, and if that shell were to expand
+ // the argument, `${GRID_API_KEY}` would become the key — in a command line `ps` shows to every
+ // user on the machine. `exec "$@"` passes positionals through untouched, which is what keeps
+ // the reference a reference; this pins it against a future change to the wrapper.
+ const launch = launchOf('claude', WITH_MCP)
+ const argv = buildEngineLaunchArgv('claude', { extraArgs: launch.args })
+ expect(argv.join(' ')).toContain('Bearer ${GRID_API_KEY}')
+ expect(argv.join(' ')).not.toContain(WIRE.apiKey)
+ })
+
+ it('adds nothing at all when the desktop sends no mcpUrl', () => {
+ // An older desktop, and the no-regression promise: the launch is byte-for-byte what it was.
+ expect(launchOf('claude', WITH_MODEL).args).toEqual([])
+ expect(launchOf('claude', WITH_MODEL).env.GRID_API_KEY).toBeUndefined()
+ expect(codexArg('mcp_servers.grid_web.url', WITH_MODEL)).toBeUndefined()
+ expect(launchOf('codex', WITH_MODEL).env.GRID_MCP_AUTHORIZATION).toBeUndefined()
+ expect(opencodeConfig(WITH_MODEL).mcp).toBeUndefined()
+ // Hermes had no config directory at all before web tools, so it goes back to having none.
+ expect(launchOf('hermes', WITH_MODEL).configDir).toBeUndefined()
+ expect(launchOf('hermes', WITH_MODEL).env.GRID_API_KEY).toBeUndefined()
+ })
+})
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index e825762a4..6768f9e37 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -40,6 +40,16 @@
import { homedir } from 'node:os'
import { join } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
+import {
+ claudeMcpConfig,
+ codexMcpArgs,
+ GRID_MCP_AUTH_VAR,
+ GRID_MCP_SERVER_NAME,
+ HERMES_MANAGED_CONFIG_FILE,
+ HERMES_MANAGED_DIR_VAR,
+ hermesManagedConfig,
+ mcpAuthorizationHeader,
+} from './gridWebMcp.js'
/** Where Pi keeps the skills the user manages, handed back through our own settings.json. */
function userPiSkillsDir(): string {
@@ -60,6 +70,19 @@ export interface GridLaunchOverride {
apiKey: string
/** Absent means "whatever the engine asks for" — the relay's own default. */
model?: string
+ /**
+ * The grid's web-tools MCP endpoint, on the CONTROL PLANE — `…/v1/grid/web-mcp/`, trailing slash
+ * included, because without it the mount answers 307 and not every client follows one.
+ *
+ * Deliberately not derived here from [baseUrl]. That is the RELAY, and grid ADR 0041 D-a takes the
+ * relay out of this path on purpose: a relay is per-grid, can be asleep, and for a self-hosted grid
+ * is a LAN address a harness may not reach. The control plane's address is also not ours to guess —
+ * it is whichever one the user's Grid CLI is signed into, and this machine may have no Grid session
+ * at all. The desktop knows; this does not.
+ *
+ * Absent means no web tools, which is exactly what an older desktop sends.
+ */
+ mcpUrl?: string
}
export type GridOverrideParse =
@@ -82,6 +105,26 @@ function requiredString(raw: Record<string, unknown>, key: string): string | nul
return trimmed
}
+/**
+ * Why [value] is not an address an engine can be handed, or null when it is one.
+ *
+ * Anything else — a `file:` URL, a bare hostname, a path — would fail inside the engine with an
+ * error naming neither the grid nor this frame. Shared by the two URL fields rather than written
+ * twice, so they cannot drift into disagreeing about what an address is.
+ */
+function urlProblem(field: string, value: string): string | null {
+ let parsed: URL
+ try {
+ parsed = new URL(value)
+ } catch {
+ return `grid ${field} is not a URL`
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ return `grid ${field} must be http(s), got ${parsed.protocol}`
+ }
+ return null
+}
+
/**
* `payload.grid` as a validated override, or the reason it is not one.
*
@@ -103,21 +146,16 @@ export function parseGridLaunchOverride(raw: unknown): GridOverrideParse {
apiKey ? null : 'apiKey',
].filter((name): name is string => name !== null)
if (missing.length) return { state: 'invalid', reason: `grid is missing ${missing.join(', ')}` }
- // An engine is about to be handed this as the address it talks to, so it has to be an address:
- // anything else (a `file:` URL, a bare hostname, a path) would fail inside the engine with an
- // error naming neither the grid nor this frame.
- let parsed: URL
- try {
- parsed = new URL(baseUrl as string)
- } catch {
- return { state: 'invalid', reason: 'grid baseUrl is not a URL' }
- }
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
- return { state: 'invalid', reason: `grid baseUrl must be http(s), got ${parsed.protocol}` }
- }
+ const badBaseUrl = urlProblem('baseUrl', baseUrl as string)
+ if (badBaseUrl) return { state: 'invalid', reason: badBaseUrl }
const hasModel = source.model !== undefined && source.model !== null
const model = hasModel ? requiredString(source, 'model') : undefined
if (hasModel && !model) return { state: 'invalid', reason: 'grid model must be a non-empty string' }
+ const hasMcpUrl = source.mcpUrl !== undefined && source.mcpUrl !== null
+ const mcpUrl = hasMcpUrl ? requiredString(source, 'mcpUrl') : undefined
+ if (hasMcpUrl && !mcpUrl) return { state: 'invalid', reason: 'grid mcpUrl must be a non-empty string' }
+ const badMcpUrl = mcpUrl ? urlProblem('mcpUrl', mcpUrl) : null
+ if (badMcpUrl) return { state: 'invalid', reason: badMcpUrl }
return {
state: 'ok',
override: {
@@ -126,6 +164,7 @@ export function parseGridLaunchOverride(raw: unknown): GridOverrideParse {
baseUrl: baseUrl as string,
apiKey: apiKey as string,
...(model ? { model } : {}),
+ ...(mcpUrl ? { mcpUrl } : {}),
},
}
}
@@ -231,6 +270,20 @@ function opencodeGridConfig(
models,
},
},
+ // The grid's web tools, referencing the key exactly the way `apiKey` above does — opencode's own
+ // `{env:…}`, so this file still contains no credential.
+ ...(override.mcpUrl
+ ? {
+ mcp: {
+ [GRID_MCP_SERVER_NAME]: {
+ type: 'remote',
+ url: override.mcpUrl,
+ enabled: true,
+ headers: { Authorization: `Bearer {env:${GRID_KEY_VAR}}` },
+ },
+ },
+ }
+ : {}),
}, null, 2)}\n`
}
@@ -329,6 +382,8 @@ export const GRID_CONFLICTING_ENV_VARS: readonly string[] = [
'COPILOT_MODEL',
'HERMES_INFERENCE_MODEL',
GRID_KEY_VAR,
+ GRID_MCP_AUTH_VAR,
+ HERMES_MANAGED_DIR_VAR,
]
/**
@@ -413,8 +468,11 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// has no standing to choose a user's model. That reasoning does not carry here: the desktop
// app ASKED, and this is the answer. Left unset when the user picked no model.
...(override.model ? { ANTHROPIC_MODEL: override.model } : {}),
+ // Only when there are web tools to reach: the variable exists to be referenced by the config
+ // below, and setting it otherwise would leave a key in the pane that nothing reads.
+ ...(override.mcpUrl ? { [GRID_KEY_VAR]: override.apiKey } : {}),
},
- args: [],
+ args: override.mcpUrl ? ['--mcp-config', claudeMcpConfig(override.mcpUrl, GRID_KEY_VAR)] : [],
}),
},
@@ -426,7 +484,10 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// The key travels in the environment under `env_key`, never in argv.
codex: {
build: (override) => ({
- env: { [GRID_KEY_VAR]: override.apiKey },
+ env: {
+ [GRID_KEY_VAR]: override.apiKey,
+ ...(override.mcpUrl ? { [GRID_MCP_AUTH_VAR]: mcpAuthorizationHeader(override.apiKey) } : {}),
+ },
args: [
'-c', 'model_provider="grid"',
'-c', 'model_providers.grid.name="Autonomous Grid"',
@@ -436,6 +497,7 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
'-c', 'model_providers.grid.wire_api="responses"',
// The relay streams HTTP SSE, not WebSocket.
'-c', 'model_providers.grid.supports_websockets=false',
+ ...(override.mcpUrl ? codexMcpArgs(override.mcpUrl) : []),
...(override.model ? ['-m', override.model] : []),
],
}),
@@ -490,15 +552,55 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
},
// Nous Research's documented trio for a custom OpenAI-compatible endpoint
- // (hermes-agent/website/docs/reference/environment-variables.md).
+ // (hermes-agent/website/docs/reference/environment-variables.md) — plus the model on the command
+ // line, which is the only place hermes reads it from in the mode this daemon actually launches.
+ //
+ // `HERMES_INFERENCE_MODEL` is read by `hermes -z` and by the gateway behind `hermes --tui`. The
+ // pane opened here is neither: it is the INTERACTIVE CLI, whose model resolution is `-m` then
+ // config.yaml and no env tier at all (`cli.py:_init_model_and_provider`, "Priority: CLI args >
+ // env vars > config file" — the env half is about the provider). And a grid move relaunches as
+ // `hermes --resume <id>`, which restores the model stored on the session row unless argv carried
+ // an explicit `-m`; that flag is the documented opt-out ("resume must not clobber an explicit -m
+ // with the session's stored model", `cli.py` / `cli_model_switch_mixin.py`).
+ //
+ // Measured on 2026-09-08 before this line existed: the pane's environment said
+ // `HERMES_INFERENCE_MODEL=GLM-4.7-Flash` — which is what the desktop's model pill read back and
+ // printed — while hermes itself ran DeepSeek-V4-Flash-0731, the default in the user's own
+ // ~/.hermes/config.yaml and the model persisted on the resumed session's row.
+ //
+ // The variable stays beside the flag: `-z`/`--tui` read it, and it is how `gridAssignment.ts`
+ // answers "which model is this agent on" for hermes without parsing a live process's argv.
+ //
+ // ⚠️ The ENDPOINT has no such flag. Hermes's custom-provider resolver deliberately ignores
+ // `OPENAI_BASE_URL` ("config.yaml is the single source of truth for endpoint URLs",
+ // `runtime_provider_backends.py`) and the CLI exposes no `--base-url`, so moving a hermes agent
+ // between grids moves its model but leaves its requests on whatever relay config.yaml names. The
+ // only lever left is `HERMES_HOME`, which would take state.db and the user's skills with it and
+ // break the resume this move depends on.
hermes: {
build: (override) => ({
env: {
OPENAI_BASE_URL: relayBaseUrl(override.baseUrl),
OPENAI_API_KEY: override.apiKey,
...(override.model ? { HERMES_INFERENCE_MODEL: override.model } : {}),
+ // Referenced by the overlay below, so it exists only when there is an overlay to read it.
+ ...(override.mcpUrl ? { [GRID_KEY_VAR]: override.apiKey } : {}),
},
- args: [],
+ args: override.model ? ['-m', override.model] : [],
+ // Hermes reads its MCP servers from one config file and takes no flag for them, so the web
+ // tools arrive as a managed-scope overlay merged over the user's own — see `gridWebMcp.ts`,
+ // including why this is `HERMES_MANAGED_DIR` and not `HERMES_HOME`.
+ ...(override.mcpUrl
+ ? {
+ configDir: {
+ envVar: HERMES_MANAGED_DIR_VAR,
+ files: [{
+ name: HERMES_MANAGED_CONFIG_FILE,
+ content: hermesManagedConfig(override.mcpUrl, GRID_KEY_VAR),
+ }],
+ },
+ }
+ : {}),
}),
},
@@ -617,6 +719,10 @@ const PROBE_OVERRIDE: GridLaunchOverride = {
baseUrl: 'https://example.invalid/probe/relay/v1',
apiKey: 'probe',
model: 'probe',
+ // Present so the probe reports the variables a launch WITH web tools sets. Retarget clears what
+ // this answers, and a probe that left them out would move an agent to another grid while its old
+ // grid's MCP credential stayed in the pane — the exact staleness the doc comment below warns of.
+ mcpUrl: 'https://example.invalid/v1/grid/web-mcp/',
}
/**
diff --git a/cli/src/lib/gridWebMcp.ts b/cli/src/lib/gridWebMcp.ts
new file mode 100644
index 000000000..e5554c817
--- /dev/null
+++ b/cli/src/lib/gridWebMcp.ts
@@ -0,0 +1,157 @@
+/**
+ * The grid's web tools, and how each harness is told where to find them.
+ *
+ * Its own module rather than more of `gridLaunch.ts` because it answers a different question: that
+ * file decides where an agent's INFERENCE goes, this one decides what the agent can reach while it
+ * thinks. They meet only in the engine contracts.
+ *
+ * A grid already pays for web search and already meters it, and grid ADR 0041 mounted it on the
+ * CONTROL PLANE (`/v1/grid/web-mcp`) precisely so a harness can reach it while the grid itself is
+ * asleep. What that ADR could not do is put it in front of an agent nobody configured by hand — so
+ * this does, for an agent the desktop launches onto a grid. The credential is the one already in
+ * `GridLaunchOverride.apiKey`: ADR 0041 D-b asks for the per-grid access token and requires no scope
+ * of it, `consumer` included, which is exactly what the desktop mints.
+ *
+ * The same three harnesses `grid mcp config` prints for, and for the same reason — these are the
+ * ones whose header handling was measured on the wire rather than read off a vendor page. An engine
+ * with no wiring here launches on the grid exactly as it did before, with no web tools.
+ *
+ * ⚠️ **The key still never reaches a file or an argv**, which is `gridLaunch.ts`'s rule and NOT ADR
+ * 0041's. That ADR rejects the environment outright, and it is right about the caller it was written
+ * for: a person pasting a block into their own dotfile has no environment to reference, and a
+ * 365-day token in an interactive shell is readable by every child of it. Here the daemon owns both
+ * ends — the variable exists only in the pane's own environment, put there by `tmux new-session -e`
+ * — and every harness measured offers a reference:
+ *
+ * * Claude Code expands `${VAR}` inside `--mcp-config`, in the JSON-STRING form too, so it needs
+ * no file at all and its argv carries the variable's NAME.
+ * * Codex reads `env_http_headers`, settable entirely through `-c`.
+ * * opencode expands `{env:VAR}` in `headers`, in the config file the launch already writes it.
+ *
+ * Measured 2026-09-08 against a header-logging listener on loopback — Claude Code 2.1.263, Codex
+ * 0.144.6, opencode 1.18.29, the first two being the versions ADR 0041 itself measured. Each sent
+ * `Authorization: Bearer <the variable's value>` on every request, the GET discovery included.
+ */
+
+/**
+ * What the server is called in the harness's own listing — an agent sees
+ * `mcp__grid-web__web_search`.
+ *
+ * ↔ `SERVER_NAME` in autonomous-grid's `cli/mcp_config.py`. Same name on purpose: a person who has
+ * run `grid mcp config` by hand and an agent launched from the desktop should be looking at one
+ * server, not two that do the same thing under different names.
+ */
+export const GRID_MCP_SERVER_NAME = 'grid-web'
+
+/**
+ * Codex's spelling of that name. Its config keys are TOML paths and `-` is not a bare TOML key,
+ * which is why `grid mcp config` prints `[mcp_servers.grid_web]` too.
+ */
+const GRID_MCP_CODEX_KEY = GRID_MCP_SERVER_NAME.replace(/-/g, '_')
+
+/**
+ * The variable Codex reads its header out of.
+ *
+ * Its own rather than the launch's key variable, because `env_http_headers` holds the WHOLE header
+ * value while every other reference here wants the bare key — ADR 0041 D-d calls confusing the two
+ * "a silent 401". `bearer_token_env_var` does take the bare key and would need no second variable;
+ * it is rejected for the reason that ADR gives beside it, that it sends no header at all during
+ * discovery.
+ */
+export const GRID_MCP_AUTH_VAR = 'GRID_MCP_AUTHORIZATION'
+
+/** The header value [GRID_MCP_AUTH_VAR] carries — the whole of it, not the key. */
+export function mcpAuthorizationHeader(apiKey: string): string {
+ return `Bearer ${apiKey}`
+}
+
+/**
+ * Claude Code's `--mcp-config`, as a JSON string rather than a file.
+ *
+ * `${…}` is Claude Code's own expansion, performed when it reads the config, so this names [keyVar]
+ * and never the key itself — and nothing is written to disk. That variable belongs to the launch,
+ * which is why it arrives as an argument rather than being imported: this module is about what an
+ * agent can reach, not about the key it reaches with.
+ *
+ * Deliberately NOT accompanied by `--strict-mcp-config`, which would drop every MCP server the user
+ * configured for themselves. Picking a grid adds web tools; it does not take an agent's own tools
+ * away.
+ */
+export function claudeMcpConfig(mcpUrl: string, keyVar: string): string {
+ return JSON.stringify({
+ mcpServers: {
+ [GRID_MCP_SERVER_NAME]: {
+ type: 'http',
+ url: mcpUrl,
+ headers: { Authorization: `Bearer \${${keyVar}}` },
+ },
+ },
+ })
+}
+
+/**
+ * The same server as Codex `-c` overrides, which is how its provider is configured too — so this
+ * needs no config file either. Values are quoted as JSON because a `-c` value is parsed as TOML.
+ */
+export function codexMcpArgs(mcpUrl: string): string[] {
+ return [
+ '-c', `mcp_servers.${GRID_MCP_CODEX_KEY}.url=${JSON.stringify(mcpUrl)}`,
+ '-c', `mcp_servers.${GRID_MCP_CODEX_KEY}.env_http_headers.Authorization=${JSON.stringify(GRID_MCP_AUTH_VAR)}`,
+ ]
+}
+
+/**
+ * Hermes keeps its MCP servers in one place — `mcp_servers` in `~/.hermes/config.yaml`
+ * (`tools/mcp_tool_config.py`) — and offers no per-invocation flag for them. What it does offer is
+ * a **managed-scope overlay**: `HERMES_MANAGED_DIR` names a directory whose `config.yaml` is
+ * `_deep_merge`d over the user's (`hermes_cli/managed_scope.get_managed_dir`,
+ * `hermes_cli/config._merge_managed_overlay`). That merge recurses dict-over-dict, so pinning
+ * `mcp_servers.grid-web` leaves every server the user configured for themselves in place — the same
+ * promise `--strict-mcp-config`'s absence makes for Claude Code.
+ *
+ * Two things were checked before choosing it over `HERMES_HOME`, which also redirects config:
+ *
+ * * `HERMES_HOME` moves the WHOLE home — `auth.json`, sessions, memory, skills — so an agent
+ * launched under one would come up unauthenticated and amnesiac. That is a far worse trade than
+ * having no web tools.
+ * * A managed DIRECTORY is not a managed INSTALL: `config.get_managed_system()` reads
+ * `HERMES_MANAGED` or a `.managed` marker file and never consults this variable, so nothing here
+ * makes Hermes think a package manager owns it and start refusing its own updates.
+ *
+ * ⚠️ **The overlay REPLACES a system scope rather than adding to it** — `get_managed_dir` prefers
+ * this variable over `/etc/hermes`. On a machine where an administrator pinned settings there, this
+ * directory would silently take their policy away for the agent's lifetime, so the caller drops it
+ * on such a machine and the agent launches without web tools instead. That check belongs where
+ * machine facts are read; see `cli.ts`.
+ *
+ * Emitted as JSON, which is a subset of YAML: Hermes parses this file with a YAML loader, and
+ * hand-rolling YAML quoting for a URL and a `${VAR}` is a way to be subtly wrong for free.
+ */
+export const HERMES_MANAGED_DIR_VAR = 'HERMES_MANAGED_DIR'
+
+/**
+ * Where Hermes looks for a managed scope when [HERMES_MANAGED_DIR_VAR] is unset
+ * (`managed_scope._DEFAULT_MANAGED_DIR`).
+ *
+ * Exported so the caller can see whether an administrator got here first. Not consulted in this
+ * module: a contract that stats the filesystem answers differently on two machines, and its spec
+ * would pass or fail depending on which one ran it.
+ */
+export const HERMES_SYSTEM_MANAGED_DIR = '/etc/hermes'
+
+/** The one file [HERMES_MANAGED_DIR_VAR] is read for. */
+export const HERMES_MANAGED_CONFIG_FILE = 'config.yaml'
+
+/** Hermes' overlay: the grid's web tools, and nothing else. */
+export function hermesManagedConfig(mcpUrl: string, keyVar: string): string {
+ return `${JSON.stringify({
+ mcp_servers: {
+ [GRID_MCP_SERVER_NAME]: {
+ url: mcpUrl,
+ // Hermes interpolates `${VAR}` Cursor-style against the process environment
+ // (`tools/mcp_tool_config._ENV_VAR_PATTERN`), so the key stays out of this file too.
+ headers: { Authorization: `Bearer \${${keyVar}}` },
+ },
+ },
+ }, null, 2)}\n`
+}
diff --git a/cli/src/lib/processEnv.ts b/cli/src/lib/processEnv.ts
index 52ac713e5..4b6be3ae1 100644
--- a/cli/src/lib/processEnv.ts
+++ b/cli/src/lib/processEnv.ts
@@ -52,7 +52,20 @@ function read(pid: number): Promise<Record<string, string> | null> {
}
return new Promise((resolve) => {
execFile('ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {
- resolve(err && !stdout ? null : parsePsEnviron(stdout))
+ if (err && !stdout) { resolve(null); return }
+ const env = parsePsEnviron(stdout)
+ // NO variables at all is macOS refusing to show them, not a process that has none.
+ //
+ // `ps` will not print the environment of an Apple PLATFORM BINARY — `/bin/zsh`, `/bin/bash`,
+ // `/bin/sleep` — to anyone, and it reports that refusal by exiting 0 with argv alone. (The
+ // status travels with the code signature, not the path: a copy of `/bin/zsh` run from
+ // somewhere else is just as opaque.) A real process always has an environment, so an empty
+ // parse here is the read failing, and saying so is what keeps `gateway` and `grid` on
+ // `undefined` — "we could not look" — instead of hardening into the finding "on no grid".
+ //
+ // This is not hypothetical or rare: it is every pane between `tmux new-session` and the
+ // engine's `exec`, which for an engine Harness installs first is the whole install.
+ resolve(Object.keys(env).length > 0 ? env : null)
})
})
}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index f14dc76c2..33904bc2a 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -170,6 +170,33 @@ describe('registry remote display names', () => {
expect(projectDisplayName(retitled!)).toBe('Manual name') // display stays fixed
})
+ it('refuses a pane title that is only the machine\'s own name', async () => {
+ // Hermes titles its terminal with the hostname and leaves it there. Adopted as a name, every
+ // hermes agent on this machine is called the same thing — which is strictly worse than the
+ // folder-and-session default it displaced.
+ const { hostname } = await import('node:os')
+ const transcriptPath = join(dataDir, 'session-host.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+
+ const { registry, projectDisplayName } = await loadRegistryModule()
+ registry.load()
+ const registered = registerProcess(registry, {
+ launcherId: 'h9',
+ sessionId: 'session-host',
+ transcriptPath,
+ tmuxPane: '%9',
+ cwd: '/tmp/demo',
+ title: hostname(),
+ })
+ expect(registered?.entry.title).toBeNull()
+ expect(projectDisplayName(registered!.entry)).toBe('demo \u00b7 sess')
+
+ // The short form is the same machine wearing another name.
+ expect(registry.updateTitle('session-host', hostname().split('.')[0])?.title).toBeNull()
+ // Anything that is genuinely about the conversation still lands.
+ expect(registry.updateTitle('session-host', 'Ship settings page')?.title).toBe('Ship settings page')
+ })
+
it('only adds or updates agent-names.json entries', async () => {
const transcriptPath = join(dataDir, 'session-3.jsonl')
writeFileSync(transcriptPath, '{}\n')
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index ef73f4354..e273c5003 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -32,7 +32,7 @@ import {
import { execFileSync } from 'node:child_process'
import { randomUUID } from 'crypto'
import { join, basename, dirname, relative } from 'path'
-import { uptime } from 'os'
+import { hostname, uptime } from 'os'
import { env } from '../config/env.js'
import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'
import { ENGINES, type AgentEngine } from '../engines/types.js'
@@ -1379,13 +1379,50 @@ function defaultProjectDisplayName(s: RegisteredSession): string {
return `${folder} · ${(s.sessionId || s.agentId).slice(0, 4)}`
}
+/**
+ * The machine's own name, in the forms a terminal title is likely to carry it.
+ *
+ * Computed once: a rename mid-run would at worst let one title through, and reading it per title
+ * would run a syscall for every agent on every title sweep.
+ */
+const SELF_NAMES: ReadonlySet<string> = (() => {
+ const names = new Set<string>()
+ try {
+ const host = hostname().trim().toLowerCase()
+ if (host) {
+ names.add(host)
+ // `MacBookPro2021.local` and `MacBookPro2021` are the same machine wearing two names, and an
+ // engine may print either.
+ const short = host.split('.')[0]
+ if (short) names.add(short)
+ }
+ } catch {
+ // No hostname is not a reason to reject nothing else; the set simply stays empty.
+ }
+ return names
+})()
+
+/**
+ * A pane title, as an agent NAME — or null when the title says nothing about this agent.
+ *
+ * Two rejections, and the second is the interesting one.
+ *
+ * The machine's own name is refused. Hermes sets its terminal title to the hostname and leaves it
+ * there, following the shell convention rather than the conversation one, so every hermes agent on
+ * this Mac was called `MacBookPro2021.local` — in the sidebar, in the pane header, forever, and
+ * identically for every one of them. A name that is the same for every agent on a machine is worse
+ * than no name: `defaultProjectDisplayName` at least says which folder and which session. This is
+ * about the machine, not the engine, so it is refused by what it SAYS rather than by who sent it —
+ * any engine that adopts the same convention is covered without a table to keep in step.
+ */
function titleDisplayName(title: string | null | undefined): string | null {
const cleaned = title
?.trim()
.replace(/^[\s\p{Mark}\p{Punctuation}\p{Symbol}]+/u, '')
.trim()
.slice(0, 80)
- return cleaned || null
+ if (!cleaned) return null
+ return SELF_NAMES.has(cleaned.toLowerCase()) ? null : cleaned
}
function validProcessIdentity(value: unknown): value is ProcessIdentity {
diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.ts
index 57c2f3a5d..94348c903 100644
--- a/cli/src/lib/runtimeProfileController.spec.ts
+++ b/cli/src/lib/runtimeProfileController.spec.ts
@@ -38,6 +38,55 @@ describe('runtime pane parsing', () => {
)).toMatchObject({ idle: true, draft: false })
})
+ it('reads hermes, which italicises its placeholder instead of dimming it', () => {
+ // Copied byte-for-byte off a live pane. Hermes carries no SGR 2 at all: the placeholder is
+ // italic (3) over a 256-colour gold, so a dim-only rule read every hermes pane as holding a
+ // draft — `idle` false for the agent's whole life, and every retarget answered AGENT_BUSY over an
+ // engine sitting at an empty prompt.
+ const placeholder = '❯ \u001b[3m\u001b[38;5;136mAsk anything, or type / for commands…\u001b[0m'
+ expect(inspectRuntimePane('hermes', placeholder)).toMatchObject({ idle: true, draft: false })
+ expect(inspectRuntimePane('hermes', '❯ what changed in this repo')).toMatchObject({ idle: false, draft: true })
+ })
+
+ it('reads opencode past the status strip its own gutter runs through', () => {
+ // The box: three composer rows, then the strip that names the mode, model and account, then the
+ // rule that closes it. Every one of those rows carries the `┃` gutter, so the last-marker rule
+ // landed on the strip and read the BOX describing itself as something the user had typed —
+ // opencode was never idle, and every retarget came back AGENT_BUSY over an empty composer.
+ const box = (composer: readonly string[]) => [
+ ' ▣ Build · DeepSeek-V4-Flash-0731 · 6.0s',
+ '',
+ ...composer.map((line) => ` ┃${line}`),
+ ' ┃ Build · DeepSeek-V4-Flash-0731 autonomous.ai',
+ ' ╹▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀',
+ ' /Users/macbook/Downloads/20260907',
+ ].join('\n')
+
+ expect(inspectRuntimePane('opencode', box(['', '', '']))).toMatchObject({ idle: true, draft: false })
+ // Wrapped text counts wherever in the box it sits: reading only the row above the strip would
+ // call a full composer empty.
+ expect(inspectRuntimePane('opencode', box(['', ' what changed in', ' this repo'])))
+ .toMatchObject({ idle: false, draft: true })
+ // No closing rule is a layout we do not recognise, and then nothing is assumed to be a status
+ // strip — a line the user typed must never be swallowed by a guess about the frame.
+ expect(inspectRuntimePane('opencode', [' ┃', ' ┃ fix the parser'].join('\n')))
+ .toMatchObject({ idle: false, draft: true })
+ // An earlier box still in scrollback is a message already SENT, not a draft.
+ expect(inspectRuntimePane(
+ 'opencode',
+ [box(['', ' LSP là gì thế', '']), 'answer text', box(['', '', ''])].join('\n'),
+ )).toMatchObject({ idle: true, draft: false })
+ })
+
+ it('does not read a truecolor foreground as a dim placeholder', () => {
+ // `38;2;<r>;<g>;<b>` carries a literal 2 that is a colour-space selector, not the dim attribute.
+ // Counting it would make a line the user had TYPED look like an empty composer — the one
+ // direction this must never be wrong in, since the pane would read idle and be respawned under
+ // the draft.
+ expect(inspectRuntimePane('claude', '\u001b[39m❯\u00a0\u001b[38;2;255;170;0mfix the parser\u001b[0m'))
+ .toMatchObject({ idle: false, draft: true })
+ })
+
it('reads devin and pi panes, whose composers look nothing like the others', () => {
// Devin's marker is ❭ (U+276D), not claude's ❯ (U+276F) — reading it as claude's found no prompt at
// all, and a pane with no prompt is never idle, so every switch would have been refused as BUSY.
diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.ts
index 7a53db3c1..1a0997451 100644
--- a/cli/src/lib/runtimeProfileController.ts
+++ b/cli/src/lib/runtimeProfileController.ts
@@ -72,9 +72,49 @@ function stripAnsi(value: string): string {
return value.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '')
}
-function hasDimSgr(value: string): boolean {
+/**
+ * The SGR attributes an escape sequence actually sets, with extended-colour arguments removed.
+ *
+ * `38`/`48`/`58` introduce a colour whose ARGUMENTS are numbers, not attributes: `5;<n>` for 256 and
+ * `2;<r>;<g>;<b>` for truecolor. Without this skip a truecolor foreground (`38;2;…`) reads as SGR 2
+ * — dim — and a line the user had typed would be mistaken for an empty composer, which is the one
+ * direction this must never be wrong in: the pane would read idle and be respawned under a draft.
+ */
+function sgrAttributes(params: readonly string[]): string[] {
+ const attributes: string[] = []
+ for (let index = 0; index < params.length; index += 1) {
+ const code = params[index]
+ if (code !== '38' && code !== '48' && code !== '58') {
+ attributes.push(code)
+ continue
+ }
+ const kind = params[index + 1]
+ index += kind === '5' ? 2 : kind === '2' ? 4 : 1
+ }
+ return attributes
+}
+
+/**
+ * Is the text after the composer marker the PLACEHOLDER, rather than something the user typed?
+ *
+ * Read from the STYLING, never the words: the placeholder sentence differs per engine and changes
+ * between versions, but every one of these TUIs greys its placeholder out somehow and none of them
+ * styles a draft the same way.
+ *
+ * Two attributes, because two are in use. SGR 2 (dim) is what claude, codex and devin draw; SGR 3
+ * (italic) is what hermes draws — its `Ask anything, or type / for commands…` is italic over a
+ * 256-colour gold (`ESC[3m ESC[38;5;136m`) and carries no dim at all. Looking only for dim made
+ * EVERY hermes pane look like a pane with a draft in it, so `idle` was false for the agent's whole
+ * life and every retarget and model switch came back AGENT_BUSY over an engine sitting at an empty
+ * prompt. Same failure the comment on `promptMarker` warns about, one step further along: the
+ * marker was found, and then the placeholder was not recognised as one.
+ */
+function hasPlaceholderSgr(value: string): boolean {
return [...value.matchAll(/\u001b\[([0-9;:]*)m/g)]
- .some((match) => match[1].split(/[;:]/).includes('2'))
+ .some((match) => {
+ const attributes = sgrAttributes(match[1].split(/[;:]/))
+ return attributes.includes('2') || attributes.includes('3')
+ })
}
function interactionText(capture: string): string {
@@ -103,6 +143,7 @@ function promptMarker(engine: RegisteredSession['engine']): RegExp {
export function inspectRuntimePane(engine: RegisteredSession['engine'], capture: string): PaneInspection {
if (engine === 'pi') return inspectPiPane(capture)
+ if (engine === 'opencode') return inspectOpencodePane(capture)
const rawLines = capture.split('\n')
const marks = promptMarker(engine)
const promptIndex = rawLines.findLastIndex((line) => {
@@ -114,18 +155,76 @@ export function inspectRuntimePane(engine: RegisteredSession['engine'], capture:
// Old picker/plan text can remain in tmux history. Only UI below the latest prompt belongs to the
// current interaction; if no prompt is visible, inspect the whole capture as a conservative fallback.
const currentUi = stripAnsi((promptIndex >= 0 ? rawLines.slice(promptIndex) : rawLines).join('\n')).replace(/\u00a0/g, ' ')
- const dialog = /Select Model(?: and Effort)?|Select Reasoning Level|Advanced Reasoning|Available models|Models matching|Edit Parameters|Type to filter.*Tab to edit|Esc to go back|Press enter to confirm|Do you want to proceed|Allow this action|permission required|Starting MCP servers?/i.test(currentUi)
+ const dialog = DIALOG_UI.test(currentUi)
const plan = engine === 'codex' ? /\bplan mode\b/i.test(currentUi) : /\bplan mode on\b/i.test(currentUi)
const marker = stripAnsi(prompt).search(marks)
let visible = marker >= 0 ? stripAnsi(prompt).slice(marker + 1).replace(/\u00a0/g, ' ').trim() : ''
const rawMarker = prompt.search(marks)
const rawTail = rawMarker >= 0 ? prompt.slice(rawMarker + 1) : ''
- const placeholder = hasDimSgr(rawTail)
+ const placeholder = hasPlaceholderSgr(rawTail)
if (placeholder) visible = ''
const draft = visible.length > 0
return { idle: !!prompt && !dialog && !draft, plan, dialog, draft }
}
+/**
+ * A modal drawn over the pane — a picker, a permission prompt, an MCP boot notice.
+ *
+ * One copy, shared by every reader here: an engine whose composer needs its own function still meets
+ * the same dialogs, and two lists of these would drift the first time either gained an entry.
+ * No `g` flag, so `test` carries no `lastIndex` between callers.
+ */
+const DIALOG_UI = /Select Model(?: and Effort)?|Select Reasoning Level|Advanced Reasoning|Available models|Models matching|Edit Parameters|Type to filter.*Tab to edit|Esc to go back|Press enter to confirm|Do you want to proceed|Allow this action|permission required|Starting MCP servers?/i
+
+/** The rule OpenCode closes its composer box with: `╹▀▀▀▀…`. */
+const OPENCODE_BOX_RULE = /[─▀▁▔]{8,}/u
+
+/**
+ * OpenCode's composer is a BOX, and its `┃` gutter does not stop at the text.
+ *
+ * The last gutter line is the box's own STATUS strip — `Build · <model> · <account>`, sitting
+ * directly on the rule that closes the box. The generic reader takes the last line carrying the
+ * marker, which is that strip, and reads what the BOX says about itself as something the user typed.
+ * So every opencode pane was permanently "holding a draft": never idle, and every retarget and model
+ * switch refused as AGENT_BUSY over an empty composer. Same symptom hermes had, opposite cause —
+ * there the placeholder was not recognised, here the wrong line was read.
+ *
+ * The composer is therefore the gutter MINUS that strip, and the strip is identified by WHERE it is
+ * — the gutter line the closing rule sits under — rather than by what it says, which is three
+ * variable fields that change with the model, the mode and the account. When no rule follows, no
+ * strip is assumed and every gutter line counts as composer: a layout we do not recognise must not
+ * silently swallow a line the user typed in.
+ *
+ * Every gutter line is checked, not just the last: a long message wraps down the box, and reading
+ * one line of it would call a full composer empty.
+ */
+function inspectOpencodePane(capture: string): PaneInspection {
+ const rawLines = capture.split('\n')
+ const marks = /┃/u
+ // The LAST contiguous run of gutter lines. Earlier runs are previous composers still in scrollback
+ // — the message the user already sent is not a draft.
+ const gutter: number[] = []
+ for (let index = rawLines.length - 1; index >= 0; index -= 1) {
+ if (marks.test(stripAnsi(rawLines[index]))) { gutter.unshift(index); continue }
+ if (gutter.length > 0) break
+ }
+ if (gutter.length === 0) return { idle: false, plan: false, dialog: false, draft: false }
+ const last = gutter[gutter.length - 1]
+ const closed = last + 1 < rawLines.length && OPENCODE_BOX_RULE.test(stripAnsi(rawLines[last + 1]))
+ const composer = closed ? gutter.slice(0, -1) : gutter
+ const currentUi = stripAnsi(rawLines.slice(gutter[0]).join('\n')).replace(/\u00a0/g, ' ')
+ const dialog = DIALOG_UI.test(currentUi)
+ const draft = composer.some((index) => {
+ const line = rawLines[index]
+ const visibleMarker = stripAnsi(line).search(marks)
+ if (visibleMarker < 0) return false
+ const rawMarker = line.search(marks)
+ if (rawMarker >= 0 && hasPlaceholderSgr(line.slice(rawMarker + 1))) return false
+ return stripAnsi(line).slice(visibleMarker + 1).replace(/\u00a0/g, ' ').trim().length > 0
+ })
+ return { idle: !dialog && !draft, plan: /\bplan mode on\b/i.test(currentUi), dialog, draft }
+}
+
/**
* Pi draws no composer marker, so idleness is read from its layout instead: the composer is the band
* between the last two `───` rules, and the footer (`minimax/minimax-m3 • high`) is only rendered by the
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index f9cbc6a2e..49a2aa123 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -825,6 +825,38 @@ export function tmuxPaneState(pane: string): Promise<TmuxPaneState | null> {
})
}
+/**
+ * The SESSION environment behind a pane, as tmux holds it.
+ *
+ * This is what `new-session -e` wrote and what every process in the pane inherits at exec, so it
+ * answers the same question `readProcessEnv` does — with one difference that matters on macOS: tmux
+ * will say, and `ps` will not. `ps` refuses to print the environment of an Apple platform binary,
+ * and the pane's own shell (`/bin/zsh`) is one, so between `new-session` and the engine's `exec`
+ * there is no process anyone is allowed to read. During an engine install that gap is minutes long.
+ *
+ * It is NOT a substitute for reading the process. tmux describes what a pane's children WILL be
+ * given; only the process says what it actually got, which is the whole point of `gridAssignment.ts`
+ * and the reason an agent the user started themselves reports the truth. Use this for the window
+ * where no readable process exists yet, and let discovery replace it the moment one does.
+ *
+ * `-VAR` lines are tmux's way of saying a variable is unset for the session; they are dropped rather
+ * than parsed, because "unset" and "absent" are the same thing to every caller here.
+ */
+export function tmuxPaneEnvironment(pane: string): Promise<Record<string, string> | null> {
+ return new Promise((resolve) => {
+ execFile('tmux', ['show-environment', '-t', pane], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {
+ if (err && !stdout) { resolve(null); return }
+ const env: Record<string, string> = {}
+ for (const line of stdout.split('\n')) {
+ const eq = line.indexOf('=')
+ if (eq <= 0 || line.startsWith('-')) continue
+ env[line.slice(0, eq)] = line.slice(eq + 1)
+ }
+ resolve(Object.keys(env).length > 0 ? env : null)
+ })
+ })
+}
+
/**
* Hand a pane back to tmux's default disposal after `create()` asked tmux to keep it when dead.
*