Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb55fad008 | ||
|
|
8995f5f627 | ||
|
|
f562c68075 | ||
|
|
6aef211188 | ||
|
|
28127b3706 | ||
|
|
d47bff5433 | ||
|
|
1c9aabbf8e | ||
|
|
eb2234b598 | ||
|
|
e7c0223bfa | ||
|
|
3ce8ee4f49 | ||
|
|
07396fbf29 | ||
|
|
9198bf6548 | ||
|
|
956ddd0dd9 | ||
|
|
5465609d54 | ||
|
|
31f2d43826 | ||
|
|
2d0d7a9b55 | ||
|
|
6f52081e51 | ||
|
|
2c0857a85b | ||
|
|
411d0f92d1 | ||
|
|
58054c5e3b | ||
|
|
e2b8b08eef | ||
|
|
2acabc56cd | ||
|
|
38c480575d | ||
|
|
717d21373d | ||
|
|
95d5c93165 | ||
|
|
6e8f59ce16 | ||
|
|
eb0e1bb2ef | ||
|
|
ee0bd66708 | ||
|
|
17c38f6ede | ||
|
|
af7e4c5d30 | ||
|
|
9229046e3b | ||
|
|
f3794a9732 | ||
|
|
f08fe96529 | ||
|
|
f61d3beecd | ||
|
|
9867ad9b4e | ||
|
|
3f0ba50130 | ||
|
|
ff226e8bdd | ||
|
|
2750a344cb | ||
|
|
489f3d615e | ||
|
|
6021ca6a64 | ||
|
|
d288ee3a1b | ||
|
|
2df032a596 | ||
|
|
d0115c2908 | ||
|
|
67cc32d714 | ||
|
|
006d433c11 | ||
|
|
ffdcc12747 | ||
|
|
6fe4314360 | ||
|
|
011da08524 | ||
|
|
21a647161b | ||
|
|
381b8fefef | ||
|
|
709a9e9391 | ||
|
|
897b4ee054 | ||
|
|
fa56c3575d | ||
|
|
fad1cba603 | ||
|
|
050a457a40 | ||
|
|
7ab51fd621 | ||
|
|
91a0aad3f2 | ||
|
|
a68c53bd86 | ||
|
|
3a539d8e7c | ||
|
|
2faad0c322 | ||
|
|
33842bc959 | ||
|
|
61a71f3439 | ||
|
|
5fef68fc4b | ||
|
|
21a85b682c | ||
|
|
a54e84a208 | ||
|
|
e68699e61f | ||
|
|
540a96fa5e | ||
|
|
5efe559c03 | ||
|
|
c6cb5f108d | ||
|
|
a165ed3019 | ||
|
|
092f38bd37 | ||
|
|
71715ed967 | ||
|
|
782f839d4f | ||
|
|
7752489936 | ||
|
|
da0108abb1 | ||
|
|
2ff1884961 | ||
|
|
97cac8d185 | ||
|
|
5c1680d0ab | ||
|
|
01a1f51464 | ||
|
|
02d922e805 | ||
|
|
0ae3542367 | ||
|
|
21b0d39de4 | ||
|
|
3e1953e77c | ||
|
|
395bd3d51b |
No files matched your search
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024">
|
||||
<path d="M854.6 288.7c6 6 9.4 14.1 9.4 22.6V928c0 17.7-14.3 32-32 32H192c-17.7 0-32-14.3-32-32V96c0-17.7 14.3-32 32-32h424.7c8.5 0 16.7 3.4 22.7 9.4l215.2 215.3zM790.2 326L602 137.8V326h188.2zM575.34 477.84l-61.22 102.3L452.3 477.8a12 12 0 0 0-10.27-5.79h-38.44a12 12 0 0 0-6.4 1.85 12 12 0 0 0-3.75 16.56l82.34 130.42-83.45 132.78a12 12 0 0 0-1.84 6.39 12 12 0 0 0 12 12h34.46a12 12 0 0 0 10.21-5.7l62.7-101.47 62.3 101.45a12 12 0 0 0 10.23 5.72h37.48a12 12 0 0 0 6.48-1.9 12 12 0 0 0 3.62-16.58l-83.83-130.55 85.3-132.47a12 12 0 0 0 1.9-6.5 12 12 0 0 0-12-12h-35.7a12 12 0 0 0-10.29 5.84z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 719 B |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024">
|
||||
<path d="M854.6 288.7L639.4 73.4c-6-6-14.2-9.4-22.7-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.6-9.4-22.6zM400 402c22.1 0 40 17.9 40 40s-17.9 40-40 40-40-17.9-40-40 17.9-40 40-40zm296 294H328c-6.7 0-10.4-7.7-6.3-12.9l99.8-127.2a8 8 0 0 1 12.6 0l41.1 52.4 77.8-99.2a8 8 0 0 1 12.6 0l136.5 174c4.3 5.2.5 12.9-6.1 12.9zm-94-370V137.8L790.2 326H602z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 530 B |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024">
|
||||
<path d="M854.6 288.7c6 6 9.4 14.1 9.4 22.6V928c0 17.7-14.3 32-32 32H192c-17.7 0-32-14.3-32-32V96c0-17.7 14.3-32 32-32h424.7c8.5 0 16.7 3.4 22.7 9.4l215.2 215.3zM790.2 326L602 137.8V326h188.2zM426.13 600.93l59.11 132.97a16 16 0 0 0 14.62 9.5h24.06a16 16 0 0 0 14.63-9.51l59.1-133.35V758a16 16 0 0 0 16.01 16H641a16 16 0 0 0 16-16V486a16 16 0 0 0-16-16h-34.75a16 16 0 0 0-14.67 9.62L512.1 662.2l-79.48-182.59a16 16 0 0 0-14.67-9.61H383a16 16 0 0 0-16 16v272a16 16 0 0 0 16 16h27.13a16 16 0 0 0 16-16V600.93z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 635 B |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024">
|
||||
<path d="M854.6 288.7c6 6 9.4 14.1 9.4 22.6V928c0 17.7-14.3 32-32 32H192c-17.7 0-32-14.3-32-32V96c0-17.7 14.3-32 32-32h424.7c8.5 0 16.7 3.4 22.7 9.4l215.2 215.3zM790.2 326L602 137.8V326h188.2zM633.22 637.26c-15.18-.5-31.32.67-49.65 2.96-24.3-14.99-40.66-35.58-52.28-65.83l1.07-4.38 1.24-5.18c4.3-18.13 6.61-31.36 7.3-44.7.52-10.07-.04-19.36-1.83-27.97-3.3-18.59-16.45-29.46-33.02-30.13-15.45-.63-29.65 8-33.28 21.37-5.91 21.62-2.45 50.07 10.08 98.59-15.96 38.05-37.05 82.66-51.2 107.54-18.89 9.74-33.6 18.6-45.96 28.42-16.3 12.97-26.48 26.3-29.28 40.3-1.36 6.49.69 14.97 5.36 21.92 5.3 7.88 13.28 13 22.85 13.74 24.15 1.87 53.83-23.03 86.6-79.26 3.29-1.1 6.77-2.26 11.02-3.7l11.9-4.02c7.53-2.54 12.99-4.36 18.39-6.11 23.4-7.62 41.1-12.43 57.2-15.17 27.98 14.98 60.32 24.8 82.1 24.8 17.98 0 30.13-9.32 34.52-23.99 3.85-12.88.8-27.82-7.48-36.08-8.56-8.41-24.3-12.43-45.65-13.12zM385.23 765.68v-.36l.13-.34a54.86 54.86 0 0 1 5.6-10.76c4.28-6.58 10.17-13.5 17.47-20.87 3.92-3.95 8-7.8 12.79-12.12 1.07-.96 7.91-7.05 9.19-8.25l11.17-10.4-8.12 12.93c-12.32 19.64-23.46 33.78-33 43-3.51 3.4-6.6 5.9-9.1 7.51a16.43 16.43 0 0 1-2.61 1.42c-.41.17-.77.27-1.13.3a2.2 2.2 0 0 1-1.12-.15 2.07 2.07 0 0 1-1.27-1.91zM511.17 547.4l-2.26 4-1.4-4.38c-3.1-9.83-5.38-24.64-6.01-38-.72-15.2.49-24.32 5.29-24.32 6.74 0 9.83 10.8 10.07 27.05.22 14.28-2.03 29.14-5.7 35.65zm-5.81 58.46l1.53-4.05 2.09 3.8c11.69 21.24 26.86 38.96 43.54 51.31l3.6 2.66-4.39.9c-16.33 3.38-31.54 8.46-52.34 16.85 2.17-.88-21.62 8.86-27.64 11.17l-5.25 2.01 2.8-4.88c12.35-21.5 23.76-47.32 36.05-79.77zm157.62 76.26c-7.86 3.1-24.78.33-54.57-12.39l-7.56-3.22 8.2-.6c23.3-1.73 39.8-.45 49.42 3.07 4.1 1.5 6.83 3.39 8.04 5.55a4.64 4.64 0 0 1-1.36 6.31 6.7 6.7 0 0 1-2.17 1.28z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.8 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024">
|
||||
<path d="M854.6 288.7c6 6 9.4 14.1 9.4 22.6V928c0 17.7-14.3 32-32 32H192c-17.7 0-32-14.3-32-32V96c0-17.7 14.3-32 32-32h424.7c8.5 0 16.7 3.4 22.7 9.4l215.2 215.3zM790.2 326L602 137.8V326h188.2zM468.53 760v-91.54h59.27c60.57 0 100.2-39.65 100.2-98.12 0-58.22-39.58-98.34-99.98-98.34H424a12 12 0 0 0-12 12v276a12 12 0 0 0 12 12h32.53a12 12 0 0 0 12-12zm0-139.33h34.9c47.82 0 67.19-12.93 67.19-50.33 0-32.05-18.12-50.12-49.87-50.12h-52.22v100.45z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 571 B |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024">
|
||||
<path d="M854.6 288.7c6 6 9.4 14.1 9.4 22.6V928c0 17.7-14.3 32-32 32H192c-17.7 0-32-14.3-32-32V96c0-17.7 14.3-32 32-32h424.7c8.5 0 16.7 3.4 22.7 9.4l215.2 215.3zM790.2 326L602 137.8V326h188.2zM320 482a8 8 0 0 0-8 8v48a8 8 0 0 0 8 8h384a8 8 0 0 0 8-8v-48a8 8 0 0 0-8-8H320zm0 136a8 8 0 0 0-8 8v48a8 8 0 0 0 8 8h184a8 8 0 0 0 8-8v-48a8 8 0 0 0-8-8H320z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 479 B |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024">
|
||||
<path d="M854.6 288.7c6 6 9.4 14.1 9.4 22.6V928c0 17.7-14.3 32-32 32H192c-17.7 0-32-14.3-32-32V96c0-17.7 14.3-32 32-32h424.7c8.5 0 16.7 3.4 22.7 9.4l215.2 215.3zM790.2 326L602 137.8V326h188.2zM512 566.1l52.81 197a12 12 0 0 0 11.6 8.9h31.77a12 12 0 0 0 11.6-8.88l74.37-276a12 12 0 0 0 .4-3.12 12 12 0 0 0-12-12h-35.57a12 12 0 0 0-11.7 9.31l-45.78 199.1-49.76-199.32A12 12 0 0 0 528.1 472h-32.2a12 12 0 0 0-11.64 9.1L434.6 680.01 388.5 481.3a12 12 0 0 0-11.68-9.29h-35.39a12 12 0 0 0-3.11.41 12 12 0 0 0-8.47 14.7l74.17 276A12 12 0 0 0 415.6 772h31.99a12 12 0 0 0 11.59-8.9l52.81-197z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 711 B |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024">
|
||||
<path d="M854.6 288.7c6 6 9.4 14.1 9.4 22.6V928c0 17.7-14.3 32-32 32H192c-17.7 0-32-14.3-32-32V96c0-17.7 14.3-32 32-32h424.7c8.5 0 16.7 3.4 22.7 9.4l215.2 215.3zM790.2 326L602 137.8V326h188.2zM296 136v64h64v-64h-64zm64 64v64h64v-64h-64zm-64 64v64h64v-64h-64zm64 64v64h64v-64h-64zm-64 64v64h64v-64h-64zm64 64v64h64v-64h-64zm-64 64v64h64v-64h-64zm0 64v160h128V584H296zm48 48h32v64h-32v-64z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 516 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" fill="currentColor" fill-rule="evenodd"><g><path d="M353 16H192.545v425.615c0 105.313-36.166 134.718-99.104 134.718-29.494 0-56.055-5.05-76.718-12.144L0 688.784C29.484 698.924 74.73 705 110.126 705 254.631 705 353 637.16 353 442.658zM702.49 0C547.26 0 449 88.126 449 204.609c0 100.313 75.67 163.12 185.696 203.629 79.577 28.358 111.03 53.695 111.03 95.218 0 45.579-36.358 74.96-105.13 74.96-63.868 0-121.849-21.311-161.146-42.573v-.042L449 662.427C486.361 683.735 556.12 705 631.741 705 813.52 705 898 607.753 898 493.293c0-97.243-54.036-160.035-170.937-204.627-86.47-34.432-122.813-53.669-122.813-97.227 0-34.45 31.446-65.834 96.3-65.834 63.834 0 107.728 21.445 133.307 34.632L872.193 32.05C832.103 14.461 778.109 0 702.49 0" transform="translate(63 160)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 833 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" fill="currentColor" fill-rule="evenodd"><path d="M212.68 692.99s-34.325 19.95 24.343 26.6c71.1 8.05 107.351 7 185.632-7.874 0 0 20.665 12.949 49.385 24.149-175.475 75.074-397.184-4.375-259.36-42.875m-21.366-98.173s-38.352 28.35 20.315 34.475c75.83 7.875 135.897 8.4 239.571-11.55 0 0 14.36 14.525 36.952 22.4-212.427 62.123-448.846 5.075-296.838-45.325m180.73-166.422c43.256 49.699-11.384 94.498-11.384 94.498s109.804-56.7 59.368-127.573c-47.11-66.15-83.185-99.049 112.255-212.273.175 0-306.819 76.65-160.24 245.348M604.26 765.439s25.393 20.825-27.846 37.1c-101.397 30.625-421.7 39.9-510.664 1.225-32.048-13.825 28.02-33.25 46.934-37.275 19.613-4.2 30.997-3.5 30.997-3.5-35.551-25.025-229.94 49.175-98.771 70.35 357.605 58.1 652.165-26.075 559.35-67.9M229.142 493.144S66.1 531.818 171.35 545.818c44.482 5.95 133.095 4.55 215.58-2.275 67.423-5.6 135.196-17.85 135.196-17.85s-23.818 10.15-40.98 21.875C315.653 591.143-3.95 570.843 87.99 526.393c77.93-37.45 141.151-33.25 141.151-33.25M521.6 656.416c168.296-87.324 90.365-171.322 36.077-159.948-13.31 2.8-19.264 5.25-19.264 5.25s4.903-7.7 14.36-11.025c107.351-37.8 190.01 111.299-34.675 170.273 0-.175 2.627-2.45 3.502-4.55M420.028 0s93.166 93.1-88.438 236.246c-145.53 114.8-33.274 180.424 0 255.148-84.936-76.65-147.28-144.024-105.425-206.848C287.634 192.672 457.68 147.873 420.028 0m-174.25 893.188c161.466 10.325 409.443-5.775 415.222-82.075 0 0-11.208 28.875-133.445 51.975-137.824 25.9-307.87 22.925-408.567 6.3 0-.175 20.665 16.975 126.79 23.8" transform="translate(182 64)"/></svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" fill="currentColor" fill-rule="evenodd"><g><path d="M443 678.5c0 15.74 12.76 28.5 28.5 28.5s28.5-12.76 28.5-28.5-12.76-28.5-28.5-28.5-28.5 12.76-28.5 28.5M300 121.5c0 15.74 12.76 28.5 28.5 28.5s28.5-12.76 28.5-28.5S344.24 93 328.5 93 300 105.76 300 121.5" transform="translate(112 112)"/><path d="M709.524 185.714h-95.238V90.476C614.286 40.571 573.714 0 523.81 0H276.19c-49.904 0-90.476 40.571-90.476 90.476v95.238H90.476C40.571 185.714 0 226.286 0 276.19v247.62c0 49.904 40.571 90.476 90.476 90.476h95.238v95.238c0 49.905 40.572 90.476 90.476 90.476h247.62c49.904 0 90.476-40.571 90.476-90.476v-95.238h95.238c49.905 0 90.476-40.572 90.476-90.476V276.19c0-49.904-40.571-90.476-90.476-90.476M90.476 557.143c-18.38 0-33.333-14.953-33.333-33.333V276.19c0-18.38 14.952-33.333 33.333-33.333h278.572c15.81 0 28.571-12.762 28.571-28.571 0-15.81-12.762-28.572-28.571-28.572h-126.19V90.476c0-18.38 14.952-33.333 33.332-33.333h247.62c18.38 0 33.333 14.952 33.333 33.333v256.476c0 13.524-10.953 24.477-24.476 24.477H267.333c-45.047 0-81.619 36.666-81.619 81.619v104.095zm652.381-33.333c0 18.38-14.952 33.333-33.333 33.333H430.952c-15.81 0-28.571 12.762-28.571 28.571 0 15.81 12.762 28.572 28.571 28.572h126.19v95.238c0 18.38-14.952 33.333-33.332 33.333H276.19c-18.38 0-33.333-14.952-33.333-33.333V453.048c0-13.524 10.953-24.477 24.476-24.477h265.334c45.047 0 81.619-36.666 81.619-81.619V242.857h95.238c18.38 0 33.333 14.953 33.333 33.333z" transform="translate(112 112)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -1,5 +1,74 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.5 - 2026-09-09 (Meldwork-V1.0.5 prerelease)
|
||||
|
||||
### Local Agent Reliability
|
||||
|
||||
- Accept validated OpenClaw gateway configuration migrations without disabling path, permission, or credential isolation checks.
|
||||
- Keep installed Agents visible when credential or capability checks fail; isolate failed probes and refresh the catalog after current readiness settles.
|
||||
- Refresh native shell settings before manual detection and preserve supported proxy, CA, cloud Provider, and model-region settings without silently replacing a selected Provider.
|
||||
|
||||
### Group Conversations
|
||||
|
||||
- Route peer requests through explicit Agent decisions instead of interpreting prose mentions or media keywords as commands.
|
||||
- Persist AI task completion separately from individual invocation success and human adoption; support single-Agent automatic work and exact visible answers.
|
||||
- Resume human clarification gates after restart, reject conflicting responses, and prevent repeated responses from replaying calls.
|
||||
- Serialize workspace writers, recover interrupted writes through bound approvals, retain partial results, and send acknowledged session context incrementally.
|
||||
- Preserve completed and stopped task states after restart and show healthy contributions alongside failed participants.
|
||||
|
||||
### Verification And Distribution
|
||||
|
||||
- Frontend 343/343, desktop 1562/1562, and deterministic evaluation 6 cases / 18 results passed.
|
||||
- Web and desktop builds, packaging, real packaged Codex/OpenClaw group execution, cancellation, and restart acceptance passed on Apple silicon macOS.
|
||||
- DMG and ZIP are ad-hoc signed, without Apple Developer ID signing or notarization. No installed user application is replaced automatically.
|
||||
- Live coverage is limited to observed CLI versions and configurations; cloud credential forwarding is not cloud-account certification. Full evidence: `docs/releases/Meldwork-V1.0.5.md`.
|
||||
|
||||
## 0.1.4 - 2026-09-01 (Meldwork-V1.0.4 prerelease)
|
||||
|
||||
### Natural Group Discussions
|
||||
|
||||
- Sequential discussion mode now runs one Agent at a time in the configured CLI order and records every round visibly.
|
||||
- Auto Discussion starts with concurrent proposals, then lets Agent responses route the next turn through exact final-line `@Agent` mentions. One mention runs one Agent; multiple mentions run concurrently.
|
||||
- Natural discussion prompts allow Agents to exchange views before work and review instead of forcing every turn into a review-only role.
|
||||
|
||||
### Session And Recovery
|
||||
|
||||
- Reuses one native Agent session per Agent task across discussion rounds and restarts.
|
||||
- Persists round messages and checkpoints before and after Agent execution so completed turns are recovered without duplicate reruns.
|
||||
- Rejects stale operation and snapshot bindings before late results can be committed.
|
||||
|
||||
### Verification And Distribution
|
||||
|
||||
- Focused natural discussion coverage: 17/17 tests passed.
|
||||
- Desktop syntax checks and `git diff --check` passed.
|
||||
- The Apple silicon DMG and ZIP are ad-hoc signed and not notarized. Live CLI behavior still depends on each installed Agent's version, authentication, Provider, and capabilities.
|
||||
|
||||
## 0.1.3 - 2026-08-18 (Meldwork-V1.0.3 prerelease)
|
||||
|
||||
### Concurrent Conversations
|
||||
|
||||
- Concurrent Responses now treats an empty explicit selection as the whole group, so users can send one message to every group Agent without adding `@` mentions first.
|
||||
- Keeps every group member in the frozen batch. Agents beyond the available Scheduler capacity remain visibly queued instead of being removed from the request.
|
||||
- Preserves valid visible proposals when a CLI omits or malforms its proposal receipt, while later Auto Discussion phases retain their strict structured-receipt boundary.
|
||||
|
||||
### Conversation Experience
|
||||
|
||||
- Refines user-message metadata, Agent logos, inline Agent/Skill/knowledge mentions, Markdown rendering, mention-menu tracking, and narrow-layout wrapping.
|
||||
- Returns newly sent conversations to the active Agent loading state and keeps the animated return-to-bottom control for readers who have scrolled up.
|
||||
- Removes the special No round limit composer background, border, shadow, and container breathing effect. The infinity status cue and real collaboration phase feedback remain available.
|
||||
|
||||
### Stop Durability
|
||||
|
||||
- Persists completed and streamed concurrent Agent replies when the user stops a batch instead of removing already visible work.
|
||||
- Records stopped Agent attempts as interrupted, rejects late post-stop results, and resumes the stable batch commit idempotently after restart.
|
||||
|
||||
### Packaging And Verification
|
||||
|
||||
- Sets the frontend and desktop package version to `0.1.3` and publishes Apple silicon DMG and ZIP prerelease artifacts with a matching SHA-256 manifest.
|
||||
- Frontend tests: 306/306 passed. Desktop tests: 1338/1338 passed.
|
||||
- Web and Electron renderer builds, Electron `pack`, packaged acceptance, and `git diff --check` passed before release packaging.
|
||||
- The prerelease remains ad-hoc signed, without Apple Developer ID signing or notarization, and may require Open Anyway on first launch.
|
||||
|
||||
## 0.1.2 - 2026-08-18 (Meldwork-V1.0.2 prerelease)
|
||||
|
||||
### Collaboration Harness V4
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# Code of Conduct
|
||||
|
||||
Meldwork is a workspace for people and Agents to build together. We want issues,
|
||||
pull requests, discussions, and community spaces to stay useful, direct, and
|
||||
respectful.
|
||||
|
||||
## Expected Behavior
|
||||
|
||||
- Be clear, constructive, and respectful when giving feedback.
|
||||
- Assume good intent while keeping discussions focused on facts, tradeoffs, and outcomes.
|
||||
- Respect different experience levels, backgrounds, languages, and working styles.
|
||||
- Keep disagreements technical, specific, and connected to the project.
|
||||
- Help maintainers keep issues and pull requests focused.
|
||||
- Protect private prompts, credentials, customer information, and other sensitive data.
|
||||
|
||||
## Unacceptable Behavior
|
||||
|
||||
The following behavior is not acceptable in Meldwork project spaces:
|
||||
|
||||
- Personal attacks, insults, harassment, or sustained disruption.
|
||||
- Demeaning comments about identity, background, language, ability, or experience.
|
||||
- Threats, intimidation, stalking, or unwanted contact.
|
||||
- Publishing another person's private information without consent.
|
||||
- Spam, trolling, discrimination, or repeated off-topic posting.
|
||||
- Submitting malicious code, secrets, private data, or intentionally misleading reports.
|
||||
- Any behavior maintainers reasonably judge to make the project unsafe or unproductive.
|
||||
|
||||
## Maintainer Responsibilities
|
||||
|
||||
Maintainers may edit or remove comments, close issues, limit participation, or
|
||||
block participants when needed to protect the project community. Enforcement
|
||||
should be proportional, documented when practical, and focused on keeping
|
||||
collaboration healthy.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report conduct concerns privately through the repository's GitHub contact or
|
||||
security reporting channel. Do not open a public issue for sensitive reports.
|
||||
|
||||
Please include:
|
||||
|
||||
- a short description of what happened;
|
||||
- links, screenshots, or message references when available;
|
||||
- whether you want follow-up, confidentiality, or no direct reply.
|
||||
|
||||
Reports will be reviewed by project maintainers. We will handle reports with
|
||||
care and limit access to people who need the information to respond.
|
||||
|
||||
This Code of Conduct applies wherever the project or its maintainers represent
|
||||
the Meldwork community. It is adapted from the Contributor Covenant and the
|
||||
community standards used by comparable open-source projects.
|
||||
@@ -1,17 +1,14 @@
|
||||
# Commercial Use And Licensing
|
||||
|
||||
Meldwork is source-available under the [Meldwork Non-Commercial Source License](LICENSE). The public repository can be inspected, evaluated, run, and modified for non-commercial purposes, but it is not licensed for commercial use.
|
||||
Meldwork is licensed under the [Apache License 2.0](LICENSE). Commercial use,
|
||||
private use, modification, redistribution, and use inside a paid service are
|
||||
permitted under the license terms.
|
||||
|
||||
Any commercial use requires prior written permission from the copyright holder. This includes monetizing Meldwork, reselling or hosting it, embedding it in a proprietary product, using it to provide paid services, or using it as part of a for-profit organization's business operations.
|
||||
This page is a practical summary and does not replace the license text. Apache
|
||||
License 2.0 does not grant trademark rights to the Meldwork name, logo,
|
||||
screenshots, or other brand assets. Third-party software, Agent products,
|
||||
models, names, logos, and other materials remain subject to their own licenses
|
||||
and terms.
|
||||
|
||||
The copyright holder may offer a separate commercial license for organizations that need permission for:
|
||||
|
||||
- proprietary redistribution or resale of Meldwork or a modified version;
|
||||
- embedding Meldwork code in a closed-source product;
|
||||
- offering a hosted, managed, or network-accessible version;
|
||||
- internal business operations at a for-profit organization;
|
||||
- separately licensed commercial features, enterprise integrations, support, or managed deployment.
|
||||
|
||||
A commercial license does not change the licenses of third-party dependencies, Agent products, names, models, or logos. The repository license also does not grant trademark rights to the Meldwork name, logo, screenshots, or other brand assets.
|
||||
|
||||
This page is a practical summary and does not replace the license text or legal advice. When a planned use may be commercial, contact the repository owner through GitHub before using, distributing, hosting, reselling, or integrating the product.
|
||||
Before distributing a product that includes third-party materials, review the
|
||||
relevant notices and preserve the required attribution and license information.
|
||||
@@ -1,8 +1,8 @@
|
||||
# Contributing
|
||||
|
||||
Meldwork is source-available under the [Meldwork Non-Commercial Source License](LICENSE). Contributions are welcome when they improve the local-first desktop product, documentation, tests, or security posture.
|
||||
Meldwork is licensed under the [Apache License 2.0](LICENSE). Contributions are welcome when they improve the local-first desktop product, documentation, tests, or security posture.
|
||||
|
||||
Unless a separate written agreement applies, a contribution accepted into this repository is available under the repository license. The project may also offer separately licensed commercial editions. Before external code is incorporated into a separately licensed commercial build, the maintainer may require a reviewed contributor-license agreement that grants the necessary relicensing rights. Opening a pull request by itself does not transfer copyright or silently grant those additional rights.
|
||||
Unless a separate written agreement applies, a contribution accepted into this repository is available under the repository license. Opening a pull request does not transfer copyright beyond the rights granted by the Apache License 2.0.
|
||||
|
||||
## Ground Rules
|
||||
|
||||
@@ -11,8 +11,9 @@ Unless a separate written agreement applies, a contribution accepted into this r
|
||||
- Do not add remote services, telemetry, credential collection, or server dependencies without explicit project approval.
|
||||
- Preserve the local-first boundary: renderer code must not gain unrestricted filesystem, shell, Provider credential, or executable-path access.
|
||||
- Include focused tests for behavior, security boundary, storage, or IPC changes.
|
||||
- Confirm that all submitted code and assets are yours to license and do not introduce incompatible license obligations.
|
||||
- Confirm that all submitted code and assets are yours to contribute and do not introduce incompatible license obligations.
|
||||
|
||||
## Commercial Editions
|
||||
## Community Standards
|
||||
|
||||
Commercial use of Meldwork requires prior written permission. Commercial editions, proprietary integrations, support, and other paid offerings may use separate terms; see [COMMERCIAL_USE.md](COMMERCIAL_USE.md).
|
||||
Please follow the [Code of Conduct](CODE_OF_CONDUCT.md) in issues, pull
|
||||
requests, discussions, and other project spaces.
|
||||
@@ -1,82 +1,201 @@
|
||||
Meldwork Non-Commercial Source License 1.0
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
Copyright (c) 2026 Ryder-MHumble.
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
This license applies to Meldwork and the source code, documentation, assets, and
|
||||
other materials in this repository, except where a file or third-party notice
|
||||
states a different license.
|
||||
1. Definitions.
|
||||
|
||||
Meldwork is source-available, not open source in the OSI sense. Commercial use is
|
||||
not permitted without prior written permission from the copyright holder.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
1. Allowed non-commercial use
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
You may download, inspect, run, copy, and modify Meldwork for personal learning,
|
||||
research, evaluation, security review, and other non-commercial purposes.
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
You may share unmodified or modified copies for non-commercial purposes if you:
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
- keep this license and all copyright, attribution, and trademark notices;
|
||||
- clearly mark your changes when you distribute a modified copy;
|
||||
- do not remove or obscure third-party notices; and
|
||||
- do not imply that the copyright holder endorses your copy or service.
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
2. Commercial use requires permission
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
You may not use Meldwork for a commercial purpose without a separate written
|
||||
license or other written permission from the copyright holder.
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
Commercial purpose includes, without limitation:
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
- selling, renting, sublicensing, or otherwise monetizing Meldwork or a modified
|
||||
version;
|
||||
- offering Meldwork or a modified version as a hosted, managed, consulting,
|
||||
outsourcing, integration, or support service;
|
||||
- embedding Meldwork code, UI, workflow, or packaged binaries in a proprietary,
|
||||
paid, or revenue-generating product;
|
||||
- using Meldwork to provide paid deliverables, paid automation, paid Agent
|
||||
operations, or other business services to a customer; and
|
||||
- use by or for a for-profit company, commercial product team, or revenue-driven
|
||||
organization as part of its business operations.
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
If you want to use Meldwork commercially, contact the repository owner and obtain
|
||||
written permission before using, distributing, hosting, reselling, or integrating
|
||||
the product.
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
3. No trademark license
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
This license does not grant rights to use the Meldwork name, logo, product
|
||||
identity, screenshots, or other brand assets except as needed to describe an
|
||||
unaltered copy of the software in a truthful, non-confusing way.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Third-party materials
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
Third-party software, Agent products, models, names, logos, dependencies, and
|
||||
other materials remain subject to their own licenses and terms. This license does
|
||||
not give you rights that the copyright holder does not own.
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
5. Contributions
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
Unless a separate written agreement says otherwise, contributions submitted to
|
||||
this repository may be used under this license. The copyright holder may require
|
||||
a separate contributor agreement before accepting contributions intended for a
|
||||
commercially licensed edition.
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
6. Termination
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
If you violate this license, your rights under it terminate automatically. The
|
||||
copyright holder may reinstate rights in writing after the violation is cured.
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
7. No warranty
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
Meldwork is provided "as is", without warranties or conditions of any kind,
|
||||
including implied warranties of merchantability, fitness for a particular
|
||||
purpose, title, and non-infringement. You are responsible for evaluating whether
|
||||
the software is suitable and lawful for your use.
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
8. Limitation of liability
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
To the maximum extent permitted by law, the copyright holder and contributors
|
||||
will not be liable for any damages arising from or related to the software or
|
||||
this license, including direct, indirect, incidental, consequential, special,
|
||||
exemplary, punitive, or business-interruption damages.
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,9 +1,7 @@
|
||||
Meldwork
|
||||
Copyright 2026 Ryder-MHumble and Meldwork contributors.
|
||||
|
||||
Meldwork is licensed under the Meldwork Non-Commercial Source License. See
|
||||
LICENSE. Commercial use requires separate written permission from the copyright
|
||||
holder.
|
||||
Meldwork is licensed under the Apache License 2.0. See LICENSE.
|
||||
|
||||
Third-party Agent names, product names, and logos remain the property of their
|
||||
respective owners. They are used only to identify compatible integrations and
|
||||
|
||||
|
After Width: | Height: | Size: 3.1 MiB |
@@ -1,11 +1,3 @@
|
||||
<!-- <p align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="frontend/public/logos/meldwork-wordmark-v3-dark.svg">
|
||||
<source media="(prefers-color-scheme: light)" srcset="frontend/public/logos/meldwork-wordmark-v3.svg">
|
||||
<img src="frontend/public/logos/meldwork-wordmark-v3.svg" alt="Meldwork" width="360">
|
||||
</picture>
|
||||
</p> -->
|
||||
|
||||
<p align="center">
|
||||
<img src="frontend/public/logos/meldwork-readme-banner-en.png" alt="Meldwork README banner" width="100%">
|
||||
</p>
|
||||
@@ -14,149 +6,129 @@
|
||||
<strong>English</strong> · <a href="README.zh-CN.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
# Meldwork builds the organization layer for AI agents.
|
||||
# Meldwork — A local-first workspace for General Agents
|
||||
|
||||
**Most tools help humans run more agents. Meldwork is built for a different job: make multi-agent work legible, accountable, and reusable.**
|
||||
**Turn several General Agents into a reviewable working group. Meldwork gives every task a shared context, lets selected Agents investigate independently or discuss across rounds, and keeps the evidence and human decision visible before anything is adopted.**
|
||||
|
||||
The current preview is a local work cell for supported Agent CLIs. It keeps participants explicit, context scoped, collaboration bounded, run state inspectable, and human review in the loop. Selected Agents can now respond concurrently or move through independent proposals, peer negotiation, responsibility-based work, single-writer integration, and independent verification around one goal.
|
||||
Meldwork is a local-first Electron workspace for using the Agent tools you already have on your Mac. It supports focused conversations, independent concurrent responses, and Auto Discussion V4 for proposal, challenge, negotiated work, synthesis, and verification. Agents can work with text, files, images, media, Skills, and selected knowledge sources, so the same workspace can support research, analysis, writing, planning, review, and implementation.
|
||||
|
||||
The product is organized around a durable review record: **Case → Finding → Evidence → Decision → Disposition**. Meldwork keeps the task snapshot, Agent contributions, run state, artifacts, Human Gates, and adoption decision together in one local work cell. Workspace writes are opt-in and remain under the user's control.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Ryder-MHumble/Meldwork/releases/download/Meldwork-V1.0.2/Meldwork-0.1.2-arm64.dmg"><strong>Download Meldwork V1.0.2 for Apple silicon macOS</strong></a>
|
||||
<a href="https://github.com/Ryder-MHumble/Meldwork/releases/download/Meldwork-V1.0.5/Meldwork-0.1.5-arm64.dmg"><strong>Download Meldwork V1.0.5 for Apple silicon macOS</strong></a>
|
||||
· <a href="architecture.md">Architecture</a>
|
||||
· <a href="LICENSE">License</a>
|
||||
</p>
|
||||
|
||||
## The missing layer
|
||||
## What Meldwork is for
|
||||
|
||||
Agent supply is growing quickly. The organization around it is not.
|
||||
Meldwork is useful when a decision benefits from more than one perspective and a clear record of why a result was adopted. Typical work includes:
|
||||
|
||||
Today, people still choose every Agent, move every piece of context, explain every role, reconcile conflicting answers, and carry the final accountability. Parallel managers improve throughput. Agent frameworks let developers program workflows. Single-Agent products improve one worker.
|
||||
- research and information synthesis across local Agent tools and selected knowledge sources;
|
||||
- product, market, operational, and technical analysis;
|
||||
- writing, planning, review, and structured document work;
|
||||
- multimodal work with local documents, images, audio, video, PDFs, and code or configuration files;
|
||||
- implementation and review tasks where findings, evidence, permissions, and the final adoption decision should remain inspectable.
|
||||
|
||||
Meldwork is focused on the work between them:
|
||||
## How a task moves through Meldwork
|
||||
|
||||
- one shared goal and acceptance boundary;
|
||||
- independent viewpoints instead of hidden routing;
|
||||
- explicit authority, responsibility, handoffs, and stopping conditions;
|
||||
- artifacts and evidence that survive Agent changes;
|
||||
- a human-controlled adoption decision.
|
||||
1. **Select** the Agents and participants for this Case.
|
||||
2. **Scope** the goal, working directory, context, attachments, Skills, knowledge sources, and permissions.
|
||||
3. **Run** a direct conversation, Concurrent Responses, or Auto Discussion V4.
|
||||
4. **Review** the findings, evidence, artifacts, trace, and any Human Gate.
|
||||
5. **Adopt** the approved result or leave the Case unresolved for further work.
|
||||
|
||||
## What works today
|
||||
## Collaboration modes
|
||||
|
||||
- **Supported local Agent CLIs:** detect, inspect, and invoke approved Agents without exposing unrestricted shell execution to the renderer.
|
||||
- **Persistent direct work:** keep local conversation history, attachments, permissions, compatible native sessions, and sanitized execution details together.
|
||||
- **Concurrent responses:** send one message to multiple selected Agents, freeze the same task context before execution, and publish their independent replies as one stable batch.
|
||||
- **Agent-negotiated collaboration:** start with independent proposals, let the selected Agents challenge proposals and unanimously agree one responsibility graph, execute distinct work packages, integrate through one writer, and verify through different Agents.
|
||||
- **Inspectable execution:** preserve bounded run events, warnings, completion states, checkpoints, and recovery actions without exposing credentials or private reasoning.
|
||||
- **Local control:** keep Meldwork conversations and orchestration state on the computer; workspace writes remain opt-in.
|
||||
|
||||
Capability still depends on the selected Agent, installed version, authentication state, Provider, and declared tool or attachment support.
|
||||
|
||||
## What Meldwork is building
|
||||
|
||||
The collaboration mechanism is not a hidden preset A → B → C assignment. The user selects the participants; those Agents expose the solution space, negotiate responsibilities, and execute inside Harness-enforced context, permission, budget, recovery, and evidence boundaries.
|
||||
|
||||
~~~mermaid
|
||||
flowchart LR
|
||||
G["Goal + outcome contract"] --> P["Independent proposals"]
|
||||
P --> C["Visible challenge"]
|
||||
C --> B["Role claims + team bids"]
|
||||
B --> R["Responsibility contract"]
|
||||
R --> X["Bounded execution"]
|
||||
X --> E["Artifact + evidence"]
|
||||
E --> H["Human adoption"]
|
||||
H --> O["Outcome receipt"]
|
||||
O -. "Agent fit + team fit" .-> P
|
||||
~~~
|
||||
|
||||
The selected-Agent proposal, challenge, responsibility, work, integration, and verification loop is available today. Automatic participant selection from a broader roster, remote Agents, enterprise governance, and outcome-driven reputation remain future direction.
|
||||
|
||||
## The Harness
|
||||
|
||||
The Harness is the control plane that keeps conversations, context, adapters, streams, and durable state aligned in one workspace. It is what makes a run continuous across sessions, timeouts, recovery, and Agent changes.
|
||||
|
||||
<p align="center">
|
||||
<img src="frontend/public/logos/Harness-readme.png" alt="Meldwork Harness" width="100%">
|
||||
</p>
|
||||
|
||||
## Where Meldwork fits
|
||||
|
||||
This is a comparison of working models, not a feature-scorecard claiming Meldwork should replace every tool.
|
||||
|
||||
| Approach | Examples | Best at | Main tradeoff | Meldwork's choice |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| One Agent CLI or AI IDE | Claude Code, Codex, Cursor, Windsurf | Deep work inside one Agent or product ecosystem | Moving to another Agent still requires a manual handoff | Preserve work across heterogeneous Agents |
|
||||
| Parallel coding-Agent managers | Superset, Vibe Kanban, Nimbalyst, Conductor | Running multiple coding tasks and isolated workspaces in parallel | Primarily optimized for throughput and code delivery | Optimize proposal quality, responsibility, evidence, and adoption |
|
||||
| Cloud Agent control planes | GitHub Agent HQ, Warp Oz, Devin, Factory, OpenHands Cloud | Dispatching and observing remote jobs, sandboxes, and Agent fleets | Work is organized around cloud or platform infrastructure | Start local-first and bring your existing Agents |
|
||||
| Programmable Agent frameworks | LangGraph, CrewAI, AutoGen, Agents SDK, ADK | Building custom graphs, roles, routing, and automation | Developers must design and maintain the orchestration | Deliver an organization and acceptance experience to users |
|
||||
| Multiple terminals and scripts | tmux, shell scripts, manual copy and paste | Maximum access to native Agent capabilities | The user becomes the router, context bus, and final judge | Make the work, boundaries, and decisions durable |
|
||||
| **Meldwork** | Supported local Agent CLIs; remote supply is direction | Concurrent independent responses and selected-Agent proposal, negotiation, responsibility, evidence, and verification | Local single-user preview today; participants are still selected by the user | Build the organization layer for the Agent workforce |
|
||||
|
||||
If one Agent and one work surface are enough, use the native tool. Use Meldwork when handoff, independent judgment, authority, evidence, and acceptance become part of the problem.
|
||||
|
||||
## See the current work cell
|
||||
|
||||
| Local Agent discovery | Direct multimodal work | Concurrent multi-Agent work |
|
||||
| Mode | What happens | Best for |
|
||||
| --- | --- | --- |
|
||||
| [](assets/meldwork-agent-discovery.png) | [](assets/meldwork-direct-multimodal.png) | [](assets/meldwork-group-collaboration.png) |
|
||||
| See which supported Agents are ready. | Keep prompts, files, permissions, and compatible sessions together. | Run concurrent replies or an Agent-negotiated collaboration with the participants you selected. |
|
||||
| **Direct** | One selected Agent keeps its conversation and native session when supported. | Focused research, writing, analysis, or execution. |
|
||||
| **Concurrent Responses** | Selected Agents receive the same frozen task snapshot and return independent responses in stable order. | Comparing perspectives before choosing a path. |
|
||||
| **Auto Discussion V4** | Agents propose, challenge, negotiate responsibilities, execute agreed work, synthesize a candidate result, and verify it across bounded rounds. Native Agent sessions continue when supported. | Multi-step work that needs discussion, division of responsibility, and review. |
|
||||
|
||||
## Connected Agents
|
||||
Participants are selected by the user. Automatic selection from a larger roster is outside the current preview.
|
||||
|
||||
Current integrations include:
|
||||
## The review record
|
||||
|
||||
**Codex · Hermes · OpenClaw · WorkBuddy · Kimi Code · MiMo Code · Claude Code · Gemini CLI · OpenCode · Qwen Code**
|
||||
Meldwork treats collaboration as a decision process rather than a stream of chat messages:
|
||||
|
||||
Specialized review:
|
||||
- **Case** defines the question, scope, context, and permissions.
|
||||
- **Finding** records an Agent's claim, observation, or proposed action.
|
||||
- **Evidence** links the finding to a response, artifact, file, knowledge result, or other bounded reference.
|
||||
- **Decision** records what the evidence supports, what remains uncertain, and which path is selected.
|
||||
- **Disposition** records whether the result was accepted, revised, rejected, superseded, or left unresolved.
|
||||
|
||||
**OpenCodeReview**
|
||||
The Run Ledger preserves phase, participant, attempt, receipt, artifact, recovery, and Human Gate state. Diagnostic tool output and sensitive runtime details stay behind the Electron main-process boundary.
|
||||
|
||||
Availability depends on installation, version, authentication, Provider, and declared capabilities. Each Agent keeps its own tools, session behavior, and permission model.
|
||||
## General Agent catalog
|
||||
|
||||
## Install
|
||||
Meldwork detects and invokes compatible locally installed Agent commands. The catalog currently includes:
|
||||
|
||||
The current release-validated target is Apple silicon macOS.
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/codex.svg" alt="Codex logo" width="32" height="32"><br><strong>Codex</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/hermes.png" alt="Hermes logo" width="32" height="32"><br><strong>Hermes</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/openclaw-transparent.png" alt="OpenClaw logo" width="32" height="32"><br><strong>OpenClaw</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/workbuddy.png" alt="WorkBuddy logo" width="32" height="32"><br><strong>WorkBuddy</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/pi.svg" alt="Pi Agent logo" width="32" height="32"><br><strong>Pi Agent</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/kimi.png" alt="Kimi Code logo" width="32" height="32"><br><strong>Kimi Code</strong></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/mimo.svg" alt="MiMo Code logo" width="32" height="32"><br><strong>MiMo Code</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/claude.png" alt="Claude Code logo" width="32" height="32"><br><strong>Claude Code</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/gemini.svg" alt="Gemini CLI logo" width="32" height="32"><br><strong>Gemini CLI</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/opencode.svg" alt="OpenCode logo" width="32" height="32"><br><strong>OpenCode</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/qwen.svg" alt="Qwen Code logo" width="32" height="32"><br><strong>Qwen Code</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/opencodereview.svg" alt="OpenCodeReview logo" width="32" height="32"><br><strong>OpenCodeReview</strong></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
1. Open the [Meldwork V1.0.2 prerelease](https://github.com/Ryder-MHumble/Meldwork/releases/tag/Meldwork-V1.0.2).
|
||||
2. Download Meldwork-0.1.2-arm64.dmg.
|
||||
3. Drag Meldwork into Applications and try to open it once.
|
||||
4. This prerelease is ad-hoc signed, not signed with an Apple Developer ID, and not Apple-notarized. If macOS blocks it, open **System Settings → Privacy & Security**, find the Meldwork warning, choose **Open Anyway**, and confirm.
|
||||
5. Connect a supported Agent CLI already installed on the computer, or configure an independent Provider profile where supported.
|
||||
Approved Agent Connectors and custom executable Agents use the desktop connector paths. The [desktop guide](desktop/README.md) contains the current adapter, installation, provider, and capability matrix.
|
||||
|
||||
Use only artifacts downloaded from the official Release.
|
||||
## Context and local boundaries
|
||||
|
||||
<details>
|
||||
<summary><strong>Build from source</strong></summary>
|
||||
Meldwork runs as a local Electron application. Conversations, group configuration, run records, and app-owned attachments stay in the local user data directory. The renderer receives only validated snapshots through a narrow preload API; executable paths, credentials, native session references, Skill paths, and unrestricted shell access remain in the main process.
|
||||
|
||||
Requires Node.js 22.12 or newer and npm.
|
||||
Selected Agents may send prompts, attachments, or Skills to their configured model Provider. Knowledge access is explicit and bounded: the current implementation supports local Obsidian retrieval and CLI-owned Feishu or DingTalk access modes. Local-first describes where Meldwork stores and coordinates work; it does not promise that a configured Agent Provider is offline.
|
||||
|
||||
~~~bash
|
||||
## Download V1.0.5
|
||||
|
||||
For Apple silicon macOS, download the [Meldwork V1.0.5 prerelease](https://github.com/Ryder-MHumble/Meldwork/releases/tag/Meldwork-V1.0.5) and choose [`Meldwork-0.1.5-arm64.dmg`](https://github.com/Ryder-MHumble/Meldwork/releases/download/Meldwork-V1.0.5/Meldwork-0.1.5-arm64.dmg). The release also includes a ZIP archive and SHA-256 manifest. Install at least one supported local Agent CLI before opening the app.
|
||||
|
||||
The preview artifacts are ad-hoc signed and not notarized with an Apple Developer ID. macOS may require **Open Anyway** under **System Settings → Privacy & Security** on first launch.
|
||||
|
||||
## Run from source
|
||||
|
||||
Prerequisites: Node.js `22.12+` and npm.
|
||||
|
||||
```bash
|
||||
npm --prefix frontend ci
|
||||
npm --prefix desktop ci
|
||||
npm --prefix desktop run dev
|
||||
~~~
|
||||
```
|
||||
|
||||
Run the repository checks before distributing a build:
|
||||
Before distributing a build:
|
||||
|
||||
~~~bash
|
||||
```bash
|
||||
npm --prefix frontend test
|
||||
npm --prefix frontend run build
|
||||
npm --prefix frontend run build:desktop
|
||||
npm --prefix desktop test
|
||||
~~~
|
||||
```
|
||||
|
||||
</details>
|
||||
## V1.0.5
|
||||
|
||||
## Trust boundaries
|
||||
V1.0.5 improves local Agent readiness and recovery, preserves healthy participants when another Agent fails, keeps completed and stopped work visible after restart, and tightens group execution and output handling. It also updates the workspace preference flow, sidebar and titlebar details, and the Pi capability probe contract.
|
||||
|
||||
- Conversations and Meldwork orchestration state stay local.
|
||||
- Model requests still follow the Agent and Provider you choose; local-first does not mean every model runs offline.
|
||||
- Credentials use operating-system-backed secure storage where supported.
|
||||
- Workspace writes are explicit and opt-in.
|
||||
- Raw chain-of-thought, executable paths, secrets, and unrestricted command output are not exposed to the renderer.
|
||||
- Cloud, Channel, automatic participant selection, enterprise governance, and an Outcome Network are not current release promises.
|
||||
Verification for this prerelease includes 343/343 frontend tests, 1,562/1,562 desktop tests, six deterministic evaluation cases with 18 results, web and desktop builds, packaging, ZIP integrity, deep code-signature verification, and packaged macOS acceptance for group execution, cancellation, and restart recovery. The artifacts remain ad-hoc signed and unnotarized; live behavior still depends on the installed Agent CLI version, authentication, Provider, and capabilities.
|
||||
|
||||
Read the [architecture](architecture.md) and [Agent Connector contract](docs/agent-connector-sdk.md) for the public technical boundary.
|
||||
## Documentation
|
||||
|
||||
- [Architecture and product boundary](architecture.md)
|
||||
- [Desktop setup and Agent matrix](desktop/README.md)
|
||||
- [Contributing](CONTRIBUTING.md)
|
||||
- [Security policy](SECURITY.md)
|
||||
|
||||
## License
|
||||
|
||||
Meldwork is source-available under the [Meldwork Non-Commercial Source License](LICENSE). You may inspect, run, modify, and share it for non-commercial purposes. Commercial use requires prior written permission; see [COMMERCIAL_USE.md](COMMERCIAL_USE.md).
|
||||
Meldwork is source-available under the [Meldwork Non-Commercial Source License 1.0](LICENSE). You may inspect, run, modify, and share it for non-commercial purposes. Commercial use requires prior written permission; see [COMMERCIAL_USE.md](COMMERCIAL_USE.md).
|
||||
@@ -1,11 +1,3 @@
|
||||
<!-- <p align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="frontend/public/logos/meldwork-wordmark-v3-dark.svg">
|
||||
<source media="(prefers-color-scheme: light)" srcset="frontend/public/logos/meldwork-wordmark-v3.svg">
|
||||
<img src="frontend/public/logos/meldwork-wordmark-v3.svg" alt="Meldwork" width="360">
|
||||
</picture>
|
||||
</p> -->
|
||||
|
||||
<p align="center">
|
||||
<img src="frontend/public/logos/meldwork-readme-banner-cn.png" alt="Meldwork README banner" width="100%">
|
||||
</p>
|
||||
@@ -14,149 +6,129 @@
|
||||
<a href="README.md">English</a> · <strong>简体中文</strong>
|
||||
</p>
|
||||
|
||||
# Meldwork 为 AI Agent 构建组织层
|
||||
# Meldwork:本地优先的 General Agent 工作空间
|
||||
|
||||
**多数工具是在帮人类管更多 Agent;Meldwork 解决的是另一件事:让多 Agent 协作变得可见、可追责、可复用。**
|
||||
**把多个 General Agent 组织成一个可复核的工作小组。Meldwork 为每个任务建立共享上下文,让选定的 Agent 独立调查或分轮讨论,并在采用结果前保留完整的证据和人工决策。**
|
||||
|
||||
当前预览版是一个面向已支持本地 Agent CLI 的本地工作单元。它把参与者、上下文、协作边界、运行状态和人类复核放在同一个工作空间里。已选 Agent 现在可以并发回复,也可以围绕同一目标先独立提案、再协商职责、分工执行、单写者整合并由其他 Agent 独立复核。
|
||||
Meldwork 是一个本地优先的 Electron 工作空间,用来连接你已经在电脑上使用的 Agent 工具。它支持直接会话、独立并发回复,以及包含提案、质询、职责协商、分工执行、整合和复核的 Auto Discussion V4。Agent 可以处理文字、文件、图片、音视频、Skill 和选定的知识源,因此同一个工作空间可以覆盖研究、分析、写作、规划、评审和实施。
|
||||
|
||||
产品围绕一条可持续复核的记录组织工作:**Case → Finding → Evidence → Decision → Disposition**。Meldwork 将任务快照、Agent 贡献、运行状态、产物、人工审批门和采用决定保存在同一个本地工作单元中。工作区写入默认受控,并由用户明确授权。
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Ryder-MHumble/Meldwork/releases/download/Meldwork-V1.0.2/Meldwork-0.1.2-arm64.dmg"><strong>下载 Meldwork V1.0.2 Apple 芯片 macOS 版</strong></a>
|
||||
<a href="https://github.com/Ryder-MHumble/Meldwork/releases/download/Meldwork-V1.0.5/Meldwork-0.1.5-arm64.dmg"><strong>下载 Meldwork V1.0.5 Apple 芯片 macOS 版</strong></a>
|
||||
· <a href="architecture.md">架构</a>
|
||||
· <a href="LICENSE">许可证</a>
|
||||
</p>
|
||||
|
||||
## Agent workforce 缺少的那一层
|
||||
## Meldwork 适合什么工作
|
||||
|
||||
Agent 的供给正在快速增长,但围绕它们工作的组织能力并没有跟上。
|
||||
当一个决定需要多个视角,并且需要留下清晰的采用依据时,Meldwork 更适合:
|
||||
|
||||
今天,人类仍然需要自己选 Agent、搬运上下文、解释角色、处理冲突答案,并承担最终责任。并行管理器优化吞吐量,多 Agent 框架让开发者编写 Workflow,单 Agent 产品优化一个 Worker。
|
||||
- 研究与信息综合:结合本地 Agent 工具和明确选择的知识源;
|
||||
- 产品、市场、运营和技术分析;
|
||||
- 写作、规划、评审和结构化文档工作;
|
||||
- 处理本地文档、图片、音频、视频、PDF、代码和配置文件的多模态工作;
|
||||
- 需要保留发现、证据、权限、运行轨迹和最终采用决定的实施工作。
|
||||
|
||||
Meldwork 关注的是中间那层工作:
|
||||
## 一个任务如何在 Meldwork 中推进
|
||||
|
||||
- 一个共享 Goal 和明确验收边界;
|
||||
- 独立判断,而不是隐藏路由;
|
||||
- 明确的权限、责任、交接和停止条件;
|
||||
- 不随 Agent 切换而丢失的 Artifact 与 Evidence;
|
||||
- 由人类掌握的最终采用决定。
|
||||
1. **选择**本 Case 的 Agent 和参与者。
|
||||
2. **限定**目标、工作目录、上下文、附件、Skill、知识源和权限。
|
||||
3. **运行**直接会话、并发回复或 Auto Discussion V4。
|
||||
4. **复核**发现、证据、产物、运行轨迹和人工审批门。
|
||||
5. **采用**批准的结果,或保留为待解决状态继续处理。
|
||||
|
||||
## 当前已经可用
|
||||
## 协作模式
|
||||
|
||||
- **支持的本地 Agent CLI**:检测、检查并受控调用已批准的 Agent,不把不受限的 Shell 暴露给 Renderer。
|
||||
- **持续的直接工作**:把本地历史、附件、权限、兼容的原生 Session 和脱敏执行详情放在一起,尽量不让上下文断线。
|
||||
- **并发回复**:一条消息同时发给多个已选 Agent,执行前冻结同一份任务上下文,并以稳定批次公布各自独立回复。
|
||||
- **Agent 自主协商协作**:先独立提案,再互相质询并全员同意一份职责图,随后执行不同工作包,由唯一写入者整合,并由不同 Agent 独立复核。
|
||||
- **可检查执行**:保留有界运行事件、警告、终态、检查点和恢复动作,不暴露凭据或私有推理。
|
||||
- **本地控制**:Meldwork 的会话和编排状态都留在电脑上;工作目录写入必须主动开启。
|
||||
|
||||
具体能力仍取决于所选 Agent、本机版本、认证状态、Provider 和声明的工具/附件支持。
|
||||
|
||||
## Meldwork 正在构建什么
|
||||
|
||||
当前协作机制不是 Harness 暗中预设的 A → B → C 分配链。用户选定参与者后,Agent 先展开解空间、自主协商职责,再在 Harness 管理的上下文、权限、预算、恢复和证据边界内执行。
|
||||
|
||||
~~~mermaid
|
||||
flowchart LR
|
||||
G["目标与验收契约"] --> P["独立竞案"]
|
||||
P --> C["公开质询"]
|
||||
C --> B["角色声明与团队竞案"]
|
||||
B --> R["责任契约"]
|
||||
R --> X["有界执行"]
|
||||
X --> E["产物与证据"]
|
||||
E --> H["人类采用"]
|
||||
H --> O["结果回执"]
|
||||
O -. "Agent Fit + Team Fit" .-> P
|
||||
~~~
|
||||
|
||||
已选 Agent 的独立提案、交叉质询、职责协商、分工执行、整合和复核现在已经可用。从更大候选池自动选人组队、远程 Agent、企业治理和 Outcome 驱动的声誉系统仍是未来方向。
|
||||
|
||||
## Harness
|
||||
|
||||
Harness 是把会话、上下文、适配器、流和持久化状态拴在一起的控制平面。它让一次任务可以跨会话、超时、恢复和 Agent 切换继续下去。
|
||||
|
||||
<p align="center">
|
||||
<img src="frontend/public/logos/Harness-readme.png" alt="Meldwork Harness" width="100%">
|
||||
</p>
|
||||
|
||||
## Meldwork 在哪里
|
||||
|
||||
这张表比较的是不同工作范式,不是一张声称 Meldwork 应当替代所有工具的功能勾选表。
|
||||
|
||||
| 范式 | 例子 | 最擅长什么 | 主要代价 | Meldwork 的选择 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 单 Agent CLI / AI IDE | Claude Code、Codex、Cursor、Windsurf | 在一个 Agent 或产品生态内完成深度工作 | 换 Agent 时仍需手工交接 | 保留跨异构 Agent 的工作 |
|
||||
| 并行 Coding-Agent 工作台 | Superset、Vibe Kanban、Nimbalyst、Conductor | 并行运行多个 Coding 任务和隔离工作区 | 主要优化吞吐量和代码交付 | 优化方案质量、责任、证据和采用 |
|
||||
| Cloud Agent 控制面 | GitHub Agent HQ、Warp Oz、Devin、Factory、OpenHands Cloud | 派发和观察远程 Job、Sandbox 与 Agent Fleet | 工作围绕云基础设施和平台边界 | 先从 Local-first 和 BYO Agent 切入 |
|
||||
| 可编程多 Agent 框架 | LangGraph、CrewAI、AutoGen、Agents SDK、ADK | 开发者自定义 Graph、角色、路由和自动化 | 需要开发者设计并维护编排 | 面向使用者交付组织与验收体验 |
|
||||
| 多终端与脚本 | tmux、Shell、手工复制粘贴 | 最大化原生 Agent 访问权 | 人类成为 Router、Context Bus 和最终裁决者 | 让工作、边界和决定保持持续 |
|
||||
| **Meldwork** | 已支持本地 Agent CLI;远程供给属于方向 | 并发独立回复,以及已选 Agent 之间的提案、协商、责任、Evidence 和复核 | 当前仍是本地单用户预览;参与者仍由用户选定 | 构建 Agent workforce 的组织层 |
|
||||
|
||||
如果一个 Agent 和一个工作面已经足够,直接使用原生工具。只有当交接、独立判断、权限、证据和验收成为问题时,才需要 Meldwork。
|
||||
|
||||
## 看看当前 Work Cell
|
||||
|
||||
| 本地 Agent 检测 | 单聊中的多模态工作 | 并发多 Agent 协作 |
|
||||
| 模式 | 运行方式 | 适合场景 |
|
||||
| --- | --- | --- |
|
||||
| [](assets/meldwork-agent-discovery.png) | [](assets/meldwork-direct-multimodal.png) | [](assets/meldwork-group-collaboration.png) |
|
||||
| 查看哪些受支持 Agent 已就绪。 | Prompt、文件、权限和兼容 Session 留在一起。 | 让已选 Agent 并发回复,或进入由 Agent 自主协商职责的协作流程。 |
|
||||
| **直接会话** | 一个已选 Agent 在适配器支持时保持对话和原生会话。 | 聚焦研究、写作、分析或执行。 |
|
||||
| **并发回复** | 已选 Agent 收到同一份冻结任务快照,并按稳定顺序返回独立回复。 | 在选择方案前比较不同视角。 |
|
||||
| **Auto Discussion V4** | Agent 先提出方案,再进行质询、职责协商、分工执行、候选结果整合和独立复核;支持时会在多轮中保持原生会话。 | 需要讨论、分工和复核的多步骤工作。 |
|
||||
|
||||
## 当前可连接的 Agent
|
||||
参与者始终由用户选择。从更大候选池自动选人组队不属于当前预览版。
|
||||
|
||||
当前集成包括:
|
||||
## 复核记录
|
||||
|
||||
**Codex · Hermes · OpenClaw · WorkBuddy · Kimi Code · MiMo Code · Claude Code · Gemini CLI · OpenCode · Qwen Code**
|
||||
Meldwork 将协作组织成一套决策过程,而不是一串聊天消息:
|
||||
|
||||
专项审查:
|
||||
- **Case**:定义问题、范围、上下文和权限;
|
||||
- **Finding**:记录 Agent 的判断、观察或行动建议;
|
||||
- **Evidence**:将 Finding 连接到回复、产物、文件、知识结果或其他受约束的依据;
|
||||
- **Decision**:记录证据支持的结论、未决问题和选定路径;
|
||||
- **Disposition**:记录结果已接受、修订、拒绝、被替代或仍未解决。
|
||||
|
||||
**OpenCodeReview**
|
||||
Run Ledger 会保留阶段、参与者、尝试、回执、产物、恢复状态和人工审批门。诊断工具输出与敏感运行信息留在 Electron 主进程边界内。
|
||||
|
||||
能否使用取决于安装、版本、认证、Provider 和声明的能力。每个 Agent 保留自己的工具、Session 行为和权限模型。
|
||||
## General Agent 目录
|
||||
|
||||
## 安装
|
||||
当适配器和 CLI 版本兼容时,Meldwork 会检测并调用已安装的 Agent 命令。当前目录包括:
|
||||
|
||||
当前经过发布验证的目标是 Apple 芯片 macOS。
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/codex.svg" alt="Codex logo" width="32" height="32"><br><strong>Codex</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/hermes.png" alt="Hermes logo" width="32" height="32"><br><strong>Hermes</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/openclaw-transparent.png" alt="OpenClaw logo" width="32" height="32"><br><strong>OpenClaw</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/workbuddy.png" alt="WorkBuddy logo" width="32" height="32"><br><strong>WorkBuddy</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/pi.svg" alt="Pi Agent logo" width="32" height="32"><br><strong>Pi Agent</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/kimi.png" alt="Kimi Code logo" width="32" height="32"><br><strong>Kimi Code</strong></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/mimo.svg" alt="MiMo Code logo" width="32" height="32"><br><strong>MiMo Code</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/claude.png" alt="Claude Code logo" width="32" height="32"><br><strong>Claude Code</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/gemini.svg" alt="Gemini CLI logo" width="32" height="32"><br><strong>Gemini CLI</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/opencode.svg" alt="OpenCode logo" width="32" height="32"><br><strong>OpenCode</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/qwen.svg" alt="Qwen Code logo" width="32" height="32"><br><strong>Qwen Code</strong></td>
|
||||
<td align="center" valign="top" width="16.66%"><img src="frontend/public/agent-logos/opencodereview.svg" alt="OpenCodeReview logo" width="32" height="32"><br><strong>OpenCodeReview</strong></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
1. 打开 [Meldwork V1.0.2 预发布页](https://github.com/Ryder-MHumble/Meldwork/releases/tag/Meldwork-V1.0.2)。
|
||||
2. 下载 Meldwork-0.1.2-arm64.dmg。
|
||||
3. 将 Meldwork 拖入“应用程序”,然后先尝试打开一次。
|
||||
4. 当前预发布版使用临时签名,没有 Apple Developer ID 签名,也尚未经过 Apple 公证。如果 macOS 阻止启动,请打开“系统设置 → 隐私与安全性”,找到 Meldwork 提示,点击“仍要打开”并确认。
|
||||
5. 连接电脑上已安装的受支持 Agent CLI,或在兼容情况下单独配置 Provider。
|
||||
已批准的 Agent Connector 和自定义可执行 Agent 使用桌面端的连接器入口。完整的适配器、安装、Provider 和能力矩阵见[桌面端指南](desktop/README.md)。
|
||||
|
||||
请只使用官方 Release 下载的产物。
|
||||
## 上下文与本地边界
|
||||
|
||||
<details>
|
||||
<summary><strong>从源码运行</strong></summary>
|
||||
Meldwork 作为本地 Electron 应用运行。对话、群组配置、运行记录和应用管理的附件保存在本地用户数据目录。渲染进程只通过受约束的 preload API 获取校验后的状态;可执行路径、凭据、原生会话引用、Skill 路径和任意 Shell 权限都留在主进程中。
|
||||
|
||||
需要 Node.js 22.12 或更高版本以及 npm。
|
||||
选定的 Agent 仍可能把 Prompt、附件或 Skill 发送给其配置的模型 Provider。知识访问必须明确选择并受边界约束:当前实现支持本地 Obsidian 检索,以及由本地 CLI 管理的飞书或钉钉访问模式。Local-first 描述的是 Meldwork 的数据和协作位置,不代表已配置的 Agent Provider 一定离线。
|
||||
|
||||
~~~bash
|
||||
## 下载 V1.0.5
|
||||
|
||||
Apple 芯片 macOS 用户请前往 [Meldwork V1.0.5 预发布页](https://github.com/Ryder-MHumble/Meldwork/releases/tag/Meldwork-V1.0.5),下载 [`Meldwork-0.1.5-arm64.dmg`](https://github.com/Ryder-MHumble/Meldwork/releases/download/Meldwork-V1.0.5/Meldwork-0.1.5-arm64.dmg)。发布页同时提供 ZIP 压缩包和 SHA-256 校验文件。启动应用前,请至少安装一个受支持的本地 Agent CLI。
|
||||
|
||||
该预览版安装包使用 ad-hoc 临时签名,未使用 Apple Developer ID 签名,也未进行公证。macOS 首次启动时可能需要在“系统设置 → 隐私与安全性”中选择“仍要打开 / Open Anyway”。
|
||||
|
||||
## 从源码运行
|
||||
|
||||
前置条件:Node.js `22.12+` 和 npm。
|
||||
|
||||
```bash
|
||||
npm --prefix frontend ci
|
||||
npm --prefix desktop ci
|
||||
npm --prefix desktop run dev
|
||||
~~~
|
||||
```
|
||||
|
||||
分发前运行:
|
||||
分发构建前运行:
|
||||
|
||||
~~~bash
|
||||
```bash
|
||||
npm --prefix frontend test
|
||||
npm --prefix frontend run build
|
||||
npm --prefix frontend run build:desktop
|
||||
npm --prefix desktop test
|
||||
~~~
|
||||
```
|
||||
|
||||
</details>
|
||||
## V1.0.5
|
||||
|
||||
## 信任边界
|
||||
V1.0.5 改进了本地 Agent 的就绪检测与恢复,在单个 Agent 失败时保留健康参与者,重启后继续显示已完成和已停止的工作,并加强了群组执行与结果导入。同时更新了工作区偏好、侧栏和标题栏细节,以及 Pi 能力探测契约。
|
||||
|
||||
- Meldwork 会话和编排状态保存在本地。
|
||||
- 模型请求仍然按照你选择的 Agent 和 Provider 发出;Local-first 不等于所有模型离线运行。
|
||||
- 兼容环境使用操作系统安全存储保存凭据。
|
||||
- 工作目录写入必须显式开启。
|
||||
- Renderer 不暴露 raw chain-of-thought、可执行路径、Secret 或不受限命令输出。
|
||||
- Cloud、Channel、自动选人组队、企业治理和 Outcome Network 不是当前发布承诺。
|
||||
本预览版已完成 343/343 前端测试、1,562/1,562 桌面端测试、6 个确定性评估场景共 18 条结果验证,并通过 Web 与桌面构建、打包、ZIP 完整性、深度代码签名校验,以及 Apple 芯片 macOS 上的群组执行、取消和重启恢复验收。安装包仍为 ad-hoc 临时签名且未公证;实际运行结果仍取决于本机 Agent CLI 版本、鉴权、Provider 和能力。
|
||||
|
||||
公开技术边界见[架构](architecture.md)和 [Agent Connector 契约](docs/agent-connector-sdk.md)。
|
||||
## 文档
|
||||
|
||||
- [架构与产品边界](architecture.md)
|
||||
- [桌面端设置与 Agent 矩阵](desktop/README.md)
|
||||
- [贡献指南](CONTRIBUTING.md)
|
||||
- [安全策略](SECURITY.md)
|
||||
|
||||
## 许可证
|
||||
|
||||
Meldwork 采用 [Meldwork 非商用源码许可](LICENSE)。你可以为非商用目的查看、运行、修改和分享;商业使用需要事先书面许可,详见 [COMMERCIAL_USE.md](COMMERCIAL_USE.md)。
|
||||
Meldwork 采用 [Meldwork 非商用源码许可 1.0](LICENSE)。你可以出于非商业目的查看、运行、修改和分享。商业使用需要事先书面许可,详见 [COMMERCIAL_USE.md](COMMERCIAL_USE.md)。
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Product Boundary
|
||||
|
||||
Meldwork is a local Electron desktop product for direct and multi-Agent work with explicitly selected Skill, image, and knowledge-source context. It has no account system, tenant model, required application server, remote conversation store, email delivery, scheduled jobs, or public SEO surface. Optional Agent, Cloud, and Channel Connectors run behind the Electron main-process trust boundary and are disabled until explicitly configured.
|
||||
Meldwork is a local Electron desktop product for multi-agent orchestration and review with explicitly selected Skill, image, and knowledge-source context. It has no account system, tenant model, required application server, remote conversation store, email delivery, scheduled jobs, or hosted web surface. Optional Agent, Cloud, and Channel Connectors run behind the Electron main-process trust boundary and are disabled until explicitly configured. The landing page at https://ryder-mhumble.github.io/Meldwork/ is the public marketing surface for search engine and AI assistant discoverability.
|
||||
|
||||
The supported product surface is the packaged Electron application. The frontend is a renderer bundle; without the local preload bridge it shows a desktop-required state and cannot operate the workspace.
|
||||
|
||||
@@ -103,7 +103,7 @@ There is no Meldwork-hosted remote data store or application account namespace.
|
||||
|
||||
- No email sending, so there is no `emails.md`.
|
||||
- No cron or scheduled background work, so there is no `cron.md`.
|
||||
- No supported public or indexable routes, so there is no `seo.md`.
|
||||
- No supported public or indexable routes in the app itself, so there is no `seo.md`. The landing page at https://ryder-mhumble.github.io/Meldwork/ serves as the public discoverability surface for search engines and AI assistants.
|
||||
|
||||
## Related Documents
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"mode": "chat"}
|
||||
@@ -28,7 +28,7 @@ Agent 管理面板提供经过白名单约束的安装入口。安装命令和
|
||||
|
||||
## 首次启动与本地 Agent 检测
|
||||
|
||||
V1.0.2 GitHub 预发布使用 ad-hoc 临时签名,不使用 Apple Developer ID,也不提交 Apple 公证。
|
||||
V1.0.3 GitHub 预发布使用 ad-hoc 临时签名,不使用 Apple Developer ID,也不提交 Apple 公证。
|
||||
如果 macOS 首次启动时拦截候选应用,请打开
|
||||
“系统设置 → 隐私与安全性”,找到 Meldwork 的拦截提示,点击“仍要打开 / Open Anyway”,
|
||||
再确认启动。
|
||||
@@ -108,12 +108,12 @@ Hermes 和 Kimi 的安装脚本来自固定 HTTPS 白名单地址;客户端不
|
||||
- `src/agents/`:Agent 兼容层、路由、运行时、CLI、安装器、连接器
|
||||
- `src/attachments/`:附件、内容存储、图片尺寸校验
|
||||
- `src/collaboration/`:对话、上下文包、产物、任务图
|
||||
- `src/workspace/`:本地工作区与自动调度
|
||||
- `src/workspace/`:本地工作区与自动调度;自动运行器的通用失败、重试和等待语义位于 `local-workspace-auto-runner-support.cjs`
|
||||
- `src/runs/`:运行、预算、事件、调度、日志
|
||||
- `src/knowledge/`:知识库与知识连接器
|
||||
- `src/skills/`:Skill 目录、快照、信任
|
||||
- `src/security/`:私有文件与敏感信息脱敏
|
||||
- `test/`:按同名领域镜像组织测试,`support/` 放测试辅助代码
|
||||
- `test/`:按同名领域镜像组织测试,`support/` 放测试辅助代码;测试发现与 suite 选择位于 `scripts/test-discovery.cjs`
|
||||
|
||||
## 本地开发
|
||||
|
||||
@@ -137,7 +137,7 @@ npm run dist
|
||||
npm run dist:public
|
||||
```
|
||||
|
||||
`pack` 用于生成未打包应用并验证 Electron 产物;`dist` 生成 V1.0.2 GitHub 预发布候选使用的 ad-hoc 签名 DMG 和 ZIP。这些产物不具备 Developer ID 信任链且未公证,不能声称通过 Gatekeeper。
|
||||
`pack` 用于生成未打包应用并验证 Electron 产物;`dist` 生成 V1.0.3 GitHub 预发布候选使用的 ad-hoc 签名 DMG 和 ZIP。这些产物不具备 Developer ID 信任链且未公证,不能声称通过 Gatekeeper。
|
||||
|
||||
`dist:public` 是未来正式签名公开发行的专用命令:它要求
|
||||
Developer ID 证书和完整公证凭据,强制代码签名,在签名后校验永久 Bundle ID、Team ID 与
|
||||
|
||||
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 368 KiB |
|
After Width: | Height: | Size: 1.4 MiB |
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "meldwork-desktop",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "meldwork-desktop",
|
||||
"version": "0.1.2",
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"version": "0.1.5",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "0.23.0",
|
||||
"@streamparser/json": "0.0.22",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"name": "meldwork-desktop",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.5",
|
||||
"private": true,
|
||||
"description": "A local-first desktop workspace for multi-Agent collaboration",
|
||||
"author": "Ryder-MHumble",
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
},
|
||||
@@ -16,6 +16,10 @@
|
||||
"eval:deterministic": "node scripts/run-evals.cjs --suite deterministic",
|
||||
"eval:provider": "node scripts/run-evals.cjs --suite provider",
|
||||
"test": "node scripts/run-tests.cjs",
|
||||
"test:agents": "node scripts/run-tests.cjs --suite agents",
|
||||
"test:runs": "node scripts/run-tests.cjs --suite runs",
|
||||
"test:workspace": "node scripts/run-tests.cjs --suite workspace",
|
||||
"test:security": "node scripts/run-tests.cjs --suite security",
|
||||
"pack": "npm run build:frontend && electron-builder --dir",
|
||||
"dist": "npm run build:frontend && electron-builder --mac dmg zip",
|
||||
"dist:public": "node scripts/public-release-preflight.cjs && npm run build:frontend && electron-builder --config electron-builder.public.cjs --mac dmg zip"
|
||||
@@ -34,6 +38,7 @@
|
||||
"productName": "Meldwork",
|
||||
"artifactName": "Meldwork-${version}-${arch}.${ext}",
|
||||
"afterPack": "scripts/after-pack.cjs",
|
||||
"afterAllArtifactBuild": "scripts/after-all-artifact-build.cjs",
|
||||
"files": [
|
||||
"src/**/*",
|
||||
"samples/**/*",
|
||||
@@ -55,6 +60,10 @@
|
||||
{
|
||||
"from": "../COMMERCIAL_USE.md",
|
||||
"to": "COMMERCIAL_USE.md"
|
||||
},
|
||||
{
|
||||
"from": "build/dmg-background-ai-v4.tiff",
|
||||
"to": "dmg-background.tiff"
|
||||
}
|
||||
],
|
||||
"mac": {
|
||||
@@ -66,21 +75,23 @@
|
||||
]
|
||||
},
|
||||
"dmg": {
|
||||
"background": "build/dmg-background-ai-v2.png",
|
||||
"background": "build/dmg-background-ai-v4.png",
|
||||
"icon": null,
|
||||
"writeUpdateInfo": false,
|
||||
"window": {
|
||||
"width": 540,
|
||||
"height": 380
|
||||
"width": 640,
|
||||
"height": 420
|
||||
},
|
||||
"iconSize": 128,
|
||||
"iconSize": 112,
|
||||
"contents": [
|
||||
{
|
||||
"x": 145,
|
||||
"y": 210,
|
||||
"x": 110,
|
||||
"y": 205,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"x": 395,
|
||||
"y": 210,
|
||||
"x": 520,
|
||||
"y": 205,
|
||||
"type": "link",
|
||||
"path": "/Applications"
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"manifest":{"connectorId":"external.local-echo-sample","connectorVersion":"1.0.0","credentials":{"mode":"none","slots":[]},"description":"Local SDK sample that returns text without delegating to a built-in Agent.","domains":["general"],"eventProtocolVersion":1,"eventTypes":["Completed","Failed","Cancelled"],"inputTypes":["text"],"invocation":{"recipeId":"sdk.local-echo.v1"},"kind":"agent","label":"Local Echo Connector Sample","license":"LicenseRef-Meldwork-NC","manifestId":"connector-manifest-6ce79bf9cbe282e9f537a1b45d742cc507e21ade5ea2859dff9e007bd4f850db","outboundDestinations":[],"permissionModes":["read-only"],"recordType":"agent-connector-manifest","schemaVersion":1,"session":{"cancel":true,"checkpoint":false,"resume":true,"supported":true},"transport":{"protocol":"json","type":"cli"},"upstream":{"id":"meldwork-sdk","maxVersion":"1.0.0","minVersion":"1.0.0"},"usage":{"costMicros":false,"elapsedMs":false,"inputTokens":false,"outboundBytes":false,"outputTokens":false,"toolCalls":false}},"packageId":"connector-package-f4908cee8fa7acf5d17a403b39bd58cb8d4a1dfec3fbfb43c62c5727ee793cd4","provider":{"config":{},"id":"sdk.local-echo.v1"},"publisher":{"id":"meldwork","name":"Meldwork"},"recordType":"agent-connector-package","schemaVersion":1}
|
||||
{"manifest":{"connectorId":"external.local-echo-sample","connectorVersion":"1.0.0","credentials":{"mode":"none","slots":[]},"description":"Local SDK sample that returns text without delegating to a built-in Agent.","domains":["general"],"eventProtocolVersion":1,"eventTypes":["Completed","Failed","Cancelled"],"inputTypes":["text"],"invocation":{"recipeId":"sdk.local-echo.v1"},"kind":"agent","label":"Local Echo Connector Sample","license":"Apache-2.0","manifestId":"connector-manifest-6ce79bf9cbe282e9f537a1b45d742cc507e21ade5ea2859dff9e007bd4f850db","outboundDestinations":[],"permissionModes":["read-only"],"recordType":"agent-connector-manifest","schemaVersion":1,"session":{"cancel":true,"checkpoint":false,"resume":true,"supported":true},"transport":{"protocol":"json","type":"cli"},"upstream":{"id":"meldwork-sdk","maxVersion":"1.0.0","minVersion":"1.0.0"},"usage":{"costMicros":false,"elapsedMs":false,"inputTokens":false,"outboundBytes":false,"outputTokens":false,"toolCalls":false}},"packageId":"connector-package-f4908cee8fa7acf5d17a403b39bd58cb8d4a1dfec3fbfb43c62c5727ee793cd4","provider":{"config":{},"id":"sdk.local-echo.v1"},"publisher":{"id":"meldwork","name":"Meldwork"},"recordType":"agent-connector-package","schemaVersion":1}
|
||||
@@ -0,0 +1,126 @@
|
||||
const fs = require('node:fs')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const { execFileSync } = require('node:child_process')
|
||||
|
||||
const ROOT_HIDDEN_RESOURCES = ['.background.tiff', '.VolumeIcon.icns']
|
||||
|
||||
function selectDmgArtifacts(artifactPaths) {
|
||||
return artifactPaths.filter(artifactPath => artifactPath.endsWith('.dmg'))
|
||||
}
|
||||
|
||||
function findBundledPython(cacheRoot = process.env.ELECTRON_BUILDER_CACHE) {
|
||||
const root = cacheRoot || path.join(os.homedir(), 'Library', 'Caches', 'electron-builder')
|
||||
const pending = [root]
|
||||
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop()
|
||||
let entries
|
||||
try {
|
||||
entries = fs.readdirSync(current, { withFileTypes: true })
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
const candidate = path.join(current, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
pending.push(candidate)
|
||||
} else if (
|
||||
entry.isFile()
|
||||
&& /^python3(?:\.\d+)?$/.test(entry.name)
|
||||
&& path.basename(current) === 'bin'
|
||||
&& candidate.includes(`${path.sep}dmg-builder@`)
|
||||
) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unable to locate dmg-builder's bundled Python under ${root}`)
|
||||
}
|
||||
|
||||
function parseAttachedVolume(plist, workDir, run = execFileSync) {
|
||||
const plistPath = path.join(workDir, 'attach.plist')
|
||||
fs.writeFileSync(plistPath, plist)
|
||||
const parsed = JSON.parse(run('plutil', ['-convert', 'json', '-o', '-', plistPath], {
|
||||
encoding: 'utf8',
|
||||
}))
|
||||
const mounted = parsed['system-entities'].find(entity => entity['mount-point'])
|
||||
if (!mounted) {
|
||||
throw new Error('hdiutil did not return a mounted DMG volume')
|
||||
}
|
||||
return { device: mounted['dev-entry'], mountPath: mounted['mount-point'] }
|
||||
}
|
||||
|
||||
function repointDmgBackground(dmgPath, options = {}) {
|
||||
const run = options.execFile || execFileSync
|
||||
const pythonPath = options.pythonPath || findBundledPython(options.cacheRoot)
|
||||
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-dmg-'))
|
||||
const readWriteDmg = path.join(workDir, 'writable.dmg')
|
||||
const repackedDmg = `${dmgPath}.repacked-${process.pid}.dmg`
|
||||
let device
|
||||
|
||||
try {
|
||||
run('hdiutil', ['convert', dmgPath, '-format', 'UDRW', '-o', readWriteDmg], {
|
||||
stdio: 'pipe',
|
||||
})
|
||||
const attached = parseAttachedVolume(run('hdiutil', [
|
||||
'attach', readWriteDmg, '-nobrowse', '-readwrite', '-plist',
|
||||
], { encoding: 'utf8' }), workDir, run)
|
||||
device = attached.device
|
||||
|
||||
const backgroundPath = path.join(
|
||||
attached.mountPath,
|
||||
'Meldwork.app',
|
||||
'Contents',
|
||||
'Resources',
|
||||
'dmg-background.tiff',
|
||||
)
|
||||
if (!fs.existsSync(backgroundPath)) {
|
||||
throw new Error(`Packaged DMG background is missing: ${backgroundPath}`)
|
||||
}
|
||||
|
||||
run(pythonPath, [
|
||||
path.join(__dirname, 'repoint-dmg-background.py'),
|
||||
path.join(attached.mountPath, '.DS_Store'),
|
||||
backgroundPath,
|
||||
], { stdio: 'pipe' })
|
||||
|
||||
for (const resource of ROOT_HIDDEN_RESOURCES) {
|
||||
fs.rmSync(path.join(attached.mountPath, resource), { force: true })
|
||||
}
|
||||
run('/usr/bin/SetFile', ['-a', 'c', attached.mountPath], { stdio: 'pipe' })
|
||||
run('/bin/sync', [], { stdio: 'pipe' })
|
||||
run('hdiutil', ['detach', device], { stdio: 'pipe' })
|
||||
device = null
|
||||
|
||||
run('hdiutil', [
|
||||
'convert', readWriteDmg, '-format', 'UDZO', '-imagekey', 'zlib-level=9', '-o', repackedDmg,
|
||||
], { stdio: 'pipe' })
|
||||
fs.renameSync(repackedDmg, dmgPath)
|
||||
} finally {
|
||||
if (device) {
|
||||
try {
|
||||
run('hdiutil', ['detach', '-force', device], { stdio: 'pipe' })
|
||||
} catch {}
|
||||
}
|
||||
fs.rmSync(repackedDmg, { force: true })
|
||||
fs.rmSync(workDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
async function afterAllArtifactBuild(buildResult) {
|
||||
for (const dmgPath of selectDmgArtifacts(buildResult.artifactPaths)) {
|
||||
repointDmgBackground(dmgPath)
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
afterAllArtifactBuild.ROOT_HIDDEN_RESOURCES = ROOT_HIDDEN_RESOURCES
|
||||
afterAllArtifactBuild.selectDmgArtifacts = selectDmgArtifacts
|
||||
afterAllArtifactBuild.findBundledPython = findBundledPython
|
||||
afterAllArtifactBuild.parseAttachedVolume = parseAttachedVolume
|
||||
afterAllArtifactBuild.repointDmgBackground = repointDmgBackground
|
||||
|
||||
module.exports = afterAllArtifactBuild
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env swift
|
||||
import AppKit
|
||||
import Foundation
|
||||
|
||||
let arguments = CommandLine.arguments
|
||||
guard arguments.count == 3 else {
|
||||
fputs("Usage: render-dmg-background.swift <source.png> <output.png>\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
let sourceURL = URL(fileURLWithPath: arguments[1])
|
||||
let outputURL = URL(fileURLWithPath: arguments[2])
|
||||
guard let source = NSImage(contentsOf: sourceURL) else {
|
||||
fputs("Unable to read source image\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
guard let bitmap = NSBitmapImageRep(
|
||||
bitmapDataPlanes: nil,
|
||||
pixelsWide: 1280,
|
||||
pixelsHigh: 840,
|
||||
bitsPerSample: 8,
|
||||
samplesPerPixel: 4,
|
||||
hasAlpha: true,
|
||||
isPlanar: false,
|
||||
colorSpaceName: .deviceRGB,
|
||||
bytesPerRow: 0,
|
||||
bitsPerPixel: 0
|
||||
) else {
|
||||
fputs("Unable to create output bitmap\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap)
|
||||
source.draw(
|
||||
in: NSRect(x: 0, y: 0, width: 1280, height: 840),
|
||||
from: NSRect(x: 0, y: 4, width: 1280, height: 840),
|
||||
operation: .copy,
|
||||
fraction: 1
|
||||
)
|
||||
|
||||
let centered = NSMutableParagraphStyle()
|
||||
centered.alignment = .center
|
||||
|
||||
let title = "INSTALL MELDWORK" as NSString
|
||||
title.draw(
|
||||
in: NSRect(x: 0, y: 712, width: 1280, height: 52),
|
||||
withAttributes: [
|
||||
.font: NSFont(name: "DIN Alternate Bold", size: 38) ?? NSFont.boldSystemFont(ofSize: 38),
|
||||
.foregroundColor: NSColor(white: 0.96, alpha: 0.94),
|
||||
.kern: 4.5,
|
||||
.paragraphStyle: centered,
|
||||
]
|
||||
)
|
||||
|
||||
let explanation = "DRAG MELDWORK INTO APPLICATIONS / YOUR WORKSPACE STAYS LOCAL" as NSString
|
||||
explanation.draw(
|
||||
in: NSRect(x: 0, y: 675, width: 1280, height: 30),
|
||||
withAttributes: [
|
||||
.font: NSFont(name: "Menlo-Regular", size: 14) ?? NSFont.monospacedSystemFont(ofSize: 14, weight: .regular),
|
||||
.foregroundColor: NSColor(white: 0.82, alpha: 0.74),
|
||||
.kern: 1.5,
|
||||
.paragraphStyle: centered,
|
||||
]
|
||||
)
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
|
||||
guard let png = bitmap.representation(using: .png, properties: [:]) else {
|
||||
fputs("Unable to encode PNG\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
try png.write(to: outputURL)
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
|
||||
from ds_store import DSStore
|
||||
from mac_alias import Alias
|
||||
|
||||
|
||||
def main():
|
||||
ds_store_path, background_path = sys.argv[1:3]
|
||||
with DSStore.open(ds_store_path, "r+") as store:
|
||||
icon_view = store["."]["icvp"]
|
||||
icon_view["backgroundImageAlias"] = Alias.for_file(background_path).to_bytes()
|
||||
store["."]["icvp"] = icon_view
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,16 +1,17 @@
|
||||
const { spawnSync } = require('node:child_process')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const { discoverTestFiles } = require('./test-discovery.cjs')
|
||||
|
||||
function testFiles(directory) {
|
||||
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
||||
const filename = path.join(directory, entry.name)
|
||||
if (entry.isDirectory()) return testFiles(filename)
|
||||
return entry.isFile() && entry.name.endsWith('.test.cjs') ? [filename] : []
|
||||
})
|
||||
function option(name, fallback) {
|
||||
const index = process.argv.indexOf(name)
|
||||
return index === -1 ? fallback : process.argv[index + 1] || fallback
|
||||
}
|
||||
|
||||
const result = spawnSync(process.execPath, ['--test', '--test-concurrency=2', ...testFiles('test').sort()], {
|
||||
const suite = option('--suite', 'all')
|
||||
const result = spawnSync(process.execPath, [
|
||||
'--test',
|
||||
'--test-concurrency=2',
|
||||
...discoverTestFiles({ suite }),
|
||||
], {
|
||||
stdio: 'inherit',
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const TEST_SUITES = Object.freeze({
|
||||
agents: ['agents'],
|
||||
attachments: ['attachments'],
|
||||
collaboration: ['collaboration'],
|
||||
core: ['channels', 'knowledge', 'media', 'providers', 'skills'],
|
||||
runs: ['runs'],
|
||||
security: ['security', 'shell'],
|
||||
workspace: ['workspace', 'gates'],
|
||||
})
|
||||
|
||||
function collectTestFiles(directory) {
|
||||
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
||||
const filename = path.join(directory, entry.name)
|
||||
if (entry.isDirectory()) return collectTestFiles(filename)
|
||||
return entry.isFile() && entry.name.endsWith('.test.cjs') ? [filename] : []
|
||||
})
|
||||
}
|
||||
|
||||
function normalizeSuite(suite) {
|
||||
const value = String(suite || 'all').trim().toLowerCase()
|
||||
if (value === 'all') return null
|
||||
if (!Object.hasOwn(TEST_SUITES, value)) {
|
||||
throw new Error(`Unknown desktop test suite: ${value}`)
|
||||
}
|
||||
return new Set(TEST_SUITES[value])
|
||||
}
|
||||
|
||||
function testSuiteForFile(filename, directory = 'test') {
|
||||
const relative = path.relative(path.resolve(directory), filename)
|
||||
return relative.split(path.sep)[0] || 'core'
|
||||
}
|
||||
|
||||
function discoverTestFiles({ directory = 'test', suite = 'all' } = {}) {
|
||||
const selectedRoots = normalizeSuite(suite)
|
||||
return collectTestFiles(path.resolve(directory))
|
||||
.filter((filename) => !selectedRoots || selectedRoots.has(testSuiteForFile(filename, directory)))
|
||||
.sort()
|
||||
}
|
||||
|
||||
module.exports = { TEST_SUITES, discoverTestFiles, normalizeSuite, testSuiteForFile }
|
||||
@@ -5,6 +5,7 @@ const AGENT_VERSION_IDENTITIES = Object.freeze({
|
||||
hermes: [/\bhermes(?:\s+agent)?\b/i],
|
||||
openclaw: [/\bopenclaw\b/i],
|
||||
workbuddy: [/\b(?:workbuddy|codebuddy)\b/i],
|
||||
pi: [/\bpi(?:\s+agent)?\b/i],
|
||||
kimi: [/\bkimi(?:\s+code)?\b/i],
|
||||
mimo: [/\bmimo(?:\s+code)?\b/i, /\bmimocode\b/i],
|
||||
claude: [/\bclaude(?:\s+code)?\b/i],
|
||||
@@ -18,6 +19,7 @@ const AGENT_EXECUTABLE_NAMES = Object.freeze({
|
||||
hermes: ['hermes'],
|
||||
openclaw: ['openclaw'],
|
||||
workbuddy: ['codebuddy'],
|
||||
pi: ['pi', 'pi-agent', 'piagent'],
|
||||
kimi: ['kimi'],
|
||||
mimo: ['mimo'],
|
||||
claude: ['claude'],
|
||||
@@ -54,6 +56,11 @@ const AGENT_COMPATIBILITY = Object.freeze({
|
||||
'json', 'plan', 'acceptEdits',
|
||||
]),
|
||||
]),
|
||||
pi: exactProfile('0.84.2', [
|
||||
probe('pi-cli', ['--help'], [
|
||||
'--mode', '--print', '--session', '--tools', '--approve', '--no-approve', 'json',
|
||||
]),
|
||||
]),
|
||||
kimi: profile('0.19.2', '0.32.0', [
|
||||
probe('kimi-stream', ['--help'], [
|
||||
'--output-format', '--auto', '--session', '--prompt', 'stream-json',
|
||||
@@ -94,11 +101,13 @@ const AGENT_COMPATIBILITY = Object.freeze({
|
||||
]),
|
||||
})
|
||||
|
||||
function probe(id, args, requiredText) {
|
||||
function probe(id, args, requiredText, validateOutput = null, timeout = null) {
|
||||
return Object.freeze({
|
||||
id,
|
||||
args: Object.freeze([...args]),
|
||||
requiredText: Object.freeze([...requiredText]),
|
||||
validateOutput,
|
||||
timeout,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -426,7 +426,7 @@ function importAgentOutputs(input, attachmentStore) {
|
||||
&& !Array.isArray(input.baseline.files)
|
||||
? input.baseline.files
|
||||
: {}
|
||||
const candidates = outputFiles(safeOutputDirectory(workdirRealPath))
|
||||
const controlledCandidates = outputFiles(safeOutputDirectory(workdirRealPath))
|
||||
.filter(file => !sameFileState(baselineFiles[file.name], file))
|
||||
.filter(file => Math.max(file.mtimeMs, file.ctimeMs) >= startedAt - 2000)
|
||||
.sort((left, right) => (
|
||||
@@ -434,6 +434,25 @@ function importAgentOutputs(input, attachmentStore) {
|
||||
|| left.name.localeCompare(right.name)
|
||||
))
|
||||
|
||||
const reportedCandidates = []
|
||||
const reportedPaths = Array.isArray(input.reportedPaths) ? input.reportedPaths : []
|
||||
for (const reportedPath of reportedPaths.slice(0, MAX_SCANNED_ENTRIES)) {
|
||||
if (typeof reportedPath !== 'string' || !path.isAbsolute(reportedPath)) continue
|
||||
try {
|
||||
const realPath = fs.realpathSync(reportedPath)
|
||||
const stat = fs.statSync(realPath)
|
||||
const extension = path.extname(realPath).toLowerCase()
|
||||
if (!stat.isFile() || !SUPPORTED_EXTENSIONS.has(extension)
|
||||
|| stat.size > 64 * 1024 * 1024 || !isInside(workdirRealPath, realPath)) continue
|
||||
reportedCandidates.push({
|
||||
name: path.basename(realPath), path: realPath, size: stat.size,
|
||||
mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs,
|
||||
})
|
||||
} catch { /* reported paths are best effort */ }
|
||||
}
|
||||
const candidates = [...controlledCandidates, ...reportedCandidates]
|
||||
.filter((file, index, all) => all.findIndex(candidate => candidate.path === file.path) === index)
|
||||
|
||||
const imported = []
|
||||
if (input.signal?.aborted) return imported
|
||||
for (const file of candidates) {
|
||||
|
||||
@@ -339,7 +339,18 @@ class AgentRouter {
|
||||
const explicitReadOnlyTargets = effectiveMode === 'explicit'
|
||||
&& explicitTargets.length > 0
|
||||
&& explicitTargets.every(kind => isCodeReviewAgentKind(kind))
|
||||
const permissionMode = explicitReadOnlyTargets
|
||||
const detected = new Map((Array.isArray(agents) ? agents : []).map(agent => [agent.kind, agent]))
|
||||
const permissionTargets = effectiveMode === 'explicit' ? explicitTargets : approvedKinds
|
||||
const targetWriteSupport = permissionTargets.map((kind) => (
|
||||
agentRuntimeCapabilities(kind, {
|
||||
agent: detected.get(kind),
|
||||
attachmentSupport: this.attachmentSupport(kind),
|
||||
}).permissionModes.includes('workspace-write')
|
||||
))
|
||||
const writePermissionCompatible = effectiveMode === 'explicit'
|
||||
? targetWriteSupport.every(Boolean)
|
||||
: targetWriteSupport.some(Boolean)
|
||||
const permissionMode = explicitReadOnlyTargets || !writePermissionCompatible
|
||||
? 'read-only'
|
||||
: group.allowWrite === true ? 'workspace-write' : 'read-only'
|
||||
const requirements = normalizeRoutingRequirements(input.routingRequirements, {
|
||||
@@ -354,7 +365,6 @@ class AgentRouter {
|
||||
const kind = explicitTargets.find(target => !approvedKinds.includes(target))
|
||||
throw routingError('LOCAL_MESSAGE_TARGET_OUT_OF_GROUP', { kind })
|
||||
}
|
||||
const detected = new Map((Array.isArray(agents) ? agents : []).map(agent => [agent.kind, agent]))
|
||||
const candidates = approvedKinds.map((kind) => evaluateCandidate(
|
||||
detected.get(kind) || { kind, available: false },
|
||||
requirements,
|
||||
|
||||
@@ -79,6 +79,10 @@ const AGENT_RUNTIME_CAPABILITIES = Object.freeze({
|
||||
domains: ['general', 'software-development', 'document-production'],
|
||||
toolClasses: ['filesystem', 'shell'],
|
||||
}),
|
||||
pi: generalProfile({
|
||||
domains: ['general', 'software-development'],
|
||||
toolClasses: ['filesystem', 'shell'],
|
||||
}),
|
||||
kimi: generalProfile({
|
||||
domains: ['general', 'software-development', 'research', 'document-production'],
|
||||
toolClasses: ['filesystem', 'shell'],
|
||||
@@ -206,6 +210,15 @@ function normalizeExternalRunRef(value) {
|
||||
return EXTERNAL_RUN_REF.test(ref) ? ref : ''
|
||||
}
|
||||
|
||||
function terminalAuthenticationDiagnostic(value) {
|
||||
const text = String(value || '').replace(/\s+/g, ' ').trim()
|
||||
if (!text || text.length > 2000) return ''
|
||||
return /^HTTP\s+(?:401|403)\s*:\s*(?:unauthorized|forbidden|(?:invalid|expired|missing)\s+(?:access\s+token|token|credentials?|api[ _-]?key|authentication))(?:\s*\(request[ _-]?id:\s*[^()]{1,160}\))?\.?$/i
|
||||
.test(text)
|
||||
? text
|
||||
: ''
|
||||
}
|
||||
|
||||
function failureCategory(code) {
|
||||
const value = String(code || '')
|
||||
if (value === 'LOCAL_AGENT_SESSION_INVALID') return 'session'
|
||||
@@ -295,6 +308,10 @@ function requireTerminalAgentResult(result) {
|
||||
failure,
|
||||
)
|
||||
}
|
||||
const authenticationDiagnostic = terminalAuthenticationDiagnostic(normalized.text)
|
||||
if (authenticationDiagnostic) {
|
||||
throw agentRuntimeError('LOCAL_AGENT_AUTH_REQUIRED', authenticationDiagnostic)
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
@@ -328,4 +345,5 @@ module.exports = {
|
||||
normalizeOutcome,
|
||||
outcomeForAcpStopReason,
|
||||
requireTerminalAgentResult,
|
||||
terminalAuthenticationDiagnostic,
|
||||
}
|
||||
@@ -745,7 +745,7 @@ function publicSessionRef(value, childEnv) {
|
||||
return safe.includes('[redacted]') ? '' : safe
|
||||
}
|
||||
|
||||
async function runAcpTurn(runtime, prompt, options, spec, profile, persistent) {
|
||||
async function runAcpTurn(runtime, prompt, options, spec, profile) {
|
||||
if (runtime.closed || runtime.failureError) {
|
||||
throw runtime.failureError || agentExecutionError('LOCAL_AGENT_PROCESS_FAILED')
|
||||
}
|
||||
@@ -812,9 +812,6 @@ async function runAcpTurn(runtime, prompt, options, spec, profile, persistent) {
|
||||
|
||||
try {
|
||||
if (!protocolSessionRef) {
|
||||
if (persistent && options.sessionRef) {
|
||||
throw agentExecutionError('LOCAL_AGENT_SESSION_INVALID')
|
||||
}
|
||||
if (spec.acpSessionStrategy !== 'new' && options.sessionRef) {
|
||||
protocolSessionRef = String(options.sessionRef)
|
||||
await operation(runtime.connection.resumeSession({
|
||||
@@ -889,6 +886,11 @@ async function runAcpTurn(runtime, prompt, options, spec, profile, persistent) {
|
||||
? 'timeout'
|
||||
: normalized.failure?.category === 'cancellation' ? 'stopped' : 'failed',
|
||||
})
|
||||
if (promptStarted && options.sessionRef
|
||||
&& runtime.replyState.bytes === 0
|
||||
&& normalized.message === 'LOCAL_AGENT_REFUSED') {
|
||||
throw agentExecutionError('LOCAL_AGENT_SESSION_INVALID')
|
||||
}
|
||||
if (!promptStarted && normalized.message !== 'LOCAL_AGENT_SESSION_INVALID') {
|
||||
allowAcpSetupFallback(normalized)
|
||||
}
|
||||
@@ -955,9 +957,6 @@ async function runPersistentAcpAgent(agent, prompt, workdir, options, spec, prof
|
||||
runtime = null
|
||||
if (options.sessionRef) throw agentExecutionError('LOCAL_AGENT_SESSION_INVALID')
|
||||
}
|
||||
if (!runtime && options.sessionRef) {
|
||||
throw agentExecutionError('LOCAL_AGENT_SESSION_INVALID')
|
||||
}
|
||||
if (!runtime) {
|
||||
if (shutdownGeneration !== acpShutdownGeneration) {
|
||||
throw agentExecutionError('LOCAL_AGENT_EXECUTION_STOPPED')
|
||||
@@ -969,7 +968,7 @@ async function runPersistentAcpAgent(agent, prompt, workdir, options, spec, prof
|
||||
}
|
||||
runtime.active = true
|
||||
try {
|
||||
return await runAcpTurn(runtime, prompt, options, spec, profile, true)
|
||||
return await runAcpTurn(runtime, prompt, options, spec, profile)
|
||||
} catch (error) {
|
||||
acpSessionRuntimes.delete(key)
|
||||
await closeAcpRuntime(runtime)
|
||||
@@ -1003,7 +1002,7 @@ async function runDisposableAcpAgent(agent, prompt, workdir, options, spec, prof
|
||||
throw agentExecutionError('LOCAL_AGENT_EXECUTION_STOPPED')
|
||||
}
|
||||
acpDisposableRuntimes.add(runtime)
|
||||
return await runAcpTurn(runtime, prompt, options, spec, profile, false)
|
||||
return await runAcpTurn(runtime, prompt, options, spec, profile)
|
||||
} finally {
|
||||
if (runtime) {
|
||||
acpDisposableRuntimes.delete(runtime)
|
||||
|
||||
@@ -15,11 +15,13 @@ const {
|
||||
parseMimoOutput,
|
||||
parseOpenCodeOutput,
|
||||
parseOpenCodeReviewOutput,
|
||||
parsePiOutput,
|
||||
parseWorkBuddyOutput,
|
||||
readHermesFinalResponse,
|
||||
readHermesMessageWatermark,
|
||||
redactChildSecrets,
|
||||
runtimeCommandSummary,
|
||||
stripExactMeldworkPromptEcho,
|
||||
structuredCliError,
|
||||
} = require('./cli-runtime-events.cjs')
|
||||
const {
|
||||
@@ -121,12 +123,14 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
? options.hermesAcpAvailable
|
||||
: agent.acpAvailable
|
||||
const spec = invocation(agent.kind, agent.executable, workdir, sessionRef, {
|
||||
platform,
|
||||
sandbox: options.sandbox,
|
||||
provider: options.provider,
|
||||
attachments: options.attachments,
|
||||
hermesAcpAvailable,
|
||||
invocationTransport: options.invocationTransport,
|
||||
sessionTransport: options.sessionTransport,
|
||||
maxTurns: options.maxTurns,
|
||||
})
|
||||
const profile = resolveConnectorEventProfile(agent.kind, {
|
||||
transport: spec.eventTransport,
|
||||
@@ -241,9 +245,12 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
let settled = false
|
||||
let stopRequested = false
|
||||
let timeoutRequested = false
|
||||
let inputError = null
|
||||
let timeout
|
||||
let forceKillTimeout
|
||||
let forceSettleTimeout
|
||||
let terminalKillTimer
|
||||
let terminalForceKillTimer
|
||||
const progress = []
|
||||
const progressIndexes = new Map()
|
||||
let anonymousProgressId = 0
|
||||
@@ -272,6 +279,7 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
&& typeof profile.createDecoder === 'function'
|
||||
? profile.createDecoder((event) => {
|
||||
structuredOutput.ingest?.(event)
|
||||
observeTerminalEvent(event)
|
||||
const progressEvent = profile.mapProgress(event)
|
||||
if (progressEvent) emitProgress(progressEvent)
|
||||
for (const runtimeEvent of profile.mapEvent(event, runtimeState)) {
|
||||
@@ -285,6 +293,8 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
clearTimeout(timeout)
|
||||
clearTimeout(forceKillTimeout)
|
||||
clearTimeout(forceSettleTimeout)
|
||||
clearTimeout(terminalKillTimer)
|
||||
clearTimeout(terminalForceKillTimer)
|
||||
options.signal?.removeEventListener('abort', abort)
|
||||
callback()
|
||||
}
|
||||
@@ -299,9 +309,31 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
child.kill(signal)
|
||||
} catch { /* the process has already exited */ }
|
||||
}
|
||||
let terminalObserved = false
|
||||
const observeTerminalEvent = (event) => {
|
||||
if (terminalObserved || !event || typeof event !== 'object') return
|
||||
const terminal = (
|
||||
(['workbuddy', 'claude', 'qwen'].includes(agent.kind) && event.type === 'result')
|
||||
|| (agent.kind === 'pi' && event.type === 'agent_end')
|
||||
|| (agent.kind === 'codex' && event.type === 'turn.completed')
|
||||
|| (['mimo', 'opencode'].includes(agent.kind) && event.type === 'step_finish')
|
||||
|| (agent.kind === 'gemini' && event.type === 'result')
|
||||
|| (agent.kind === 'kimi' && event.type === 'session.resume_hint')
|
||||
)
|
||||
if (!terminal) return
|
||||
terminalObserved = true
|
||||
terminalKillTimer = setTimeout(() => {
|
||||
if (settled) return
|
||||
signalProcessTree('SIGTERM')
|
||||
terminalForceKillTimer = setTimeout(() => {
|
||||
if (!settled) signalProcessTree('SIGKILL')
|
||||
}, 1500)
|
||||
}, 250)
|
||||
}
|
||||
const abort = () => {
|
||||
if (settled || stopRequested) return
|
||||
stopRequested = true
|
||||
const terminalError = inputError || new Error('LOCAL_AGENT_EXECUTION_STOPPED')
|
||||
if (platform === 'win32' && child.pid) {
|
||||
const killer = spawnFn('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], {
|
||||
stdio: 'ignore', windowsHide: true,
|
||||
@@ -313,8 +345,8 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
child.stdout.destroy()
|
||||
child.stderr.destroy()
|
||||
rejectTerminal(
|
||||
new Error('LOCAL_AGENT_EXECUTION_STOPPED'),
|
||||
timeoutRequested ? 'timeout' : 'stopped',
|
||||
terminalError,
|
||||
inputError ? 'failed' : (timeoutRequested ? 'timeout' : 'stopped'),
|
||||
)
|
||||
}), KILL_SETTLE_MS)
|
||||
return
|
||||
@@ -328,8 +360,8 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
child.stdout.destroy()
|
||||
child.stderr.destroy()
|
||||
rejectTerminal(
|
||||
new Error('LOCAL_AGENT_EXECUTION_STOPPED'),
|
||||
timeoutRequested ? 'timeout' : 'stopped',
|
||||
terminalError,
|
||||
inputError ? 'failed' : (timeoutRequested ? 'timeout' : 'stopped'),
|
||||
)
|
||||
}), KILL_SETTLE_MS)
|
||||
}, TERMINATE_GRACE_MS)
|
||||
@@ -351,36 +383,33 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
stderr.push(chunk)
|
||||
noteActivity()
|
||||
})
|
||||
child.stdin.on('error', (error) => {
|
||||
if (settled || inputError) return
|
||||
inputError = agentExecutionError(
|
||||
'LOCAL_AGENT_SEND_FAILED',
|
||||
redactChildSecrets(error?.message || error, childEnv),
|
||||
)
|
||||
abort()
|
||||
})
|
||||
child.on('error', error => finish(() => rejectTerminal(
|
||||
stopRequested
|
||||
inputError || (stopRequested
|
||||
? agentExecutionError('LOCAL_AGENT_EXECUTION_STOPPED')
|
||||
: agentExecutionError(
|
||||
'LOCAL_AGENT_SPAWN_FAILED',
|
||||
redactChildSecrets(error?.message || error, childEnv),
|
||||
),
|
||||
stopRequested ? (timeoutRequested ? 'timeout' : 'stopped') : 'failed',
|
||||
)),
|
||||
stopRequested ? (inputError ? 'failed' : (timeoutRequested ? 'timeout' : 'stopped')) : 'failed',
|
||||
)))
|
||||
child.on('close', (code, signal) => finish(() => {
|
||||
void (async () => {
|
||||
runtimeStreamParser?.end()
|
||||
if (stopRequested || options.signal?.aborted) {
|
||||
rejectTerminal(
|
||||
new Error('LOCAL_AGENT_EXECUTION_STOPPED'),
|
||||
timeoutRequested ? 'timeout' : 'stopped',
|
||||
inputError || new Error('LOCAL_AGENT_EXECUTION_STOPPED'),
|
||||
inputError ? 'failed' : (timeoutRequested ? 'timeout' : 'stopped'),
|
||||
)
|
||||
return
|
||||
}
|
||||
if (code !== 0) {
|
||||
const rawStdout = stdout.text()
|
||||
const rawStderr = stderr.text().trim()
|
||||
const structuredDetail = structuredCliError(rawStdout)
|
||||
const detail = redactChildSecrets(
|
||||
[rawStderr, structuredDetail].filter(Boolean).join('\n'),
|
||||
childEnv,
|
||||
)
|
||||
rejectTerminal(failedAgentProcessError(detail, { sessionRef: failureSessionRef }))
|
||||
return
|
||||
}
|
||||
const rawStderr = stderr.text()
|
||||
const nextSessionRef = profile.resolveSessionRef({
|
||||
stderr: rawStderr,
|
||||
@@ -389,7 +418,23 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
})
|
||||
let result = structuredOutput.end({
|
||||
sessionRef: nextSessionRef,
|
||||
prompt,
|
||||
})
|
||||
const rawStdout = stdout.text()
|
||||
const structuredDetail = structuredCliError(rawStdout)
|
||||
const usableNonZeroResult = code !== 0
|
||||
&& result
|
||||
&& typeof result.text === 'string'
|
||||
&& result.text.trim()
|
||||
&& ['completed', 'partial'].includes(result.outcome)
|
||||
if (code !== 0 && !usableNonZeroResult) {
|
||||
const detail = redactChildSecrets(
|
||||
[rawStderr, structuredDetail].filter(Boolean).join('\n'),
|
||||
childEnv,
|
||||
)
|
||||
rejectTerminal(failedAgentProcessError(detail, { sessionRef: failureSessionRef }))
|
||||
return
|
||||
}
|
||||
if (result.error) {
|
||||
rejectTerminal(failedAgentProcessError(
|
||||
redactChildSecrets(result.error, childEnv),
|
||||
@@ -407,6 +452,10 @@ async function runAgent(agent, prompt, workdir, options = {}) {
|
||||
runContext: profileRunContext,
|
||||
options,
|
||||
})
|
||||
result = {
|
||||
...result,
|
||||
text: stripExactMeldworkPromptEcho(result.text, prompt),
|
||||
}
|
||||
if (progress.length) result.progress = progress
|
||||
const redactedText = redactChildSecrets(result.text, childEnv)
|
||||
let output
|
||||
@@ -453,6 +502,7 @@ module.exports = {
|
||||
parseMimoOutput,
|
||||
parseOpenCodeOutput,
|
||||
parseOpenCodeReviewOutput,
|
||||
parsePiOutput,
|
||||
parseWorkBuddyOutput,
|
||||
prepareCommand,
|
||||
readHermesFinalResponse,
|
||||
|
||||
@@ -3,6 +3,7 @@ const fs = require('node:fs')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const { promisify } = require('node:util')
|
||||
const { networkEnvironment } = require('./cli-network-environment.cjs')
|
||||
const {
|
||||
assessAgentVersion,
|
||||
capabilityProbes,
|
||||
@@ -15,6 +16,7 @@ const AGENT_PROFILES = {
|
||||
hermes: { label: 'Hermes', commands: ['hermes'] },
|
||||
openclaw: { label: 'OpenClaw', commands: ['openclaw'] },
|
||||
workbuddy: { label: 'WorkBuddy', commands: ['codebuddy'] },
|
||||
pi: { label: 'Pi Agent', commands: ['pi', 'pi-agent', 'piagent'] },
|
||||
kimi: { label: 'Kimi', commands: ['kimi'] },
|
||||
mimo: { label: 'MiMo', commands: ['mimo'] },
|
||||
claude: { label: 'Claude', commands: ['claude'] },
|
||||
@@ -25,6 +27,8 @@ const AGENT_PROFILES = {
|
||||
}
|
||||
const ALLOWED_KINDS = Object.keys(AGENT_PROFILES)
|
||||
const DEFAULT_WINDOWS_PATHEXT = ['.COM', '.EXE', '.BAT', '.CMD']
|
||||
const CAPABILITY_CACHE_TTL_MS = 5 * 60 * 1000
|
||||
const capabilityCache = new Map()
|
||||
const SYSTEM_CHILD_ENV_KEYS = Object.freeze([
|
||||
'HOME', 'USER', 'LOGNAME', 'SHELL',
|
||||
'TMPDIR', 'TMP', 'TEMP',
|
||||
@@ -37,7 +41,7 @@ const SYSTEM_CHILD_ENV_KEYS = Object.freeze([
|
||||
'APPDATA', 'LOCALAPPDATA', 'PROGRAMDATA',
|
||||
'PROGRAMFILES', 'PROGRAMFILES(X86)', 'PROGRAMW6432',
|
||||
'OS', 'PROCESSOR_ARCHITECTURE', 'PROCESSOR_IDENTIFIER', 'NUMBER_OF_PROCESSORS',
|
||||
'SSL_CERT_FILE', 'SSL_CERT_DIR', 'NODE_EXTRA_CA_CERTS',
|
||||
'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'PI_CODING_AGENT_DIR',
|
||||
])
|
||||
|
||||
function envValue(env, name) {
|
||||
@@ -46,7 +50,7 @@ function envValue(env, name) {
|
||||
}
|
||||
|
||||
function systemChildEnvironment(sourceEnv = process.env, platform = process.platform) {
|
||||
const env = {}
|
||||
const env = networkEnvironment(sourceEnv, platform)
|
||||
for (const name of SYSTEM_CHILD_ENV_KEYS) {
|
||||
const value = envValue(sourceEnv, name)
|
||||
if (typeof value === 'string' && value) env[name] = value
|
||||
@@ -333,27 +337,50 @@ async function probeAgentCapabilities(kind, executable, options = {}) {
|
||||
...systemChildEnvironment(env, platform),
|
||||
PATH: searchPath(options),
|
||||
}
|
||||
let identity = ''
|
||||
try {
|
||||
const stat = (options.statFn || fs.statSync)(executable)
|
||||
identity = JSON.stringify([
|
||||
kind, executable, options.version || '', stat.dev, stat.ino,
|
||||
stat.size, stat.mtimeMs, stat.ctimeMs,
|
||||
])
|
||||
} catch { /* caching requires a verifiable executable identity */ }
|
||||
const cacheKey = `${kind}:${executable}`
|
||||
const prior = capabilityCache.get(cacheKey)
|
||||
const recentCompatible = identity && prior?.identity === identity
|
||||
&& Date.now() - prior.checkedAt < CAPABILITY_CACHE_TTL_MS
|
||||
const results = await Promise.all(capabilityProbes(kind).map(async (probe) => {
|
||||
try {
|
||||
const command = prepareCommandFn(executable, probe.args, options)
|
||||
const result = await execFileFn(command.command, command.args, {
|
||||
timeout: 8000,
|
||||
windowsHide: true,
|
||||
env: childEnv,
|
||||
})
|
||||
return {
|
||||
probe,
|
||||
output: `${result.stdout || ''}\n${result.stderr || ''}`,
|
||||
}
|
||||
} catch {
|
||||
return {
|
||||
probe,
|
||||
error: true,
|
||||
for (const timeout of probe.timeout ? [probe.timeout] : [8000, 16000]) {
|
||||
try {
|
||||
const command = prepareCommandFn(executable, probe.args, options)
|
||||
const result = await execFileFn(command.command, command.args, {
|
||||
timeout,
|
||||
windowsHide: true,
|
||||
env: childEnv,
|
||||
})
|
||||
return { probe, output: `${result.stdout || ''}\n${result.stderr || ''}` }
|
||||
} catch (error) {
|
||||
const timedOut = error?.killed === true || error?.code === 'ETIMEDOUT'
|
||||
if (timedOut && timeout === 8000) continue
|
||||
return { probe, error: true, timedOut }
|
||||
}
|
||||
}
|
||||
}))
|
||||
const failed = results.find(result => !result.timedOut && (result.error
|
||||
|| result.probe.requiredText.some(value => !result.output.includes(value))
|
||||
|| (result.probe.validateOutput && !result.probe.validateOutput(result.output))))
|
||||
if (failed) capabilityCache.delete(cacheKey)
|
||||
for (const result of results) {
|
||||
const { probe } = result
|
||||
if (result.timedOut && !failed) {
|
||||
if (recentCompatible) continue
|
||||
return {
|
||||
compatibilityState: 'unknown',
|
||||
incompatibilityReason: 'LOCAL_AGENT_CAPABILITY_PROBE_TIMEOUT',
|
||||
incompatibilityProbe: probe.id,
|
||||
}
|
||||
}
|
||||
if (result.timedOut) continue
|
||||
if (result.error) {
|
||||
return {
|
||||
compatibilityState: 'incompatible',
|
||||
@@ -371,6 +398,9 @@ async function probeAgentCapabilities(kind, executable, options = {}) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (identity && !results.some(result => result.timedOut)) {
|
||||
capabilityCache.set(cacheKey, { identity, checkedAt: Date.now() })
|
||||
}
|
||||
return {
|
||||
compatibilityState: 'compatible',
|
||||
incompatibilityReason: '',
|
||||
@@ -401,18 +431,17 @@ async function inspectAgentCandidate(kind, executable, options, childEnv) {
|
||||
version: identified?.line || '',
|
||||
versionIdentified: Boolean(identified),
|
||||
}
|
||||
} catch { /* a broken shim is not a usable CLI */ }
|
||||
} catch { /* capability probes can still establish whether this installation works */ }
|
||||
return { succeeded: false, version: '', versionIdentified: false }
|
||||
})()
|
||||
|
||||
const { succeeded: versionCommandSucceeded, version } = await versionTask
|
||||
if (!versionCommandSucceeded) return null
|
||||
const { version } = await versionTask
|
||||
const versionCompatibility = assessAgentVersion(kind, version)
|
||||
const capabilityTask = Promise.resolve().then(async () => {
|
||||
const result = await (options.probeAgentCapabilitiesFn || probeAgentCapabilities)(
|
||||
kind,
|
||||
executable,
|
||||
{ ...options, childEnv },
|
||||
{ ...options, childEnv, version },
|
||||
)
|
||||
return result && typeof result === 'object' ? result : incompatibleCapabilities
|
||||
}).catch(() => incompatibleCapabilities)
|
||||
@@ -432,7 +461,7 @@ async function inspectAgentCandidate(kind, executable, options, childEnv) {
|
||||
})()
|
||||
: Promise.resolve(undefined)
|
||||
const [capabilityCompatibility, acpAvailable] = await Promise.all([capabilityTask, acpTask])
|
||||
const compatibility = capabilityCompatibility.compatibilityState === 'incompatible'
|
||||
const compatibility = capabilityCompatibility.compatibilityState !== 'compatible'
|
||||
? { ...versionCompatibility, ...capabilityCompatibility }
|
||||
: {
|
||||
...versionCompatibility,
|
||||
|
||||
@@ -14,6 +14,7 @@ const {
|
||||
parseMimoOutput,
|
||||
parseOpenCodeOutput,
|
||||
parseOpenCodeReviewOutput,
|
||||
parsePiOutput,
|
||||
parseWorkBuddyOutput,
|
||||
readHermesFinalResponse,
|
||||
readHermesMessageWatermark,
|
||||
@@ -26,11 +27,13 @@ const {
|
||||
createAcpRuntimeState,
|
||||
createClaudeQwenRuntimeState,
|
||||
createGeminiRuntimeState,
|
||||
createPiRuntimeState,
|
||||
finalOnlyRuntimeEvents,
|
||||
geminiStreamJsonRuntimeEvents,
|
||||
kimiStreamJsonRuntimeEvents,
|
||||
mimoJsonRuntimeEvents,
|
||||
openCodeJsonRuntimeEvents,
|
||||
piJsonRuntimeEvents,
|
||||
} = require('./cli-runtime-event-mappers.cjs')
|
||||
|
||||
function createStatelessRuntimeState() {
|
||||
@@ -75,6 +78,7 @@ const FINAL_OUTPUT_PARSERS = Object.freeze({
|
||||
codex: parseCodexOutput,
|
||||
openclaw: stdout => ({ text: normalizeOpenClawOutput(stdout), sessionRef: '' }),
|
||||
workbuddy: parseWorkBuddyOutput,
|
||||
pi: parsePiOutput,
|
||||
kimi: parseKimiOutput,
|
||||
mimo: parseMimoOutput,
|
||||
claude: parseClaudeQwenOutput,
|
||||
@@ -353,6 +357,21 @@ const OPENCODE_JSON_EVENTS_PROFILE = profile({
|
||||
createFinalOutputAccumulator: createFinalOutputAccumulator('opencode'),
|
||||
})
|
||||
|
||||
const PI_JSON_EVENTS_PROFILE = profile({
|
||||
profileId: 'pi-json-events-v2',
|
||||
protocol: 'pi-json',
|
||||
framing: 'jsonl',
|
||||
source: 'stdout',
|
||||
capabilities: {
|
||||
answerMode: 'delta', tools: FULL_TOOL_LIFECYCLE,
|
||||
plan: false, reasoning: true, session: true, terminal: true,
|
||||
},
|
||||
createDecoder: createJsonLineParser,
|
||||
createState: createPiRuntimeState,
|
||||
mapEvent: piJsonRuntimeEvents,
|
||||
createFinalOutputAccumulator: createFinalOutputAccumulator('pi'),
|
||||
})
|
||||
|
||||
const OPENCLAW_TERMINAL_DOCUMENT_PROFILE = profile({
|
||||
profileId: 'openclaw-terminal-document-v1',
|
||||
protocol: 'openclaw-terminal-document',
|
||||
@@ -436,6 +455,7 @@ const CONNECTOR_EVENT_PROFILES = Object.freeze({
|
||||
hermes: ACP_JSONRPC_PROFILE,
|
||||
openclaw: ACP_JSONRPC_PROFILE,
|
||||
workbuddy: WORKBUDDY_TERMINAL_RESULT_PROFILE,
|
||||
pi: PI_JSON_EVENTS_PROFILE,
|
||||
kimi: ACP_JSONRPC_PROFILE,
|
||||
mimo: MIMO_JSON_EVENTS_PROFILE,
|
||||
claude: ANTHROPIC_STREAM_JSON_PROFILE,
|
||||
@@ -450,6 +470,7 @@ const TRANSPORT_EVENT_PROFILES = Object.freeze({
|
||||
openclaw: Object.freeze({ legacy: OPENCLAW_TERMINAL_DOCUMENT_PROFILE }),
|
||||
kimi: Object.freeze({ 'stream-json': KIMI_STREAM_JSON_PROFILE }),
|
||||
mimo: Object.freeze({ acp: ACP_JSONRPC_PROFILE }),
|
||||
pi: Object.freeze({ json: PI_JSON_EVENTS_PROFILE }),
|
||||
opencode: Object.freeze({ acp: ACP_JSONRPC_PROFILE }),
|
||||
workbuddy: Object.freeze({ 'stream-json': ANTHROPIC_STREAM_JSON_PROFILE }),
|
||||
})
|
||||
|
||||
@@ -6,6 +6,17 @@ const IMAGE_ATTACHMENT_LIMITS = Object.freeze({
|
||||
hermes: 1,
|
||||
opencode: 4,
|
||||
})
|
||||
const DEFAULT_INTERNAL_TURN_LIMITS = Object.freeze({
|
||||
// Meldwork already owns the outer discussion rounds. Keep WorkBuddy's
|
||||
// nested tool loop bounded so one participant cannot dominate a round.
|
||||
workbuddy: 8,
|
||||
})
|
||||
|
||||
function internalTurnLimit(kind, requested) {
|
||||
const value = Number(requested)
|
||||
if (Number.isInteger(value) && value >= 1 && value <= 50) return value
|
||||
return DEFAULT_INTERNAL_TURN_LIMITS[kind]
|
||||
}
|
||||
|
||||
function codexSandbox(requested) {
|
||||
if (requested != null) {
|
||||
@@ -62,9 +73,10 @@ function invocation(kind, executable, workdir, sessionRef = '', options = {}) {
|
||||
}
|
||||
}
|
||||
if (kind === 'hermes') {
|
||||
const legacySessionRef = options.sessionTransport === 'acp' ? '' : sessionRef
|
||||
// Hermes uses the same native conversation identifier across its ACP and
|
||||
// legacy transports. Keep it when an attachment requires the legacy path.
|
||||
const legacySessionRef = sessionRef
|
||||
const useAcp = options.invocationTransport !== 'legacy'
|
||||
&& !attachments.length
|
||||
&& options.hermesAcpAvailable !== false
|
||||
&& (!sessionRef || options.sessionTransport === 'acp')
|
||||
if (useAcp) {
|
||||
@@ -125,6 +137,7 @@ function invocation(kind, executable, workdir, sessionRef = '', options = {}) {
|
||||
}
|
||||
}
|
||||
if (kind === 'workbuddy') {
|
||||
const maxTurns = internalTurnLimit(kind, options.maxTurns)
|
||||
return {
|
||||
command: executable,
|
||||
args: [
|
||||
@@ -132,13 +145,28 @@ function invocation(kind, executable, workdir, sessionRef = '', options = {}) {
|
||||
'--output-format', 'stream-json',
|
||||
'--include-partial-messages',
|
||||
'--permission-mode', options.sandbox === 'workspace-write' ? 'acceptEdits' : 'plan',
|
||||
'--max-turns', '20',
|
||||
...(options.sandbox === 'workspace-write' ? ['--dangerously-skip-permissions'] : []),
|
||||
...(maxTurns ? ['--max-turns', String(maxTurns)] : []),
|
||||
...(sessionRef ? ['--resume', sessionRef] : []),
|
||||
],
|
||||
promptArg: true,
|
||||
eventTransport: 'stream-json',
|
||||
}
|
||||
}
|
||||
if (kind === 'pi') {
|
||||
return {
|
||||
command: executable,
|
||||
args: [
|
||||
'--mode', 'json', '--print',
|
||||
...(options.sandbox === 'workspace-write'
|
||||
? ['--approve']
|
||||
: ['--no-approve', '--tools', 'read,grep,find,ls']),
|
||||
...(sessionRef ? ['--session', sessionRef] : []),
|
||||
],
|
||||
promptArg: true,
|
||||
eventTransport: 'json',
|
||||
}
|
||||
}
|
||||
if (kind === 'kimi') {
|
||||
if (options.sandbox !== 'workspace-write') {
|
||||
return {
|
||||
@@ -161,7 +189,7 @@ function invocation(kind, executable, workdir, sessionRef = '', options = {}) {
|
||||
}
|
||||
}
|
||||
if (kind === 'mimo') {
|
||||
if (options.invocationTransport !== 'json') {
|
||||
if (!attachments.length && options.invocationTransport !== 'json') {
|
||||
return {
|
||||
command: executable,
|
||||
args: ['acp', '--pure', '--cwd', workdir],
|
||||
@@ -190,6 +218,24 @@ function invocation(kind, executable, workdir, sessionRef = '', options = {}) {
|
||||
'--include-partial-messages',
|
||||
'--verbose',
|
||||
'--permission-mode', options.sandbox === 'workspace-write' ? 'acceptEdits' : 'plan',
|
||||
...(options.provider?.id === 'anthropic' ? [
|
||||
'--settings', JSON.stringify({
|
||||
// Native settings.env overrides process env. The helper keeps the key out of argv.
|
||||
apiKeyHelper: (options.platform || process.platform) === 'win32'
|
||||
? 'powershell.exe -NoLogo -NoProfile -NonInteractive -Command "[Console]::Write([Environment]::GetEnvironmentVariable(\'MELDWORK_PROVIDER_API_KEY\'))"'
|
||||
: 'printf \'%s\' "$MELDWORK_PROVIDER_API_KEY"',
|
||||
env: {
|
||||
CLAUDE_CODE_USE_BEDROCK: '0', CLAUDE_CODE_USE_VERTEX: '0',
|
||||
CLAUDE_CODE_USE_FOUNDRY: '0', CLAUDE_CODE_USE_MANTLE: '0',
|
||||
ANTHROPIC_BASE_URL: options.provider.baseUrl,
|
||||
ANTHROPIC_API_KEY: '', ANTHROPIC_AUTH_TOKEN: '', CLAUDE_CODE_OAUTH_TOKEN: '',
|
||||
ANTHROPIC_CUSTOM_HEADERS: '',
|
||||
ANTHROPIC_DEFAULT_OPUS_MODEL: '', ANTHROPIC_DEFAULT_SONNET_MODEL: '',
|
||||
ANTHROPIC_DEFAULT_HAIKU_MODEL: '',
|
||||
},
|
||||
}),
|
||||
] : []),
|
||||
...(options.provider?.model ? ['--model', options.provider.model] : []),
|
||||
...(sessionRef ? ['--resume', sessionRef] : []),
|
||||
],
|
||||
promptArg: true,
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
const NETWORK_ENV_KEYS = Object.freeze([
|
||||
'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
|
||||
'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy',
|
||||
'SSL_CERT_FILE', 'SSL_CERT_DIR', 'NODE_EXTRA_CA_CERTS',
|
||||
'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'NODE_USE_ENV_PROXY',
|
||||
])
|
||||
|
||||
function networkEnvironment(source = {}, platform = process.platform) {
|
||||
const result = {}
|
||||
for (const [key, value] of Object.entries(source)) {
|
||||
const allowed = platform === 'win32'
|
||||
? NETWORK_ENV_KEYS.find(name => name.toLowerCase() === key.toLowerCase())
|
||||
: NETWORK_ENV_KEYS.find(name => name === key)
|
||||
if (allowed && typeof value === 'string') result[allowed] = value
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
module.exports = { NETWORK_ENV_KEYS, networkEnvironment }
|
||||
@@ -7,7 +7,10 @@ const {
|
||||
TERMINATE_GRACE_MS,
|
||||
childEnvironment,
|
||||
} = require('./cli-process-support.cjs')
|
||||
const { configureOpenClawGatewayRuntime } = require('./openclaw-runtime.cjs')
|
||||
const {
|
||||
configureOpenClawGatewayRuntime,
|
||||
refreshOpenClawRuntimeAfterStartup,
|
||||
} = require('./openclaw-runtime.cjs')
|
||||
|
||||
const GATEWAY_READY_MARKER = '[gateway] ready'
|
||||
const GATEWAY_READY_TIMEOUT_MS = 15_000
|
||||
@@ -286,8 +289,11 @@ async function withOpenClawGateway(options, callback) {
|
||||
signal: options.signal,
|
||||
workdir: options.workdir,
|
||||
})
|
||||
runtimeOptions = refreshOpenClawRuntimeAfterStartup(runtimeOptions)
|
||||
} catch (error) {
|
||||
await terminateGateway(child)
|
||||
// Startup can migrate the config before a port conflict or health failure.
|
||||
runtimeOptions = refreshOpenClawRuntimeAfterStartup(runtimeOptions)
|
||||
if (error?.retryable && attempt + 1 < GATEWAY_SETUP_ATTEMPTS) continue
|
||||
throw attachRuntimeOptions(error, runtimeOptions)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ const MAX_RUNTIME_JSON_PENDING_CHARS = 1024 * 1024
|
||||
const MAX_STRUCTURED_JSON_BYTES = 64 * 1024 * 1024
|
||||
const MAX_STRUCTURED_TEXT_CHARS = 1024 * 1024
|
||||
const STRUCTURED_JSONL_KINDS = new Set([
|
||||
'codex', 'workbuddy', 'kimi', 'mimo', 'claude', 'gemini', 'opencode', 'qwen',
|
||||
'codex', 'workbuddy', 'pi', 'kimi', 'mimo', 'claude', 'gemini', 'opencode', 'qwen',
|
||||
])
|
||||
const STRUCTURED_DOCUMENT_KINDS = new Set(['openclaw', 'opencodereview'])
|
||||
function parseCodexOutput(stdout) {
|
||||
@@ -90,6 +90,65 @@ function appendStructuredText(state, value, separator = '\n') {
|
||||
state.text += `${prefix}${text}`.slice(0, remaining)
|
||||
}
|
||||
|
||||
function stripPiInternalPromptEcho(value) {
|
||||
let text = String(value || '').trim()
|
||||
if (!text) return ''
|
||||
const preamble = /^You are participating in a local multi-agent discussion\.[\s\S]*?^Answer the user naturally(?: in Markdown)?\.?\s*/im
|
||||
text = text.replace(preamble, '').trim()
|
||||
// Pi may resume from a compact continuation prompt and echo only the
|
||||
// protocol instructions or the selected Harness records. Remove those
|
||||
// internal lines while preserving any user-facing text on the same line.
|
||||
text = text.replace(/^Do not output JSON, XML, receipt markers, protocol labels, hidden orchestration instructions, or a fixed response template\.\s*/im, '')
|
||||
text = text.replace(/^Do not claim another Agent performed work, and do not modify shared workspace state unless this turn explicitly grants that permission\.\s*/im, '')
|
||||
const lines = text.split(/\r?\n/)
|
||||
const cleaned = []
|
||||
let inRecords = false
|
||||
for (const line of lines) {
|
||||
const valueLine = line.trim()
|
||||
if (/^Selected records from completed phases:\s*$/i.test(valueLine)) {
|
||||
inRecords = true
|
||||
continue
|
||||
}
|
||||
if (inRecords) {
|
||||
if (/^MELDWORK_V4_COLLABORATION_PACKAGE_V1$/i.test(valueLine)
|
||||
|| /^\[index\]\s+\S+/i.test(valueLine)
|
||||
|| /^Artifact:\s+\S+/i.test(valueLine)
|
||||
|| /^Evidence:\s+\S+/i.test(valueLine)) continue
|
||||
const phasePrefix = /^(?:\[(?:challenge|proposal)\]\s+agent=\S+\s+Completed the (?:challenge|proposal) phase\.\s*)/i
|
||||
const remainder = line.replace(phasePrefix, '')
|
||||
if (remainder !== line) {
|
||||
if (remainder.trim()) cleaned.push(remainder)
|
||||
continue
|
||||
}
|
||||
inRecords = false
|
||||
}
|
||||
cleaned.push(line)
|
||||
}
|
||||
return cleaned.join('\n').replace(/\n{3,}/g, '\n\n').trim()
|
||||
}
|
||||
|
||||
function stripPiPromptEcho(value, prompt) {
|
||||
const text = String(value || '').trim()
|
||||
const expected = String(prompt || '').trim()
|
||||
if (expected && text.startsWith(expected)) {
|
||||
return text.slice(expected.length).trim()
|
||||
}
|
||||
return stripPiInternalPromptEcho(text)
|
||||
}
|
||||
|
||||
function stripExactMeldworkPromptEcho(value, prompt) {
|
||||
const text = String(value || '')
|
||||
const expected = String(prompt || '').trim()
|
||||
if (!expected.includes('Current user task (authoritative):')
|
||||
|| !expected.startsWith('You are participating in the local ')) {
|
||||
return text.trim()
|
||||
}
|
||||
const candidate = text.trimStart()
|
||||
return candidate.startsWith(expected)
|
||||
? candidate.slice(expected.length).trimStart()
|
||||
: text.trim()
|
||||
}
|
||||
|
||||
function markStructuredFailure(state, code = 'LOCAL_AGENT_PROCESS_FAILED', diagnostic = '') {
|
||||
state.outcome = 'failed'
|
||||
state.failure = agentRuntimeFailure(code)
|
||||
@@ -116,6 +175,16 @@ function stepFinishOutcome(reason) {
|
||||
function ingestStructuredEvent(state, event) {
|
||||
if (!event || typeof event !== 'object' || Array.isArray(event)) return
|
||||
state.seen = true
|
||||
if (['workbuddy', 'claude', 'qwen'].includes(state.kind)
|
||||
&& event.type === 'result' && typeof event.result === 'string') {
|
||||
if (typeof event.session_id === 'string') state.sessionRef = event.session_id
|
||||
state.failure = null
|
||||
state.diagnostic = ''
|
||||
state.text = ''
|
||||
appendStructuredText(state, event.result, '')
|
||||
state.outcome = event.is_error === true ? 'partial' : 'completed'
|
||||
return
|
||||
}
|
||||
if (structuredEventFailed(event)) {
|
||||
markStructuredFailure(state)
|
||||
return
|
||||
@@ -133,15 +202,7 @@ function ingestStructuredEvent(state, event) {
|
||||
return
|
||||
}
|
||||
|
||||
if (['workbuddy', 'claude', 'qwen'].includes(state.kind)) {
|
||||
if (typeof event.session_id === 'string') state.sessionRef = event.session_id
|
||||
if (event.type === 'result' && typeof event.result === 'string') {
|
||||
state.text = ''
|
||||
appendStructuredText(state, event.result, '')
|
||||
state.outcome = 'completed'
|
||||
}
|
||||
return
|
||||
}
|
||||
if (['workbuddy', 'claude', 'qwen'].includes(state.kind)) return
|
||||
|
||||
if (state.kind === 'kimi') {
|
||||
if (event.role === 'assistant' && typeof event.content === 'string') {
|
||||
@@ -154,6 +215,39 @@ function ingestStructuredEvent(state, event) {
|
||||
return
|
||||
}
|
||||
|
||||
if (state.kind === 'pi') {
|
||||
if (event.type === 'session' && typeof event.id === 'string') state.sessionRef = event.id
|
||||
const update = event.assistantMessageEvent
|
||||
if (event.type === 'message_update' && update?.type === 'text_delta'
|
||||
&& typeof update.delta === 'string') {
|
||||
appendStructuredText(state, update.delta, '')
|
||||
}
|
||||
if (event.type === 'message_end' && event.message?.role === 'assistant'
|
||||
&& Array.isArray(event.message?.content)) {
|
||||
for (const block of event.message.content) {
|
||||
if (block?.type === 'text' && typeof block.text === 'string') {
|
||||
if (!state.text) appendStructuredText(state, block.text, '')
|
||||
}
|
||||
}
|
||||
const stopReason = event.message.stopReason
|
||||
if (stopReason) state.outcome = stepFinishOutcome(stopReason)
|
||||
}
|
||||
if (event.type === 'turn_end') {
|
||||
state.outcome = stepFinishOutcome(event.message?.stopReason || event.stopReason || 'stop')
|
||||
}
|
||||
if (event.type === 'agent_end') {
|
||||
const lastAssistant = event.messages?.findLast(message => message?.role === 'assistant')
|
||||
if (lastAssistant?.stopReason) state.outcome = stepFinishOutcome(lastAssistant.stopReason)
|
||||
else if (!state.outcome) state.outcome = 'completed'
|
||||
if (state.outcome === 'completed' && event.willRetry !== true) {
|
||||
state.failure = null
|
||||
state.diagnostic = ''
|
||||
}
|
||||
}
|
||||
if (state.outcome === 'failed') markStructuredFailure(state)
|
||||
return
|
||||
}
|
||||
|
||||
if (['mimo', 'opencode'].includes(state.kind)) {
|
||||
if (typeof event.sessionID === 'string') state.sessionRef = event.sessionID
|
||||
if (event.type === 'text' && event.part?.type === 'text'
|
||||
@@ -273,7 +367,7 @@ function openCodeReviewTerminal(status, manifest, manifestPresent = manifest !=
|
||||
}
|
||||
}
|
||||
|
||||
function finalizeStructuredState(state) {
|
||||
function finalizeStructuredState(state, context = {}) {
|
||||
if (state.parseError) {
|
||||
return {
|
||||
text: '',
|
||||
@@ -315,7 +409,9 @@ function finalizeStructuredState(state) {
|
||||
if (!state.seen && !state.text && !state.outcome) return null
|
||||
const outcome = state.outcome || (state.text ? 'partial' : 'failed')
|
||||
const result = {
|
||||
text: state.text.trim(),
|
||||
text: state.kind === 'pi'
|
||||
? stripPiPromptEcho(state.text, context.prompt)
|
||||
: state.text.trim(),
|
||||
sessionRef: state.sessionRef,
|
||||
outcome,
|
||||
}
|
||||
@@ -348,7 +444,7 @@ function createStructuredOutputAccumulator(kind, sessionRef = '') {
|
||||
return {
|
||||
format: 'jsonl',
|
||||
ingest: event => ingestStructuredEvent(state, event),
|
||||
end: () => finalizeStructuredState(state),
|
||||
end: context => finalizeStructuredState(state, context),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -611,6 +707,30 @@ function parseOpenCodeOutput(stdout) {
|
||||
}
|
||||
}
|
||||
|
||||
function parsePiOutput(stdout) {
|
||||
const events = parseJsonOutputEvents(stdout)
|
||||
let sessionRef = ''
|
||||
let text = ''
|
||||
for (const event of events) {
|
||||
if (typeof event.id === 'string' && event.type === 'session') sessionRef = event.id
|
||||
if (event.type === 'message_update'
|
||||
&& event.assistantMessageEvent?.type === 'text_delta'
|
||||
&& typeof event.assistantMessageEvent.delta === 'string') {
|
||||
text += event.assistantMessageEvent.delta
|
||||
}
|
||||
if (!text && event.type === 'message_end' && event.message?.role === 'assistant'
|
||||
&& Array.isArray(event.message?.content)) {
|
||||
text = event.message.content
|
||||
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
||||
.map(block => block.text)
|
||||
.join('')
|
||||
}
|
||||
}
|
||||
const parsedText = text.trim()
|
||||
const answer = stripPiInternalPromptEcho(parsedText)
|
||||
return { text: parsedText ? answer : events.length ? '' : String(stdout || '').trim(), sessionRef }
|
||||
}
|
||||
|
||||
function openCodeReviewText(output) {
|
||||
const sections = []
|
||||
if (typeof output.message === 'string' && output.message.trim()) {
|
||||
@@ -686,6 +806,14 @@ function classifyCliOutcome(kind, stdout) {
|
||||
}
|
||||
|
||||
const events = parseJsonOutputEvents(stdout)
|
||||
if (['workbuddy', 'claude', 'qwen'].includes(kind)) {
|
||||
const result = events.findLast(event => event?.type === 'result' && typeof event.result === 'string')
|
||||
if (result) {
|
||||
return {
|
||||
outcome: result.is_error === true ? 'partial' : 'completed',
|
||||
}
|
||||
}
|
||||
}
|
||||
const failed = events.findLast(event => (
|
||||
event?.type === 'error'
|
||||
|| event?.status === 'failed'
|
||||
@@ -706,11 +834,6 @@ function classifyCliOutcome(kind, stdout) {
|
||||
: 'partial',
|
||||
}
|
||||
}
|
||||
if (['workbuddy', 'claude', 'qwen'].includes(kind)) {
|
||||
return {
|
||||
outcome: events.some(event => event?.type === 'result') ? 'completed' : 'partial',
|
||||
}
|
||||
}
|
||||
if (kind === 'kimi') {
|
||||
return {
|
||||
outcome: events.some(event => event?.type === 'session.resume_hint')
|
||||
@@ -718,6 +841,14 @@ function classifyCliOutcome(kind, stdout) {
|
||||
: 'partial',
|
||||
}
|
||||
}
|
||||
if (kind === 'pi') {
|
||||
const terminal = events.findLast(event => event?.type === 'turn_end' || event?.type === 'agent_end')
|
||||
const lastAssistant = terminal?.messages?.findLast(message => message?.role === 'assistant')
|
||||
const previousTurn = events.findLast(event => event?.type === 'turn_end')
|
||||
const reason = terminal?.message?.stopReason || terminal?.stopReason || lastAssistant?.stopReason
|
||||
|| previousTurn?.message?.stopReason || previousTurn?.stopReason
|
||||
return { outcome: reason ? stepFinishOutcome(reason) : terminal ? 'completed' : 'partial' }
|
||||
}
|
||||
if (['mimo', 'opencode'].includes(kind)) {
|
||||
const finish = events.findLast(event => (
|
||||
event?.type === 'step_finish' || event?.part?.type === 'step-finish'
|
||||
@@ -833,11 +964,13 @@ module.exports = {
|
||||
parseKimiOutput,
|
||||
parseMimoOutput,
|
||||
parseOpenCodeOutput,
|
||||
parsePiOutput,
|
||||
parseOpenCodeReviewOutput,
|
||||
parseWorkBuddyOutput,
|
||||
readHermesFinalResponse,
|
||||
readHermesMessageWatermark,
|
||||
stripAnsi,
|
||||
stripExactMeldworkPromptEcho,
|
||||
structuredCliError,
|
||||
classifyCliOutcome,
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
const path = require('node:path')
|
||||
const { searchPath, systemChildEnvironment } = require('./cli-discovery.cjs')
|
||||
const { NETWORK_ENV_KEYS, networkEnvironment } = require('./cli-network-environment.cjs')
|
||||
const { redactChildSecrets } = require('./cli-runtime-events.cjs')
|
||||
const { agentRuntimeError } = require('../agent-runtime-contract.cjs')
|
||||
const { agentRuntimeError, terminalAuthenticationDiagnostic } = require('../agent-runtime-contract.cjs')
|
||||
const { validateOpenClawRuntimeGuard } = require('./openclaw-runtime.cjs')
|
||||
|
||||
const TERMINATE_GRACE_MS = 500
|
||||
@@ -21,14 +22,20 @@ const OPENCLAW_RUNTIME_PATH_KEYS = Object.freeze([
|
||||
'OPENCLAW_CONFIG_PATH',
|
||||
'OPENCLAW_WORKSPACE_DIR',
|
||||
])
|
||||
const CONTROLLED_RUNTIME_ENV = /^(?:AWS_|AZURE_|GOOGLE_|GEMINI_|ANTHROPIC_|OPENAI_|OPENROUTER_|CODEBUDDY_|HERMES_|PI_|KIMI_|MIMO_|DASHSCOPE_|CLAUDE_|OCR_|CLOUDSDK_|VERTEX_|CLOUD_ML_|MOONSHOT_|CONNECTOR_TEST_|MELDWORK_TEST_)/
|
||||
const BLOCKED_RUNTIME_ENV = /^(?:NODE_OPTIONS|NODE_PATH|LD_PRELOAD|LD_LIBRARY_PATH|DYLD_|ELECTRON_RUN_AS_NODE)$/
|
||||
|
||||
function agentExecutionError(code, diagnostic = '') {
|
||||
return agentRuntimeError(code, diagnostic)
|
||||
}
|
||||
|
||||
function authConfigurationFailure(detail) {
|
||||
return /api[ _-]?key|access[ _-]?token|refresh[ _-]?token|auth[ _-]?token|credential|auth(?:entication|orization)?|log(?:ged)?[ -]?in|sign(?:ed)?[ -]?in|unauthorized|forbidden|\b(?:401|403)\b|select an auth type|(?:provider|model).{0,80}(?:reject|configur|missing|invalid)|(?:reject|configur|missing|invalid).{0,80}(?:provider|model)|令牌|凭据|登录|认证|鉴权|(?:提供商|供应商|模型).{0,40}(?:配置|拒绝|缺失|无效)|(?:配置|拒绝|缺失|无效).{0,40}(?:提供商|供应商|模型)/i
|
||||
.test(String(detail || ''))
|
||||
return String(detail || '').split(/\r?\n/).some((line) => {
|
||||
const text = line.trim().replace(/^(?:error|fatal)\s*:\s*/i, '')
|
||||
return Boolean(terminalAuthenticationDiagnostic(text))
|
||||
|| /^(?:(?:invalid|expired|missing|incorrect)\s+(?:api[ _-]?key|(?:access|refresh|auth)[ _-]?token|credentials?)\b|(?:authentication|authorization)\s+(?:failed|required)\b|(?:please\s+)?(?:log|sign)\s+in\b|not\s+logged\s+in\b|select an auth type\b|provider rejected\b)/i.test(text)
|
||||
|| /^(?:认证|鉴权|登录)(?:失败|过期)|^(?:令牌|凭据|密钥)(?:无效|缺失|已过期)|^请(?:先|重新)登录/.test(text)
|
||||
})
|
||||
}
|
||||
|
||||
function invalidSessionFailure(detail) {
|
||||
@@ -60,7 +67,10 @@ function openClawChildEnvironment(workdir, options, platform) {
|
||||
throw new Error('OPENCLAW_RUNTIME_UNSAFE_PATH')
|
||||
}
|
||||
|
||||
const env = systemChildEnvironment(process.env, platform)
|
||||
const env = {
|
||||
...systemChildEnvironment(process.env, platform),
|
||||
...networkEnvironment(source, platform),
|
||||
}
|
||||
for (const key of [
|
||||
'HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH',
|
||||
'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME',
|
||||
@@ -103,9 +113,14 @@ function childEnvironment(agent, workdir, options, platform) {
|
||||
? { OPENCODE_PERMISSION: OPENCODE_READ_ONLY_PERMISSION }
|
||||
: {}
|
||||
const source = { ...process.env, ...options.env }
|
||||
const controlled = Object.fromEntries(Object.entries(options.env || {}).filter(([key, value]) => (
|
||||
typeof value === 'string'
|
||||
&& (CONTROLLED_RUNTIME_ENV.test(key) || NETWORK_ENV_KEYS.includes(key))
|
||||
&& !BLOCKED_RUNTIME_ENV.test(key)
|
||||
)))
|
||||
return {
|
||||
...systemChildEnvironment(process.env, platform),
|
||||
...options.env,
|
||||
...controlled,
|
||||
...hermesSafetyEnv,
|
||||
...openCodeSafetyEnv,
|
||||
PATH: searchPath({ platform, env: source }),
|
||||
|
||||
@@ -345,6 +345,70 @@ function openCodeJsonRuntimeEvents(event) {
|
||||
return []
|
||||
}
|
||||
|
||||
function createPiRuntimeState() {
|
||||
return {
|
||||
reasoning: new Map(),
|
||||
tools: new Map(),
|
||||
}
|
||||
}
|
||||
|
||||
function piJsonRuntimeEvents(event, state) {
|
||||
if (!event || typeof event !== 'object') return []
|
||||
const update = event.assistantMessageEvent
|
||||
if (event.type === 'message_update' && update && typeof update === 'object') {
|
||||
const index = Number.isInteger(update.contentIndex) ? update.contentIndex : 0
|
||||
const id = `content:${index}`
|
||||
if (update.type === 'thinking_start') {
|
||||
state.reasoning.set(id, '')
|
||||
return [{ id, type: 'reasoning_summary', title: 'reasoning', status: 'running' }]
|
||||
}
|
||||
if (update.type === 'thinking_delta' && typeof update.delta === 'string') {
|
||||
const summary = `${state.reasoning.get(id) || ''}${update.delta}`.slice(-2000)
|
||||
state.reasoning.set(id, summary)
|
||||
return [{ id, type: 'reasoning_summary', title: 'reasoning', status: 'running', summary }]
|
||||
}
|
||||
if (update.type === 'thinking_end') {
|
||||
const summary = String(update.content || state.reasoning.get(id) || '').trim()
|
||||
state.reasoning.set(id, summary)
|
||||
return [{ id, type: 'reasoning_summary', title: 'reasoning', status: 'completed', ...(summary ? { summary } : {}) }]
|
||||
}
|
||||
if (update.type === 'text_delta' && typeof update.delta === 'string') {
|
||||
return [{ type: 'answer_delta', status: 'running', delta: update.delta }]
|
||||
}
|
||||
if (['toolcall_start', 'tool_call_start'].includes(update.type)) {
|
||||
const toolId = String(update.toolCallId || update.id || `tool:${index}`)
|
||||
const title = String(update.toolName || update.name || 'tool')
|
||||
state.tools.set(toolId, title)
|
||||
return [{ id: toolId, type: 'tool_start', title, status: 'running' }]
|
||||
}
|
||||
if (['toolcall_end', 'tool_call_end'].includes(update.type)) {
|
||||
const toolId = String(update.toolCallId || update.id || `tool:${index}`)
|
||||
return [{
|
||||
id: toolId,
|
||||
type: 'tool_result_summary',
|
||||
title: state.tools.get(toolId) || String(update.toolName || update.name || 'tool'),
|
||||
status: update.isError === true || update.error ? 'failed' : 'completed',
|
||||
}]
|
||||
}
|
||||
}
|
||||
if (event.type === 'tool_execution_start' || event.type === 'tool_start') {
|
||||
const id = String(event.toolCallId || event.id || 'tool')
|
||||
const title = String(event.toolName || event.name || 'tool')
|
||||
state.tools.set(id, title)
|
||||
return [{ id, type: 'tool_start', title, status: 'running' }]
|
||||
}
|
||||
if (event.type === 'tool_execution_end' || event.type === 'tool_end') {
|
||||
const id = String(event.toolCallId || event.id || 'tool')
|
||||
return [{
|
||||
id,
|
||||
type: 'tool_result_summary',
|
||||
title: state.tools.get(id) || String(event.toolName || event.name || 'tool'),
|
||||
status: event.isError === true || event.error ? 'failed' : 'completed',
|
||||
}]
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function finalOnlyRuntimeEvents() {
|
||||
return []
|
||||
}
|
||||
@@ -432,4 +496,6 @@ module.exports = {
|
||||
kimiStreamJsonRuntimeEvents,
|
||||
mimoJsonRuntimeEvents,
|
||||
openCodeJsonRuntimeEvents,
|
||||
piJsonRuntimeEvents,
|
||||
createPiRuntimeState,
|
||||
}
|
||||
@@ -28,21 +28,38 @@ function utf8ByteLength(value) {
|
||||
|
||||
function redactChildSecrets(value, env) {
|
||||
let result = String(value || '')
|
||||
for (const [name, secret] of Object.entries(env)) {
|
||||
if (!/(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|AUTHORIZATION)/i.test(name)
|
||||
|| typeof secret !== 'string' || utf8ByteLength(secret) < 8) continue
|
||||
for (const secret of childSecrets(env)) {
|
||||
result = result.split(secret).join('[redacted]')
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function childSecrets(env) {
|
||||
return Object.entries(env || {})
|
||||
.filter(([name, secret]) => (
|
||||
/(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|AUTHORIZATION)/i.test(name)
|
||||
&& typeof secret === 'string' && utf8ByteLength(secret) >= 8
|
||||
))
|
||||
.map(([, secret]) => secret)
|
||||
const secrets = new Set()
|
||||
for (const [name, value] of Object.entries(env || {})) {
|
||||
if (typeof value !== 'string' || !value) continue
|
||||
if (/(?:API[_-]?KEY|ACCESS[_-]?KEY|TOKEN|SECRET|PASSWORD|AUTHORIZATION)/i.test(name)
|
||||
&& utf8ByteLength(value) >= 8) secrets.add(value)
|
||||
if (!/^(?:https?|all)_proxy$/i.test(name)) continue
|
||||
if (value.includes('@')) secrets.add(value)
|
||||
try {
|
||||
const url = new URL(value)
|
||||
if (!url.username && !url.password) continue
|
||||
secrets.add(value)
|
||||
secrets.add(url.href)
|
||||
const userinfo = `${url.username}:${url.password}`
|
||||
secrets.add(userinfo)
|
||||
const decoded = decodeURIComponent(userinfo)
|
||||
secrets.add(decoded)
|
||||
secrets.add(Buffer.from(decoded).toString('base64'))
|
||||
for (const part of [url.username, url.password]) {
|
||||
if (utf8ByteLength(part) >= 8) secrets.add(part)
|
||||
const literal = decodeURIComponent(part)
|
||||
if (utf8ByteLength(literal) >= 8) secrets.add(literal)
|
||||
}
|
||||
} catch { /* malformed proxy URLs are diagnosed by the native runtime */ }
|
||||
}
|
||||
return [...secrets].sort((left, right) => right.length - left.length)
|
||||
}
|
||||
|
||||
function assignmentNameVariants(parts) {
|
||||
|
||||
@@ -13,10 +13,12 @@ const {
|
||||
parseMimoOutput,
|
||||
parseOpenCodeOutput,
|
||||
parseOpenCodeReviewOutput,
|
||||
parsePiOutput,
|
||||
parseWorkBuddyOutput,
|
||||
readHermesFinalResponse,
|
||||
readHermesMessageWatermark,
|
||||
stripAnsi,
|
||||
stripExactMeldworkPromptEcho,
|
||||
structuredCliError,
|
||||
} = require('./cli-output-parsers.cjs')
|
||||
const {
|
||||
@@ -53,11 +55,13 @@ module.exports = {
|
||||
parseMimoOutput,
|
||||
parseOpenCodeOutput,
|
||||
parseOpenCodeReviewOutput,
|
||||
parsePiOutput,
|
||||
parseWorkBuddyOutput,
|
||||
readHermesFinalResponse,
|
||||
readHermesMessageWatermark,
|
||||
redactChildSecrets,
|
||||
runtimeCommandSummary,
|
||||
stripAnsi,
|
||||
stripExactMeldworkPromptEcho,
|
||||
structuredCliError,
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
const crypto = require('node:crypto')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const { isDeepStrictEqual } = require('node:util')
|
||||
|
||||
const { atomicWritePrivateFile } = require('../../security/private-file.cjs')
|
||||
|
||||
@@ -42,6 +43,7 @@ const OPENCLAW_RUNTIME_CREDENTIAL_KEYS = new Set([
|
||||
])
|
||||
const issuedOpenClawRuntimeGuards = new WeakSet()
|
||||
const openClawRuntimeCredentialDigests = new WeakMap()
|
||||
const openClawRuntimeConfigs = new WeakMap()
|
||||
const OPENCLAW_ENV_SECRET_NAME = /^[A-Z][A-Z0-9_]{0,127}$/
|
||||
const OPENCLAW_SECRET_MARKERS = new Set([
|
||||
'secretref-managed',
|
||||
@@ -89,7 +91,7 @@ function directoryIdentity(filename) {
|
||||
})
|
||||
}
|
||||
|
||||
function fileIdentity(filename) {
|
||||
function readRuntimeConfigFile(filename) {
|
||||
const resolved = path.resolve(filename)
|
||||
const entry = fs.lstatSync(resolved)
|
||||
if (!entry.isFile() || entry.isSymbolicLink() || fs.realpathSync(resolved) !== resolved) {
|
||||
@@ -99,14 +101,22 @@ function fileIdentity(filename) {
|
||||
const descriptor = fs.openSync(resolved, fs.constants.O_RDONLY | noFollow)
|
||||
try {
|
||||
const before = fs.fstatSync(descriptor)
|
||||
if (!before.isFile() || !sameFilesystemIdentity(before, {
|
||||
if (!before.isFile() || before.size > 256 * 1024 || !sameFilesystemIdentity(before, {
|
||||
dev: identityValue(entry.dev),
|
||||
ino: identityValue(entry.ino),
|
||||
birthtime: identityValue(entry.birthtimeMs),
|
||||
})) {
|
||||
throw new Error('OPENCLAW_RUNTIME_UNSAFE_PATH')
|
||||
}
|
||||
const contents = fs.readFileSync(descriptor)
|
||||
const buffer = Buffer.alloc(256 * 1024 + 1)
|
||||
let length = 0
|
||||
while (length < buffer.length) {
|
||||
const count = fs.readSync(descriptor, buffer, length, buffer.length - length, null)
|
||||
if (!count) break
|
||||
length += count
|
||||
}
|
||||
if (length === buffer.length) throw new Error('OPENCLAW_RUNTIME_UNSAFE_PATH')
|
||||
const contents = buffer.subarray(0, length)
|
||||
const after = fs.fstatSync(descriptor)
|
||||
const current = fs.lstatSync(resolved)
|
||||
if (!sameFilesystemIdentity(after, {
|
||||
@@ -121,7 +131,7 @@ function fileIdentity(filename) {
|
||||
}) || fs.realpathSync(resolved) !== resolved) {
|
||||
throw new Error('OPENCLAW_RUNTIME_UNSAFE_PATH')
|
||||
}
|
||||
return Object.freeze({
|
||||
const identity = Object.freeze({
|
||||
path: resolved,
|
||||
dev: identityValue(before.dev),
|
||||
ino: identityValue(before.ino),
|
||||
@@ -130,11 +140,16 @@ function fileIdentity(filename) {
|
||||
size: contents.length,
|
||||
digest: crypto.createHash('sha256').update(contents).digest('hex'),
|
||||
})
|
||||
return { identity, contents: contents.toString('utf8') }
|
||||
} finally {
|
||||
fs.closeSync(descriptor)
|
||||
}
|
||||
}
|
||||
|
||||
function fileIdentity(filename) {
|
||||
return readRuntimeConfigFile(filename).identity
|
||||
}
|
||||
|
||||
function validateDirectoryIdentities(identities) {
|
||||
for (const expected of identities) {
|
||||
const current = directoryIdentity(expected.path)
|
||||
@@ -268,6 +283,7 @@ function writeRuntimeConfig(runtime, config, credentials, credentialKey) {
|
||||
credentialKeys: Object.freeze(credentialEntries.map(([key]) => key)),
|
||||
})
|
||||
issuedOpenClawRuntimeGuards.add(guard)
|
||||
openClawRuntimeConfigs.set(guard, contents)
|
||||
openClawRuntimeCredentialDigests.set(guard, Object.freeze(Object.fromEntries(
|
||||
credentialEntries.map(([key, value]) => [
|
||||
key,
|
||||
@@ -277,7 +293,7 @@ function writeRuntimeConfig(runtime, config, credentials, credentialKey) {
|
||||
return guard
|
||||
}
|
||||
|
||||
function validateOpenClawRuntimeGuard(guard, env = {}) {
|
||||
function validateRuntimeScope(guard, env = {}) {
|
||||
const credentialDigests = guard && typeof guard === 'object'
|
||||
? openClawRuntimeCredentialDigests.get(guard)
|
||||
: undefined
|
||||
@@ -301,10 +317,57 @@ function validateOpenClawRuntimeGuard(guard, env = {}) {
|
||||
}
|
||||
}
|
||||
validateDirectoryIdentities(guard.directories)
|
||||
}
|
||||
|
||||
function validateOpenClawRuntimeGuard(guard, env = {}) {
|
||||
validateRuntimeScope(guard, env)
|
||||
validateFileIdentity(guard.config)
|
||||
return true
|
||||
}
|
||||
|
||||
function comparableMigratedConfig(config) {
|
||||
// OpenClaw materializes the implicit main agent and stamps migrations at startup.
|
||||
const result = JSON.parse(JSON.stringify(config))
|
||||
const meta = result.meta
|
||||
if (meta && typeof meta === 'object' && !Array.isArray(meta)
|
||||
&& Object.keys(meta).every(key => ['migrations', 'lastTouchedVersion', 'lastTouchedAt'].includes(key))
|
||||
&& (meta.lastTouchedVersion === undefined || /^\d{4}\.\d{1,2}\.\d{1,2}(?:[-+.][\w.-]+)?$/.test(meta.lastTouchedVersion))
|
||||
&& (meta.lastTouchedAt === undefined || (typeof meta.lastTouchedAt === 'string' && Number.isFinite(Date.parse(meta.lastTouchedAt))))
|
||||
&& (meta.migrations === undefined || isDeepStrictEqual(meta.migrations, { modelPolicyAllowlist: true }))) {
|
||||
delete result.meta
|
||||
}
|
||||
if (isDeepStrictEqual(result.agents?.entries, { main: {} })) delete result.agents.entries
|
||||
if (isDeepStrictEqual(result.discovery?.wideArea, { enabled: false })) {
|
||||
result.discovery.wideArea = {}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function refreshOpenClawRuntimeAfterStartup(options) {
|
||||
const guard = options?.openClawRuntimeGuard
|
||||
const env = options?.env || {}
|
||||
validateRuntimeScope(guard, env)
|
||||
const { identity: config, contents } = readRuntimeConfigFile(guard.config.path)
|
||||
if (process.platform !== 'win32' && (config.mode & 0o777) !== 0o600) {
|
||||
throw new Error('OPENCLAW_RUNTIME_UNSAFE_PATH')
|
||||
}
|
||||
validateDirectoryIdentities(guard.directories)
|
||||
validateFileIdentity(config)
|
||||
let equivalent = false
|
||||
try {
|
||||
equivalent = isDeepStrictEqual(
|
||||
comparableMigratedConfig(JSON.parse(openClawRuntimeConfigs.get(guard))),
|
||||
comparableMigratedConfig(JSON.parse(contents)),
|
||||
)
|
||||
} catch { /* malformed config is rejected below */ }
|
||||
if (!equivalent) throw new Error('OPENCLAW_RUNTIME_UNSAFE_PATH')
|
||||
const refreshed = Object.freeze({ ...guard, config })
|
||||
issuedOpenClawRuntimeGuards.add(refreshed)
|
||||
openClawRuntimeConfigs.set(refreshed, contents)
|
||||
openClawRuntimeCredentialDigests.set(refreshed, openClawRuntimeCredentialDigests.get(guard))
|
||||
return { ...options, openClawRuntimeGuard: refreshed }
|
||||
}
|
||||
|
||||
function configureOpenClawGatewayRuntime(options, port) {
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('OPENCLAW_GATEWAY_PORT_INVALID')
|
||||
@@ -313,7 +376,7 @@ function configureOpenClawGatewayRuntime(options, port) {
|
||||
const env = options?.env || {}
|
||||
validateOpenClawRuntimeGuard(guard, env)
|
||||
|
||||
const config = JSON.parse(fs.readFileSync(guard.config.path, 'utf8'))
|
||||
const config = JSON.parse(openClawRuntimeConfigs.get(guard))
|
||||
const gatewayCredentialKey = 'OPENCLAW_GATEWAY_TOKEN'
|
||||
const nextConfig = {
|
||||
...config,
|
||||
@@ -557,5 +620,6 @@ module.exports = {
|
||||
isOpenClawSecretReference,
|
||||
managedOpenClawOptions,
|
||||
nativeOpenClawOptions,
|
||||
refreshOpenClawRuntimeAfterStartup,
|
||||
validateOpenClawRuntimeGuard,
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
const fs = require('node:fs')
|
||||
const http = require('node:http')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const { spawn, spawnSync } = require('node:child_process')
|
||||
|
||||
const requestedPort = Number(process.env.MELDWORK_AGENT_BRIDGE_PORT || 8765)
|
||||
const PORT = Number.isInteger(requestedPort) && requestedPort >= 1024 && requestedPort <= 65535
|
||||
? requestedPort
|
||||
: 8765
|
||||
const MAX_REQUEST_BYTES = 4 * 1024 * 1024
|
||||
const MAX_RESPONSE_BYTES = 256 * 1024
|
||||
const MAX_SKILLS = 64
|
||||
const PUBLIC_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/
|
||||
|
||||
const AGENT_DEFINITIONS = Object.freeze([
|
||||
{
|
||||
id: 'codex', label: 'Codex',
|
||||
description: 'Codex CLI exposed through an SSH-local Bridge.',
|
||||
auth(command) { return command('codex', ['login', 'status']).status === 0 },
|
||||
},
|
||||
{
|
||||
id: 'hermes', label: 'Hermes',
|
||||
description: 'Hermes Agent exposed through an SSH-local Bridge.',
|
||||
auth() { return true },
|
||||
},
|
||||
{
|
||||
id: 'claude', label: 'Claude Code',
|
||||
description: 'Claude Code exposed through an SSH-local Bridge.',
|
||||
auth(command) {
|
||||
const result = command('claude', ['auth', 'status'])
|
||||
if (result.status !== 0) return false
|
||||
try { return JSON.parse(String(result.stdout || '')).loggedIn === true } catch { return false }
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
function json(res, status, body) {
|
||||
const payload = JSON.stringify(body)
|
||||
res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) })
|
||||
res.end(payload)
|
||||
}
|
||||
|
||||
function versionFrom(value) {
|
||||
return String(value || '').match(/(?:^|[^0-9])v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/)?.[1] || ''
|
||||
}
|
||||
|
||||
function commandResult(spawnSyncFn, command, args) {
|
||||
const result = spawnSyncFn(command, args, { encoding: 'utf8', timeout: 5000 }) || {}
|
||||
return {
|
||||
status: Number.isInteger(result.status) ? result.status : 1,
|
||||
stdout: String(result.stdout || ''),
|
||||
}
|
||||
}
|
||||
|
||||
function listSkills(kind, options = {}) {
|
||||
const readdirSync = options.readdirSync || fs.readdirSync
|
||||
const home = options.home || os.homedir()
|
||||
const roots = {
|
||||
codex: [path.join(home, '.codex', 'skills'), path.join(home, '.agents', 'skills')],
|
||||
hermes: [path.join(home, '.hermes', 'skills'), path.join(home, '.agents', 'skills')],
|
||||
claude: [path.join(home, '.claude', 'skills'), path.join(home, '.agents', 'skills')],
|
||||
}[kind] || []
|
||||
const names = new Set()
|
||||
for (const root of roots) {
|
||||
let entries = []
|
||||
try { entries = readdirSync(root, { withFileTypes: true }) } catch { continue }
|
||||
for (const entry of entries) {
|
||||
if (names.size >= MAX_SKILLS) break
|
||||
if ((entry.isDirectory?.() || entry.isSymbolicLink?.()) && PUBLIC_NAME.test(entry.name)) names.add(entry.name)
|
||||
}
|
||||
}
|
||||
return [...names].sort().map(name => ({ namespace: kind, slug: name, name }))
|
||||
}
|
||||
|
||||
function discoverAgents(options = {}) {
|
||||
const spawnSyncFn = options.spawnSync || spawnSync
|
||||
const listSkillsFn = options.listSkills || (kind => listSkills(kind))
|
||||
const command = (name, args) => commandResult(spawnSyncFn, name, args)
|
||||
const agents = []
|
||||
for (const definition of AGENT_DEFINITIONS) {
|
||||
const versionResult = command(definition.id, ['--version'])
|
||||
const version = versionResult.status === 0 ? versionFrom(versionResult.stdout) : ''
|
||||
if (!version) continue
|
||||
const available = definition.auth(command)
|
||||
agents.push({
|
||||
id: definition.id,
|
||||
sourceKind: definition.id,
|
||||
label: definition.label,
|
||||
version,
|
||||
description: definition.description,
|
||||
domains: ['general'],
|
||||
inputTypes: ['text'],
|
||||
permissionModes: ['read-only'],
|
||||
available,
|
||||
credentialState: available ? 'ready' : 'missing',
|
||||
skills: listSkillsFn(definition.id),
|
||||
session: {
|
||||
supported: true,
|
||||
resume: true,
|
||||
cancel: true,
|
||||
checkpoint: false,
|
||||
},
|
||||
})
|
||||
}
|
||||
return agents
|
||||
}
|
||||
|
||||
function invocationFor(agentId, prompt, sessionRef = '') {
|
||||
if (agentId === 'codex') {
|
||||
return {
|
||||
command: 'codex',
|
||||
args: sessionRef
|
||||
? ['exec', 'resume', '--json', '--skip-git-repo-check', '--sandbox', 'read-only', sessionRef, '-']
|
||||
: ['exec', '--json', '--skip-git-repo-check', '--sandbox', 'read-only', '-'],
|
||||
input: prompt,
|
||||
}
|
||||
}
|
||||
if (agentId === 'hermes') {
|
||||
return {
|
||||
command: 'hermes',
|
||||
args: ['chat', '--quiet', ...(sessionRef ? ['--resume', sessionRef] : []), '--query', prompt],
|
||||
input: '',
|
||||
}
|
||||
}
|
||||
if (agentId === 'claude') {
|
||||
return {
|
||||
command: 'claude',
|
||||
args: [
|
||||
'--print', '--output-format', 'json', '--permission-mode', 'plan',
|
||||
...(sessionRef ? ['--resume', sessionRef] : []), prompt,
|
||||
],
|
||||
input: '',
|
||||
}
|
||||
}
|
||||
throw new Error('REMOTE_AGENT_UNSUPPORTED')
|
||||
}
|
||||
|
||||
function parseAgentOutput(agentId, stdout) {
|
||||
if (agentId === 'codex') {
|
||||
const messages = []
|
||||
let sessionRef = ''
|
||||
for (const line of String(stdout || '').split(/\r?\n/)) {
|
||||
try {
|
||||
const event = JSON.parse(line)
|
||||
if (event.type === 'thread.started' && typeof event.thread_id === 'string') sessionRef = event.thread_id
|
||||
if (event.type === 'item.completed' && event.item?.type === 'agent_message'
|
||||
&& typeof event.item.text === 'string') messages.push(event.item.text)
|
||||
} catch { /* ignore non-JSON diagnostics */ }
|
||||
}
|
||||
const text = messages.join('\n').trim()
|
||||
return text ? { text, sessionRef, outcome: 'completed' } : null
|
||||
}
|
||||
if (agentId === 'hermes') {
|
||||
const lines = String(stdout || '').split(/\r?\n/)
|
||||
let sessionRef = ''
|
||||
const text = lines.filter((line) => {
|
||||
const match = line.match(/^session_id:\s*(\S+)\s*$/)
|
||||
if (match) {
|
||||
sessionRef = match[1]
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}).join('\n').trim()
|
||||
return text ? { text, sessionRef, outcome: 'completed' } : null
|
||||
}
|
||||
if (agentId === 'claude') {
|
||||
let result
|
||||
try { result = JSON.parse(String(stdout || '')) } catch { return null }
|
||||
if (result?.is_error === true || typeof result?.result !== 'string' || !result.result.trim()) return null
|
||||
return { text: result.result.trim(), sessionRef: String(result.session_id || ''), outcome: 'completed' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function readBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let body = ''
|
||||
req.on('data', chunk => {
|
||||
body += chunk.toString('utf8')
|
||||
if (Buffer.byteLength(body) > MAX_REQUEST_BYTES) reject(new Error('request too large'))
|
||||
})
|
||||
req.once('end', () => resolve(body))
|
||||
req.once('error', reject)
|
||||
})
|
||||
}
|
||||
|
||||
function parentSessionDetached(parentPid = process.ppid, readFileSync = fs.readFileSync) {
|
||||
if (!Number.isInteger(parentPid) || parentPid <= 1 || process.ppid === 1) return true
|
||||
try {
|
||||
const stat = String(readFileSync(`/proc/${parentPid}/stat`, 'utf8'))
|
||||
const match = stat.match(/^\d+\s+\(.+\)\s+\S+\s+(\d+)\s/)
|
||||
return match ? Number(match[1]) === 1 : false
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
function runAgent(agentId, prompt, sessionRef = '') {
|
||||
return new Promise(resolve => {
|
||||
let invocation
|
||||
try { invocation = invocationFor(agentId, prompt, sessionRef) } catch {
|
||||
resolve({ outcome: 'failed', failure: { code: 'REMOTE_AGENT_UNSUPPORTED' } })
|
||||
return
|
||||
}
|
||||
const child = spawn(invocation.command, invocation.args, {
|
||||
stdio: ['pipe', 'pipe', 'pipe'], cwd: process.env.HOME || undefined,
|
||||
})
|
||||
let stdout = ''
|
||||
child.stdout.on('data', chunk => {
|
||||
stdout += chunk.toString('utf8')
|
||||
if (Buffer.byteLength(stdout) > MAX_RESPONSE_BYTES) child.kill('SIGTERM')
|
||||
})
|
||||
child.stderr.resume()
|
||||
child.once('error', () => resolve({ outcome: 'failed', failure: { code: 'REMOTE_AGENT_UNAVAILABLE' } }))
|
||||
child.once('close', code => {
|
||||
if (code !== 0) return resolve({ outcome: 'failed', failure: { code: 'REMOTE_AGENT_FAILED' } })
|
||||
resolve(parseAgentOutput(agentId, stdout)
|
||||
|| { outcome: 'failed', failure: { code: 'REMOTE_AGENT_RESPONSE_INVALID' } })
|
||||
})
|
||||
child.stdin.end(invocation.input)
|
||||
})
|
||||
}
|
||||
|
||||
function createServer() {
|
||||
return http.createServer(async (req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/.well-known/meldwork-agent-bridge') {
|
||||
return json(res, 200, {
|
||||
protocol: 'meldwork-agent-bridge', version: 1,
|
||||
server: { id: 'ssh-session', label: 'SSH Agent Server' },
|
||||
agents: discoverAgents(),
|
||||
})
|
||||
}
|
||||
const match = req.method === 'POST' && req.url?.match(/^\/v1\/agents\/([A-Za-z0-9._-]+)\/runs$/)
|
||||
if (!match) return json(res, 404, { error: 'NOT_FOUND' })
|
||||
try {
|
||||
const body = JSON.parse(await readBody(req))
|
||||
const agent = discoverAgents().find(item => item.id === match[1] && item.available)
|
||||
if (!agent || typeof body.prompt !== 'string' || body.permissionMode !== 'read-only') {
|
||||
return json(res, 400, { error: 'REQUEST_INVALID' })
|
||||
}
|
||||
return json(res, 200, await runAgent(agent.id, body.prompt, body.sessionRef || ''))
|
||||
} catch {
|
||||
return json(res, 400, { error: 'REQUEST_INVALID' })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function startServer() {
|
||||
const server = createServer()
|
||||
const parentPid = process.ppid
|
||||
const parentTimer = setInterval(() => {
|
||||
if (!parentSessionDetached(parentPid)) return
|
||||
server.close(() => process.exit(0))
|
||||
}, 1000)
|
||||
server.once('close', () => clearInterval(parentTimer))
|
||||
server.listen(PORT, '127.0.0.1', () => {
|
||||
process.stdout.write(`MELDWORK_AGENT_BRIDGE_READY ${PORT}\n`)
|
||||
})
|
||||
process.once('SIGTERM', () => server.close(() => process.exit(0)))
|
||||
process.once('SIGINT', () => server.close(() => process.exit(0)))
|
||||
return server
|
||||
}
|
||||
|
||||
if (require.main === module || !require.main) startServer()
|
||||
|
||||
module.exports = {
|
||||
createServer,
|
||||
discoverAgents,
|
||||
invocationFor,
|
||||
listSkills,
|
||||
parentSessionDetached,
|
||||
parseAgentOutput,
|
||||
runAgent,
|
||||
startServer,
|
||||
}
|
||||
@@ -0,0 +1,721 @@
|
||||
const crypto = require('node:crypto')
|
||||
const { spawn } = require('node:child_process')
|
||||
const fs = require('node:fs')
|
||||
const net = require('node:net')
|
||||
|
||||
const { canonicalJson } = require('../../collaboration/outcome-records.cjs')
|
||||
const { atomicWritePrivateFile } = require('../../security/private-file.cjs')
|
||||
const { createAgentConnectorManifest } = require('../connectors/agent-connector-manifest.cjs')
|
||||
|
||||
const BRIDGE_PROTOCOL = 'meldwork-agent-bridge'
|
||||
const BRIDGE_VERSION = 1
|
||||
const BRIDGE_RECIPE_ID = 'external.cloud-agent-bridge'
|
||||
const SSH_RECIPE_ID = 'external.cloud-agent-ssh'
|
||||
const BRIDGE_UPSTREAM_ID = 'meldwork-cloud'
|
||||
const BRIDGE_UPSTREAM_VERSION = '1.0.0'
|
||||
const BRIDGE_ID = /^cloud-bridge-[a-f0-9]{24}$/
|
||||
const PUBLIC_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/
|
||||
const MAX_RESPONSE_BYTES = 256 * 1024
|
||||
const MAX_AGENTS = 32
|
||||
const MAX_SKILLS = 64
|
||||
const STORE_VERSION = 1
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 3 * 60 * 1000
|
||||
const DEFAULT_RUN_TIMEOUT_MS = 10 * 60 * 1000
|
||||
const MAX_REQUEST_TIMEOUT_MS = 15 * 60 * 1000
|
||||
const SSH_DISCOVERY_COMMAND = 'if command -v codex >/dev/null 2>&1; then codex --version; fi'
|
||||
const SSH_CODEX_COMMAND = 'exec codex exec --json --skip-git-repo-check --sandbox read-only -'
|
||||
const SSH_TUNNEL_READY = 'MELDWORK_AGENT_BRIDGE_READY'
|
||||
const SSH_BRIDGE_SCRIPT = fs.readFileSync(require.resolve('./cloud-agent-bridge-server.cjs'), 'utf8')
|
||||
|
||||
function loginShellCommand(command) {
|
||||
const escaped = String(command).replace(/'/g, `'"'"'`)
|
||||
return `bash -lc '${escaped}'`
|
||||
}
|
||||
|
||||
function bridgeError(code) {
|
||||
const error = new Error(code)
|
||||
error.code = code
|
||||
return error
|
||||
}
|
||||
|
||||
function fail(code) {
|
||||
throw bridgeError(code)
|
||||
}
|
||||
|
||||
function clone(value) {
|
||||
return JSON.parse(canonicalJson(value))
|
||||
}
|
||||
|
||||
function cleanText(value, max = 240) {
|
||||
const text = String(value || '').trim()
|
||||
if (!text || text.length > max || /[\u0000-\u001f\u007f]/.test(text)) return ''
|
||||
return text
|
||||
}
|
||||
|
||||
function normalizeSkill(input) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
|
||||
const namespace = cleanText(input.namespace, 80)
|
||||
const slug = cleanText(input.slug, 120)
|
||||
const name = cleanText(input.name || input.slug, 120)
|
||||
if (!PUBLIC_ID.test(namespace) || !PUBLIC_ID.test(slug) || !name) return null
|
||||
return { namespace, slug, name }
|
||||
}
|
||||
|
||||
function normalizeAddress(value) {
|
||||
const raw = String(value || '').trim().replace(/\/$/, '')
|
||||
const address = /^[a-z][a-z\d+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`
|
||||
let parsed
|
||||
try { parsed = new URL(address) } catch { fail('CLOUD_AGENT_BRIDGE_ADDRESS_INVALID') }
|
||||
if (!['https:'].includes(parsed.protocol)
|
||||
|| parsed.username || parsed.password || parsed.pathname !== '/'
|
||||
|| parsed.search || parsed.hash || !parsed.hostname
|
||||
|| net.isIP(parsed.hostname) === 0) {
|
||||
fail('CLOUD_AGENT_BRIDGE_ADDRESS_INVALID')
|
||||
}
|
||||
return parsed.origin
|
||||
}
|
||||
|
||||
function normalizeSshAddress(value) {
|
||||
const raw = String(value || '').trim()
|
||||
if (!raw || /^[a-z][a-z\d+.-]*:\/\//i.test(raw) || /[\s@/?#]/.test(raw)) {
|
||||
fail('CLOUD_AGENT_SSH_ADDRESS_INVALID')
|
||||
}
|
||||
const match = raw.match(/^([^:]+)(?::(\d{1,5}))?$/)
|
||||
if (!match || net.isIP(match[1]) === 0) fail('CLOUD_AGENT_SSH_ADDRESS_INVALID')
|
||||
const port = match[2] ? Number(match[2]) : 22
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) fail('CLOUD_AGENT_SSH_ADDRESS_INVALID')
|
||||
return { host: match[1], port, address: port === 22 ? match[1] : `${match[1]}:${port}` }
|
||||
}
|
||||
|
||||
function normalizeTunnelEndpoint(value) {
|
||||
let parsed
|
||||
try { parsed = new URL(String(value || '')) } catch { fail('CLOUD_AGENT_SSH_TUNNEL_INVALID') }
|
||||
if (parsed.protocol !== 'http:' || parsed.hostname !== '127.0.0.1'
|
||||
|| parsed.pathname !== '/' || parsed.search || parsed.hash
|
||||
|| parsed.username || parsed.password || !parsed.port) {
|
||||
fail('CLOUD_AGENT_SSH_TUNNEL_INVALID')
|
||||
}
|
||||
return parsed.origin
|
||||
}
|
||||
|
||||
function normalizeAgent(input) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
||||
fail('CLOUD_AGENT_BRIDGE_MANIFEST_INVALID')
|
||||
}
|
||||
const id = cleanText(input.id, 80)
|
||||
const sourceKind = cleanText(input.sourceKind || input.id, 80)
|
||||
const label = cleanText(input.label || input.name, 120)
|
||||
const version = cleanText(input.version, 80)
|
||||
if (!PUBLIC_ID.test(id) || !PUBLIC_ID.test(sourceKind) || !label || !version) {
|
||||
fail('CLOUD_AGENT_BRIDGE_MANIFEST_INVALID')
|
||||
}
|
||||
const domains = Array.isArray(input.domains) && input.domains.length
|
||||
? input.domains.map(item => cleanText(item, 80)).filter(item => PUBLIC_ID.test(item))
|
||||
: ['general']
|
||||
const inputTypes = Array.isArray(input.inputTypes) && input.inputTypes.length
|
||||
? input.inputTypes.filter(item => ['text', 'image', 'audio', 'video', 'file', 'structured-data'].includes(item))
|
||||
: ['text']
|
||||
const permissionModes = Array.isArray(input.permissionModes) && input.permissionModes.length
|
||||
? input.permissionModes.filter(item => ['read-only', 'workspace-write'].includes(item))
|
||||
: ['read-only']
|
||||
if (!domains.length || !inputTypes.includes('text') || !permissionModes.length) {
|
||||
fail('CLOUD_AGENT_BRIDGE_MANIFEST_INVALID')
|
||||
}
|
||||
const credentialState = ['ready', 'missing', 'unknown'].includes(input.credentialState)
|
||||
? input.credentialState
|
||||
: (input.available === false ? 'unknown' : 'ready')
|
||||
const skills = (Array.isArray(input.skills) ? input.skills : [])
|
||||
.map(normalizeSkill)
|
||||
.filter(Boolean)
|
||||
.slice(0, MAX_SKILLS)
|
||||
return {
|
||||
id, sourceKind, label, version,
|
||||
description: cleanText(input.description, 400),
|
||||
available: input.available !== false,
|
||||
credentialState,
|
||||
skills,
|
||||
domains: [...new Set(domains)].slice(0, 16),
|
||||
inputTypes: [...new Set(inputTypes)].slice(0, 16),
|
||||
permissionModes: [...new Set(permissionModes)],
|
||||
session: {
|
||||
supported: input.session?.supported !== false,
|
||||
resume: input.session?.resume !== false,
|
||||
cancel: input.session?.cancel !== false,
|
||||
checkpoint: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeProbe(value) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)
|
||||
|| value.protocol !== BRIDGE_PROTOCOL || value.version !== BRIDGE_VERSION
|
||||
|| !Array.isArray(value.agents) || !value.agents.length || value.agents.length > MAX_AGENTS) {
|
||||
fail('CLOUD_AGENT_BRIDGE_MANIFEST_INVALID')
|
||||
}
|
||||
const serverLabel = cleanText(value.server?.label || value.server?.name, 120)
|
||||
return {
|
||||
serverId: cleanText(value.server?.id, 120),
|
||||
serverLabel: serverLabel || 'Cloud Agent Server',
|
||||
agents: value.agents.map(normalizeAgent),
|
||||
}
|
||||
}
|
||||
|
||||
function bridgeIdFor(address) {
|
||||
return `cloud-bridge-${crypto.createHash('sha256').update(address).digest('hex').slice(0, 24)}`
|
||||
}
|
||||
|
||||
function instanceIdFor(bridgeId, agentId) {
|
||||
return `cloud-${crypto.createHash('sha256').update(`${bridgeId}:${agentId}`).digest('hex').slice(0, 24)}`
|
||||
}
|
||||
|
||||
function manifestFor(record, agent) {
|
||||
const ssh = record.transport === 'ssh'
|
||||
const tunnel = record.transport === 'ssh-tunnel'
|
||||
return createAgentConnectorManifest({
|
||||
connectorId: instanceIdFor(record.bridgeId, agent.id),
|
||||
connectorVersion: '1.0.0',
|
||||
kind: 'agent',
|
||||
label: `${agent.label} @ ${record.label}`,
|
||||
description: agent.description || `Agent CLI exposed by ${record.label}.`,
|
||||
transport: ssh ? { type: 'cli', protocol: 'jsonl' } : { type: 'http', protocol: 'json' },
|
||||
upstream: ssh
|
||||
? { id: agent.id, minVersion: BRIDGE_UPSTREAM_VERSION, maxVersion: BRIDGE_UPSTREAM_VERSION }
|
||||
: { id: BRIDGE_UPSTREAM_ID, minVersion: BRIDGE_UPSTREAM_VERSION, maxVersion: BRIDGE_UPSTREAM_VERSION },
|
||||
invocation: { recipeId: ssh ? SSH_RECIPE_ID : BRIDGE_RECIPE_ID, idempotencyMode: 'durable' },
|
||||
domains: agent.domains,
|
||||
session: agent.session,
|
||||
inputTypes: agent.inputTypes,
|
||||
permissionModes: agent.permissionModes,
|
||||
eventProtocolVersion: 1,
|
||||
eventTypes: ['Completed', 'Failed', 'Cancelled'],
|
||||
usage: {
|
||||
inputTokens: false, outputTokens: false, costMicros: false,
|
||||
toolCalls: false, outboundBytes: !ssh && !tunnel, elapsedMs: true,
|
||||
},
|
||||
outboundDestinations: ssh || tunnel ? [] : [record.address],
|
||||
credentials: { mode: 'none', slots: [] },
|
||||
license: 'LicenseRef-Meldwork-NC',
|
||||
})
|
||||
}
|
||||
|
||||
function instanceFor(record, agent, manifest) {
|
||||
return {
|
||||
instanceId: manifest.connectorId,
|
||||
connectorId: manifest.connectorId,
|
||||
connectorVersion: manifest.connectorVersion,
|
||||
upstreamVersion: BRIDGE_UPSTREAM_VERSION,
|
||||
label: manifest.label,
|
||||
credentialRef: null,
|
||||
manifestId: manifest.manifestId,
|
||||
bridgeId: record.bridgeId,
|
||||
agentId: agent.id,
|
||||
}
|
||||
}
|
||||
|
||||
class CloudAgentBridgeStore {
|
||||
constructor(options = {}) {
|
||||
if (!options || typeof options.storagePath !== 'string' || !options.storagePath
|
||||
|| typeof options.fetch !== 'function') {
|
||||
fail('CLOUD_AGENT_BRIDGE_OPTIONS_INVALID')
|
||||
}
|
||||
this.storagePath = options.storagePath
|
||||
this.fetch = options.fetch
|
||||
this.spawn = options.spawn || spawn
|
||||
this.sshExecute = typeof options.sshExecute === 'function' ? options.sshExecute : null
|
||||
this.sshTunnelStart = typeof options.sshTunnelStart === 'function' ? options.sshTunnelStart : null
|
||||
this.tunnels = new Map()
|
||||
this.timeoutMs = Number.isFinite(options.timeoutMs)
|
||||
? Math.max(1000, Math.min(MAX_REQUEST_TIMEOUT_MS, Math.floor(options.timeoutMs)))
|
||||
: DEFAULT_REQUEST_TIMEOUT_MS
|
||||
this.runTimeoutMs = Number.isFinite(options.runTimeoutMs)
|
||||
? Math.max(1000, Math.min(MAX_REQUEST_TIMEOUT_MS, Math.floor(options.runTimeoutMs)))
|
||||
: DEFAULT_RUN_TIMEOUT_MS
|
||||
this.records = this.read().records
|
||||
}
|
||||
|
||||
read() {
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(this.storagePath, 'utf8'))
|
||||
if (parsed?.version !== STORE_VERSION || !Array.isArray(parsed.records)) throw new Error('invalid')
|
||||
return { version: STORE_VERSION, records: parsed.records.map(value => this.normalizeRecord(value)) }
|
||||
} catch {
|
||||
return { version: STORE_VERSION, records: [] }
|
||||
}
|
||||
}
|
||||
|
||||
normalizeRecord(value) {
|
||||
const transport = ['ssh', 'ssh-tunnel'].includes(value?.transport) ? value.transport : 'bridge'
|
||||
const sshAddress = ['ssh', 'ssh-tunnel'].includes(transport) ? normalizeSshAddress(value?.address) : null
|
||||
const address = sshAddress?.address || normalizeAddress(value?.address)
|
||||
const bridgeId = String(value?.bridgeId || bridgeIdFor(`${transport}:${address}`))
|
||||
if (!BRIDGE_ID.test(bridgeId)) fail('CLOUD_AGENT_BRIDGE_STORE_INVALID')
|
||||
const agents = Array.isArray(value?.agents) ? value.agents.map(normalizeAgent).slice(0, MAX_AGENTS) : []
|
||||
return {
|
||||
bridgeId,
|
||||
transport,
|
||||
address,
|
||||
endpoint: transport === 'ssh-tunnel' ? normalizeTunnelEndpoint(value?.endpoint) : '',
|
||||
label: cleanText(value?.label, 120) || (transport === 'ssh' ? address : 'Cloud Agent Server'),
|
||||
serverId: cleanText(value?.serverId, 120),
|
||||
agents,
|
||||
available: transport === 'ssh-tunnel' ? false : value?.available === true,
|
||||
lastError: cleanText(value?.lastError, 120),
|
||||
checkedAt: cleanText(value?.checkedAt, 40),
|
||||
}
|
||||
}
|
||||
|
||||
persist() {
|
||||
atomicWritePrivateFile(this.storagePath, `${JSON.stringify({ version: STORE_VERSION, records: this.records })}\n`)
|
||||
}
|
||||
|
||||
async request(pathname, options = {}) {
|
||||
const controller = new AbortController()
|
||||
const timeoutMs = Number.isFinite(options.timeoutMs)
|
||||
? Math.max(1000, Math.min(MAX_REQUEST_TIMEOUT_MS, Math.floor(options.timeoutMs)))
|
||||
: this.timeoutMs
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
const activityIntervalMs = Math.min(1000, Math.max(10, Math.floor(timeoutMs / 4)))
|
||||
const reportActivity = () => {
|
||||
try { options.onActivity?.() } catch { /* activity reporting must not fail the request */ }
|
||||
}
|
||||
reportActivity()
|
||||
const activityTimer = options.onActivity
|
||||
? setInterval(reportActivity, activityIntervalMs)
|
||||
: null
|
||||
const abortFromCaller = () => controller.abort()
|
||||
options.signal?.addEventListener?.('abort', abortFromCaller, { once: true })
|
||||
try {
|
||||
const response = await this.fetch(`${options.address}${pathname}`, {
|
||||
method: options.method || 'GET',
|
||||
redirect: 'error',
|
||||
signal: controller.signal,
|
||||
headers: { accept: 'application/json', ...(options.body ? { 'content-type': 'application/json' } : {}) },
|
||||
...(options.body ? { body: JSON.stringify(options.body) } : {}),
|
||||
})
|
||||
if (!response?.ok) throw bridgeError(`CLOUD_AGENT_BRIDGE_HTTP_${response?.status || 'FAILED'}`)
|
||||
const text = await response.text()
|
||||
if (Buffer.byteLength(text, 'utf8') > MAX_RESPONSE_BYTES) fail('CLOUD_AGENT_BRIDGE_RESPONSE_TOO_LARGE')
|
||||
try { return JSON.parse(text) } catch { fail('CLOUD_AGENT_BRIDGE_RESPONSE_INVALID') }
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError') fail('CLOUD_AGENT_BRIDGE_TIMEOUT')
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
if (activityTimer) clearInterval(activityTimer)
|
||||
options.signal?.removeEventListener?.('abort', abortFromCaller)
|
||||
}
|
||||
}
|
||||
|
||||
async probe(address) {
|
||||
const normalizedAddress = normalizeAddress(address)
|
||||
return normalizeProbe(await this.request('/.well-known/meldwork-agent-bridge', { address: normalizedAddress }))
|
||||
}
|
||||
|
||||
async sshCommand(address, command, input = '', signal) {
|
||||
const parsed = normalizeSshAddress(address)
|
||||
if (signal?.aborted) fail('CLOUD_AGENT_SSH_CANCELLED')
|
||||
if (this.sshExecute) return this.sshExecute({
|
||||
address: parsed.address, command, input, signal,
|
||||
})
|
||||
const args = [
|
||||
'-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', '-o', 'StrictHostKeyChecking=yes',
|
||||
...(parsed.port === 22 ? [] : ['-p', String(parsed.port)]),
|
||||
parsed.host, command,
|
||||
]
|
||||
return new Promise((resolve, reject) => {
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
let settled = false
|
||||
const child = this.spawn('ssh', args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
|
||||
const finish = (error, value) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
signal?.removeEventListener?.('abort', abort)
|
||||
if (error) reject(error)
|
||||
else resolve(value)
|
||||
}
|
||||
const append = (target, chunk) => {
|
||||
const next = `${target}${Buffer.from(chunk).toString('utf8')}`
|
||||
if (Buffer.byteLength(next, 'utf8') > MAX_RESPONSE_BYTES) {
|
||||
child.kill('SIGTERM')
|
||||
finish(bridgeError('CLOUD_AGENT_SSH_RESPONSE_TOO_LARGE'))
|
||||
return target
|
||||
}
|
||||
return next
|
||||
}
|
||||
const abort = () => {
|
||||
child.kill('SIGTERM')
|
||||
finish(bridgeError('CLOUD_AGENT_SSH_CANCELLED'))
|
||||
}
|
||||
child.once('error', () => finish(bridgeError('CLOUD_AGENT_SSH_UNAVAILABLE')))
|
||||
child.stdout.on('data', chunk => { stdout = append(stdout, chunk) })
|
||||
child.stderr.on('data', chunk => { stderr = append(stderr, chunk) })
|
||||
child.once('close', code => {
|
||||
if (signal?.aborted) return finish(bridgeError('CLOUD_AGENT_SSH_CANCELLED'))
|
||||
if (code !== 0) return finish(bridgeError('CLOUD_AGENT_SSH_UNAVAILABLE'))
|
||||
finish(null, { stdout, stderr })
|
||||
})
|
||||
signal?.addEventListener?.('abort', abort, { once: true })
|
||||
child.stdin.end(input)
|
||||
})
|
||||
}
|
||||
|
||||
async allocateLocalPort() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer()
|
||||
server.once('error', reject)
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const port = server.address()?.port
|
||||
server.close(error => error ? reject(error) : resolve(port))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async startSshTunnel(address) {
|
||||
const parsed = normalizeSshAddress(address)
|
||||
if (this.sshTunnelStart) return this.sshTunnelStart({ address: parsed.address })
|
||||
const localPort = await this.allocateLocalPort()
|
||||
const remotePort = localPort
|
||||
const args = [
|
||||
'-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', '-o', 'StrictHostKeyChecking=yes',
|
||||
'-L', `127.0.0.1:${localPort}:127.0.0.1:${remotePort}`,
|
||||
...(parsed.port === 22 ? [] : ['-p', String(parsed.port)]),
|
||||
parsed.host, loginShellCommand(`MELDWORK_AGENT_BRIDGE_PORT=${remotePort} exec node -`),
|
||||
]
|
||||
const child = this.spawn('ssh', args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
|
||||
child.stderr.resume()
|
||||
return new Promise((resolve, reject) => {
|
||||
let output = ''
|
||||
let settled = false
|
||||
const timer = setTimeout(() => finish(bridgeError('CLOUD_AGENT_SSH_TUNNEL_TIMEOUT')), this.timeoutMs)
|
||||
const finish = error => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
if (error) {
|
||||
child.kill('SIGTERM')
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
resolve({ child, endpoint: `http://127.0.0.1:${localPort}` })
|
||||
}
|
||||
child.once('error', () => finish(bridgeError('CLOUD_AGENT_SSH_TUNNEL_UNAVAILABLE')))
|
||||
child.stdout.on('data', chunk => {
|
||||
output += Buffer.from(chunk).toString('utf8')
|
||||
if (Buffer.byteLength(output, 'utf8') > 16 * 1024) {
|
||||
finish(bridgeError('CLOUD_AGENT_SSH_TUNNEL_PROTOCOL'))
|
||||
return
|
||||
}
|
||||
if (new RegExp(`${SSH_TUNNEL_READY}\\s+${remotePort}\\b`).test(output)) finish()
|
||||
})
|
||||
child.once('close', code => {
|
||||
if (!settled) finish(bridgeError(code === 0
|
||||
? 'CLOUD_AGENT_SSH_TUNNEL_UNAVAILABLE'
|
||||
: 'CLOUD_AGENT_SSH_TUNNEL_FAILED'))
|
||||
})
|
||||
child.stdin.end(SSH_BRIDGE_SCRIPT)
|
||||
})
|
||||
}
|
||||
|
||||
stopTunnel(bridgeId) {
|
||||
const tunnel = this.tunnels.get(bridgeId)
|
||||
if (!tunnel) return
|
||||
this.tunnels.delete(bridgeId)
|
||||
try { tunnel.child?.kill('SIGTERM') } catch { /* already closed */ }
|
||||
}
|
||||
|
||||
async ensureSshTunnel(record) {
|
||||
const existing = this.tunnels.get(record.bridgeId)
|
||||
if (existing?.child && !existing.child.killed) return existing.endpoint
|
||||
const tunnel = await this.startSshTunnel(record.address)
|
||||
this.tunnels.set(record.bridgeId, tunnel)
|
||||
tunnel.child?.once?.('close', () => {
|
||||
if (this.tunnels.get(record.bridgeId) === tunnel) this.tunnels.delete(record.bridgeId)
|
||||
})
|
||||
return tunnel.endpoint
|
||||
}
|
||||
|
||||
async probeSsh(address) {
|
||||
const result = await this.sshCommand(address, SSH_DISCOVERY_COMMAND)
|
||||
const version = String(result.stdout || '').match(/\b(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\b/)?.[1]
|
||||
if (!version) fail('CLOUD_AGENT_SSH_NO_AGENT')
|
||||
return {
|
||||
serverId: '',
|
||||
serverLabel: normalizeSshAddress(address).address,
|
||||
agents: [{
|
||||
id: 'codex', label: 'Codex CLI', version, description: '', domains: ['general'],
|
||||
inputTypes: ['text'], permissionModes: ['read-only'],
|
||||
session: { supported: false, resume: false, cancel: true, checkpoint: false },
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
async connect(input = {}) {
|
||||
const rawAddress = String(input.address || '').trim()
|
||||
let sshError = null
|
||||
if (!/^[a-z][a-z\d+.-]*:\/\//i.test(rawAddress)) {
|
||||
try { return await this.connectSshTunnel(input) } catch (error) { sshError = error }
|
||||
try { return await this.connectSsh(input) } catch (error) { sshError = error }
|
||||
}
|
||||
try {
|
||||
const address = normalizeAddress(input.address)
|
||||
const probe = await this.probe(address)
|
||||
const bridgeId = bridgeIdFor(address)
|
||||
const record = this.normalizeRecord({
|
||||
bridgeId,
|
||||
address,
|
||||
label: cleanText(input.label, 120) || probe.serverLabel,
|
||||
serverId: probe.serverId,
|
||||
agents: probe.agents,
|
||||
available: true,
|
||||
lastError: '',
|
||||
checkedAt: new Date().toISOString(),
|
||||
})
|
||||
const index = this.records.findIndex(item => item.bridgeId === bridgeId)
|
||||
if (index >= 0) this.records[index] = record
|
||||
else this.records.push(record)
|
||||
this.records.sort((left, right) => left.label.localeCompare(right.label) || left.bridgeId.localeCompare(right.bridgeId))
|
||||
this.persist()
|
||||
return this.publicRecord(record)
|
||||
} catch (error) {
|
||||
throw sshError || error
|
||||
}
|
||||
}
|
||||
|
||||
async connectSsh(input = {}) {
|
||||
const sshAddress = normalizeSshAddress(input.address)
|
||||
const probe = await this.probeSsh(sshAddress.address)
|
||||
const bridgeId = bridgeIdFor(`ssh:${sshAddress.address}`)
|
||||
const record = this.normalizeRecord({
|
||||
bridgeId,
|
||||
transport: 'ssh',
|
||||
address: sshAddress.address,
|
||||
label: cleanText(input.label, 120) || probe.serverLabel,
|
||||
serverId: probe.serverId,
|
||||
agents: probe.agents,
|
||||
available: true,
|
||||
lastError: '',
|
||||
checkedAt: new Date().toISOString(),
|
||||
})
|
||||
const index = this.records.findIndex(item => item.bridgeId === bridgeId)
|
||||
if (index >= 0) this.records[index] = record
|
||||
else this.records.push(record)
|
||||
this.records.sort((left, right) => left.label.localeCompare(right.label) || left.bridgeId.localeCompare(right.bridgeId))
|
||||
this.persist()
|
||||
return this.publicRecord(record)
|
||||
}
|
||||
|
||||
async connectSshTunnel(input = {}) {
|
||||
const sshAddress = normalizeSshAddress(input.address)
|
||||
const existing = this.records.find(record => (
|
||||
record.address === sshAddress.address && ['ssh', 'ssh-tunnel'].includes(record.transport)
|
||||
))
|
||||
const bridgeId = existing?.bridgeId || bridgeIdFor(`ssh-tunnel:${sshAddress.address}`)
|
||||
const endpoint = await this.ensureSshTunnel({ bridgeId, address: sshAddress.address })
|
||||
try {
|
||||
const probe = normalizeProbe(await this.request('/.well-known/meldwork-agent-bridge', { address: endpoint }))
|
||||
const record = this.normalizeRecord({
|
||||
bridgeId,
|
||||
transport: 'ssh-tunnel',
|
||||
address: sshAddress.address,
|
||||
endpoint,
|
||||
label: cleanText(input.label, 120) || probe.serverLabel,
|
||||
serverId: probe.serverId,
|
||||
agents: probe.agents,
|
||||
available: true,
|
||||
lastError: '',
|
||||
checkedAt: new Date().toISOString(),
|
||||
})
|
||||
record.available = true
|
||||
const index = this.records.findIndex(item => item.bridgeId === bridgeId)
|
||||
if (index >= 0) this.records[index] = record
|
||||
else this.records.push(record)
|
||||
this.records = this.records.filter(item => (
|
||||
item.bridgeId === bridgeId || item.address !== sshAddress.address
|
||||
))
|
||||
this.records.sort((left, right) => left.label.localeCompare(right.label) || left.bridgeId.localeCompare(right.bridgeId))
|
||||
this.persist()
|
||||
return this.publicRecord(record)
|
||||
} catch (error) {
|
||||
this.stopTunnel(bridgeId)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
for (const current of this.records) {
|
||||
try {
|
||||
let probe
|
||||
if (current.transport === 'ssh-tunnel') {
|
||||
current.endpoint = await this.ensureSshTunnel(current)
|
||||
probe = normalizeProbe(await this.request('/.well-known/meldwork-agent-bridge', {
|
||||
address: current.endpoint,
|
||||
}))
|
||||
current.available = true
|
||||
} else if (current.transport === 'ssh') {
|
||||
try {
|
||||
current.endpoint = await this.ensureSshTunnel(current)
|
||||
probe = normalizeProbe(await this.request('/.well-known/meldwork-agent-bridge', {
|
||||
address: current.endpoint,
|
||||
}))
|
||||
current.transport = 'ssh-tunnel'
|
||||
current.available = true
|
||||
} catch {
|
||||
probe = await this.probeSsh(current.address)
|
||||
}
|
||||
} else {
|
||||
probe = await this.probe(current.address)
|
||||
}
|
||||
Object.assign(current, {
|
||||
serverId: probe.serverId,
|
||||
agents: probe.agents.map(normalizeAgent),
|
||||
available: true,
|
||||
lastError: '', checkedAt: new Date().toISOString(),
|
||||
})
|
||||
} catch (error) {
|
||||
if (current.transport === 'ssh-tunnel') this.stopTunnel(current.bridgeId)
|
||||
current.available = false
|
||||
current.lastError = String(error?.code || 'CLOUD_AGENT_BRIDGE_PROBE_FAILED').slice(0, 120)
|
||||
}
|
||||
}
|
||||
this.persist()
|
||||
return this.list()
|
||||
}
|
||||
|
||||
publicRecord(record) {
|
||||
return clone({
|
||||
bridgeId: record.bridgeId, address: record.address, label: record.label,
|
||||
transport: record.transport,
|
||||
serverId: record.serverId, available: record.available,
|
||||
lastError: record.lastError, checkedAt: record.checkedAt,
|
||||
agents: record.agents.map(agent => ({
|
||||
id: agent.id, sourceKind: agent.sourceKind, label: agent.label, version: agent.version,
|
||||
description: agent.description, domains: agent.domains,
|
||||
available: agent.available,
|
||||
credentialState: agent.credentialState,
|
||||
skills: agent.skills,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
list() {
|
||||
return this.records.map(record => this.publicRecord(record))
|
||||
}
|
||||
|
||||
remove(bridgeId) {
|
||||
const id = String(bridgeId || '')
|
||||
const index = this.records.findIndex(record => record.bridgeId === id)
|
||||
if (index < 0) fail('CLOUD_AGENT_BRIDGE_NOT_FOUND')
|
||||
this.stopTunnel(id)
|
||||
this.records.splice(index, 1)
|
||||
this.persist()
|
||||
return { deleted: true, bridgeId: id }
|
||||
}
|
||||
|
||||
connectorEntries() {
|
||||
return this.records.filter(record => record.available).flatMap(record => record.agents
|
||||
.filter(agent => agent.available !== false)
|
||||
.map(agent => {
|
||||
const manifest = manifestFor(record, agent)
|
||||
return { record: clone(record), agent: clone(agent), manifest, instance: instanceFor(record, agent, manifest) }
|
||||
}))
|
||||
}
|
||||
|
||||
catalogEntries() {
|
||||
return this.records.flatMap(record => record.agents.map(agent => ({
|
||||
kind: instanceIdFor(record.bridgeId, agent.id),
|
||||
sourceKind: agent.sourceKind,
|
||||
label: `${agent.label} @ ${record.label}`,
|
||||
name: `${agent.label} @ ${record.label}`,
|
||||
description: agent.description,
|
||||
version: agent.version,
|
||||
installed: true,
|
||||
installSupported: false,
|
||||
installErrorCode: '',
|
||||
providerCompatible: false,
|
||||
providerMode: 'connector',
|
||||
imageAttachmentLimit: 0,
|
||||
custom: false,
|
||||
connector: true,
|
||||
cloud: true,
|
||||
available: record.available && agent.available !== false,
|
||||
credentialState: agent.credentialState,
|
||||
serverLabel: record.label,
|
||||
})))
|
||||
}
|
||||
|
||||
skillsForInstance(instanceId) {
|
||||
const id = String(instanceId || '')
|
||||
for (const record of this.records) {
|
||||
const agent = record.agents.find(item => instanceIdFor(record.bridgeId, item.id) === id)
|
||||
if (agent) return clone(agent.skills)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async run(input) {
|
||||
const bridgeId = String(input?.bridgeId || '')
|
||||
const agentId = String(input?.agentId || '')
|
||||
const record = this.records.find(item => item.bridgeId === bridgeId && item.available)
|
||||
if (!record || !PUBLIC_ID.test(agentId)) fail('CLOUD_AGENT_BRIDGE_NOT_FOUND')
|
||||
const agent = record.agents.find(item => item.id === agentId)
|
||||
if (!agent) fail('CLOUD_AGENT_BRIDGE_AGENT_NOT_FOUND')
|
||||
if (agent.available === false) fail('CLOUD_AGENT_BRIDGE_AGENT_UNAVAILABLE')
|
||||
if (record.transport === 'ssh') return this.runSsh(record, agent, input)
|
||||
return this.request(`/v1/agents/${encodeURIComponent(agentId)}/runs`, {
|
||||
address: record.transport === 'ssh-tunnel' ? record.endpoint : record.address,
|
||||
method: 'POST',
|
||||
signal: input.signal,
|
||||
timeoutMs: this.runTimeoutMs,
|
||||
onActivity: input.onActivity,
|
||||
body: {
|
||||
prompt: input.prompt,
|
||||
sessionRef: input.sessionRef || null,
|
||||
permissionMode: input.permissionMode,
|
||||
operationId: input.operationId,
|
||||
resume: input.resume || null,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async runSsh(record, agent, input) {
|
||||
if (agent.id !== 'codex' || input.permissionMode !== 'read-only') {
|
||||
fail('CLOUD_AGENT_SSH_PERMISSION_UNSUPPORTED')
|
||||
}
|
||||
const result = await this.sshCommand(record.address, SSH_CODEX_COMMAND, input.prompt, input.signal)
|
||||
const messages = []
|
||||
let sessionRef = ''
|
||||
for (const line of String(result.stdout || '').split('\n')) {
|
||||
try {
|
||||
const event = JSON.parse(line)
|
||||
if (event.type === 'thread.started' && typeof event.thread_id === 'string') sessionRef = event.thread_id
|
||||
if (event.type === 'item.completed' && event.item?.type === 'agent_message'
|
||||
&& typeof event.item.text === 'string') messages.push(event.item.text)
|
||||
} catch { /* SSH transport permits only Codex JSONL output */ }
|
||||
}
|
||||
const text = messages.join('\n').trim()
|
||||
if (!text) fail('CLOUD_AGENT_SSH_RESPONSE_INVALID')
|
||||
return { text, sessionRef: '', outcome: 'completed' }
|
||||
}
|
||||
|
||||
bridgeForInstance(instanceId) {
|
||||
for (const entry of this.connectorEntries()) {
|
||||
if (entry.instance.instanceId === instanceId) return entry
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
close() {
|
||||
for (const bridgeId of this.tunnels.keys()) this.stopTunnel(bridgeId)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BRIDGE_RECIPE_ID,
|
||||
SSH_RECIPE_ID,
|
||||
CloudAgentBridgeStore,
|
||||
loginShellCommand,
|
||||
manifestFor,
|
||||
normalizeAddress,
|
||||
normalizeProbe,
|
||||
}
|
||||
@@ -17,6 +17,7 @@ const {
|
||||
MAX_PACKAGE_BYTES,
|
||||
createAgentConnectorPackage,
|
||||
} = require('./agent-connector-package-store.cjs')
|
||||
const { BRIDGE_RECIPE_ID, SSH_RECIPE_ID } = require('../cloud/cloud-agent-bridge.cjs')
|
||||
|
||||
const LOCAL_DELEGATE_RECIPE_ID = 'external.local-agent.delegate'
|
||||
const MAX_LOCAL_MANIFESTS = 64
|
||||
@@ -48,7 +49,7 @@ const SAMPLE_AGENT_CONNECTOR_MANIFEST = createAgentConnectorManifest({
|
||||
},
|
||||
outboundDestinations: [],
|
||||
credentials: { mode: 'none', slots: [] },
|
||||
license: 'LicenseRef-Meldwork-NC',
|
||||
license: 'Apache-2.0',
|
||||
})
|
||||
const SAMPLE_CREDENTIAL_AGENT_CONNECTOR_MANIFEST = createAgentConnectorManifest({
|
||||
connectorId: 'external.codex-provider-sample',
|
||||
@@ -81,7 +82,7 @@ const SAMPLE_CREDENTIAL_AGENT_CONNECTOR_MANIFEST = createAgentConnectorManifest(
|
||||
mode: 'credential-ref',
|
||||
slots: [{ slotId: 'openai-api-key', type: 'api-key', required: true }],
|
||||
},
|
||||
license: 'LicenseRef-Meldwork-NC',
|
||||
license: 'Apache-2.0',
|
||||
})
|
||||
const APPROVED_AGENT_CONNECTOR_MANIFESTS = Object.freeze([
|
||||
SAMPLE_AGENT_CONNECTOR_MANIFEST,
|
||||
@@ -116,7 +117,7 @@ const SAMPLE_LOCAL_ECHO_AGENT_CONNECTOR_MANIFEST = createAgentConnectorManifest(
|
||||
},
|
||||
outboundDestinations: [],
|
||||
credentials: { mode: 'none', slots: [] },
|
||||
license: 'LicenseRef-Meldwork-NC',
|
||||
license: 'Apache-2.0',
|
||||
})
|
||||
const SAMPLE_LOCAL_ECHO_AGENT_CONNECTOR_PACKAGE = createAgentConnectorPackage({
|
||||
publisher: { id: 'meldwork', name: 'Meldwork' },
|
||||
@@ -137,7 +138,7 @@ function fail(code) {
|
||||
function exactOptions(value) {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
&& Object.keys(value).every(key => [
|
||||
'fetch', 'instanceStore', 'manifestDirectory', 'packageStore', 'runAgent', 'seedSample',
|
||||
'cloudBridges', 'fetch', 'instanceStore', 'manifestDirectory', 'packageStore', 'runAgent', 'seedSample',
|
||||
].includes(key))
|
||||
}
|
||||
|
||||
@@ -240,6 +241,7 @@ class LocalAgentConnectors {
|
||||
this.upstreams = new Map()
|
||||
this.detectedUpstreams = []
|
||||
this.lastDiagnostics = []
|
||||
this.cloudBridges = options.cloudBridges || null
|
||||
}
|
||||
|
||||
createRegistry() {
|
||||
@@ -247,7 +249,7 @@ class LocalAgentConnectors {
|
||||
? this.packageStore.installedPackages().map(item => item.manifest)
|
||||
: []
|
||||
return new AgentConnectorRegistry({
|
||||
approvedRecipeIds: [LOCAL_DELEGATE_RECIPE_ID, ...SDK_RECIPE_IDS],
|
||||
approvedRecipeIds: [LOCAL_DELEGATE_RECIPE_ID, BRIDGE_RECIPE_ID, SSH_RECIPE_ID, ...SDK_RECIPE_IDS],
|
||||
approvedExternalManifestIds: [
|
||||
...APPROVED_AGENT_CONNECTOR_MANIFESTS.map(item => item.manifestId),
|
||||
...installedPackageManifests.map(item => item.manifestId),
|
||||
@@ -262,6 +264,8 @@ class LocalAgentConnectors {
|
||||
[LOCAL_DELEGATE_RECIPE_ID]: input => this.runDelegated(input),
|
||||
[SDK_LOCAL_ECHO_RECIPE_ID]: input => this.runLocalEcho(input),
|
||||
[SDK_HTTP_JSON_RECIPE_ID]: input => this.runHttpJson(input),
|
||||
[BRIDGE_RECIPE_ID]: input => this.runCloudBridge(input),
|
||||
[SSH_RECIPE_ID]: input => this.runCloudBridge(input),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -350,6 +354,29 @@ class LocalAgentConnectors {
|
||||
diagnostics.push({ name: 'instances', code: safeFailureCode(error) })
|
||||
}
|
||||
const manifests = registry.listManifests()
|
||||
for (const entry of this.cloudBridges?.connectorEntries?.() || []) {
|
||||
try {
|
||||
const manifest = registry.registerBuiltin(entry.manifest)
|
||||
const instance = registry.registerInstance({
|
||||
instanceId: entry.instance.instanceId,
|
||||
connectorId: manifest.connectorId,
|
||||
connectorVersion: manifest.connectorVersion,
|
||||
upstreamVersion: entry.instance.upstreamVersion,
|
||||
label: entry.instance.label,
|
||||
credentialRef: null,
|
||||
})
|
||||
upstreams.set(instance.instanceId, Object.freeze({
|
||||
kind: instance.instanceId,
|
||||
label: instance.label,
|
||||
name: instance.label,
|
||||
version: instance.upstreamVersion,
|
||||
compatibilityState: 'compatible',
|
||||
cloud: true,
|
||||
}))
|
||||
} catch (error) {
|
||||
diagnostics.push({ name: entry.instance.instanceId, code: safeFailureCode(error) })
|
||||
}
|
||||
}
|
||||
for (const stored of storedInstances) {
|
||||
const manifest = manifests.find(item => (
|
||||
item.manifestId === stored.manifestId
|
||||
@@ -405,9 +432,10 @@ class LocalAgentConnectors {
|
||||
|
||||
detectAgents() {
|
||||
return this.runtime.detectAgents().map((agent) => {
|
||||
const { instance } = this.registry.resolveInstance(agent.connectorInstanceId)
|
||||
const { instance, manifest } = this.registry.resolveInstance(agent.connectorInstanceId)
|
||||
return Object.freeze({
|
||||
...agent,
|
||||
cloud: [BRIDGE_RECIPE_ID, SSH_RECIPE_ID].includes(manifest.invocation.recipeId),
|
||||
credentialConfigured: Boolean(instance.credentialRef),
|
||||
})
|
||||
}).sort((left, right) => (
|
||||
@@ -563,20 +591,26 @@ class LocalAgentConnectors {
|
||||
catalog() {
|
||||
return this.detectAgents().map((agent) => {
|
||||
const { manifest } = this.registry.resolveInstance(agent.connectorInstanceId)
|
||||
const cloud = [BRIDGE_RECIPE_ID, SSH_RECIPE_ID].includes(manifest.invocation.recipeId)
|
||||
const cloudEntry = cloud ? this.cloudBridges?.bridgeForInstance?.(agent.kind) : null
|
||||
return Object.freeze({
|
||||
kind: agent.kind,
|
||||
sourceKind: cloudEntry?.agent?.sourceKind || '',
|
||||
label: agent.label,
|
||||
name: agent.name,
|
||||
description: manifest.description,
|
||||
version: agent.version,
|
||||
version: cloudEntry?.agent?.version || agent.version,
|
||||
installed: true,
|
||||
installSupported: false,
|
||||
installErrorCode: '',
|
||||
providerCompatible: false,
|
||||
providerMode: 'connector',
|
||||
imageAttachmentLimit: manifest.inputTypes.includes('image') ? 32 : 0,
|
||||
custom: true,
|
||||
custom: !cloud,
|
||||
connector: true,
|
||||
cloud,
|
||||
credentialState: cloudEntry?.agent?.credentialState || 'unknown',
|
||||
serverLabel: cloudEntry?.record?.label || '',
|
||||
connectorId: manifest.connectorId,
|
||||
connectorVersion: manifest.connectorVersion,
|
||||
upstreamVersion: agent.upstreamVersion,
|
||||
@@ -768,6 +802,64 @@ class LocalAgentConnectors {
|
||||
return { outcome: 'failed', failure }
|
||||
}
|
||||
}
|
||||
|
||||
async runCloudBridge(input) {
|
||||
const entry = this.cloudBridges?.bridgeForInstance?.(input.connector.instanceId)
|
||||
if (!entry) fail('CLOUD_AGENT_BRIDGE_NOT_FOUND')
|
||||
const terminal = {
|
||||
eventId: `${input.agentRunId}:terminal`,
|
||||
cursor: `${input.agentRunId}:terminal`,
|
||||
sequence: 1,
|
||||
}
|
||||
try {
|
||||
if (!['ssh', 'ssh-tunnel'].includes(entry.record.transport)) {
|
||||
input.onOutboundPayload({ destination: entry.record.address, transport: 'http' })
|
||||
}
|
||||
const result = await this.cloudBridges.run({
|
||||
bridgeId: entry.record.bridgeId,
|
||||
agentId: entry.agent.id,
|
||||
prompt: input.prompt,
|
||||
sessionRef: input.sessionRef,
|
||||
// Cloud bridge tasks never receive local workspace write authority.
|
||||
permissionMode: 'read-only',
|
||||
operationId: input.operationId,
|
||||
resume: input.resume,
|
||||
signal: input.signal,
|
||||
onActivity: input.onActivity,
|
||||
})
|
||||
if (!result || typeof result !== 'object' || Array.isArray(result)
|
||||
|| typeof result.text !== 'string' || result.text.includes('\u0000')
|
||||
|| (result.sessionRef !== undefined
|
||||
&& (typeof result.sessionRef !== 'string' || result.sessionRef.length > 8192
|
||||
|| /[\u0000-\u001f\u007f]/.test(result.sessionRef)))
|
||||
|| !['completed', 'partial', 'failed', 'cancelled'].includes(result.outcome || 'completed')) {
|
||||
fail('CLOUD_AGENT_BRIDGE_RESPONSE_INVALID')
|
||||
}
|
||||
if (result.outcome === 'failed') {
|
||||
const failure = failureDetails(result.failure || result)
|
||||
input.emit({ ...terminal, type: 'Failed', ...failure })
|
||||
return { outcome: 'failed', failure }
|
||||
}
|
||||
if (result.outcome === 'cancelled') {
|
||||
input.emit({ ...terminal, type: 'Cancelled', reason: 'user' })
|
||||
return { outcome: 'cancelled', sessionRef: result.sessionRef || input.sessionRef || '' }
|
||||
}
|
||||
input.emit({ ...terminal, type: 'Completed', outcome: result.outcome || 'completed' })
|
||||
return {
|
||||
text: result.text,
|
||||
sessionRef: typeof result.sessionRef === 'string' ? result.sessionRef : input.sessionRef || '',
|
||||
outcome: result.outcome || 'completed',
|
||||
}
|
||||
} catch (error) {
|
||||
if (input.signal?.aborted || error?.name === 'AbortError') {
|
||||
input.emit({ ...terminal, type: 'Cancelled', reason: 'user' })
|
||||
return { outcome: 'cancelled', sessionRef: input.sessionRef || '' }
|
||||
}
|
||||
const failure = failureDetails(error)
|
||||
input.emit({ ...terminal, type: 'Failed', ...failure })
|
||||
return { outcome: 'failed', failure }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -53,6 +53,12 @@ const NPM_RELEASES = Object.freeze({
|
||||
version: '2026.7.1-2',
|
||||
integrity: 'sha512-ycF3yPcbjN6bUPeaUx6Mh6vze1hQWoD3CT/wWcmD7a8xaHHHRUaAlaq+lFxMHf1ssEgODVAwjlzYqp2twkYZ7g==',
|
||||
}),
|
||||
pi: Object.freeze({
|
||||
packageName: '@earendil-works/pi-coding-agent',
|
||||
version: '0.84.2',
|
||||
integrity: 'sha512-l4E+B7hgXKWddRo8bC/eSue2aWZjEgJ9xIpf5p0Og+lq8a2TArCwJ0HCoCPCgaBP/tN4zbYH/wOwvx9pJpeLCA==',
|
||||
ignoreScripts: true,
|
||||
}),
|
||||
qwen: Object.freeze({
|
||||
packageName: '@qwen-code/qwen-code',
|
||||
version: '0.21.5',
|
||||
@@ -93,17 +99,37 @@ const NPM_RELEASES = Object.freeze({
|
||||
const ALLOWED_SCRIPT_URLS = new Set(Object.values(HERMES_RECIPES).map(recipe => recipe.url))
|
||||
|
||||
const AGENT_CATALOG = Object.freeze([
|
||||
{
|
||||
kind: 'codex', label: 'Codex', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'responses-required',
|
||||
},
|
||||
{
|
||||
kind: 'claude', label: 'Claude Code', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'anthropic-required',
|
||||
},
|
||||
{
|
||||
kind: 'hermes', label: 'Hermes', recommended: true, providerCompatible: true,
|
||||
providerSupport: 'supported',
|
||||
},
|
||||
{
|
||||
kind: 'workbuddy', label: 'WorkBuddy', recommended: true, providerCompatible: true,
|
||||
providerSupport: 'experimental',
|
||||
},
|
||||
{
|
||||
kind: 'openclaw', label: 'OpenClaw', recommended: true, providerCompatible: true,
|
||||
providerSupport: 'supported',
|
||||
},
|
||||
{
|
||||
kind: 'workbuddy', label: 'WorkBuddy', recommended: true, providerCompatible: true,
|
||||
providerSupport: 'experimental',
|
||||
kind: 'pi', label: 'Pi Agent', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'native-config',
|
||||
},
|
||||
{
|
||||
kind: 'opencode', label: 'OpenCode', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'native-config',
|
||||
},
|
||||
{
|
||||
kind: 'opencodereview', label: 'OpenCodeReview', recommended: false, providerCompatible: true,
|
||||
providerSupport: 'supported',
|
||||
},
|
||||
{
|
||||
kind: 'kimi', label: 'Kimi Code', recommended: false, providerCompatible: false,
|
||||
@@ -113,30 +139,10 @@ const AGENT_CATALOG = Object.freeze([
|
||||
kind: 'mimo', label: 'MiMo Code', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'native-config',
|
||||
},
|
||||
{
|
||||
kind: 'codex', label: 'Codex', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'responses-required',
|
||||
},
|
||||
{
|
||||
kind: 'claude', label: 'Claude Code', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'anthropic-required',
|
||||
},
|
||||
{
|
||||
kind: 'gemini', label: 'Gemini CLI', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'native-config',
|
||||
},
|
||||
{
|
||||
kind: 'opencode', label: 'OpenCode', recommended: false, providerCompatible: false,
|
||||
providerSupport: 'native-config',
|
||||
},
|
||||
{
|
||||
kind: 'qwen', label: 'Qwen Code', recommended: false, providerCompatible: true,
|
||||
providerSupport: 'supported',
|
||||
},
|
||||
{
|
||||
kind: 'opencodereview', label: 'OpenCodeReview', recommended: false, providerCompatible: true,
|
||||
providerSupport: 'supported',
|
||||
},
|
||||
])
|
||||
|
||||
function installRecipe(kind, platform) {
|
||||
|
||||
@@ -60,12 +60,15 @@ function publicCompatibility(agent) {
|
||||
? agent.versionIdentified
|
||||
: Boolean(resolvedVersion)
|
||||
const compatible = compatibilityState === 'compatible'
|
||||
const incompatibilityReason = compatibilityState === 'incompatible'
|
||||
const incompatibilityReason = compatibilityState === 'unknown'
|
||||
&& agent.incompatibilityReason === 'LOCAL_AGENT_CAPABILITY_PROBE_TIMEOUT'
|
||||
? 'LOCAL_AGENT_CAPABILITY_PROBE_TIMEOUT'
|
||||
: compatibilityState === 'incompatible'
|
||||
? (COMPATIBILITY_REASONS.has(agent.incompatibilityReason)
|
||||
? agent.incompatibilityReason
|
||||
: 'LOCAL_AGENT_VERSION_UNSUPPORTED')
|
||||
: ''
|
||||
const incompatibilityProbe = compatibilityState === 'incompatible'
|
||||
const incompatibilityProbe = Boolean(incompatibilityReason)
|
||||
&& /^[a-z0-9-]{1,80}$/.test(String(agent.incompatibilityProbe || ''))
|
||||
? agent.incompatibilityProbe
|
||||
: ''
|
||||
@@ -164,6 +167,9 @@ class AgentInstaller extends EventEmitter {
|
||||
agents: AGENT_CATALOG.map(profile => {
|
||||
const agent = installed.get(profile.kind)
|
||||
const recipe = installRecipe(profile.kind, this.platform)
|
||||
const targetVersion = recipe?.detectedVersion || recipe?.version || ''
|
||||
const currentVersion = String(agent?.version || '')
|
||||
const upToDate = Boolean(agent && targetVersion && currentVersion.includes(targetVersion))
|
||||
let installSupported = Boolean(recipe)
|
||||
let installErrorCode = ''
|
||||
if (!recipe) {
|
||||
@@ -177,6 +183,8 @@ class AgentInstaller extends EventEmitter {
|
||||
...profile,
|
||||
installed: Boolean(agent),
|
||||
version: agent?.version || '',
|
||||
targetVersion,
|
||||
installAction: agent ? (upToDate ? 'current' : 'update') : 'install',
|
||||
...publicCompatibility(agent),
|
||||
installSupported,
|
||||
installErrorCode,
|
||||
@@ -230,7 +238,10 @@ class AgentInstaller extends EventEmitter {
|
||||
this.invalidateDetectionCache()
|
||||
const installed = await abortable(this.detectedAgents(), signal)
|
||||
if (signal.aborted) throw abortError()
|
||||
if (installed.some(agent => agent.kind === profile.kind)) {
|
||||
const current = installed.find(agent => agent.kind === profile.kind)
|
||||
const targetVersion = recipe.detectedVersion || recipe.version
|
||||
if (current && (current.compatibilityState !== 'compatible'
|
||||
|| String(current.version || '').includes(targetVersion))) {
|
||||
throw installerError('INSTALL_AGENT_ALREADY_INSTALLED')
|
||||
}
|
||||
let command = recipe.interpreter || ''
|
||||
@@ -295,7 +306,9 @@ class AgentInstaller extends EventEmitter {
|
||||
throw installerError('INSTALL_AGENT_INTEGRITY_FAILED')
|
||||
}
|
||||
args = [
|
||||
'install', '--global', npmPackageSpec(recipe),
|
||||
'install', '--global',
|
||||
...(recipe.ignoreScripts ? ['--ignore-scripts'] : []),
|
||||
npmPackageSpec(recipe),
|
||||
'--registry', NPM_REGISTRY,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
const { execFile } = require('node:child_process')
|
||||
const { createHash } = require('node:crypto')
|
||||
const fs = require('node:fs')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const { promisify } = require('node:util')
|
||||
const { prepareCommand, searchPath } = require('./cli/cli-adapters.cjs')
|
||||
const { isOpenClawSecretReference } = require('./cli/openclaw-runtime.cjs')
|
||||
const { NETWORK_ENV_KEYS, networkEnvironment } = require('./cli/cli-network-environment.cjs')
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
@@ -28,11 +30,13 @@ const MAX_CREDENTIAL_FILE_BYTES = 2 * 1024 * 1024
|
||||
const MAX_SHELL_ENV_BYTES = 256 * 1024
|
||||
const SHELL_ENV_CACHE_TTL_MS = 30000
|
||||
const SHELL_ENV_MARKER = '__MELDWORK_NATIVE_ENV_V1__'
|
||||
const VERTEX_MODEL_REGION_KEY = /^VERTEX_REGION_[A-Z0-9_]{1,120}$/
|
||||
const CREDENTIAL_ENV_KEYS = Object.freeze({
|
||||
codex: ['OPENAI_API_KEY'],
|
||||
hermes: ['OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'ANTHROPIC_API_KEY'],
|
||||
openclaw: ['OPENAI_API_KEY', 'OPENROUTER_API_KEY'],
|
||||
workbuddy: ['CODEBUDDY_API_KEY', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY'],
|
||||
pi: ['PI_API_KEY', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'OPENROUTER_API_KEY', 'GEMINI_API_KEY'],
|
||||
kimi: ['MOONSHOT_API_KEY', 'KIMI_API_KEY', 'KIMI_MODEL_API_KEY', 'OPENAI_API_KEY'],
|
||||
mimo: ['MIMO_API_KEY'],
|
||||
claude: ['ANTHROPIC_API_KEY'],
|
||||
@@ -41,8 +45,13 @@ const CREDENTIAL_ENV_KEYS = Object.freeze({
|
||||
opencode: ['OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'OPENROUTER_API_KEY'],
|
||||
opencodereview: ['OCR_LLM_TOKEN', 'OPENAI_API_KEY'],
|
||||
})
|
||||
const GOOGLE_CLOUD_ENV_KEYS = [
|
||||
'GOOGLE_APPLICATION_CREDENTIALS', 'GOOGLE_CLOUD_PROJECT', 'GCLOUD_PROJECT',
|
||||
'GOOGLE_CLOUD_LOCATION', 'GOOGLE_CLOUD_QUOTA_PROJECT', 'CLOUDSDK_CONFIG',
|
||||
]
|
||||
const NATIVE_CONFIG_ROOT_KEYS = new Set(['CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'PI_CODING_AGENT_DIR'])
|
||||
const RUNTIME_ENV_KEYS = Object.freeze({
|
||||
codex: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL'],
|
||||
codex: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL', 'CODEX_HOME'],
|
||||
hermes: [
|
||||
'OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'ANTHROPIC_API_KEY',
|
||||
'OPENAI_BASE_URL', 'OPENAI_MODEL', 'HERMES_INFERENCE_PROVIDER', 'HERMES_INFERENCE_MODEL',
|
||||
@@ -52,15 +61,36 @@ const RUNTIME_ENV_KEYS = Object.freeze({
|
||||
'CODEBUDDY_API_KEY', 'CODEBUDDY_BASE_URL', 'CODEBUDDY_MODEL',
|
||||
'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL', 'ANTHROPIC_API_KEY',
|
||||
],
|
||||
pi: [
|
||||
'PI_API_KEY', 'PI_BASE_URL', 'PI_MODEL',
|
||||
'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL', 'ANTHROPIC_API_KEY',
|
||||
'OPENROUTER_API_KEY', 'GEMINI_API_KEY', 'PI_CODING_AGENT_DIR',
|
||||
],
|
||||
kimi: [
|
||||
'MOONSHOT_API_KEY', 'KIMI_API_KEY', 'KIMI_MODEL_API_KEY',
|
||||
'KIMI_MODEL_BASE_URL', 'KIMI_MODEL_NAME',
|
||||
'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL',
|
||||
],
|
||||
mimo: ['MIMO_API_KEY', 'MIMO_BASE_URL', 'MIMO_MODEL'],
|
||||
claude: ['ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL'],
|
||||
claude: [
|
||||
'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN',
|
||||
'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL', 'CLAUDE_CONFIG_DIR',
|
||||
'ANTHROPIC_DEFAULT_OPUS_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL',
|
||||
'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY', 'CLAUDE_CODE_USE_MANTLE',
|
||||
'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', 'AWS_BEARER_TOKEN_BEDROCK',
|
||||
'AWS_PROFILE', 'AWS_REGION', 'AWS_DEFAULT_REGION', 'AWS_CONFIG_FILE', 'AWS_SHARED_CREDENTIALS_FILE',
|
||||
'AWS_ROLE_ARN', 'AWS_ROLE_SESSION_NAME', 'AWS_WEB_IDENTITY_TOKEN_FILE',
|
||||
'ANTHROPIC_BEDROCK_BASE_URL', 'ANTHROPIC_BEDROCK_MANTLE_BASE_URL', 'ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION',
|
||||
...GOOGLE_CLOUD_ENV_KEYS,
|
||||
'CLOUD_ML_REGION', 'ANTHROPIC_VERTEX_PROJECT_ID', 'ANTHROPIC_VERTEX_BASE_URL',
|
||||
'ANTHROPIC_FOUNDRY_RESOURCE', 'ANTHROPIC_FOUNDRY_BASE_URL',
|
||||
'ANTHROPIC_FOUNDRY_API_KEY', 'ANTHROPIC_FOUNDRY_AUTH_TOKEN',
|
||||
'AZURE_CLIENT_ID', 'AZURE_TENANT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_AUTHORITY_HOST',
|
||||
'AZURE_CLIENT_CERTIFICATE_PATH', 'AZURE_CLIENT_CERTIFICATE_PASSWORD', 'AZURE_FEDERATED_TOKEN_FILE',
|
||||
'AZURE_CONFIG_DIR',
|
||||
],
|
||||
qwen: ['DASHSCOPE_API_KEY', 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL'],
|
||||
gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GEMINI_MODEL'],
|
||||
gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GEMINI_MODEL', ...GOOGLE_CLOUD_ENV_KEYS],
|
||||
opencode: [
|
||||
'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'OPENROUTER_API_KEY',
|
||||
'OPENAI_BASE_URL', 'OPENAI_MODEL',
|
||||
@@ -72,6 +102,7 @@ const RUNTIME_ENV_KEYS = Object.freeze({
|
||||
})
|
||||
const SHELL_ENV_KEYS = Object.freeze([...new Set([
|
||||
'PATH',
|
||||
...NETWORK_ENV_KEYS,
|
||||
...Object.values(RUNTIME_ENV_KEYS).flat(),
|
||||
])])
|
||||
let shellEnvironmentCache = null
|
||||
@@ -89,6 +120,8 @@ function readCredentialFile(filename) {
|
||||
function containsCredential(value) {
|
||||
if (!value || typeof value !== 'object') return false
|
||||
if (Array.isArray(value)) return value.some(containsCredential)
|
||||
if (value.type === 'api_key' && credentialLiteral(value.key)) return true
|
||||
if (value.type === 'oauth' && (credentialLiteral(value.access) || credentialLiteral(value.refresh))) return true
|
||||
return Object.entries(value).some(([key, child]) => {
|
||||
if (CREDENTIAL_FIELD.test(key) && credentialLiteral(child)) return true
|
||||
return child && typeof child === 'object' && containsCredential(child)
|
||||
@@ -126,10 +159,13 @@ function textContainsCredential(filename) {
|
||||
}
|
||||
}
|
||||
|
||||
function nativeCredentialEnvironment(kind, env = process.env) {
|
||||
function nativeCredentialEnvironment(kind, env = process.env, options = {}) {
|
||||
const result = {}
|
||||
for (const key of RUNTIME_ENV_KEYS[kind] || []) {
|
||||
if (typeof env[key] === 'string' && env[key].trim()) result[key] = env[key]
|
||||
const keys = [...(RUNTIME_ENV_KEYS[kind] || []), ...(kind === 'claude'
|
||||
? Object.keys(env).filter(key => VERTEX_MODEL_REGION_KEY.test(key)) : [])]
|
||||
for (const key of keys) {
|
||||
if (options.providerConfigured && !NATIVE_CONFIG_ROOT_KEYS.has(key)) continue
|
||||
if (typeof env[key] === 'string') result[key] = env[key]
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -142,23 +178,41 @@ function nativeCredentialKeyEnvironment(kind, env = process.env) {
|
||||
return result
|
||||
}
|
||||
|
||||
function allowedShellEnvironment(env = process.env) {
|
||||
function allowedShellEnvironment(env = process.env, platform = process.platform) {
|
||||
const source = { ...env, ...networkEnvironment(env, platform) }
|
||||
const result = {}
|
||||
for (const key of SHELL_ENV_KEYS) {
|
||||
const value = env[key]
|
||||
if (typeof value !== 'string' || !value || value.length > MAX_SHELL_ENV_BYTES) continue
|
||||
for (const key of [...SHELL_ENV_KEYS, ...Object.keys(source).filter(key => VERTEX_MODEL_REGION_KEY.test(key))]) {
|
||||
const value = source[key]
|
||||
if (typeof value !== 'string' || value.length > MAX_SHELL_ENV_BYTES) continue
|
||||
result[key] = value
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function nativeShellCommand() {
|
||||
function nativeShellCommand(shellName) {
|
||||
const keys = SHELL_ENV_KEYS.join(' ')
|
||||
// Enumerate names only; do not dump unrelated values or depend on Electron RunAsNode.
|
||||
const regionNames = shellName === 'zsh'
|
||||
? 'builtin print -rl -- ${(k)parameters[(I)VERTEX_REGION_*]}'
|
||||
: [
|
||||
'if [ -n "${BASH_VERSION-}" ]; then',
|
||||
' builtin compgen -e VERTEX_REGION_',
|
||||
'elif [ -x /bin/bash ]; then',
|
||||
" BASH_ENV= ENV= /bin/bash --noprofile --norc -c 'builtin compgen -e VERTEX_REGION_'",
|
||||
'fi',
|
||||
].join('\n')
|
||||
return [
|
||||
`printf '${SHELL_ENV_MARKER}\\0'`,
|
||||
`for __meldwork_key in ${keys}; do`,
|
||||
`for __meldwork_key in ${keys} $(${regionNames}); do`,
|
||||
' case "$__meldwork_key" in ""|*[!A-Za-z0-9_]*) continue ;; esac',
|
||||
' case "$__meldwork_key" in VERTEX_REGION_*)',
|
||||
' __meldwork_model=${__meldwork_key#VERTEX_REGION_}',
|
||||
' case "$__meldwork_model" in ""|*[!A-Z0-9_]*) continue ;; esac',
|
||||
' [ ${#__meldwork_model} -le 120 ] || continue ;;',
|
||||
' esac',
|
||||
' eval "__meldwork_value=\\${$__meldwork_key-}"',
|
||||
' if [ -n "$__meldwork_value" ]; then',
|
||||
' eval "__meldwork_set=\\${$__meldwork_key+x}"',
|
||||
' if [ -n "$__meldwork_set" ]; then',
|
||||
" printf '%s=%s\\0' \"$__meldwork_key\" \"$__meldwork_value\"",
|
||||
' fi',
|
||||
'done',
|
||||
@@ -177,7 +231,8 @@ function parseNativeShellEnvironment(output) {
|
||||
if (separator <= 0) continue
|
||||
const key = entry.slice(0, separator)
|
||||
const value = entry.slice(separator + 1)
|
||||
if (!allowed.has(key) || !value || value.length > MAX_SHELL_ENV_BYTES) continue
|
||||
if ((!allowed.has(key) && !VERTEX_MODEL_REGION_KEY.test(key))
|
||||
|| value.length > MAX_SHELL_ENV_BYTES) continue
|
||||
result[key] = value
|
||||
}
|
||||
return result
|
||||
@@ -187,7 +242,7 @@ async function queryNativeShellEnvironment(options = {}) {
|
||||
const source = options.env || process.env
|
||||
const platform = options.platform || process.platform
|
||||
const home = options.home || os.homedir()
|
||||
const fallback = allowedShellEnvironment(source)
|
||||
const fallback = allowedShellEnvironment(source, platform)
|
||||
if (platform === 'win32') return { env: fallback, source: 'process' }
|
||||
const shell = String(options.shell || source.SHELL || (platform === 'darwin' ? '/bin/zsh' : '/bin/sh'))
|
||||
const shellName = path.basename(shell)
|
||||
@@ -202,7 +257,7 @@ async function queryNativeShellEnvironment(options = {}) {
|
||||
try {
|
||||
const result = await execFileFn(
|
||||
shell,
|
||||
[shellName === 'sh' ? '-lc' : '-lic', nativeShellCommand()],
|
||||
[shellName === 'sh' ? '-lc' : '-lic', nativeShellCommand(shellName)],
|
||||
{
|
||||
timeout: 5000,
|
||||
maxBuffer: MAX_SHELL_ENV_BYTES,
|
||||
@@ -227,9 +282,12 @@ function resolveNativeShellEnvironment(options = {}) {
|
||||
const platform = options.platform || process.platform
|
||||
const home = options.home || os.homedir()
|
||||
const shell = String(options.shell || source.SHELL || '')
|
||||
const key = [platform, home, shell, String(source.PATH || '')].join('\u0000')
|
||||
const environmentHash = createHash('sha256')
|
||||
.update(JSON.stringify(allowedShellEnvironment(source, platform))).digest('hex')
|
||||
const key = [platform, home, shell, environmentHash].join('\u0000')
|
||||
const now = Date.now()
|
||||
if (shellEnvironmentCache?.key === key && shellEnvironmentCache.expiresAt > now) {
|
||||
if (options.refresh !== true && shellEnvironmentCache?.key === key
|
||||
&& shellEnvironmentCache.expiresAt > now) {
|
||||
return shellEnvironmentCache.promise
|
||||
}
|
||||
const promise = queryNativeShellEnvironment(options)
|
||||
@@ -240,6 +298,9 @@ function resolveNativeShellEnvironment(options = {}) {
|
||||
function nativeCredentialState(kind, options = {}) {
|
||||
const home = options.home || os.homedir()
|
||||
const env = options.env || process.env
|
||||
const codexHome = env.CODEX_HOME || path.join(home, '.codex')
|
||||
const claudeHome = env.CLAUDE_CONFIG_DIR || path.join(home, '.claude')
|
||||
const piHome = env.PI_CODING_AGENT_DIR || path.join(home, '.pi', 'agent')
|
||||
if (Object.keys(nativeCredentialKeyEnvironment(kind, env)).length) {
|
||||
return {
|
||||
state: 'ready',
|
||||
@@ -248,22 +309,30 @@ function nativeCredentialState(kind, options = {}) {
|
||||
}
|
||||
|
||||
const jsonFiles = {
|
||||
codex: [path.join(home, '.codex', 'auth.json'), path.join(home, '.codex', 'config.json')],
|
||||
codex: [path.join(codexHome, 'auth.json'), path.join(codexHome, 'config.json')],
|
||||
hermes: [path.join(home, '.hermes', 'auth.json'), path.join(home, '.hermes', 'config.json')],
|
||||
openclaw: [path.join(home, '.openclaw', 'openclaw.json')],
|
||||
workbuddy: [path.join(home, '.workbuddy', 'models.json')],
|
||||
pi: [
|
||||
path.join(piHome, 'auth.json'),
|
||||
path.join(piHome, 'models.json'),
|
||||
path.join(home, '.pi', 'auth.json'),
|
||||
path.join(home, '.pi', 'config.json'),
|
||||
path.join(home, '.pi-agent', 'auth.json'),
|
||||
path.join(home, '.pi-agent', 'config.json'),
|
||||
],
|
||||
kimi: [path.join(home, '.kimi-code', 'credentials', 'kimi-code.json')],
|
||||
claude: [
|
||||
path.join(home, '.claude', '.credentials.json'),
|
||||
path.join(home, '.claude', 'settings.json'),
|
||||
path.join(home, '.claude', 'settings.local.json'),
|
||||
path.join(claudeHome, '.credentials.json'),
|
||||
path.join(claudeHome, 'settings.json'),
|
||||
path.join(claudeHome, 'settings.local.json'),
|
||||
],
|
||||
qwen: [path.join(home, '.qwen', 'oauth_creds.json'), path.join(home, '.qwen', 'settings.json')],
|
||||
gemini: [
|
||||
path.join(home, '.gemini', 'oauth_creds.json'),
|
||||
path.join(home, '.gemini', 'settings.json'),
|
||||
],
|
||||
opencode: [path.join(home, '.local', 'share', 'opencode', 'auth.json')],
|
||||
opencode: [path.join(env.XDG_DATA_HOME || path.join(home, '.local', 'share'), 'opencode', 'auth.json')],
|
||||
opencodereview: [path.join(home, '.opencodereview', 'config.json')],
|
||||
}[kind] || []
|
||||
if (jsonFiles.some(jsonContainsCredential)) {
|
||||
@@ -271,7 +340,7 @@ function nativeCredentialState(kind, options = {}) {
|
||||
}
|
||||
|
||||
const textFiles = {
|
||||
codex: [path.join(home, '.codex', '.env'), path.join(home, '.codex', 'config.toml')],
|
||||
codex: [path.join(codexHome, '.env'), path.join(codexHome, 'config.toml')],
|
||||
hermes: [
|
||||
path.join(home, '.hermes', '.env'),
|
||||
path.join(home, '.hermes', 'config.yaml'),
|
||||
@@ -279,13 +348,19 @@ function nativeCredentialState(kind, options = {}) {
|
||||
],
|
||||
openclaw: [path.join(home, '.openclaw', '.env')],
|
||||
workbuddy: [path.join(home, '.workbuddy', '.env')],
|
||||
pi: [
|
||||
path.join(home, '.pi', '.env'),
|
||||
path.join(home, '.pi', 'config.toml'),
|
||||
path.join(home, '.pi-agent', '.env'),
|
||||
path.join(home, '.pi-agent', 'config.toml'),
|
||||
],
|
||||
kimi: [
|
||||
path.join(home, '.kimi', 'config.toml'),
|
||||
path.join(home, '.kimi-code', 'config.toml'),
|
||||
path.join(home, '.kimi-code', '.env'),
|
||||
],
|
||||
mimo: [path.join(home, '.mimo', '.env'), path.join(home, '.mimocode', '.env')],
|
||||
claude: [path.join(home, '.claude', '.env')],
|
||||
claude: [path.join(claudeHome, '.env')],
|
||||
qwen: [path.join(home, '.qwen', '.env')],
|
||||
gemini: [path.join(home, '.gemini', '.env')],
|
||||
opencode: [
|
||||
@@ -305,13 +380,14 @@ function probeEnvironment(kind, options = {}) {
|
||||
const source = options.env || process.env
|
||||
const platform = options.platform || process.platform
|
||||
const home = options.home || os.homedir()
|
||||
const env = {}
|
||||
const env = networkEnvironment(source, platform)
|
||||
for (const key of [
|
||||
'USER', 'LOGNAME', 'TMPDIR', 'TMP', 'TEMP',
|
||||
'LANG', 'LANGUAGE', 'LC_ALL', 'LC_CTYPE',
|
||||
'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'USERNAME',
|
||||
'SYSTEMROOT', 'WINDIR', 'COMSPEC', 'PATHEXT',
|
||||
'APPDATA', 'LOCALAPPDATA',
|
||||
'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME',
|
||||
]) {
|
||||
if (typeof source[key] === 'string' && source[key]) env[key] = source[key]
|
||||
}
|
||||
@@ -325,6 +401,13 @@ function probeEnvironment(kind, options = {}) {
|
||||
function claudeAuthState(output) {
|
||||
try {
|
||||
const status = JSON.parse(String(output || '').trim())
|
||||
// Cloud status recognizes a provider selection without checking SDK credentials.
|
||||
if (status?.loggedIn === true && status.authMethod === 'third_party') {
|
||||
return { state: 'unknown', source: 'unverified' }
|
||||
}
|
||||
if (status?.loggedIn === true && status.authMethod === 'api_key') {
|
||||
return { state: 'ready', source: 'native-credential' }
|
||||
}
|
||||
if (status?.loggedIn === true) return { state: 'ready', source: 'native-auth-status' }
|
||||
if (status?.loggedIn === false) return { state: 'missing', source: 'native-auth-status' }
|
||||
} catch { /* keep the file-based result */ }
|
||||
@@ -649,8 +732,7 @@ async function resolveNativeCredentialState(kind, options = {}) {
|
||||
? status.credentialState
|
||||
: { state: 'unknown', source: 'native-runtime-unavailable' }
|
||||
}
|
||||
if (kind !== 'claude' || !options.executable
|
||||
|| Object.keys(nativeCredentialKeyEnvironment(kind, options.env)).length) return current
|
||||
if (kind !== 'claude' || !options.executable) return current
|
||||
|
||||
const platform = options.platform || process.platform
|
||||
const prepareCommandFn = options.prepareCommandFn || prepareCommand
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const crypto = require('node:crypto')
|
||||
const { parseTaskDecision } = require('./task-decision.cjs')
|
||||
|
||||
const { normalizeContentBlobRef } = require('../attachments/content-blob-store.cjs')
|
||||
const { canonicalJson } = require('./context-pack-records.cjs')
|
||||
@@ -9,7 +10,7 @@ const V4_TEMPLATES = new Set(['concurrent-batch', 'discussion'])
|
||||
const V4_WORKFLOWS = new Set(['manual', 'auto', 'concurrent-batch', 'discussion'])
|
||||
const V4_PHASES = new Set([
|
||||
'prepare', 'dispatch', 'running', 'reconcile',
|
||||
'proposal', 'challenge', 'coordination', 'work', 'synthesis', 'verification',
|
||||
'proposal', 'discussion', 'challenge', 'coordination', 'work', 'synthesis', 'verification',
|
||||
'commit', 'committed', 'completed', 'failed', 'stopped', 'human-gate',
|
||||
])
|
||||
const V4_SLOT_STATUSES = new Set([
|
||||
@@ -60,7 +61,7 @@ const MESSAGE_ID = /^message-[a-f0-9]{64}$/u
|
||||
const EVIDENCE_ID = /^evidence-[a-f0-9]{64}$/u
|
||||
|
||||
const ORCHESTRATION_FIELDS = new Set([
|
||||
'version', 'workflow', 'template', 'phase', 'batchId', 'round',
|
||||
'version', 'workflow', 'template', 'phase', 'discussionStyle', 'discussionWriterKind', 'batchId', 'round',
|
||||
'currentKind', 'currentKinds', 'pendingKinds', 'activeKinds',
|
||||
'successfulKinds', 'agreementKinds', 'attachmentRecipients',
|
||||
'totalSuccesses', 'terminalFailureOccurred', 'collaboration', 'taskGraph',
|
||||
@@ -347,13 +348,13 @@ function createCoordinationPlan(input = {}) {
|
||||
}
|
||||
const finalizerKind = cleanId(input.finalizerKind)
|
||||
const verifierKinds = uniqueIds(
|
||||
input.verifierKinds || [], Math.min(2, MAX_V4_SLOTS), true,
|
||||
input.verifierKinds || [], MAX_V4_SLOTS, true,
|
||||
).sort()
|
||||
const agreedBy = uniqueIds(input.agreedBy || [], MAX_V4_SLOTS, true).sort()
|
||||
const supportReceiptIds = input.supportReceiptIds == null
|
||||
? null
|
||||
: uniqueIds(input.supportReceiptIds, MAX_V4_SLOTS, true).sort()
|
||||
const requiredVerifierCount = Math.min(2, targetKinds.length - 1)
|
||||
const requiredVerifierCount = targetKinds.length - 1
|
||||
if (!finalizerKind || !targetKinds.includes(finalizerKind)
|
||||
|| verifierKinds.length !== requiredVerifierCount
|
||||
|| verifierKinds.some(kind => !targetKinds.includes(kind) || kind === finalizerKind)
|
||||
@@ -829,7 +830,7 @@ function normalizeDeliveryState(input, targetKinds, index) {
|
||||
if (!isRecord(input) || !exactFields(input, [
|
||||
'recipientKind', 'sessionRefHash', 'sessionProvenanceHash',
|
||||
'sourceAgentKind', 'sourcePhase', 'watermark', 'snapshotHash', 'operationId',
|
||||
'packageHash', 'deliveryId', 'status', 'updatedAt',
|
||||
'packageHash', 'deliveryId', 'status', 'updatedAt', 'sourceMessages',
|
||||
])) fail('ORCHESTRATION_V4_DELIVERY_STATE_INVALID')
|
||||
const recipientKind = cleanId(input.recipientKind)
|
||||
const sourceAgentKind = cleanId(input.sourceAgentKind)
|
||||
@@ -841,6 +842,20 @@ function normalizeDeliveryState(input, targetKinds, index) {
|
||||
const packageHash = String(input.packageHash || '')
|
||||
const deliveryId = cleanId(input.deliveryId)
|
||||
const status = String(input.status || '')
|
||||
let sourceMessages
|
||||
if (hasOwn(input, 'sourceMessages')) {
|
||||
if (!Array.isArray(input.sourceMessages) || !input.sourceMessages.length
|
||||
|| input.sourceMessages.length > 100) fail('ORCHESTRATION_V4_DELIVERY_STATE_INVALID')
|
||||
sourceMessages = input.sourceMessages.map(message => {
|
||||
if (!isRecord(message) || !exactFields(message, ['id', 'hash'])
|
||||
|| !cleanId(message.id) || cleanId(message.id) !== message.id
|
||||
|| typeof message.hash !== 'string' || !SHA256.test(message.hash)) fail('ORCHESTRATION_V4_DELIVERY_STATE_INVALID')
|
||||
return { id: message.id, hash: message.hash }
|
||||
})
|
||||
if (new Set(sourceMessages.map(message => message.id)).size !== sourceMessages.length) {
|
||||
fail('ORCHESTRATION_V4_DELIVERY_STATE_INVALID')
|
||||
}
|
||||
}
|
||||
if (!recipientKind || !sourceAgentKind || !targetKinds.includes(recipientKind)
|
||||
|| !targetKinds.includes(sourceAgentKind) || !V4_PHASES.has(sourcePhase)
|
||||
|| !Number.isSafeInteger(input.watermark) || input.watermark < 0
|
||||
@@ -861,6 +876,7 @@ function normalizeDeliveryState(input, targetKinds, index) {
|
||||
packageHash,
|
||||
deliveryId,
|
||||
status,
|
||||
...(sourceMessages ? { sourceMessages } : {}),
|
||||
updatedAt: safeTimestamp(input.updatedAt, index),
|
||||
}
|
||||
}
|
||||
@@ -1601,10 +1617,18 @@ function validateV4Relations(orchestration, targetKinds) {
|
||||
|| orchestration.synthesisBinding?.writerKind
|
||||
|| orchestration.coordinationPlan?.finalizerKind
|
||||
|| orchestration.commitState.writerKind
|
||||
|| orchestration.discussionWriterKind
|
||||
if (writableSlots.length > 1 || writableSlots.some(slot => (
|
||||
slot.agentKind !== effectiveWriterKind
|
||||
|| !['synthesis', 'human-gate'].includes(orchestration.phase)
|
||||
|| !['discussion', 'synthesis', 'human-gate'].includes(orchestration.phase)
|
||||
|| (orchestration.phase === 'discussion' && !orchestration.discussionWriterKind)
|
||||
))) fail('ORCHESTRATION_V4_PERMISSION_INVALID')
|
||||
for (const assignment of orchestration.phase === 'discussion' ? orchestration.plan.assignments : []) {
|
||||
const slot = orchestration.slots.find(item => item.slotId === assignment.slotId)
|
||||
if (slot && assignment.readOnly !== (slot.permission !== 'workspace-write')) {
|
||||
fail('ORCHESTRATION_V4_PERMISSION_INVALID')
|
||||
}
|
||||
}
|
||||
}
|
||||
const watermarkKeys = orchestration.deliveryWatermarks.map(item => `${item.agentKind}\u0000${item.phase}`)
|
||||
if (new Set(watermarkKeys).size !== watermarkKeys.length) {
|
||||
@@ -1784,6 +1808,14 @@ function parseOrchestrationV4(input, options = {}) {
|
||||
}
|
||||
const { workflow, template } = normalizeWorkflow(input.workflow, input.template)
|
||||
const phase = phaseForTemplate(template, String(input.phase || ''))
|
||||
const discussionStyle = hasOwn(input, 'discussionStyle')
|
||||
? String(input.discussionStyle || '')
|
||||
: ''
|
||||
if (discussionStyle && (
|
||||
workflow !== 'auto'
|
||||
|| template !== 'discussion'
|
||||
|| !['sequential', 'agent-led'].includes(discussionStyle)
|
||||
)) fail('ORCHESTRATION_V4_SCHEMA_INVALID')
|
||||
const batchId = cleanId(input.batchId)
|
||||
const snapshotHash = String(input.snapshotHash || '')
|
||||
if (!batchId || !SHA256.test(snapshotHash)) fail('ORCHESTRATION_V4_SCHEMA_INVALID')
|
||||
@@ -1831,6 +1863,15 @@ function parseOrchestrationV4(input, options = {}) {
|
||||
const planKinds = plan.assignments.map(assignment => assignment.agentKind)
|
||||
const effectiveKinds = targetKinds || [...new Set([...inferredKinds, ...planKinds])]
|
||||
if (currentKinds.some(kind => !effectiveKinds.includes(kind))) fail('ORCHESTRATION_V4_REFERENCE_INVALID')
|
||||
const activeKinds = hasOwn(input, 'activeKinds')
|
||||
? uniqueIds(input.activeKinds, MAX_V4_SLOTS)
|
||||
: effectiveKinds
|
||||
if (activeKinds.some(kind => !effectiveKinds.includes(kind))) {
|
||||
fail('ORCHESTRATION_V4_REFERENCE_INVALID')
|
||||
}
|
||||
const participantKinds = workflow === 'auto' && template === 'discussion'
|
||||
? activeKinds
|
||||
: effectiveKinds
|
||||
if (!Array.isArray(input.slots) || input.slots.length > MAX_V4_SLOTS) {
|
||||
fail('ORCHESTRATION_V4_SLOT_INVALID')
|
||||
}
|
||||
@@ -1865,26 +1906,35 @@ function parseOrchestrationV4(input, options = {}) {
|
||||
fail('ORCHESTRATION_V4_DELIVERY_STATE_INVALID')
|
||||
}
|
||||
const challengeBindings = hasOwn(input, 'challengeBindings')
|
||||
? normalizeChallengeBindings(input.challengeBindings, effectiveKinds, input.round)
|
||||
? normalizeChallengeBindings(input.challengeBindings, participantKinds, input.round)
|
||||
: null
|
||||
if (challengeBindings && (workflow !== 'auto' || template !== 'discussion')) {
|
||||
fail('ORCHESTRATION_V4_CHALLENGE_BINDING_INVALID')
|
||||
}
|
||||
const synthesisBinding = hasOwn(input, 'synthesisBinding')
|
||||
? normalizeSynthesisBinding(input.synthesisBinding, effectiveKinds, snapshot?.bodyHash)
|
||||
? normalizeSynthesisBinding(input.synthesisBinding, participantKinds, snapshot?.bodyHash)
|
||||
: null
|
||||
if (synthesisBinding && (workflow !== 'auto' || template !== 'discussion')) {
|
||||
fail('ORCHESTRATION_V4_SYNTHESIS_BINDING_INVALID')
|
||||
}
|
||||
const coordinationPlan = hasOwn(input, 'coordinationPlan')
|
||||
? normalizeCoordinationPlan(input.coordinationPlan, effectiveKinds, snapshotHash)
|
||||
? normalizeCoordinationPlan(input.coordinationPlan, participantKinds, snapshotHash)
|
||||
: null
|
||||
if (coordinationPlan && (workflow !== 'auto' || template !== 'discussion')) {
|
||||
fail('ORCHESTRATION_V4_COORDINATION_PLAN_INVALID')
|
||||
}
|
||||
const discussionWriterKind = hasOwn(input, 'discussionWriterKind') ? cleanId(input.discussionWriterKind) : ''
|
||||
if (hasOwn(input, 'discussionWriterKind') && (!discussionWriterKind
|
||||
|| input.discussionWriterKind !== discussionWriterKind
|
||||
|| !effectiveKinds.includes(discussionWriterKind)
|
||||
|| workflow !== 'auto' || template !== 'discussion'
|
||||
|| !['proposal', 'discussion', 'stopped', 'failed'].includes(phase)
|
||||
|| synthesisBinding || coordinationPlan || commitState.writerKind)) {
|
||||
fail('ORCHESTRATION_V4_PERMISSION_INVALID')
|
||||
}
|
||||
if (coordinationPlan) {
|
||||
validateCoordinationAgreement(
|
||||
coordinationPlan, slots, challengeBindings, effectiveKinds, snapshotHash,
|
||||
coordinationPlan, slots, challengeBindings, participantKinds, snapshotHash,
|
||||
)
|
||||
}
|
||||
const workReceipts = hasOwn(input, 'workReceipts')
|
||||
@@ -1901,7 +1951,7 @@ function parseOrchestrationV4(input, options = {}) {
|
||||
}
|
||||
const synthesisRecovery = hasOwn(input, 'synthesisRecovery')
|
||||
? normalizeSynthesisRecovery(
|
||||
input.synthesisRecovery, effectiveKinds, synthesisBinding, coordinationPlan, input.round,
|
||||
input.synthesisRecovery, participantKinds, synthesisBinding, coordinationPlan, input.round,
|
||||
)
|
||||
: null
|
||||
if (synthesisRecovery && (workflow !== 'auto' || template !== 'discussion')) {
|
||||
@@ -1915,7 +1965,7 @@ function parseOrchestrationV4(input, options = {}) {
|
||||
fail('ORCHESTRATION_V4_CONVERGENCE_INVALID')
|
||||
}
|
||||
const hasCompletedChallengeEvidence = completedChallengeEvidence(
|
||||
slots, effectiveKinds, snapshotHash, challengeBindings,
|
||||
slots, participantKinds, snapshotHash, challengeBindings,
|
||||
)
|
||||
const synthesisObservable = workflow === 'auto' && template === 'discussion'
|
||||
&& (synthesisStateObservable(phase, slots)
|
||||
@@ -1924,10 +1974,12 @@ function parseOrchestrationV4(input, options = {}) {
|
||||
const completedChallengeCheckpoint = phase === 'challenge'
|
||||
&& currentKinds.length === 0
|
||||
&& (!Array.isArray(input.pendingKinds) || input.pendingKinds.length === 0)
|
||||
&& slots.every(slot => slot.status === 'completed')
|
||||
&& participantKinds.every(kind => slots.some(slot => (
|
||||
slot.agentKind === kind && slot.status === 'completed'
|
||||
)))
|
||||
const retainedChallengeBinding = phase === 'challenge'
|
||||
&& completedChallengeEvidence(
|
||||
slots, effectiveKinds, snapshotHash, challengeBindings, deliveryWatermarks, true,
|
||||
slots, participantKinds, snapshotHash, challengeBindings, deliveryWatermarks, true,
|
||||
)
|
||||
&& postChallengeReceiptObservable(slots, deliveryWatermarks, snapshotHash)
|
||||
if (synthesisBinding && (
|
||||
@@ -2006,8 +2058,11 @@ function parseOrchestrationV4(input, options = {}) {
|
||||
workflow,
|
||||
template,
|
||||
phase,
|
||||
...(discussionStyle ? { discussionStyle } : {}),
|
||||
...(discussionWriterKind ? { discussionWriterKind } : {}),
|
||||
batchId,
|
||||
currentKinds,
|
||||
activeKinds,
|
||||
snapshotHash,
|
||||
...(snapshot ? { snapshot } : {}),
|
||||
plan,
|
||||
@@ -2024,7 +2079,7 @@ function parseOrchestrationV4(input, options = {}) {
|
||||
...(workReceipts ? { workReceipts } : {}),
|
||||
}
|
||||
for (const key of [
|
||||
'round', 'currentKind', 'pendingKinds', 'activeKinds', 'successfulKinds',
|
||||
'round', 'currentKind', 'pendingKinds', 'successfulKinds',
|
||||
'agreementKinds', 'attachmentRecipients', 'totalSuccesses', 'terminalFailureOccurred',
|
||||
'collaboration', 'taskGraph',
|
||||
]) {
|
||||
@@ -2149,7 +2204,7 @@ function parseCollaborationControlBlock(input, options = {}) {
|
||||
'claims', 'findings', 'refs', 'writer', 'writerKind', 'batchId', 'entryIds',
|
||||
'capabilities', 'intendedWork', 'deliverables', 'dependencies',
|
||||
'proposedAssignments', 'finalizerKind', 'verifierKinds', 'supportedPlanHash',
|
||||
'agreeToPlan', 'workItemId',
|
||||
'agreeToPlan', 'workItemId', 'taskDecision',
|
||||
]) || input.version !== 1) {
|
||||
fail('COLLABORATION_CONTROL_BLOCK_INVALID')
|
||||
}
|
||||
@@ -2159,6 +2214,8 @@ function parseCollaborationControlBlock(input, options = {}) {
|
||||
fail('COLLABORATION_CONTROL_BLOCK_INVALID')
|
||||
}
|
||||
const summary = safeText(input.summary, MAX_V4_SUMMARY_CHARS, true)
|
||||
const taskDecision = input.taskDecision == null ? null : parseTaskDecision(input.taskDecision)
|
||||
if (taskDecision && phase !== 'discussion') fail('COLLABORATION_CONTROL_BLOCK_INVALID')
|
||||
const boundedList = (value, limit = MAX_V4_REFS, textLimit = MAX_V4_TEXT_CHARS) => {
|
||||
if (value == null) return []
|
||||
if (!Array.isArray(value) || value.length > limit) fail('COLLABORATION_CONTROL_BLOCK_INVALID')
|
||||
@@ -2203,7 +2260,7 @@ function parseCollaborationControlBlock(input, options = {}) {
|
||||
}
|
||||
})
|
||||
const finalizerKind = input.finalizerKind == null ? '' : safeText(input.finalizerKind, 120, false)
|
||||
const verifierKinds = boundedList(input.verifierKinds, Math.min(2, MAX_V4_SLOTS), 120)
|
||||
const verifierKinds = boundedList(input.verifierKinds, MAX_V4_SLOTS, 120)
|
||||
const supportedPlanHash = input.supportedPlanHash == null
|
||||
? '' : String(input.supportedPlanHash)
|
||||
const workItemId = input.workItemId == null ? '' : safeText(input.workItemId, 120, false)
|
||||
@@ -2289,6 +2346,7 @@ function parseCollaborationControlBlock(input, options = {}) {
|
||||
status,
|
||||
summary,
|
||||
conclusion,
|
||||
...(taskDecision ? { taskDecision } : {}),
|
||||
artifactIds,
|
||||
evidenceIds,
|
||||
findingIds,
|
||||
@@ -2327,6 +2385,7 @@ function collaborationChars(block) {
|
||||
...(Array.isArray(block.intendedWork) ? block.intendedWork : []),
|
||||
...(Array.isArray(block.deliverables) ? block.deliverables : []),
|
||||
...(Array.isArray(block.dependencies) ? block.dependencies : []),
|
||||
...(block.taskDecision ? [block.taskDecision.reason, ...block.taskDecision.deliverables] : []),
|
||||
...(Array.isArray(block.proposedAssignments)
|
||||
? block.proposedAssignments.flatMap(item => [item.objective, item.expectedOutput])
|
||||
: []),
|
||||
@@ -2535,6 +2594,7 @@ function createCollaborationReceipt(input, options = {}) {
|
||||
...(input.supportedPlanHash ? { supportedPlanHash: input.supportedPlanHash } : {}),
|
||||
...(typeof input.agreeToPlan === 'boolean' ? { agreeToPlan: input.agreeToPlan } : {}),
|
||||
...(input.workItemId ? { workItemId: input.workItemId } : {}),
|
||||
...(input.taskDecision ? { taskDecision: input.taskDecision } : {}),
|
||||
deliveryWatermark: input.deliveryWatermark || 0,
|
||||
snapshotHash: input.snapshotHash,
|
||||
...(typeof input.writer === 'boolean' ? { writer: input.writer } : {}),
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
const { redactSecrets } = require('../security/secret-redaction.cjs')
|
||||
|
||||
function parseTaskDecision(input) {
|
||||
const invalid = () => { throw new Error('LOCAL_RUN_TASK_DECISION_INVALID') }
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)
|
||||
|| Object.keys(input).some(key => !['status', 'reason', 'deliverables', 'handoffTo', 'nextKinds'].includes(key))
|
||||
|| !['completed', 'continue', 'blocked', 'needs-human'].includes(input.status)) invalid()
|
||||
const text = (value, limit) => {
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > limit
|
||||
|| /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value)) invalid()
|
||||
return redactSecrets(value.trim())
|
||||
}
|
||||
const reason = text(input.reason, 1600)
|
||||
if (!Array.isArray(input.deliverables) || input.deliverables.length > 16) invalid()
|
||||
const deliverables = input.deliverables.map(value => text(value, 800))
|
||||
if (input.status === 'completed' && !deliverables.length) invalid()
|
||||
if (input.handoffTo != null && (input.status !== 'continue'
|
||||
|| typeof input.handoffTo !== 'string'
|
||||
|| !/^[a-z0-9][a-z0-9-]{0,79}$/.test(input.handoffTo))) invalid()
|
||||
if (input.nextKinds != null && (!Array.isArray(input.nextKinds)
|
||||
|| input.nextKinds.length > 32
|
||||
|| input.nextKinds.some(kind => typeof kind !== 'string'
|
||||
|| !/^[a-z0-9][a-z0-9-]{0,79}$/i.test(kind))
|
||||
|| (input.nextKinds.length > 0 && input.status !== 'continue'))) invalid()
|
||||
const nextKinds = input.nextKinds?.map(kind => kind.toLowerCase())
|
||||
if (nextKinds && new Set(nextKinds).size !== nextKinds.length) invalid()
|
||||
return {
|
||||
status: input.status, reason, deliverables,
|
||||
...(input.handoffTo != null ? { handoffTo: input.handoffTo } : {}),
|
||||
...(nextKinds ? { nextKinds } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { parseTaskDecision }
|
||||
@@ -208,9 +208,11 @@ class HumanGateCoordinator {
|
||||
status,
|
||||
optionId: option.optionId,
|
||||
actorId: input.actorId || 'local-user',
|
||||
decidedAt: input.decidedAt || this.now(),
|
||||
decidedAt: input.decidedAt || current.decision?.decidedAt || this.now(),
|
||||
...(response ? { response } : {}),
|
||||
})
|
||||
// Recovery owns recorded decisions; repeated submissions must not dispatch them again.
|
||||
if (current.status !== 'pending') return publicHumanGate(record)
|
||||
this.clearExpiry(record.gateId)
|
||||
try {
|
||||
this.onResumed(record, record.decision)
|
||||
|
||||
@@ -25,10 +25,12 @@ const {
|
||||
shutdownAcpSessionRuntime,
|
||||
} = require('./agents/cli/cli-adapters.cjs')
|
||||
const { AgentInstaller } = require('./agents/installer/agent-installer.cjs')
|
||||
const { networkEnvironment } = require('./agents/cli/cli-network-environment.cjs')
|
||||
const { AgentConnectorInstanceStore } = require('./agents/connectors/agent-connector-instance-store.cjs')
|
||||
const { LocalAgentConnectors } = require('./agents/connectors/agent-connector-local.cjs')
|
||||
const { AgentConnectorPackageStore } = require('./agents/connectors/agent-connector-package-store.cjs')
|
||||
const { CloudAgentOperationStore } = require('./agents/cloud/cloud-agent-operation-store.cjs')
|
||||
const { CloudAgentBridgeStore } = require('./agents/cloud/cloud-agent-bridge.cjs')
|
||||
const {
|
||||
CloudAgentRuntime,
|
||||
createCloudAgentStartRetry = ({ runtime }) => Object.freeze({
|
||||
@@ -46,8 +48,6 @@ const {
|
||||
resolveNativeShellEnvironment,
|
||||
} = require('./agents/local-agent-readiness.cjs')
|
||||
const { LocalWorkspace } = require('./workspace/local-workspace.cjs')
|
||||
const { MediaGenerationRuntime } = require('./media/media-generation-runtime.cjs')
|
||||
const { resolveMediaProvider } = require('./media/media-provider-resolution.cjs')
|
||||
const { registerDesktopIpc } = require('./shell/main-ipc.cjs')
|
||||
const {
|
||||
isAllowedExternalUrl,
|
||||
@@ -77,7 +77,7 @@ const {
|
||||
providerOptionsFor,
|
||||
} = require('./providers/provider-options.cjs')
|
||||
const LOCAL_AGENT_KINDS = new Set([
|
||||
'codex', 'hermes', 'openclaw', 'workbuddy', 'kimi', 'mimo', 'claude', 'gemini', 'opencode', 'qwen',
|
||||
'codex', 'hermes', 'openclaw', 'workbuddy', 'pi', 'kimi', 'mimo', 'claude', 'gemini', 'opencode', 'qwen',
|
||||
'opencodereview',
|
||||
])
|
||||
const QUIT_CLEANUP_TIMEOUT_MS = 2500
|
||||
@@ -92,6 +92,7 @@ let providerStore = null
|
||||
let customAgentStore = null
|
||||
let agentConnectors = null
|
||||
let cloudAgentRuntime = null
|
||||
let cloudAgentBridges = null
|
||||
let cloudAgentStartRetry = null
|
||||
let channelIngressRuntime = null
|
||||
let knowledgeBaseStore = null
|
||||
@@ -236,9 +237,9 @@ function providerOptions(kind, context = {}) {
|
||||
)
|
||||
}
|
||||
|
||||
async function nativeShellEnvironment() {
|
||||
async function nativeShellEnvironment(options = {}) {
|
||||
const home = app.getPath('home')
|
||||
const resolved = await resolveNativeShellEnvironment({ home })
|
||||
const resolved = await resolveNativeShellEnvironment({ home, refresh: options.refresh === true })
|
||||
return {
|
||||
...resolved,
|
||||
env: { ...process.env, ...resolved.env },
|
||||
@@ -251,37 +252,6 @@ async function detectLocalAgents() {
|
||||
return detectAgents({ env: shellEnvironment.env, home: shellEnvironment.home })
|
||||
}
|
||||
|
||||
function mediaFallbackProviders(env = process.env) {
|
||||
const apiKey = String(
|
||||
env.ZGCI_MEDIA_API_KEY
|
||||
|| env.ZGCI_API_KEY
|
||||
|| env.ZCGI_API_KEY
|
||||
|| env.ZGCI_LLM_API_KEY
|
||||
|| '',
|
||||
).trim()
|
||||
if (!apiKey) return []
|
||||
const baseUrl = String(env.ZGCI_MEDIA_BASE_URL || 'https://hub.zgci.org/v1')
|
||||
.trim()
|
||||
.replace(/\/+$/, '')
|
||||
.replace(/\/chat\/completions$/i, '')
|
||||
let parsed
|
||||
try { parsed = new URL(baseUrl) } catch { return [] }
|
||||
if (parsed.protocol !== 'https:' || parsed.username || parsed.password
|
||||
|| parsed.search || parsed.hash) {
|
||||
return []
|
||||
}
|
||||
return [{
|
||||
kind: 'zgci-media',
|
||||
status: {
|
||||
configured: true,
|
||||
provider: 'ZGCI Media',
|
||||
baseUrl,
|
||||
model: 'glm',
|
||||
},
|
||||
credentials: { OPENAI_API_KEY: apiKey },
|
||||
}]
|
||||
}
|
||||
|
||||
function workspaceStoragePath(userData = app.getPath('userData')) {
|
||||
return path.join(userData, 'meldwork-workspace.json')
|
||||
}
|
||||
@@ -372,6 +342,9 @@ async function runCoreAgent(agent, prompt, workdir, options = {}) {
|
||||
const runOptions = { ...options }
|
||||
delete runOptions.connectorCredentialIsolation
|
||||
const status = providerStore.status(agent.kind)
|
||||
if (!connectorCredentialIsolation && status.error) {
|
||||
throw new Error('PROVIDER_CREDENTIAL_UNAVAILABLE')
|
||||
}
|
||||
const shellEnvironment = connectorCredentialIsolation ? null : await nativeShellEnvironment()
|
||||
const nativeRuntime = !connectorCredentialIsolation
|
||||
&& agent.kind === 'openclaw' && !status.configured
|
||||
@@ -392,7 +365,9 @@ async function runCoreAgent(agent, prompt, workdir, options = {}) {
|
||||
const nativeEnv = connectorCredentialIsolation || agent.kind === 'openclaw'
|
||||
? {}
|
||||
: {
|
||||
...nativeCredentialEnvironment(agent.kind, shellEnvironment.env),
|
||||
...nativeCredentialEnvironment(agent.kind, shellEnvironment.env, {
|
||||
providerConfigured: status.configured,
|
||||
}),
|
||||
...(shellEnvironment.env.PATH ? { PATH: shellEnvironment.env.PATH } : {}),
|
||||
}
|
||||
const callerEnv = connectorCredentialIsolation || agent.kind !== 'openclaw'
|
||||
@@ -401,7 +376,10 @@ async function runCoreAgent(agent, prompt, workdir, options = {}) {
|
||||
return runAgent(agent, prompt, workdir, {
|
||||
...runOptions,
|
||||
...injected,
|
||||
env: { ...nativeEnv, ...callerEnv, ...injected.env },
|
||||
env: {
|
||||
...networkEnvironment(shellEnvironment?.env),
|
||||
...nativeEnv, ...callerEnv, ...injected.env,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -506,6 +484,7 @@ function createWorkspace() {
|
||||
safeStorage: lazySafeStorage,
|
||||
}),
|
||||
runAgent: runCoreAgent,
|
||||
cloudBridges: cloudAgentBridges,
|
||||
})
|
||||
const outcomeStore = new OutcomeStore({
|
||||
rootPath: path.join(privateRoot, 'outcomes'),
|
||||
@@ -530,17 +509,6 @@ function createWorkspace() {
|
||||
}),
|
||||
connectors: [],
|
||||
})
|
||||
const mediaGeneration = new MediaGenerationRuntime({
|
||||
getProvider: (kind, type, excludedKinds) => resolveMediaProvider({
|
||||
requestedKind: kind,
|
||||
type,
|
||||
kinds: EXTERNAL_PROVIDER_KINDS,
|
||||
excludedKinds,
|
||||
statusFor: candidateKind => providerStore.status(candidateKind),
|
||||
credentialsFor: candidateKind => providerStore.envForAgent(candidateKind),
|
||||
fallbackProviders: mediaFallbackProviders(),
|
||||
}),
|
||||
})
|
||||
const localWorkspace = new LocalWorkspace({
|
||||
storagePath: workspaceStoragePath(),
|
||||
contentBlobStore,
|
||||
@@ -551,6 +519,7 @@ function createWorkspace() {
|
||||
agentFitMatrix: FROZEN_AGENT_FIT_MATRIX,
|
||||
runLedger: cloudAgentRuntime.workspaceLedger(),
|
||||
detectAgents: async () => {
|
||||
await cloudAgentBridges?.refresh()
|
||||
const [installedAgents, customAgents] = await Promise.all([
|
||||
installer.detectedAgents(),
|
||||
customAgentStore.detectAgents(),
|
||||
@@ -573,6 +542,9 @@ function createWorkspace() {
|
||||
credentialState: async (kind, agent) => {
|
||||
if (customAgentStore.has(kind)) return { state: 'ready', source: 'custom-agent' }
|
||||
if (agentConnectors.has(kind)) return { state: 'ready', source: 'agent-connector' }
|
||||
if (providerStore.status(kind).error) {
|
||||
return { state: 'unknown', source: 'provider-credential-unavailable' }
|
||||
}
|
||||
const shellEnvironment = await nativeShellEnvironment()
|
||||
return resolveNativeCredentialState(kind, {
|
||||
executable: agent?.executable,
|
||||
@@ -584,7 +556,7 @@ function createWorkspace() {
|
||||
agentLabel: kind => customAgentStore.label(kind) || agentConnectors.label(kind),
|
||||
sharedProviderReady: kind => EXTERNAL_PROVIDER_KINDS.has(kind) && providerStore.status(kind).configured,
|
||||
connectorRuntime: agentConnectors,
|
||||
generateMedia: input => mediaGeneration.generate(input),
|
||||
naturalAgentResponses: true,
|
||||
runAgent: async (agent, prompt, workdir, options = {}) => {
|
||||
if (customAgentStore.has(agent.kind)) {
|
||||
return customAgentStore.run(agent.kind, prompt, workdir, {
|
||||
@@ -610,6 +582,7 @@ function createWorkspace() {
|
||||
}
|
||||
|
||||
async function localAgentCatalog() {
|
||||
await cloudAgentBridges?.refresh()
|
||||
const [catalog, customAgents, installedAgents] = await Promise.all([
|
||||
installer.catalog(),
|
||||
customAgentStore.catalog(),
|
||||
@@ -617,10 +590,17 @@ async function localAgentCatalog() {
|
||||
])
|
||||
agentConnectors?.refresh(installedAgents)
|
||||
const connectorAgents = agentConnectors?.catalog() || []
|
||||
const mergedAgents = new Map()
|
||||
for (const agent of [...catalog.agents, ...customAgents, ...connectorAgents]) {
|
||||
mergedAgents.set(agent.kind, agent)
|
||||
}
|
||||
for (const agent of cloudAgentBridges?.catalogEntries?.() || []) {
|
||||
mergedAgents.set(agent.kind, { ...(mergedAgents.get(agent.kind) || {}), ...agent })
|
||||
}
|
||||
const states = new Map((workspace?.snapshot().agents || []).map(agent => [agent.kind, agent]))
|
||||
return {
|
||||
...catalog,
|
||||
agents: [...catalog.agents, ...customAgents, ...connectorAgents].map((agent) => {
|
||||
agents: [...mergedAgents.values()].map((agent) => {
|
||||
const state = states.get(agent.kind)
|
||||
const support = localAttachmentSupport(agent.kind)
|
||||
return {
|
||||
@@ -635,7 +615,9 @@ async function localAgentCatalog() {
|
||||
recentlyVerified: Boolean(agent.installed && state?.recentlyVerified),
|
||||
capabilities: state?.capabilities || agent.capabilities || null,
|
||||
available: Boolean(agent.installed && state?.invocable),
|
||||
credentialState: agent.installed ? (state?.credentialState || 'unknown') : 'missing',
|
||||
credentialState: agent.installed
|
||||
? (state?.credentialState || agent.credentialState || 'unknown')
|
||||
: 'missing',
|
||||
availabilitySource: agent.installed ? (state?.availabilitySource || 'unverified') : 'none',
|
||||
showInSidebar: Boolean(agent.installed && state?.showInSidebar),
|
||||
attachmentTypes: Object.entries(support)
|
||||
@@ -651,6 +633,7 @@ async function refreshLocalAgentState() {
|
||||
if (!target) return null
|
||||
const task = localAgentRefreshQueue.then(async () => {
|
||||
if (workspace !== target) return workspace?.snapshot() || null
|
||||
await nativeShellEnvironment({ refresh: true })
|
||||
const snapshot = await target.refreshAgents()
|
||||
if (workspace !== target) return workspace?.snapshot() || null
|
||||
return snapshot
|
||||
@@ -755,6 +738,7 @@ function registerIpc() {
|
||||
getAttachmentStore: () => attachmentStore,
|
||||
getAgentConnectors: () => agentConnectors,
|
||||
getCloudAgentRuntime: () => cloudAgentRuntime,
|
||||
getCloudAgentBridges: () => cloudAgentBridges,
|
||||
getMainWindow: () => mainWindow,
|
||||
getWorkspace: () => workspace,
|
||||
installer,
|
||||
@@ -797,6 +781,10 @@ if (!hasSingleInstanceLock) {
|
||||
customAgentStore = new CustomAgentStore({
|
||||
storagePath: path.join(app.getPath('userData'), 'meldwork-custom-agents.json'),
|
||||
})
|
||||
cloudAgentBridges = new CloudAgentBridgeStore({
|
||||
storagePath: path.join(app.getPath('userData'), 'meldwork-cloud-agent-bridges.json'),
|
||||
fetch: globalThis.fetch,
|
||||
})
|
||||
providerStore = new ProviderStore({
|
||||
storagePath: path.join(app.getPath('userData'), 'meldwork-provider.json'),
|
||||
safeStorage: lazySafeStorage,
|
||||
@@ -871,6 +859,7 @@ if (!hasSingleInstanceLock) {
|
||||
if (installRunning) installer.cancel(installerState.taskId)
|
||||
quitCleanup = runQuitCleanup([
|
||||
() => channelIngressRuntime?.shutdown(),
|
||||
() => cloudAgentBridges?.close(),
|
||||
() => cloudAgentRuntime?.shutdown(),
|
||||
async () => {
|
||||
try {
|
||||
|
||||
@@ -117,6 +117,12 @@ if (isLocalDocument) Object.assign(desktopApi, {
|
||||
),
|
||||
cancel: runId => ipcRenderer.invoke('local-cloud-agent:cancel', runId),
|
||||
}),
|
||||
cloudAgentBridge: Object.freeze({
|
||||
list: () => ipcRenderer.invoke('local-cloud-agent-bridge:list'),
|
||||
connect: input => ipcRenderer.invoke('local-cloud-agent-bridge:connect', input),
|
||||
refresh: () => ipcRenderer.invoke('local-cloud-agent-bridge:refresh'),
|
||||
delete: bridgeId => ipcRenderer.invoke('local-cloud-agent-bridge:delete', bridgeId),
|
||||
}),
|
||||
localOutcome: Object.freeze({
|
||||
recordAdoption: input => ipcRenderer.invoke('local-outcome:record-adoption', input),
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const { managedOpenClawOptions, nativeOpenClawOptions } = require('../agents/cli/openclaw-runtime.cjs')
|
||||
|
||||
const EXTERNAL_PROVIDER_KINDS = new Set([
|
||||
'codex', 'hermes', 'openclaw', 'workbuddy', 'kimi', 'mimo', 'claude', 'gemini', 'opencode', 'qwen',
|
||||
'codex', 'hermes', 'openclaw', 'workbuddy', 'pi', 'kimi', 'mimo', 'claude', 'gemini', 'opencode', 'qwen',
|
||||
'opencodereview',
|
||||
])
|
||||
|
||||
@@ -10,6 +10,7 @@ const OFFICIAL_PROVIDER_BASE_URLS = Object.freeze({
|
||||
hermes: 'https://api.openai.com/v1',
|
||||
openclaw: 'https://api.openai.com/v1',
|
||||
workbuddy: '',
|
||||
pi: '',
|
||||
kimi: 'https://api.moonshot.cn/v1',
|
||||
mimo: '',
|
||||
claude: 'https://api.anthropic.com',
|
||||
@@ -67,6 +68,16 @@ function providerOptionsFor(kind, generic, context = {}, status = {}) {
|
||||
},
|
||||
}
|
||||
}
|
||||
if (kind === 'pi') {
|
||||
return {
|
||||
env: {
|
||||
...generic,
|
||||
PI_MODEL: generic.OPENAI_MODEL,
|
||||
PI_API_KEY: generic.OPENAI_API_KEY,
|
||||
PI_BASE_URL: generic.OPENAI_BASE_URL,
|
||||
},
|
||||
}
|
||||
}
|
||||
if (kind === 'kimi') {
|
||||
return {
|
||||
env: {
|
||||
@@ -91,9 +102,11 @@ function providerOptionsFor(kind, generic, context = {}, status = {}) {
|
||||
}
|
||||
if (kind === 'claude') {
|
||||
return {
|
||||
provider: { id: 'anthropic', model: generic.OPENAI_MODEL, baseUrl: generic.OPENAI_BASE_URL },
|
||||
env: {
|
||||
...generic,
|
||||
ANTHROPIC_API_KEY: generic.OPENAI_API_KEY,
|
||||
MELDWORK_PROVIDER_API_KEY: generic.OPENAI_API_KEY,
|
||||
ANTHROPIC_BASE_URL: generic.OPENAI_BASE_URL,
|
||||
ANTHROPIC_MODEL: generic.OPENAI_MODEL,
|
||||
},
|
||||
|
||||
@@ -17,6 +17,7 @@ const OFFICIAL_PROVIDERS = Object.freeze({
|
||||
hermes: { provider: 'OpenAI API', baseUrl: 'https://api.openai.com/v1' },
|
||||
openclaw: { provider: 'OpenAI API', baseUrl: 'https://api.openai.com/v1' },
|
||||
workbuddy: { provider: 'WorkBuddy Official', baseUrl: '' },
|
||||
pi: { provider: 'Pi Native', baseUrl: '' },
|
||||
kimi: { provider: 'Moonshot AI', baseUrl: 'https://api.moonshot.cn/v1' },
|
||||
mimo: { provider: 'MiMo Native', baseUrl: '' },
|
||||
claude: { provider: 'Anthropic', baseUrl: 'https://api.anthropic.com' },
|
||||
@@ -115,31 +116,34 @@ class ProviderStore {
|
||||
const encryptionAvailable = this.encryptionAvailable()
|
||||
let metadata = EMPTY_METADATA
|
||||
let configured = false
|
||||
let credentialUnavailable = false
|
||||
let activePreset = 'official'
|
||||
const profiles = {}
|
||||
if (encryptionAvailable && credentialStored) {
|
||||
if (credentialStored) {
|
||||
try {
|
||||
const agent = this.readDocument().agents[targetKind]
|
||||
if (agent) {
|
||||
activePreset = agent.activePreset
|
||||
for (const [preset, entry] of Object.entries(agent.profiles)) {
|
||||
profiles[preset] = {
|
||||
provider: entry.provider,
|
||||
baseUrl: entry.baseUrl,
|
||||
model: entry.model,
|
||||
configured: false,
|
||||
}
|
||||
try {
|
||||
this.decryptEntry(entry)
|
||||
profiles[preset] = {
|
||||
provider: entry.provider,
|
||||
baseUrl: entry.baseUrl,
|
||||
model: entry.model,
|
||||
configured: true,
|
||||
}
|
||||
} catch { /* keep an unreadable profile unavailable */ }
|
||||
profiles[preset].configured = true
|
||||
} catch { /* retain saved metadata while the credential is unavailable */ }
|
||||
}
|
||||
const activeEntry = profiles[activePreset]
|
||||
if (activeEntry) {
|
||||
metadata = activeEntry
|
||||
configured = true
|
||||
configured = activeEntry.configured
|
||||
credentialUnavailable = !configured
|
||||
}
|
||||
}
|
||||
} catch { /* unreadable credentials stay unavailable */ }
|
||||
} catch { credentialUnavailable = true }
|
||||
}
|
||||
return {
|
||||
provider: metadata.provider,
|
||||
@@ -149,6 +153,7 @@ class ProviderStore {
|
||||
profiles,
|
||||
encryptionAvailable,
|
||||
configured,
|
||||
...(credentialUnavailable ? { error: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -147,7 +147,7 @@ function classifiedCategory(error, code, status) {
|
||||
if (/INCOMPAT|UNSUPPORTED|PROTOCOL_UNAVAILABLE|REVIEW_ONLY|VERSION_MISMATCH/.test(code)) {
|
||||
return 'compatibility'
|
||||
}
|
||||
if (/SPAWN|EXITED|PROCESS|PROTOCOL|OUTCOME|OUTPUT_LIMIT|EMPTY_RESPONSE/.test(code)) {
|
||||
if (/SPAWN|EXITED|PROCESS|PROTOCOL|OUTCOME|OUTPUT_LIMIT|EMPTY_RESPONSE|COLLABORATION_RECEIPT/.test(code)) {
|
||||
return 'protocol'
|
||||
}
|
||||
return 'execution'
|
||||
@@ -157,7 +157,7 @@ function retryability(category, error) {
|
||||
if (category === 'session') return 'refresh_session'
|
||||
if (category === 'authentication') return 'never'
|
||||
if (category === 'compatibility') return 'never'
|
||||
if (['rate_limit', 'network', 'provider'].includes(category)) return 'retry'
|
||||
if (['rate_limit', 'network', 'provider', 'timeout', 'protocol'].includes(category)) return 'retry'
|
||||
if (error?.failure?.retryable === true) return 'retry'
|
||||
return 'never'
|
||||
}
|
||||
|
||||
@@ -122,6 +122,8 @@ function normalizeSessionMeta(input) {
|
||||
meta.inheritedTaskIds = inheritedTaskIds
|
||||
meta.provenanceCompleteness = provenanceCompleteness
|
||||
}
|
||||
const lastDeliveredMessageId = cleanId(input.lastDeliveredMessageId)
|
||||
if (lastDeliveredMessageId) meta.lastDeliveredMessageId = lastDeliveredMessageId
|
||||
return meta
|
||||
}
|
||||
|
||||
@@ -157,6 +159,8 @@ function nextSessionMeta(meta, usage = {}) {
|
||||
if (Object.hasOwn(usage, field)) next[field] = usage[field]
|
||||
else if (Object.hasOwn(previous, field)) next[field] = previous[field]
|
||||
}
|
||||
if (usage.lastDeliveredMessageId) next.lastDeliveredMessageId = usage.lastDeliveredMessageId
|
||||
else if (previous.lastDeliveredMessageId) next.lastDeliveredMessageId = previous.lastDeliveredMessageId
|
||||
return normalizeSessionMeta(next)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const MAX_CAPSULE_EVENTS = 12
|
||||
const { parseTaskDecision } = require('../collaboration/task-decision.cjs')
|
||||
|
||||
const { redactSecrets } = require('../security/secret-redaction.cjs')
|
||||
const { normalizeContentBlobRef } = require('../attachments/content-blob-store.cjs')
|
||||
@@ -31,6 +32,10 @@ const FINAL_STATUSES = new Set([
|
||||
const CAPSULE_EVENT_TYPES = new Set([
|
||||
'reasoning_summary', 'plan', 'tool_start', 'tool_update', 'tool_result_summary', 'warning',
|
||||
])
|
||||
const TRACE_PHASES = new Set([
|
||||
'proposal', 'challenge', 'coordination', 'work', 'synthesis', 'verification', 'commit',
|
||||
'discussion', 'synthesis-recovery', 'manual_retry',
|
||||
])
|
||||
const INCOMPLETE_TOOL_EVENT_TYPES = new Set(['tool_start', 'tool_update'])
|
||||
const FAILED_TOOL_STATUSES = new Set(['failed', 'stopped', 'timeout', 'interrupted'])
|
||||
const PUBLIC_ID = /^[A-Za-z0-9._:-]{1,120}$/
|
||||
@@ -248,6 +253,10 @@ function normalizeContextStats(input) {
|
||||
const value = String(input[field] || '')
|
||||
if (SHA256.test(value)) context[field] = value
|
||||
}
|
||||
const operationId = cleanId(input.operationId)
|
||||
if (operationId) context.operationId = operationId
|
||||
const snapshotHash = String(input.snapshotHash || '')
|
||||
if (SHA256.test(snapshotHash)) context.snapshotHash = snapshotHash
|
||||
if (input.sessionRotated === true) context.sessionRotated = true
|
||||
const contextPackId = normalizeContextPackId(input.contextPackId)
|
||||
if (contextPackId) context.contextPackId = contextPackId
|
||||
@@ -264,6 +273,10 @@ function normalizeContextStats(input) {
|
||||
if (externalRunRef) context.externalRunRef = externalRunRef
|
||||
const outcomeRefs = normalizeOutcomeRefs(input.outcomeRefs)
|
||||
if (Object.keys(outcomeRefs).length) context.outcomeRefs = outcomeRefs
|
||||
if (input.taskDecision != null) {
|
||||
try { context.taskDecision = parseTaskDecision(input.taskDecision) }
|
||||
catch { /* malformed task judgments cannot authorize completion */ }
|
||||
}
|
||||
const connectorContext = normalizeConnectorContext(input)
|
||||
if (connectorContext) Object.assign(context, connectorContext)
|
||||
return context
|
||||
@@ -328,6 +341,11 @@ function normalizeCapsuleRound(value, runId, agentRunId, hasExplicitRound) {
|
||||
return inferred <= 100000 ? inferred : null
|
||||
}
|
||||
|
||||
function normalizeTracePhase(value) {
|
||||
const phase = cleanText(value, 40, { inline: true }).toLowerCase()
|
||||
return TRACE_PHASES.has(phase) ? phase : ''
|
||||
}
|
||||
|
||||
function normalizeTraceCapsule(input) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
|
||||
const runId = cleanId(input.runId)
|
||||
@@ -339,6 +357,8 @@ function normalizeTraceCapsule(input) {
|
||||
agentRunId,
|
||||
Object.prototype.hasOwnProperty.call(input, 'round'),
|
||||
)
|
||||
const phase = normalizeTracePhase(input.phase)
|
||||
const executionSequence = boundedNumber(input.executionSequence, 1, 100000)
|
||||
const events = (Array.isArray(input.events) ? input.events : [])
|
||||
.slice(0, MAX_CAPSULE_EVENTS)
|
||||
.map(normalizeCapsuleEvent)
|
||||
@@ -347,6 +367,8 @@ function normalizeTraceCapsule(input) {
|
||||
runId,
|
||||
agentRunId,
|
||||
...(round != null ? { round } : {}),
|
||||
...(phase ? { phase } : {}),
|
||||
...(executionSequence != null ? { executionSequence } : {}),
|
||||
status: cleanStatus(input.status, 'completed'),
|
||||
summary: cleanText(input.summary, 1200),
|
||||
events,
|
||||
@@ -363,6 +385,7 @@ function traceCapsuleFromAgentRun(input, options = {}) {
|
||||
const kind = cleanId(input.kind || input.agentKind)
|
||||
if (!runId || !agentRunId || !kind) return null
|
||||
const round = boundedNumber(input.round, 0, 100000)
|
||||
const phase = normalizeTracePhase(options.phase || input.phase)
|
||||
const status = cleanStatus(options.status || input.status, 'interrupted')
|
||||
const capsuleEvents = (Array.isArray(input.events) ? input.events : [])
|
||||
.filter(item => CAPSULE_EVENT_TYPES.has(String(item?.type || '').toLowerCase()))
|
||||
@@ -387,6 +410,10 @@ function traceCapsuleFromAgentRun(input, options = {}) {
|
||||
runId,
|
||||
agentRunId,
|
||||
round,
|
||||
...(phase ? { phase } : {}),
|
||||
...(Number.isInteger(options.executionSequence)
|
||||
? { executionSequence: options.executionSequence }
|
||||
: {}),
|
||||
status,
|
||||
summary: narrative?.summary || input.summary || '',
|
||||
events: capsuleEvents,
|
||||
|
||||
@@ -298,10 +298,15 @@ class RunHarness {
|
||||
status: run.status,
|
||||
title: 'agent',
|
||||
})
|
||||
const phase = context && typeof context === 'object' ? context.phase : ''
|
||||
run.context = normalizeContextStats(context)
|
||||
const capsule = traceCapsuleFromAgentRun(run, {
|
||||
runId: this.runId,
|
||||
status: run.status,
|
||||
phase,
|
||||
executionSequence: context && Number.isInteger(context.executionSequence)
|
||||
? context.executionSequence
|
||||
: undefined,
|
||||
context: run.context,
|
||||
})
|
||||
return { event, capsule }
|
||||
|
||||
@@ -3,8 +3,10 @@ const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const { hasValidStoredRecordShape } = require('./run-ledger-records.cjs')
|
||||
const { atomicWritePrivateFile } = require('../security/private-file.cjs')
|
||||
|
||||
const JOURNAL_VERSION = 1
|
||||
const DEFAULT_COMPACTION_BYTES = 4 * 1024 * 1024
|
||||
const JOURNAL_ID = /^[A-Za-z0-9._:-]{1,160}$/
|
||||
const MAX_CHANGE_ITEMS = 1024
|
||||
const CHANGE_FIELDS = new Set(['replace', 'upserts', 'removedRunIds'])
|
||||
@@ -26,8 +28,8 @@ const CONTEXT_FIELDS = new Set([
|
||||
'includedCount', 'omittedCount', 'charCount', 'sessionRotated', 'externalRunRef',
|
||||
'contextMode', 'promptChars', 'contextPackId', 'contextPackState', 'deliveryRecordIds',
|
||||
'sessionProvenance', 'outcomeRefs', 'sourceCount', 'sourceHash', 'promptBytes',
|
||||
'promptHash', 'wirePayloadBytes', 'wirePayloadHash',
|
||||
'connector', 'connectorEventState',
|
||||
'promptHash', 'wirePayloadBytes', 'wirePayloadHash', 'operationId', 'snapshotHash',
|
||||
'connector', 'connectorEventState', 'taskDecision',
|
||||
])
|
||||
|
||||
function clone(value) {
|
||||
@@ -89,6 +91,9 @@ class RunJournal {
|
||||
? options.storagePath.trim()
|
||||
: ''
|
||||
if (!this.storagePath) throw new Error('RUN_JOURNAL_STORAGE_REQUIRED')
|
||||
this.compactionBytes = Number.isFinite(options.compactionBytes)
|
||||
? Math.max(1024, Math.floor(options.compactionBytes))
|
||||
: DEFAULT_COMPACTION_BYTES
|
||||
this.sequence = 0
|
||||
this.loadError = null
|
||||
this.hasBaseline = false
|
||||
@@ -231,6 +236,56 @@ class RunJournal {
|
||||
this.commit(transactionId, timestamp)
|
||||
}
|
||||
|
||||
compact(runs, timestamp) {
|
||||
this.assertLoaded()
|
||||
const change = {
|
||||
replace: true,
|
||||
upserts: clone(runs),
|
||||
removedRunIds: [],
|
||||
}
|
||||
if (!validChange(change)) throw new Error('RUN_JOURNAL_CHANGE_INVALID')
|
||||
const transactionId = `txn-${timestamp}-${crypto.randomBytes(8).toString('hex')}`
|
||||
const entries = [
|
||||
{
|
||||
version: JOURNAL_VERSION,
|
||||
sequence: 1,
|
||||
transactionId,
|
||||
timestamp,
|
||||
phase: 'prepare',
|
||||
change,
|
||||
},
|
||||
{
|
||||
version: JOURNAL_VERSION,
|
||||
sequence: 2,
|
||||
transactionId,
|
||||
timestamp,
|
||||
phase: 'commit',
|
||||
},
|
||||
]
|
||||
atomicWritePrivateFile(
|
||||
this.storagePath,
|
||||
`${entries.map(entry => JSON.stringify(entry)).join('\n')}\n`,
|
||||
)
|
||||
this.sequence = 2
|
||||
this.runs.clear()
|
||||
this.pending.clear()
|
||||
this.hasBaseline = false
|
||||
this.apply(change)
|
||||
}
|
||||
|
||||
compactIfNeeded(runs, timestamp) {
|
||||
this.assertLoaded()
|
||||
try {
|
||||
if (!fs.existsSync(this.storagePath) || fs.statSync(this.storagePath).size < this.compactionBytes) {
|
||||
return false
|
||||
}
|
||||
this.compact(runs, timestamp)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
recover() {
|
||||
this.assertLoaded()
|
||||
return this.hasBaseline ? clone([...this.runs.values()]) : null
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const { redactSecrets } = require('../security/secret-redaction.cjs')
|
||||
const { parseTaskDecision } = require('../collaboration/task-decision.cjs')
|
||||
const { normalizeExternalRunRef } = require('../agents/agent-runtime-contract.cjs')
|
||||
const { parseConnectorRunSnapshot } = require('../agents/connectors/agent-connector-registry.cjs')
|
||||
const { parseRunEventState } = require('./run-event-protocol.cjs')
|
||||
@@ -42,8 +43,8 @@ const CONTEXT_FIELDS = new Set([
|
||||
'includedCount', 'omittedCount', 'charCount', 'sessionRotated', 'externalRunRef',
|
||||
'contextMode', 'promptChars', 'contextPackId', 'contextPackState', 'deliveryRecordIds',
|
||||
'sessionProvenance', 'outcomeRefs', 'sourceCount', 'sourceHash', 'promptBytes',
|
||||
'promptHash', 'wirePayloadBytes', 'wirePayloadHash',
|
||||
'connector', 'connectorEventState',
|
||||
'promptHash', 'wirePayloadBytes', 'wirePayloadHash', 'operationId', 'snapshotHash',
|
||||
'connector', 'connectorEventState', 'taskDecision',
|
||||
])
|
||||
const CONTEXT_PACK_STATES = new Set(['captured', 'legacy-unavailable'])
|
||||
const REQUIRED_BUDGET_FIELDS = new Set(['limits', 'used', 'source', 'enforcement', 'startedAt'])
|
||||
@@ -62,11 +63,11 @@ const CONTINUATION_FIELDS = new Set([
|
||||
])
|
||||
const CONTINUATION_INVOCATION_FIELDS = ['phase', 'slotId', 'operationId', 'snapshotHash']
|
||||
const CONTINUATION_V4_PHASES = new Set([
|
||||
'proposal', 'challenge', 'work', 'synthesis', 'verification',
|
||||
'proposal', 'discussion', 'challenge', 'work', 'synthesis', 'verification',
|
||||
])
|
||||
const CONTINUATION_GATE_TYPES = new Set(['permission', 'budget', 'decision', 'retry', 'input'])
|
||||
const CONTINUATION_RESUME_KINDS = new Set([
|
||||
'agent_slot', 'role_review_decision', 'v4_human_gate', 'v4_synthesis_recovery',
|
||||
'agent_slot', 'role_review_decision', 'v4_human_gate', 'v4_synthesis_recovery', 'v4_task_decision',
|
||||
])
|
||||
const CONTINUATION_STATES = new Set([
|
||||
'pending', 'ready', 'resuming', 'completed', 'failed', 'cancelled',
|
||||
@@ -75,8 +76,9 @@ const ACTIVE_CONTINUATION_STATES = new Set(['pending', 'ready', 'resuming'])
|
||||
const ORCHESTRATION_FIELDS = new Set([
|
||||
'version', 'workflow', 'currentKind', 'pendingKinds', 'activeKinds',
|
||||
'successfulKinds', 'agreementKinds', 'attachmentRecipients',
|
||||
'totalSuccesses', 'terminalFailureOccurred', 'collaboration', 'template', 'taskGraph',
|
||||
'phase', 'batchId', 'round', 'currentKinds', 'snapshotHash', 'snapshot', 'plan',
|
||||
'totalSuccesses', 'terminalFailureOccurred', 'executionSequence',
|
||||
'collaboration', 'template', 'taskGraph',
|
||||
'phase', 'discussionStyle', 'discussionWriterKind', 'batchId', 'round', 'currentKinds', 'snapshotHash', 'snapshot', 'plan',
|
||||
'slots', 'deliveryWatermarks', 'deliveryState', 'commitState', 'challengeBindings', 'synthesisBinding',
|
||||
'synthesisRecovery', 'convergence', 'coordinationPlan', 'workReceipts', 'candidateCommit',
|
||||
])
|
||||
@@ -239,7 +241,7 @@ function normalizeAgentRun(input, parent, fallbackTimestamp) {
|
||||
'includedCount', 'omittedCount', 'charCount', 'sessionRotated', 'externalRunRef',
|
||||
'contextMode', 'promptChars', 'contextPackId', 'deliveryRecordIds', 'sessionProvenance', 'outcomeRefs',
|
||||
'sourceCount', 'sourceHash', 'promptBytes', 'promptHash', 'wirePayloadBytes', 'wirePayloadHash',
|
||||
'connector', 'connectorEventState',
|
||||
'operationId', 'snapshotHash', 'connector', 'connectorEventState', 'taskDecision',
|
||||
].some(key => hasOwn(input.context, key))
|
||||
const rawEvents = Array.isArray(input.events) ? input.events : []
|
||||
const rawSourceIds = Array.isArray(input.sourceMessageIds) ? input.sourceMessageIds : []
|
||||
@@ -403,16 +405,18 @@ function normalizeContinuation(input) {
|
||||
|| !CONTINUATION_STATES.has(state) || !agentRunId || !agentKind
|
||||
|| (hasPublicAgentRunId && !publicAgentRunId)
|
||||
|| (resumeKind === 'role_review_decision' && gateType !== 'decision')
|
||||
|| (resumeKind === 'v4_task_decision'
|
||||
&& (gateType !== 'input' || !hasInvocationBinding || phase !== 'discussion'))
|
||||
|| (resumeKind === 'v4_human_gate'
|
||||
&& (gateType !== 'decision' || !hasStateEpoch || stateEpoch < 1))
|
||||
|| (resumeKind === 'v4_synthesis_recovery'
|
||||
&& (gateType !== 'decision' || !hasStateEpoch))
|
||||
|| (!['v4_human_gate', 'v4_synthesis_recovery'].includes(resumeKind) && hasStateEpoch)
|
||||
|| (invocationFieldCount > 0 && !hasInvocationBinding)
|
||||
|| (hasInvocationBinding && (resumeKind !== 'agent_slot'
|
||||
|| (hasInvocationBinding && (!['agent_slot', 'v4_task_decision'].includes(resumeKind)
|
||||
|| !CONTINUATION_V4_PHASES.has(phase) || !slotId || !operationId
|
||||
|| !SHA256.test(snapshotHash)))
|
||||
|| (gateType === 'input' && !hasRequestBinding)
|
||||
|| (gateType === 'input' && resumeKind !== 'v4_task_decision' && !hasRequestBinding)
|
||||
|| (!hasRequestBinding && [requestId, requestHash, sessionRefHash, sessionProvenanceHash]
|
||||
.some(Boolean))) return undefined
|
||||
return {
|
||||
@@ -441,7 +445,8 @@ function continuationBindingMatchesOrchestration(continuation, orchestration) {
|
||||
}
|
||||
const hasBinding = CONTINUATION_INVOCATION_FIELDS.every(field => hasOwn(continuation || {}, field))
|
||||
if (!hasBinding) return true
|
||||
if (continuation.resumeKind !== 'agent_slot' || orchestration?.version !== 4) return false
|
||||
if (!['agent_slot', 'v4_task_decision'].includes(continuation.resumeKind)
|
||||
|| orchestration?.version !== 4) return false
|
||||
if (!['pending', 'ready', 'resuming'].includes(continuation.state)) return true
|
||||
const slots = orchestration.slots.filter(slot => slot.slotId === continuation.slotId)
|
||||
const orchestrationRound = orchestration.workflow === 'manual'
|
||||
@@ -489,8 +494,9 @@ function normalizeOrchestration(input) {
|
||||
const agreementKinds = normalizeKinds(input.agreementKinds)
|
||||
const attachmentRecipients = normalizeKinds(input.attachmentRecipients)
|
||||
const totalSuccesses = boundedNumber(input.totalSuccesses, 0, 1000000)
|
||||
const executionSequence = boundedNumber(input.executionSequence, 0, 1000000)
|
||||
const v4OnlyFields = [
|
||||
'phase', 'batchId', 'round', 'currentKinds', 'snapshotHash', 'snapshot', 'plan',
|
||||
'phase', 'discussionStyle', 'discussionWriterKind', 'batchId', 'round', 'currentKinds', 'snapshotHash', 'snapshot', 'plan',
|
||||
'slots', 'deliveryWatermarks', 'deliveryState', 'commitState', 'challengeBindings',
|
||||
'synthesisBinding', 'synthesisRecovery', 'convergence', 'candidateCommit',
|
||||
]
|
||||
@@ -498,6 +504,10 @@ function normalizeOrchestration(input) {
|
||||
|| (version === 1 && hasOwn(input, 'collaboration'))
|
||||
|| (version === 2 && workflow !== 'auto')
|
||||
|| (version < 3 && (hasOwn(input, 'template') || hasOwn(input, 'taskGraph')))
|
||||
|| (hasOwn(input, 'executionSequence')
|
||||
&& (!Number.isInteger(input.executionSequence)
|
||||
|| input.executionSequence < 0
|
||||
|| input.executionSequence > 1000000))
|
||||
|| (version < 4 && v4OnlyFields.some(field => hasOwn(input, field)))
|
||||
|| (version === 3 && (workflow !== 'auto' || input.template !== 'task-graph'))) {
|
||||
return undefined
|
||||
@@ -529,6 +539,7 @@ function normalizeOrchestration(input) {
|
||||
attachmentRecipients,
|
||||
totalSuccesses,
|
||||
terminalFailureOccurred: input.terminalFailureOccurred === true,
|
||||
...(hasOwn(input, 'executionSequence') ? { executionSequence } : {}),
|
||||
...(version >= 2 ? { collaboration } : {}),
|
||||
...(version === 3 ? { template: 'task-graph', taskGraph } : {}),
|
||||
}
|
||||
@@ -694,6 +705,11 @@ function hasValidStoredRecordShape(input) {
|
||||
&& (typeof agentRun.context[field] !== 'string'
|
||||
|| !SHA256.test(agentRun.context[field]))) return false
|
||||
}
|
||||
if (hasOwn(agentRun.context, 'operationId')
|
||||
&& cleanId(agentRun.context.operationId) !== agentRun.context.operationId) return false
|
||||
if (hasOwn(agentRun.context, 'snapshotHash')
|
||||
&& (typeof agentRun.context.snapshotHash !== 'string'
|
||||
|| !SHA256.test(agentRun.context.snapshotHash))) return false
|
||||
if (hasOwn(agentRun.context, 'contextPackId')
|
||||
&& normalizeContextPackId(agentRun.context.contextPackId)
|
||||
!== agentRun.context.contextPackId) return false
|
||||
@@ -721,6 +737,12 @@ function hasValidStoredRecordShape(input) {
|
||||
|| canonicalJson(normalizedProvenance)
|
||||
!== canonicalJson(agentRun.context.sessionProvenance)) return false
|
||||
}
|
||||
if (hasOwn(agentRun.context, 'taskDecision')) {
|
||||
try {
|
||||
if (canonicalJson(parseTaskDecision(agentRun.context.taskDecision))
|
||||
!== canonicalJson(agentRun.context.taskDecision)) return false
|
||||
} catch { return false }
|
||||
}
|
||||
if (hasOwn(agentRun.context, 'outcomeRefs')) {
|
||||
if (!isRecord(agentRun.context.outcomeRefs)) return false
|
||||
const normalizedOutcomeRefs = normalizeOutcomeRefs(agentRun.context.outcomeRefs)
|
||||
|
||||
@@ -165,7 +165,10 @@ class RunLedger {
|
||||
))
|
||||
this.loadError = null
|
||||
this.snapshotError = null
|
||||
this.journal = new RunJournal({ storagePath: this.journalPath })
|
||||
this.journal = new RunJournal({
|
||||
storagePath: this.journalPath,
|
||||
compactionBytes: options.journalCompactionBytes,
|
||||
})
|
||||
this.runs = this.load()
|
||||
}
|
||||
|
||||
@@ -373,6 +376,7 @@ class RunLedger {
|
||||
}
|
||||
this.runs = nextRuns
|
||||
this.snapshotError = null
|
||||
this.journal.compactIfNeeded(this.journalBaseline(), timestamp)
|
||||
}
|
||||
|
||||
checkpoint(record) {
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
const DEFAULT_TASK_CONCURRENCY = 2
|
||||
const DEFAULT_WORKSPACE_CONCURRENCY = 2
|
||||
const DEFAULT_GLOBAL_CONCURRENCY = 4
|
||||
const DEFAULT_TASK_CONCURRENCY = null
|
||||
const DEFAULT_WORKSPACE_CONCURRENCY = null
|
||||
const DEFAULT_GLOBAL_CONCURRENCY = null
|
||||
const schedulerPauseTokens = new WeakMap()
|
||||
const schedulerLeaseBindings = new WeakMap()
|
||||
|
||||
function positiveLimit(value, fallback) {
|
||||
if (value == null) return fallback
|
||||
const number = Number(value)
|
||||
if (!Number.isFinite(number) || number < 1) return fallback
|
||||
return Math.min(1024, Math.floor(number))
|
||||
}
|
||||
|
||||
function belowLimit(active, limit) {
|
||||
return limit === null || active < limit
|
||||
}
|
||||
|
||||
function schedulerError(code) {
|
||||
return Object.assign(new Error(code), { code })
|
||||
}
|
||||
@@ -53,6 +58,7 @@ class RunScheduler {
|
||||
this.activeGlobal = 0
|
||||
this.activeTasks = new Map()
|
||||
this.activeWorkspaces = new Map()
|
||||
this.activeWorkspaceWriters = new Set()
|
||||
this.queue = []
|
||||
this.sequence = 0
|
||||
schedulerPauseTokens.set(this, new Map())
|
||||
@@ -64,9 +70,11 @@ class RunScheduler {
|
||||
|
||||
canGrant(entry) {
|
||||
return taskPauseAllows(this, entry)
|
||||
&& this.activeGlobal < this.limits.global
|
||||
&& this.resourceCount(this.activeTasks, entry.taskId) < this.limits.task
|
||||
&& this.resourceCount(this.activeWorkspaces, entry.workspaceKey) < this.limits.workspace
|
||||
&& (entry.permissionMode !== 'workspace-write'
|
||||
|| !this.activeWorkspaceWriters.has(entry.workspaceKey))
|
||||
&& belowLimit(this.activeGlobal, this.limits.global)
|
||||
&& belowLimit(this.resourceCount(this.activeTasks, entry.taskId), this.limits.task)
|
||||
&& belowLimit(this.resourceCount(this.activeWorkspaces, entry.workspaceKey), this.limits.workspace)
|
||||
}
|
||||
|
||||
changeCount(collection, key, change) {
|
||||
@@ -79,12 +87,14 @@ class RunScheduler {
|
||||
this.activeGlobal += 1
|
||||
this.changeCount(this.activeTasks, entry.taskId, 1)
|
||||
this.changeCount(this.activeWorkspaces, entry.workspaceKey, 1)
|
||||
if (entry.permissionMode === 'workspace-write') this.activeWorkspaceWriters.add(entry.workspaceKey)
|
||||
entry.signal?.removeEventListener('abort', entry.abortHandler)
|
||||
let released = false
|
||||
const lease = Object.freeze({
|
||||
leaseId: entry.requestId,
|
||||
taskId: entry.taskId,
|
||||
workspaceKey: entry.workspaceKey,
|
||||
permissionMode: entry.permissionMode,
|
||||
queuedAt: entry.queuedAt,
|
||||
acquiredAt: this.now(),
|
||||
release: () => {
|
||||
@@ -93,6 +103,7 @@ class RunScheduler {
|
||||
this.activeGlobal -= 1
|
||||
this.changeCount(this.activeTasks, entry.taskId, -1)
|
||||
this.changeCount(this.activeWorkspaces, entry.workspaceKey, -1)
|
||||
if (entry.permissionMode === 'workspace-write') this.activeWorkspaceWriters.delete(entry.workspaceKey)
|
||||
this.drain()
|
||||
return true
|
||||
},
|
||||
@@ -100,6 +111,7 @@ class RunScheduler {
|
||||
schedulerLeaseBindings.set(lease, Object.freeze({
|
||||
taskId: entry.taskId,
|
||||
workspaceKey: entry.workspaceKey,
|
||||
permissionMode: entry.permissionMode,
|
||||
signal: entry.signal,
|
||||
}))
|
||||
entry.resolve(lease)
|
||||
@@ -124,9 +136,13 @@ class RunScheduler {
|
||||
#enqueueAcquire(input = {}, pauseToken = null) {
|
||||
let taskId
|
||||
let workspaceKey
|
||||
const permissionMode = input.permissionMode == null ? 'read-only' : input.permissionMode
|
||||
try {
|
||||
taskId = resourceKey(input.taskId, 'RUN_SCHEDULER_TASK_REQUIRED')
|
||||
workspaceKey = resourceKey(input.workspaceKey, 'RUN_SCHEDULER_WORKSPACE_REQUIRED')
|
||||
if (!['read-only', 'workspace-write'].includes(permissionMode)) {
|
||||
throw schedulerError('RUN_SCHEDULER_PERMISSION_INVALID')
|
||||
}
|
||||
} catch (error) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
@@ -137,6 +153,7 @@ class RunScheduler {
|
||||
requestId: `lease-${++this.sequence}`,
|
||||
taskId,
|
||||
workspaceKey,
|
||||
permissionMode,
|
||||
queuedAt: this.now(),
|
||||
signal,
|
||||
resolve,
|
||||
@@ -171,6 +188,7 @@ class RunScheduler {
|
||||
get leaseId() { return activeLease?.leaseId || '' },
|
||||
get taskId() { return activeLease?.taskId || '' },
|
||||
get workspaceKey() { return activeLease?.workspaceKey || '' },
|
||||
get permissionMode() { return activeLease?.permissionMode || '' },
|
||||
get queuedAt() { return activeLease?.queuedAt || 0 },
|
||||
get acquiredAt() { return activeLease?.acquiredAt || 0 },
|
||||
release: () => {
|
||||
|
||||
@@ -172,6 +172,7 @@ function registerDesktopIpc(options) {
|
||||
getAttachmentStore,
|
||||
getAgentConnectors,
|
||||
getCloudAgentRuntime,
|
||||
getCloudAgentBridges,
|
||||
getKnowledgeConnectors,
|
||||
getMainWindow,
|
||||
getOutcomeStore,
|
||||
@@ -362,6 +363,44 @@ function registerDesktopIpc(options) {
|
||||
if (!LOCAL_RUN_IDENTIFIER.test(normalizedRunId)) throw new Error('CLOUD_AGENT_RUN_INVALID')
|
||||
return runtime.cancel(normalizedRunId)
|
||||
})
|
||||
registerTrustedHandle('local-cloud-agent-bridge:list', (...args) => {
|
||||
if (args.length) throw new Error('CLOUD_AGENT_BRIDGE_REQUEST_INVALID')
|
||||
const bridges = getCloudAgentBridges?.()
|
||||
if (!bridges) throw new Error('CLOUD_AGENT_BRIDGE_RUNTIME_UNAVAILABLE')
|
||||
return bridges.list()
|
||||
})
|
||||
registerTrustedHandle('local-cloud-agent-bridge:connect', async (...args) => {
|
||||
if (args.length !== 1 || !args[0] || typeof args[0] !== 'object'
|
||||
|| Array.isArray(args[0])
|
||||
|| Reflect.ownKeys(args[0]).some(key => !['address', 'label'].includes(key))
|
||||
|| typeof args[0].address !== 'string'
|
||||
|| (args[0].label !== undefined && typeof args[0].label !== 'string')) {
|
||||
throw new Error('CLOUD_AGENT_BRIDGE_REQUEST_INVALID')
|
||||
}
|
||||
const bridges = getCloudAgentBridges?.()
|
||||
if (!bridges) throw new Error('CLOUD_AGENT_BRIDGE_RUNTIME_UNAVAILABLE')
|
||||
const result = await bridges.connect(args[0])
|
||||
await refreshLocalAgentState()
|
||||
return result
|
||||
})
|
||||
registerTrustedHandle('local-cloud-agent-bridge:refresh', async (...args) => {
|
||||
if (args.length) throw new Error('CLOUD_AGENT_BRIDGE_REQUEST_INVALID')
|
||||
const bridges = getCloudAgentBridges?.()
|
||||
if (!bridges) throw new Error('CLOUD_AGENT_BRIDGE_RUNTIME_UNAVAILABLE')
|
||||
const result = await bridges.refresh()
|
||||
await refreshLocalAgentState()
|
||||
return result
|
||||
})
|
||||
registerTrustedHandle('local-cloud-agent-bridge:delete', async (...args) => {
|
||||
if (args.length !== 1 || typeof args[0] !== 'string') {
|
||||
throw new Error('CLOUD_AGENT_BRIDGE_REQUEST_INVALID')
|
||||
}
|
||||
const bridges = getCloudAgentBridges?.()
|
||||
if (!bridges) throw new Error('CLOUD_AGENT_BRIDGE_RUNTIME_UNAVAILABLE')
|
||||
const result = bridges.remove(args[0])
|
||||
await refreshLocalAgentState()
|
||||
return result
|
||||
})
|
||||
registerTrustedHandle('local-outcome:record-adoption', (...args) => {
|
||||
if (args.length !== 1) throw new Error('LOCAL_ADOPTION_REQUEST_INVALID')
|
||||
const outcomeStore = getOutcomeStore?.()
|
||||
@@ -385,6 +424,11 @@ function registerDesktopIpc(options) {
|
||||
if (customAgentStore.has(selectedKind)) {
|
||||
return { supported: false, skills: [], total: 0, limit: 0 }
|
||||
}
|
||||
const cloudSkills = getCloudAgentBridges?.()?.skillsForInstance?.(selectedKind)
|
||||
if (cloudSkills !== null && cloudSkills !== undefined) {
|
||||
const skills = cloudSkills.map(skill => ({ ...skill, targetKind: selectedKind }))
|
||||
return { supported: true, skills, total: skills.length, limit: 64 }
|
||||
}
|
||||
return installer.skills(selectedKind)
|
||||
})
|
||||
registerTrustedHandle('local-skill-trust:list', () => {
|
||||
|
||||
@@ -3,6 +3,15 @@ const {
|
||||
} = require('../agents/agent-runtime-contract.cjs')
|
||||
|
||||
const RECENT_VERIFICATION_MS = 24 * 60 * 60 * 1000
|
||||
const AUTH_FAILURE_RETRY_MS = 30 * 1000
|
||||
|
||||
function expiredAuthFailure(runtime, now) {
|
||||
if (runtime?.credentialState !== 'missing') return false
|
||||
const checkedAt = Date.parse(String(runtime.checkedAt || ''))
|
||||
const current = Date.parse(String(now || ''))
|
||||
return !Number.isFinite(checkedAt) || (Number.isFinite(current)
|
||||
&& (current < checkedAt || current - checkedAt >= AUTH_FAILURE_RETRY_MS))
|
||||
}
|
||||
|
||||
function agentVersionIdentified(agent) {
|
||||
if (agent?.custom === true) return true
|
||||
@@ -40,21 +49,48 @@ class LocalWorkspaceAgentCatalog {
|
||||
this.emitChanged = options.emitChanged
|
||||
this.snapshot = options.snapshot
|
||||
this.now = options.now
|
||||
this.refreshTask = null
|
||||
this.refreshAgain = false
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
if (this.refreshTask) {
|
||||
this.refreshAgain = true
|
||||
return this.refreshTask
|
||||
}
|
||||
const task = (async () => {
|
||||
let snapshot
|
||||
do {
|
||||
this.refreshAgain = false
|
||||
snapshot = await this.refreshOnce()
|
||||
} while (this.refreshAgain)
|
||||
return snapshot
|
||||
})()
|
||||
const pending = task.finally(() => {
|
||||
if (this.refreshTask === pending) this.refreshTask = null
|
||||
})
|
||||
this.refreshTask = pending
|
||||
return pending
|
||||
}
|
||||
|
||||
async refreshOnce() {
|
||||
const runtimeAtRefreshStart = new Map(Object.entries(this.state().agentRuntime))
|
||||
const detected = await this.detectAgents()
|
||||
const nativeStates = await Promise.all(detected.map((agent) => {
|
||||
const nativeStates = await Promise.all(detected.map(async (agent) => {
|
||||
const runtime = runtimeAtRefreshStart.get(agent.kind)
|
||||
const sharedProviderReady = Boolean(this.sharedProviderReady(agent.kind))
|
||||
if (sharedProviderReady && runtime?.credentialState === 'missing') {
|
||||
if (sharedProviderReady && runtime?.credentialState === 'missing'
|
||||
&& !expiredAuthFailure(runtime, this.now())) {
|
||||
return { state: 'missing', source: 'runtime-auth-failure' }
|
||||
}
|
||||
if (sharedProviderReady) {
|
||||
return { state: 'ready', source: 'shared-provider' }
|
||||
}
|
||||
return this.credentialState(agent.kind, agent)
|
||||
try {
|
||||
return await this.credentialState(agent.kind, agent)
|
||||
} catch {
|
||||
return { state: 'unknown', source: 'native-probe-failed' }
|
||||
}
|
||||
}))
|
||||
const state = this.state()
|
||||
let recoveredRuntimeCredential = false
|
||||
@@ -65,6 +101,15 @@ class LocalWorkspaceAgentCatalog {
|
||||
const nativeState = ['ready', 'missing'].includes(native?.state) ? native.state : 'unknown'
|
||||
const authoritativeNativeState = native?.source === 'native-auth-status'
|
||||
const sharedProviderRequired = native?.source === 'shared-provider-required'
|
||||
const providerCredentialUnavailable = native?.source === 'provider-credential-unavailable'
|
||||
// Give corrected native credentials a retry after the cooldown, never erase a newer failure.
|
||||
if (expiredAuthFailure(runtime, this.now())
|
||||
&& !(authoritativeNativeState && nativeState === 'ready')
|
||||
&& runtime === runtimeAtRefreshStart.get(agent.kind)) {
|
||||
delete state.agentRuntime[agent.kind]
|
||||
runtime = undefined
|
||||
recoveredRuntimeCredential = true
|
||||
}
|
||||
// A probe that started before a newer runtime failure cannot clear that failure.
|
||||
if (authoritativeNativeState && nativeState === 'ready'
|
||||
&& ['missing', 'unknown'].includes(runtime?.credentialState)
|
||||
@@ -91,23 +136,32 @@ class LocalWorkspaceAgentCatalog {
|
||||
if (!runtimeMissing && sharedProviderReady) credentialState = 'ready'
|
||||
else if (!runtimeMissing && nativeState === 'ready') credentialState = 'ready'
|
||||
else if (!runtimeMissing && verifiedReady && nativeState !== 'missing') credentialState = 'ready'
|
||||
if (providerCredentialUnavailable) credentialState = 'unknown'
|
||||
const installed = true
|
||||
const versionIdentified = agentVersionIdentified(agent)
|
||||
const compatible = agentCompatible(agent)
|
||||
const configured = sharedProviderReady
|
||||
const nativeConfigurationUnknown = !runtimeMissing
|
||||
&& !providerCredentialUnavailable
|
||||
&& nativeState === 'unknown'
|
||||
&& native?.source !== 'native-runtime-unavailable'
|
||||
&& native?.source !== 'native-probe-failed'
|
||||
const configured = providerCredentialUnavailable || sharedProviderReady
|
||||
|| nativeState === 'ready'
|
||||
|| native?.source === 'native-auth-status'
|
||||
|| native?.source === 'native-runtime-unavailable'
|
||||
|| verifiedReady
|
||||
|| runtimeMissing
|
||||
const authenticated = !runtimeMissing && nativeState !== 'missing' && (
|
||||
sharedProviderReady || nativeState === 'ready' || verifiedReady
|
||||
|| nativeConfigurationUnknown
|
||||
const authenticated = !providerCredentialUnavailable && !runtimeMissing && nativeState !== 'missing' && (
|
||||
sharedProviderReady || nativeState === 'ready' || verifiedReady || nativeConfigurationUnknown
|
||||
)
|
||||
const runtimePrerequisitesReady = native?.source !== 'native-runtime-unavailable'
|
||||
&& (native?.source !== 'native-probe-failed' || recentlyVerified(runtime, this.now()))
|
||||
const invocable = installed && versionIdentified && compatible && configured
|
||||
&& authenticated && runtimePrerequisitesReady
|
||||
const verifiedRecently = (authoritativeNativeState && nativeState === 'ready')
|
||||
|| recentlyVerified(runtime, this.now())
|
||||
const verifiedRecently = !providerCredentialUnavailable && (
|
||||
(authoritativeNativeState && nativeState === 'ready') || recentlyVerified(runtime, this.now())
|
||||
)
|
||||
const available = invocable
|
||||
const preferred = state.agentPreferences[agent.kind]?.showInSidebar
|
||||
const capabilities = agentRuntimeCapabilities(agent.kind, {
|
||||
@@ -116,11 +170,14 @@ class LocalWorkspaceAgentCatalog {
|
||||
})
|
||||
let availabilitySource = 'unverified'
|
||||
if (!compatible) availabilitySource = 'incompatible'
|
||||
else if (providerCredentialUnavailable) availabilitySource = 'provider-credential-unavailable'
|
||||
else if (runtimeMissing) availabilitySource = 'runtime-auth-failure'
|
||||
else if (sharedProviderReady) availabilitySource = nativeReadySource || 'shared-provider'
|
||||
else if (nativeState === 'missing') availabilitySource = native.source || 'none'
|
||||
else if (native?.source === 'native-probe-failed') availabilitySource = 'native-probe-failed'
|
||||
else if (nativeReadySource) availabilitySource = nativeReadySource
|
||||
else if (verifiedReady) availabilitySource = 'verified-run'
|
||||
else if (nativeConfigurationUnknown) availabilitySource = 'local-cli'
|
||||
return {
|
||||
...agent,
|
||||
installed,
|
||||
@@ -136,8 +193,7 @@ class LocalWorkspaceAgentCatalog {
|
||||
task: capabilities.task,
|
||||
resumable: capabilities.resumable,
|
||||
capabilities,
|
||||
showInSidebar: available
|
||||
&& (typeof preferred === 'boolean' ? preferred : true),
|
||||
showInSidebar: typeof preferred === 'boolean' ? preferred : true,
|
||||
}
|
||||
})
|
||||
this.setDetectedAgents(agents)
|
||||
@@ -149,10 +205,9 @@ class LocalWorkspaceAgentCatalog {
|
||||
setSidebarVisibility(kind, visible) {
|
||||
const agent = this.detectedAgents().find(item => item.kind === kind)
|
||||
if (!agent) throw new Error('LOCAL_AGENT_NOT_INSTALLED')
|
||||
if (visible && !agent.available) throw new Error('LOCAL_AGENT_UNAVAILABLE')
|
||||
const state = this.state()
|
||||
state.agentPreferences[kind] = { showInSidebar: Boolean(visible) }
|
||||
agent.showInSidebar = agent.available && Boolean(visible)
|
||||
agent.showInSidebar = Boolean(visible)
|
||||
this.save()
|
||||
this.emitChanged()
|
||||
return this.snapshot()
|
||||
@@ -165,7 +220,8 @@ class LocalWorkspaceAgentCatalog {
|
||||
checkedAt: this.now(),
|
||||
}
|
||||
const agent = this.detectedAgents().find(item => item.kind === kind)
|
||||
if (agent) {
|
||||
if (agent && agent.availabilitySource !== 'provider-credential-unavailable'
|
||||
&& !(credentialState === 'unknown' && agent.authenticated === true)) {
|
||||
agent.credentialState = credentialState
|
||||
agent.versionIdentified = agentVersionIdentified(agent)
|
||||
agent.compatible = agentCompatible(agent)
|
||||
@@ -183,8 +239,7 @@ class LocalWorkspaceAgentCatalog {
|
||||
? 'runtime-auth-failure'
|
||||
: 'unverified'
|
||||
const preferred = state.agentPreferences[kind]?.showInSidebar
|
||||
agent.showInSidebar = agent.available
|
||||
&& (typeof preferred === 'boolean' ? preferred : true)
|
||||
agent.showInSidebar = typeof preferred === 'boolean' ? preferred : true
|
||||
}
|
||||
this.save()
|
||||
this.emitChanged()
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
const { createHash, randomUUID } = require('node:crypto')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const { parseTaskDecision } = require('../collaboration/task-decision.cjs')
|
||||
const {
|
||||
agentRuntimeCapabilities,
|
||||
isCodeReviewAgentKind,
|
||||
requireTerminalAgentResult,
|
||||
} = require('../agents/agent-runtime-contract.cjs')
|
||||
@@ -7,7 +11,6 @@ const {
|
||||
nextSessionMeta,
|
||||
normalizeOutcomeRefs,
|
||||
normalizeSessionMeta,
|
||||
shouldRotateSession,
|
||||
} = require('../runs/run-harness.cjs')
|
||||
const {
|
||||
canonicalJson,
|
||||
@@ -46,6 +49,12 @@ const OUTCOME_REF_FIELDS = Object.freeze([
|
||||
'workflowOutcomeRefs',
|
||||
])
|
||||
|
||||
function extractReportedOutputPaths(text) {
|
||||
if (typeof text !== 'string') return []
|
||||
const matches = text.match(/(?:\/(?:Users|home|tmp|private\/tmp)\/[^\s"'<>`\]\[)]+)/g) || []
|
||||
return [...new Set(matches.map(value => value.replace(/[.,;:!?]+$/, '')))]
|
||||
}
|
||||
|
||||
function mergeOutcomeRefs(sources, options = {}) {
|
||||
const merged = {}
|
||||
const seen = new Map(OUTCOME_REF_FIELDS.map(field => [field, new Set()]))
|
||||
@@ -68,29 +77,35 @@ function mergeOutcomeRefs(sources, options = {}) {
|
||||
return normalizeOutcomeRefs(merged)
|
||||
}
|
||||
|
||||
function canUseNativeMediaFallback(error) {
|
||||
const code = String(error?.code || error?.message || '')
|
||||
return /^(?:MEDIA_GENERATION_(?:PROVIDER_UNAVAILABLE|MODEL_UNAVAILABLE|NETWORK_FAILED|INVALID_RESPONSE|FAILED|DOWNLOAD_FAILED)|MEDIA_GENERATION_(?:HTTP|DOWNLOAD_HTTP)_\d+)$/.test(code)
|
||||
}
|
||||
|
||||
function agentReturnedMediaProviderFailure(text) {
|
||||
const normalized = String(text || '').replace(/\s+/g, ' ').trim()
|
||||
if (!normalized) return false
|
||||
return /configured providers do not offer the required media model/i.test(normalized)
|
||||
|| /use a provider credential with access to (?:that|the) image, audio, or video model/i.test(normalized)
|
||||
|| /provider.+(?:does not|do not).+(?:offer|support).+(?:media|image|audio|video).+model/i.test(normalized)
|
||||
}
|
||||
const OPERATION_ID = /^[A-Za-z0-9._:-]{1,120}$/
|
||||
const SHA256 = /^[a-f0-9]{64}$/
|
||||
const V4_PHASES = new Set(['proposal', 'challenge', 'work', 'synthesis', 'verification'])
|
||||
const V4_PHASES = new Set([
|
||||
'proposal', 'discussion', 'challenge', 'work', 'synthesis', 'verification',
|
||||
])
|
||||
const V4_RECEIPT_MARKER_PREFIX = '[[MELDWORK_COLLABORATION'
|
||||
const V4_RECEIPT_MARKER = /\s*\[\[MELDWORK_COLLABORATION(?:_JSON)?:([\s\S]*?)\]\]\s*$/i
|
||||
const V4_RECEIPT_BLOCK = /\s*\[\[MELDWORK_COLLABORATION(?:_JSON)?\]\]([\s\S]*?)\[\[\/MELDWORK_COLLABORATION(?:_JSON)?\]\]\s*$/i
|
||||
const V4_RECEIPT_MARKER = /\s*\[\[MELDWORK_COLLABORATION(?:_JSON)?:([\s\S]*?)\]\]/i
|
||||
const V4_RECEIPT_BLOCK = /\s*\[\[MELDWORK_COLLABORATION(?:_JSON)?\]\]([\s\S]*?)\[\[\/MELDWORK_COLLABORATION(?:_JSON)?\]\]/i
|
||||
const LEGACY_CONSENSUS_MARKER = /^\s*\[\[MELDWORK_CONSENSUS:(?:agree|continue)\]\]\s*$/gim
|
||||
const V4_RECEIPT_MAX_TEXT = 800
|
||||
const V4_RECEIPT_MAX_ITEMS = 16
|
||||
const V4_RECEIPT_MAX_BYTES = 16 * 1024
|
||||
|
||||
function isV4InternalProtocolCommentary(value) {
|
||||
const text = String(value || '').replace(/\s+/g, ' ').trim()
|
||||
if (!text || text.length > 4000 || /\[\[MELDWORK_COLLABORATION/i.test(text)) return false
|
||||
const mentionsControl = /(?:\breceipt\b|structured marker|MELDWORK framework|ExitPlanMode|\u7ed3\u6784\u5316\s*receipt|receipt\s*\u6807\u8bb0)/i.test(text)
|
||||
const describesInternalProcess = /(?:coordination\/self-introduction|not a code implementation task|no plan file|implementation planning|plan mode|waiting for (?:the )?(?:next|subsequent).*(?:phase|instruction)|\u534f\u4f5c\u534f\u8c03\u7c7b\u6587\u672c\u4ea7\u51fa|\u975e\u4ee3\u7801\u5b9e\u73b0\u4efb\u52a1|\u6267\u884c\u8ba1\u5212\u6d41\u7a0b|\u4e0d\u8c03\u7528\s*ExitPlanMode|\u672c\u8f6e\u4ea4\u4ed8|\u7b49\u5f85\u540e\u7eed.*(?:\u9636\u6bb5|\u6307\u4ee4))/i.test(text)
|
||||
return mentionsControl && describesInternalProcess
|
||||
}
|
||||
|
||||
function stripV4InternalProtocolTail(value) {
|
||||
const paragraphs = String(value || '').trim().split(/\n{2,}/)
|
||||
while (paragraphs.length && isV4InternalProtocolCommentary(paragraphs.at(-1))) {
|
||||
paragraphs.pop()
|
||||
}
|
||||
return paragraphs.join('\n\n').trim()
|
||||
}
|
||||
|
||||
function boundedReceiptText(value, limit = V4_RECEIPT_MAX_TEXT) {
|
||||
if (typeof value !== 'string' || value.trim().length > limit) return ''
|
||||
const text = cleanText(value, limit)
|
||||
@@ -107,13 +122,18 @@ function boundedReceiptList(value) {
|
||||
return result
|
||||
}
|
||||
|
||||
function parseV4CollaborationReceipt(result, required = false, expectedPhase = '') {
|
||||
function parseV4CollaborationReceiptStrict(result, required = false, expectedPhase = '', options = {}) {
|
||||
const rawText = typeof result?.text === 'string' ? result.text : ''
|
||||
if (!required) return { text: rawText, collaboration: null }
|
||||
let text = rawText
|
||||
let receipt = result?.collaboration
|
||||
const block = rawText.match(V4_RECEIPT_BLOCK) || rawText.match(V4_RECEIPT_MARKER)
|
||||
if (block) {
|
||||
const markerStart = Number(block.index) || 0
|
||||
const suffix = rawText.slice(markerStart + block[0].length).trim()
|
||||
if (suffix && !isV4InternalProtocolCommentary(suffix)) {
|
||||
throw new Error('LOCAL_RUN_COLLABORATION_RECEIPT_INVALID')
|
||||
}
|
||||
const encoded = String(block[1] || '').trim()
|
||||
if (!encoded || Buffer.byteLength(encoded) > V4_RECEIPT_MAX_BYTES) {
|
||||
throw new Error('LOCAL_RUN_COLLABORATION_RECEIPT_INVALID')
|
||||
@@ -128,11 +148,28 @@ function parseV4CollaborationReceipt(result, required = false, expectedPhase = '
|
||||
if (error?.message === 'LOCAL_RUN_COLLABORATION_RECEIPT_MISMATCH') throw error
|
||||
throw new Error('LOCAL_RUN_COLLABORATION_RECEIPT_INVALID')
|
||||
}
|
||||
text = rawText.slice(0, rawText.length - block[0].length)
|
||||
text = rawText.slice(0, markerStart)
|
||||
} else if (/\[\[MELDWORK_COLLABORATION/i.test(rawText)) {
|
||||
throw new Error('LOCAL_RUN_COLLABORATION_RECEIPT_INVALID')
|
||||
}
|
||||
text = text.replace(LEGACY_CONSENSUS_MARKER, '').replace(/\n{3,}/g, '\n\n').trim()
|
||||
text = stripV4InternalProtocolTail(
|
||||
text.replace(LEGACY_CONSENSUS_MARKER, '').replace(/\n{3,}/g, '\n\n'),
|
||||
)
|
||||
if (receipt == null && options.allowMissingV4Receipt === true && text) {
|
||||
return { text, collaboration: null }
|
||||
}
|
||||
if (receipt == null && expectedPhase === 'proposal'
|
||||
&& options.allowMissingProposalReceipt === true && text) {
|
||||
receipt = {
|
||||
version: 1,
|
||||
phase: 'proposal',
|
||||
summary: 'The Agent returned a visible proposal without a structured receipt.',
|
||||
capabilities: ['Delivered a user-facing proposal'],
|
||||
intendedWork: ['Addressed the current user task'],
|
||||
deliverables: ['Visible Agent response'],
|
||||
dependencies: [],
|
||||
}
|
||||
}
|
||||
if (receipt == null) throw new Error('LOCAL_RUN_COLLABORATION_RECEIPT_REQUIRED')
|
||||
if (!receipt || typeof receipt !== 'object' || Array.isArray(receipt)) {
|
||||
throw new Error('LOCAL_RUN_COLLABORATION_RECEIPT_INVALID')
|
||||
@@ -149,6 +186,7 @@ function parseV4CollaborationReceipt(result, required = false, expectedPhase = '
|
||||
const summary = boundedReceiptText(receipt.summary)
|
||||
const allowed = new Set([
|
||||
'version', 'phase', 'summary',
|
||||
...(phase === 'discussion' ? ['taskDecision'] : []),
|
||||
...(['challenge', 'verification'].includes(phase) ? ['verdict'] : []),
|
||||
...(phase === 'proposal'
|
||||
? ['capabilities', 'intendedWork', 'deliverables', 'dependencies'] : []),
|
||||
@@ -203,6 +241,8 @@ function parseV4CollaborationReceipt(result, required = false, expectedPhase = '
|
||||
version: 1,
|
||||
phase,
|
||||
summary,
|
||||
...(phase === 'discussion' && receipt.taskDecision != null
|
||||
? { taskDecision: parseTaskDecision(receipt.taskDecision) } : {}),
|
||||
...(['challenge', 'verification'].includes(phase) ? { verdict: receipt.verdict } : {}),
|
||||
...(phase === 'proposal' ? {
|
||||
capabilities: proposalList('capabilities', true),
|
||||
@@ -212,7 +252,15 @@ function parseV4CollaborationReceipt(result, required = false, expectedPhase = '
|
||||
} : {}),
|
||||
...(phase === 'challenge' ? {
|
||||
...(Array.isArray(receipt.proposedAssignments)
|
||||
? { proposedAssignments: receipt.proposedAssignments } : {}),
|
||||
? {
|
||||
proposedAssignments: receipt.proposedAssignments.map(assignment => (
|
||||
assignment && typeof assignment === 'object' && !Array.isArray(assignment)
|
||||
&& assignment.role === 'finalizer'
|
||||
? { ...assignment, role: 'integrator' }
|
||||
: assignment
|
||||
)),
|
||||
}
|
||||
: {}),
|
||||
...(receipt.finalizerKind ? { finalizerKind: boundedReceiptText(receipt.finalizerKind, 120) } : {}),
|
||||
...(Array.isArray(receipt.verifierKinds) ? { verifierKinds: boundedList(receipt.verifierKinds) } : {}),
|
||||
...(receipt.supportedPlanHash ? { supportedPlanHash: receipt.supportedPlanHash } : {}),
|
||||
@@ -227,6 +275,39 @@ function parseV4CollaborationReceipt(result, required = false, expectedPhase = '
|
||||
return { text, collaboration: Object.freeze(JSON.parse(canonicalJson(normalized))) }
|
||||
}
|
||||
|
||||
function parseV4CollaborationReceipt(result, required = false, expectedPhase = '', options = {}) {
|
||||
try {
|
||||
return parseV4CollaborationReceiptStrict(result, required, expectedPhase, options)
|
||||
} catch (error) {
|
||||
const code = String(error?.message || '')
|
||||
if (expectedPhase !== 'proposal'
|
||||
|| options.allowMissingProposalReceipt !== true
|
||||
|| !['LOCAL_RUN_COLLABORATION_RECEIPT_INVALID', 'LOCAL_RUN_COLLABORATION_RECEIPT_REQUIRED']
|
||||
.includes(code)) {
|
||||
throw error
|
||||
}
|
||||
const rawText = typeof result?.text === 'string' ? result.text : ''
|
||||
const markerIndex = rawText.search(/\[\[MELDWORK_COLLABORATION/i)
|
||||
const visibleText = (markerIndex >= 0 ? rawText.slice(0, markerIndex) : rawText)
|
||||
.replace(LEGACY_CONSENSUS_MARKER, '')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim()
|
||||
if (!visibleText) throw error
|
||||
return {
|
||||
text: visibleText,
|
||||
collaboration: Object.freeze({
|
||||
version: 1,
|
||||
phase: 'proposal',
|
||||
summary: 'The Agent returned a visible proposal without a valid structured receipt.',
|
||||
capabilities: ['Delivered a user-facing proposal'],
|
||||
intendedWork: ['Addressed the current user task'],
|
||||
deliverables: ['Visible Agent response'],
|
||||
dependencies: [],
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function attachInvocationFailure(error, input) {
|
||||
if (!error || (typeof error !== 'object' && typeof error !== 'function')) return error
|
||||
const existing = error.invocationFailure && typeof error.invocationFailure === 'object'
|
||||
@@ -246,7 +327,8 @@ function attachInvocationFailure(error, input) {
|
||||
}
|
||||
|
||||
function isolatedInvocationContext(context) {
|
||||
if (!['isolated', 'frozen'].includes(context?.sessionPolicy)) return null
|
||||
if (!['isolated', 'frozen'].includes(context?.sessionPolicy)
|
||||
&& !(context?.v4 === true && typeof context.promptOverride === 'string')) return null
|
||||
const promptOverride = typeof context.promptOverride === 'string'
|
||||
? context.promptOverride
|
||||
: ''
|
||||
@@ -259,7 +341,7 @@ function isolatedInvocationContext(context) {
|
||||
return {
|
||||
promptOverride,
|
||||
contextPackId,
|
||||
policy: context.sessionPolicy,
|
||||
policy: ['isolated', 'frozen'].includes(context?.sessionPolicy) ? context.sessionPolicy : '',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,7 +353,7 @@ function createdSessionProvenance(group, taskId, stateless = false) {
|
||||
}
|
||||
}
|
||||
return {
|
||||
scope: group.conversationType === 'direct' ? 'conversation' : 'task',
|
||||
scope: 'conversation',
|
||||
reuse: false,
|
||||
origin: 'created',
|
||||
originTaskId: taskId || null,
|
||||
@@ -409,7 +491,9 @@ class LocalWorkspaceAgentInvocation {
|
||||
this.detectedAgents = options.detectedAgents
|
||||
this.activeRuns = options.activeRuns
|
||||
this.runAgentTimeoutMs = options.runAgentTimeoutMs
|
||||
this.runAgentToolTimeoutMs = options.runAgentToolTimeoutMs
|
||||
this.runAbortGraceMs = options.runAbortGraceMs
|
||||
this.defaultYolo = options.defaultYolo !== false
|
||||
this.captureAgentOutputs = options.captureAgentOutputs
|
||||
this.captureArtifactOutputs = options.captureArtifactOutputs
|
||||
this.captureAgentOutcomeDescriptors = options.captureAgentOutcomeDescriptors
|
||||
@@ -444,7 +528,7 @@ class LocalWorkspaceAgentInvocation {
|
||||
this.completeHumanGateContinuation = options.completeHumanGateContinuation
|
||||
this.connectorRuntime = options.connectorRuntime || null
|
||||
this.attachmentSupport = options.attachmentSupport || (() => ({}))
|
||||
this.generateMedia = typeof options.generateMedia === 'function' ? options.generateMedia : null
|
||||
this.activeAgentSnapshots = new Map()
|
||||
}
|
||||
|
||||
commitSessionState(mutator) {
|
||||
@@ -466,9 +550,24 @@ class LocalWorkspaceAgentInvocation {
|
||||
const activeRun = this.activeRuns.get(group.id)
|
||||
const taskId = cleanText(activeRun?.taskId || context.taskId || threadRootId, 120)
|
||||
if (!taskId) throw new Error('LOCAL_RUN_TASK_INVALID')
|
||||
let workspacePath = group.workdir ? path.resolve(group.workdir) : group.id
|
||||
try { workspacePath = fs.realpathSync(workspacePath) } catch { /* runtime validates unavailable directories */ }
|
||||
// Direct chats are independent execution surfaces. Scope their scheduler
|
||||
// resource to the chat so one writable chat cannot block another Agent.
|
||||
const schedulerWorkspaceKey = group.conversationType === 'direct'
|
||||
? `${workspacePath}\u0000direct:${group.id}`
|
||||
: workspacePath
|
||||
const workspaceKey = createHash('sha256')
|
||||
.update(String(group.workdir || group.id))
|
||||
.update(String(schedulerWorkspaceKey))
|
||||
.digest('hex')
|
||||
const writerKind = cleanText(context.singleWriterKind || context.writerKind, 80)
|
||||
const permissionMode = group.allowWrite === true
|
||||
&& (context.permissionMode == null || context.permissionMode === 'workspace-write')
|
||||
&& (!writerKind || writerKind === kind)
|
||||
&& isolatedInvocationContext(context)?.policy !== 'isolated'
|
||||
&& !isCodeReviewAgentKind(kind)
|
||||
? 'workspace-write' : 'read-only'
|
||||
context = { ...context, permissionMode }
|
||||
const agentController = new AbortController()
|
||||
const registration = { agentRunId: '' }
|
||||
let queuedAbortHandler = null
|
||||
@@ -482,6 +581,7 @@ class LocalWorkspaceAgentInvocation {
|
||||
return await this.runScheduler.withLease({
|
||||
taskId,
|
||||
workspaceKey,
|
||||
permissionMode,
|
||||
signal: agentController.signal,
|
||||
}, (lease) => {
|
||||
if (signal && queuedAbortHandler) {
|
||||
@@ -511,7 +611,24 @@ class LocalWorkspaceAgentInvocation {
|
||||
async invokeLeased(
|
||||
group, kind, mode, signal, threadRootId = '', context = {}, invocation = {},
|
||||
) {
|
||||
const agent = this.detectedAgents().find(item => item.kind === kind && item.available)
|
||||
const detected = this.detectedAgents()
|
||||
const activeRun = this.activeRuns.get(group.id)
|
||||
const candidate = detected.find(item => item.kind === kind)
|
||||
const snapshotKey = `${group.id}:${activeRun?.runId || 'active'}:${kind}`
|
||||
if (candidate) this.activeAgentSnapshots.set(snapshotKey, { ...candidate })
|
||||
const snapshot = this.activeAgentSnapshots.get(snapshotKey)
|
||||
const agent = detected.find(item => item.kind === kind && item.available)
|
||||
|| (activeRun?.targetKinds?.includes(kind)
|
||||
&& candidate
|
||||
&& candidate.installed !== false
|
||||
&& candidate.compatibilityState !== 'incompatible'
|
||||
&& candidate.credentialState !== 'missing'
|
||||
&& candidate.availabilitySource !== 'runtime-auth-failure'
|
||||
&& candidate.availabilitySource !== 'none'
|
||||
? candidate
|
||||
: activeRun?.targetKinds?.includes(kind) && !candidate && snapshot
|
||||
? snapshot
|
||||
: null)
|
||||
if (!agent) throw new Error('LOCAL_AGENT_UNAVAILABLE')
|
||||
const reviewOnly = isCodeReviewAgentKind(kind)
|
||||
const invocationContext = isolatedInvocationContext(context)
|
||||
@@ -524,9 +641,12 @@ class LocalWorkspaceAgentInvocation {
|
||||
: (context.permissionMode === 'workspace-write' ? 'workspace-write' : 'read-only')
|
||||
const writerKind = cleanText(context.singleWriterKind || context.writerKind, 80)
|
||||
const writerAllowed = !writerKind || writerKind === kind
|
||||
const supportsWorkspaceWrite = agentRuntimeCapabilities(kind, { agent })
|
||||
.permissionModes.includes('workspace-write')
|
||||
const allowWrite = group.allowWrite === true
|
||||
&& requestedPermission === 'workspace-write'
|
||||
&& writerAllowed
|
||||
&& supportsWorkspaceWrite
|
||||
&& !reviewOnly
|
||||
&& !isolated
|
||||
const skillInputTypes = new Set(['text'])
|
||||
@@ -546,10 +666,18 @@ class LocalWorkspaceAgentInvocation {
|
||||
})
|
||||
}
|
||||
const state = this.state()
|
||||
const activeRun = this.activeRuns.get(group.id)
|
||||
const taskId = cleanText(activeRun?.taskId || context.taskId || threadRootId, 120)
|
||||
const responseVersionRootId = cleanText(context.responseVersionRootId, 100)
|
||||
const round = mode === 'auto' ? (activeRun?.currentRound || 1) : 0
|
||||
const responseVersionRootId = cleanText(context.responseVersionRootId, 100)
|
||||
|| (mode === 'auto'
|
||||
? `response-${sha256(JSON.stringify([
|
||||
group.id,
|
||||
threadRootId,
|
||||
kind,
|
||||
round,
|
||||
cleanText(context.phase, 40) || 'response',
|
||||
])).slice(0, 48)}`
|
||||
: '')
|
||||
if (!isolated && !frozen) {
|
||||
const requiredContext = this.packedPromptContext(
|
||||
group.id, '', threadRootId, context.contextOptions || {},
|
||||
@@ -577,9 +705,9 @@ class LocalWorkspaceAgentInvocation {
|
||||
}
|
||||
: null
|
||||
const idempotencyMode = agent.idempotencyMode === 'durable' ? 'durable' : 'none'
|
||||
const resolvedSession = reviewOnly || isolated
|
||||
const resolvedSession = reviewOnly
|
||||
? {
|
||||
key: this.sessionKey(group.id, kind, group.conversationType === 'direct' ? '' : taskId),
|
||||
key: this.sessionKey(group.id, kind),
|
||||
sessionRef: '',
|
||||
sessionMeta: {},
|
||||
provenance: createdSessionProvenance(group, taskId, true),
|
||||
@@ -601,7 +729,9 @@ class LocalWorkspaceAgentInvocation {
|
||||
&& !resumedConnectorGate
|
||||
? context.resumedGate
|
||||
: null
|
||||
const sessionNeedsRotation = sessionRef && shouldRotateSession(sessionMeta)
|
||||
// A conversation owns one native session for its lifetime. Rebuild only
|
||||
// when the Agent reports that the existing native session is invalid.
|
||||
const sessionNeedsRotation = false
|
||||
if (resumedPermission) {
|
||||
const requestHash = sha256(canonicalJson(resumedPermission.request))
|
||||
const persistedBinding = {
|
||||
@@ -646,7 +776,7 @@ class LocalWorkspaceAgentInvocation {
|
||||
const hermesNeedsLegacy = kind === 'hermes' && sessionTransport === 'acp'
|
||||
&& (!HERMES_WORKSPACE_ACP_ENABLED
|
||||
|| agent.acpAvailable === false
|
||||
|| (context.attachments || []).length > 0)
|
||||
)
|
||||
if (resumedPermission && hermesNeedsLegacy) {
|
||||
throw new Error('LOCAL_RUN_PERMISSION_RESUME_UNAVAILABLE')
|
||||
}
|
||||
@@ -689,7 +819,13 @@ class LocalWorkspaceAgentInvocation {
|
||||
idempotencyMode,
|
||||
})
|
||||
}
|
||||
let transcriptAfterKind = !sessionRotated && storedSessionRef && storedSessionRef === sessionRef
|
||||
const knownSessionHistory = group.conversationType === 'direct'
|
||||
|| sessionProvenance.completeness !== 'unknown-legacy'
|
||||
const sameTaskSession = !taskId
|
||||
|| taskId === sessionMeta.originTaskId
|
||||
|| (Array.isArray(sessionMeta.inheritedTaskIds) && sessionMeta.inheritedTaskIds.includes(taskId))
|
||||
let transcriptAfterKind = knownSessionHistory && !sessionRotated && storedSessionRef && storedSessionRef === sessionRef
|
||||
&& (!sessionMeta.lastDeliveredMessageId || !sameTaskSession)
|
||||
? kind
|
||||
: ''
|
||||
// Group Sessions already contain the immutable bootstrap instructions after
|
||||
@@ -698,9 +834,13 @@ class LocalWorkspaceAgentInvocation {
|
||||
let promptMode = group.conversationType !== 'direct'
|
||||
&& Boolean(sessionRef)
|
||||
&& !sessionRotated
|
||||
&& knownSessionHistory
|
||||
&& sessionMeta.turns > 0
|
||||
? 'continuation'
|
||||
: 'bootstrap'
|
||||
const sessionContextOptions = (!isolated && !frozen && promptMode === 'continuation' && sameTaskSession)
|
||||
? { ...(context.contextOptions || {}), afterMessageId: sessionMeta.lastDeliveredMessageId || '' }
|
||||
: (context.contextOptions || {})
|
||||
let packedContext = isolated || frozen
|
||||
? {
|
||||
text: v4Prompt,
|
||||
@@ -721,7 +861,7 @@ class LocalWorkspaceAgentInvocation {
|
||||
continuationText: v4Prompt,
|
||||
}
|
||||
: this.packedPromptContext(
|
||||
group.id, transcriptAfterKind, threadRootId, context.contextOptions || {},
|
||||
group.id, transcriptAfterKind, threadRootId, sessionContextOptions,
|
||||
)
|
||||
if (!isolated && !frozen) {
|
||||
packedContext = withCollaborationPackage(
|
||||
@@ -768,6 +908,8 @@ class LocalWorkspaceAgentInvocation {
|
||||
let watchdogReject = null
|
||||
let watchdogLastProgressAt = Date.now()
|
||||
let watchdogPaused = false
|
||||
let watchdogEstablished = false
|
||||
let watchdogToolActive = false
|
||||
let parentAbortHandler = null
|
||||
let parentAbortPromise = null
|
||||
let capturePromise = null
|
||||
@@ -781,6 +923,19 @@ class LocalWorkspaceAgentInvocation {
|
||||
let resumedPermissionUsed = false
|
||||
let resumedPermissionError = null
|
||||
const startedAt = Date.now()
|
||||
// Automatic discussions must make progress between rounds even when an
|
||||
// Agent keeps emitting heartbeat events without ever returning a result.
|
||||
// The watchdog is an inactivity timeout: streamed text, tool lifecycle,
|
||||
// and structured progress refresh it. Raw local process activity alone is
|
||||
// not proof of progress because some CLIs emit empty heartbeats forever.
|
||||
// Heartbeats keep a process alive long enough to prove that it started,
|
||||
// but cannot keep a turn alive forever without substantive output. Once a
|
||||
// real runtime event or structured progress arrives, the deadline is
|
||||
// lifted and the inactivity watchdog becomes event-driven.
|
||||
const hardDeadlineAt = mode === 'auto' && Number.isFinite(this.runAgentTimeoutMs)
|
||||
&& this.runAgentTimeoutMs > 0
|
||||
? startedAt + this.runAgentTimeoutMs
|
||||
: Number.POSITIVE_INFINITY
|
||||
if (signal) {
|
||||
parentAbortPromise = new Promise((_, reject) => {
|
||||
parentAbortHandler = () => {
|
||||
@@ -797,13 +952,20 @@ class LocalWorkspaceAgentInvocation {
|
||||
if (watchdogTimer || watchdogPaused || agentController.signal.aborted
|
||||
|| !Number.isFinite(this.runAgentTimeoutMs) || this.runAgentTimeoutMs <= 0) return
|
||||
const elapsedSinceProgress = Date.now() - watchdogLastProgressAt
|
||||
const remainingMs = Math.max(0, this.runAgentTimeoutMs - elapsedSinceProgress)
|
||||
const inactivityTimeoutMs = watchdogToolActive
|
||||
? this.runAgentToolTimeoutMs
|
||||
: this.runAgentTimeoutMs
|
||||
const inactivityRemainingMs = Math.max(0, inactivityTimeoutMs - elapsedSinceProgress)
|
||||
const hardRemainingMs = Math.max(
|
||||
0, (watchdogEstablished ? Number.POSITIVE_INFINITY : hardDeadlineAt) - Date.now(),
|
||||
)
|
||||
const remainingMs = Math.min(inactivityRemainingMs, hardRemainingMs)
|
||||
watchdogTimer = setTimeout(() => {
|
||||
watchdogTimer = null
|
||||
if (parentAbortObserved || signal?.aborted || watchdogPaused
|
||||
|| agentController.signal.aborted) return
|
||||
// This is an inactivity/stall timeout. Any progress signal refreshes the
|
||||
// window, so a slow tool or streamed response can run indefinitely.
|
||||
// This is an inactivity/stall timeout. Substantive progress refreshes
|
||||
// the window, while an unmatched tool lifecycle remains bounded.
|
||||
watchdogTimedOut = true
|
||||
watchdogError = new Error('LOCAL_AGENT_TIMEOUT')
|
||||
agentController.abort()
|
||||
@@ -824,6 +986,12 @@ class LocalWorkspaceAgentInvocation {
|
||||
armWatchdog()
|
||||
}
|
||||
}
|
||||
const establishWatchdog = () => {
|
||||
if (watchdogEstablished || agentController.signal.aborted) return
|
||||
watchdogEstablished = true
|
||||
clearTimeout(watchdogTimer)
|
||||
watchdogTimer = null
|
||||
}
|
||||
const resumeWatchdog = () => {
|
||||
watchdogPaused = false
|
||||
watchdogLastProgressAt = Date.now()
|
||||
@@ -848,6 +1016,7 @@ class LocalWorkspaceAgentInvocation {
|
||||
const onProgress = (step) => {
|
||||
if (agentCallbacksClosed || agentController.signal.aborted
|
||||
|| !activeRun || this.activeRuns.get(group.id) !== activeRun) return
|
||||
establishWatchdog()
|
||||
noteWatchdogProgress()
|
||||
const next = [...attemptProgress]
|
||||
const progressId = typeof step?.id === 'string' && /^[A-Za-z0-9._:-]{1,100}$/.test(step.id)
|
||||
@@ -875,6 +1044,21 @@ class LocalWorkspaceAgentInvocation {
|
||||
|| !harness || !harnessRun || !rawEvent) return
|
||||
const event = harness.ingest(kind, round, rawEvent, harnessRun.agentRunId)
|
||||
if (!event) return
|
||||
// Once a connector has produced a real runtime event, the process is
|
||||
// demonstrably alive. Active tools use a longer shared inactivity window.
|
||||
establishWatchdog()
|
||||
const eventType = String(event.type || '').toLowerCase()
|
||||
const eventStatus = String(event.status || '').toLowerCase()
|
||||
if (['tool_start', 'tool_update'].includes(eventType)
|
||||
&& ['queued', 'running', 'waiting', 'in_progress', 'streaming'].includes(eventStatus)) {
|
||||
watchdogToolActive = true
|
||||
noteWatchdogProgress()
|
||||
} else if (eventType === 'tool_result_summary'
|
||||
|| (eventType === 'status' && ['completed', 'failed', 'stopped', 'timeout', 'interrupted']
|
||||
.includes(eventStatus))) {
|
||||
watchdogToolActive = false
|
||||
noteWatchdogProgress()
|
||||
}
|
||||
this.emitRunEvent(event)
|
||||
this.armAgentSilence(activeRun, kind, round, harnessRun.agentRunId)
|
||||
if (event.type !== 'answer_delta' || event.seq % 8 === 0) {
|
||||
@@ -965,8 +1149,6 @@ class LocalWorkspaceAgentInvocation {
|
||||
let outputBaseline = null
|
||||
let artifactOutputBaseline = null
|
||||
let stagedInputs = null
|
||||
let generatedMedia = null
|
||||
let nativeMediaFallback = false
|
||||
let result
|
||||
let operationStarted = false
|
||||
let sideEffectsStarted = false
|
||||
@@ -1013,6 +1195,16 @@ class LocalWorkspaceAgentInvocation {
|
||||
...deliveredContext.context,
|
||||
contextMode: promptMode,
|
||||
sessionRotated,
|
||||
...(context.phase ? { phase: context.phase } : {}),
|
||||
...(Number.isInteger(context.executionSequence)
|
||||
? { executionSequence: context.executionSequence }
|
||||
: {}),
|
||||
...(v4AgentSlotBinding
|
||||
? {
|
||||
operationId: v4AgentSlotBinding.operationId,
|
||||
snapshotHash: v4AgentSlotBinding.snapshotHash,
|
||||
}
|
||||
: {}),
|
||||
...runtimeContext,
|
||||
...deliveryContext,
|
||||
...connectorContext,
|
||||
@@ -1066,21 +1258,6 @@ class LocalWorkspaceAgentInvocation {
|
||||
/* artifact output capture is best effort */
|
||||
}
|
||||
}
|
||||
if (allowWrite && context.mediaRequest && this.generateMedia) {
|
||||
sideEffectsStarted = true
|
||||
try {
|
||||
generatedMedia = await abortableOperation(() => this.generateMedia({
|
||||
kind,
|
||||
request: context.mediaRequest,
|
||||
workdir: group.workdir,
|
||||
signal: agentController.signal,
|
||||
onEvent: emitRuntimeEvent,
|
||||
}), agentController.signal)
|
||||
} catch (error) {
|
||||
if (agentController.signal.aborted || !canUseNativeMediaFallback(error)) throw error
|
||||
nativeMediaFallback = true
|
||||
}
|
||||
}
|
||||
const nativeImageLimit = Math.max(
|
||||
0,
|
||||
Math.floor(Number(this.attachmentSupport(kind)?.image) || 0),
|
||||
@@ -1101,24 +1278,21 @@ class LocalWorkspaceAgentInvocation {
|
||||
].join('\n')
|
||||
const buildPrompt = (afterKind, contextPackage) => isolated || frozen
|
||||
? v4Prompt
|
||||
: group.conversationType === 'direct'
|
||||
? (sessionRotated
|
||||
? (contextPackage.continuationText || contextPackage.stableText
|
||||
|| contextPackage.currentTaskText)
|
||||
: contextPackage.currentTaskText)
|
||||
: [
|
||||
this.promptFor(
|
||||
group, kind, context.completionPolicy === 'typed' ? 'manual' : mode,
|
||||
threadRootId, context.skillHints || [],
|
||||
context.knowledgeBaseHints || [], afterKind, contextPackage, promptMode,
|
||||
activeRun?.unlimitedRounds === true,
|
||||
),
|
||||
context.v4 === true && v4Prompt
|
||||
? v4Prompt
|
||||
: this.promptFor(
|
||||
group, kind, context.completionPolicy === 'typed' ? 'manual' : mode,
|
||||
threadRootId, context.skillHints || [],
|
||||
context.knowledgeBaseHints || [], afterKind, contextPackage, promptMode,
|
||||
activeRun?.unlimitedRounds === true,
|
||||
),
|
||||
stagedAgentInputPrompt(stagedInputs),
|
||||
generatedMedia
|
||||
? `Meldwork generated and will attach ${generatedMedia.filename}. Confirm the delivered media briefly; do not claim a different file was created.`
|
||||
: '',
|
||||
nativeMediaFallback
|
||||
? [
|
||||
'Meldwork shared media generator was unavailable. Use your native media-generation tools or installed local skills to fulfill the current request.',
|
||||
'Write or copy every real generated media file into .meldwork-output/ so Meldwork can validate and attach it to the reply.',
|
||||
'Do not return only a prompt and do not claim success unless a real media file was created. If no native media tool is available, explain that accurately.',
|
||||
].join('\n')
|
||||
: '',
|
||||
runtimeInstruction ? `Harness recovery task:\n${runtimeInstruction}` : '',
|
||||
regenerationInstruction
|
||||
? `Fresh response instruction:\n${regenerationInstruction}`
|
||||
@@ -1262,10 +1436,13 @@ class LocalWorkspaceAgentInvocation {
|
||||
}
|
||||
const runOptions = {
|
||||
sessionRef,
|
||||
...(Number.isInteger(context.executionSequence)
|
||||
? { executionSequence: context.executionSequence }
|
||||
: {}),
|
||||
onSessionRef: (nextSessionRef, metadata = {}) => {
|
||||
if (agentCallbacksClosed || agentController.signal.aborted) return
|
||||
noteWatchdogProgress()
|
||||
if (reviewOnly || isolated) return
|
||||
if (reviewOnly) return
|
||||
const transport = ['legacy', 'acp'].includes(metadata?.transport)
|
||||
? metadata.transport
|
||||
: ''
|
||||
@@ -1278,17 +1455,39 @@ class LocalWorkspaceAgentInvocation {
|
||||
}))
|
||||
},
|
||||
onSessionInvalidated: () => {
|
||||
if (kind !== 'hermes' || isolated || resumedPermission) return null
|
||||
if (kind !== 'hermes' || reviewOnly || resumedPermission) return null
|
||||
return { prompt: rebuildFreshSession() }
|
||||
},
|
||||
signal: agentController.signal,
|
||||
sandbox: allowWrite ? 'workspace-write' : 'read-only',
|
||||
operationId,
|
||||
onActivity: noteWatchdogProgress,
|
||||
onActivity: () => {
|
||||
// A cloud request has no local process events while the remote CLI
|
||||
// is working. Its activity callback is therefore the first proof
|
||||
// that the run has started and must release the initial deadline.
|
||||
if (agent.cloud === true) establishWatchdog()
|
||||
if (agent.cloud === true || !watchdogToolActive) {
|
||||
noteWatchdogProgress()
|
||||
}
|
||||
},
|
||||
onProgress,
|
||||
onEvent: emitRuntimeEvent,
|
||||
onOutboundPayload: recordOutboundPayload,
|
||||
onPermissionRequest: (request, permissionContext = {}) => {
|
||||
// Permission prompts default to yolo for every local invocation.
|
||||
// Callers can opt into an interactive Gate explicitly with
|
||||
// `yolo: false`; sandbox and workspace authorization remain enforced
|
||||
// before this callback is reached.
|
||||
if ((context.yolo ?? this.defaultYolo) !== false) {
|
||||
const option = Array.isArray(request?.options)
|
||||
? request.options.find(candidate => candidate?.kind === 'allow_once')
|
||||
|| request.options.find(candidate => candidate?.kind === 'allow_always')
|
||||
|| request.options[0]
|
||||
: null
|
||||
if (option?.optionId) {
|
||||
return Promise.resolve({ status: 'approved', optionId: option.optionId })
|
||||
}
|
||||
}
|
||||
const pending = Promise.resolve().then(async () => {
|
||||
if (resumedPermission && !resumedPermissionUsed) {
|
||||
if (!matchesResumedPermission(request, resumedPermission)) {
|
||||
@@ -1336,12 +1535,16 @@ class LocalWorkspaceAgentInvocation {
|
||||
return pending
|
||||
},
|
||||
sessionTransport,
|
||||
...(kind === 'workbuddy' && Number.isInteger(context.maxInternalTurns)
|
||||
? { maxTurns: context.maxInternalTurns }
|
||||
: {}),
|
||||
attachments: isolated || frozen ? [] : (stagedInputs?.nativeImagePaths || []),
|
||||
// ACP runtimes are shared by the stable group/task session key. OpenClaw
|
||||
// is excluded because its gateway wrapper owns the process lifetime and
|
||||
// is intentionally torn down after each invocation.
|
||||
...(kind !== 'openclaw' ? { acpPersistenceKey: key } : {}),
|
||||
...(kind === 'hermes'
|
||||
? {
|
||||
acpPersistenceKey: key,
|
||||
hermesAcpAvailable: HERMES_WORKSPACE_ACP_ENABLED && agent.acpAvailable !== false,
|
||||
}
|
||||
? { hermesAcpAvailable: HERMES_WORKSPACE_ACP_ENABLED && agent.acpAvailable !== false }
|
||||
: {}),
|
||||
}
|
||||
const runCurrentSession = () => {
|
||||
@@ -1359,7 +1562,12 @@ class LocalWorkspaceAgentInvocation {
|
||||
...currentRunOptions,
|
||||
runId: activeRun.runId,
|
||||
agentRunId: harnessRun.agentRunId,
|
||||
onActivity: noteWatchdogProgress,
|
||||
onActivity: () => {
|
||||
if (agent.cloud === true) establishWatchdog()
|
||||
if (agent.cloud === true || !watchdogToolActive) {
|
||||
noteWatchdogProgress()
|
||||
}
|
||||
},
|
||||
onConnectorState: (nextContext) => {
|
||||
noteWatchdogProgress()
|
||||
connectorContext = nextContext
|
||||
@@ -1535,26 +1743,18 @@ class LocalWorkspaceAgentInvocation {
|
||||
this.markRuntimeCredential(kind, 'ready')
|
||||
|
||||
const collaborationReply = parseV4CollaborationReceipt(
|
||||
result,
|
||||
context.v4 === true,
|
||||
context.phase || '',
|
||||
result,
|
||||
context.v4 === true,
|
||||
context.phase || '',
|
||||
{
|
||||
allowMissingProposalReceipt: context.allowMissingProposalReceipt === true,
|
||||
allowMissingV4Receipt: context.allowMissingV4Receipt === true,
|
||||
},
|
||||
)
|
||||
const reply = mode === 'auto' && context.completionPolicy !== 'typed'
|
||||
? parseAutoReply(collaborationReply.text)
|
||||
: { text: collaborationReply.text, consensus: false }
|
||||
if (!reply.text) throw new Error('LOCAL_AGENT_EMPTY_RESPONSE')
|
||||
if (allowWrite && context.mediaRequest && this.generateMedia && nativeMediaFallback
|
||||
&& !generatedMedia && agentReturnedMediaProviderFailure(reply.text)) {
|
||||
sideEffectsStarted = true
|
||||
generatedMedia = await abortableOperation(() => this.generateMedia({
|
||||
kind,
|
||||
request: context.mediaRequest,
|
||||
workdir: group.workdir,
|
||||
signal: agentController.signal,
|
||||
onEvent: emitRuntimeEvent,
|
||||
}), agentController.signal)
|
||||
reply.text = `Meldwork generated and attached ${generatedMedia.filename}.`
|
||||
}
|
||||
const progress = attemptProgress.length ? attemptProgress : result.progress
|
||||
const toolCalls = cleanProgressSteps(progress).map(step => ({
|
||||
...step,
|
||||
@@ -1594,6 +1794,7 @@ class LocalWorkspaceAgentInvocation {
|
||||
baseline: outputBaseline,
|
||||
startedAt,
|
||||
agentKind: kind,
|
||||
reportedPaths: extractReportedOutputPaths(reply.text),
|
||||
signal: agentController.signal,
|
||||
}))
|
||||
importPromise.catch(() => {})
|
||||
@@ -1672,6 +1873,8 @@ class LocalWorkspaceAgentInvocation {
|
||||
promptHash: sha256(prompt),
|
||||
externalRunRef: result.externalRunRef,
|
||||
outcomeRefs: auditOutcomeRefs,
|
||||
...(collaborationReply.collaboration?.taskDecision
|
||||
? { taskDecision: collaborationReply.collaboration.taskDecision } : {}),
|
||||
})
|
||||
const messageMetadata = {
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
@@ -1702,13 +1905,14 @@ class LocalWorkspaceAgentInvocation {
|
||||
pendingMessage.metadata,
|
||||
)
|
||||
: null
|
||||
if (!reviewOnly && !isolated) {
|
||||
if (!reviewOnly) {
|
||||
this.persistSessionState(key, result.sessionRef || sessionRef, completedSessionMeta(
|
||||
sessionMeta, sessionProvenance, taskId, {
|
||||
promptChars: prompt.length,
|
||||
replyChars: reply.text.length,
|
||||
rotated: sessionRotated,
|
||||
transport: sessionTransport,
|
||||
lastDeliveredMessageId: packedContext.latestMessageId || sessionMeta.lastDeliveredMessageId,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -1755,7 +1959,7 @@ class LocalWorkspaceAgentInvocation {
|
||||
? agentStoppedError()
|
||||
: caughtError
|
||||
if (credentialFailure(error) && context.deferCredentialFailure !== true) {
|
||||
this.markRuntimeCredential(kind, 'missing')
|
||||
this.markRuntimeCredential(kind, 'unknown')
|
||||
}
|
||||
const status = parentTimedOut
|
||||
? 'timeout'
|
||||
@@ -1804,25 +2008,33 @@ class LocalWorkspaceAgentInvocation {
|
||||
}
|
||||
|
||||
resetSession(group, kind, rotateOpenClaw = true, taskId = '') {
|
||||
const scopedTaskId = group.conversationType === 'direct' ? '' : cleanText(taskId, 120)
|
||||
const key = this.sessionKey(group.id, kind, scopedTaskId)
|
||||
const key = this.sessionKey(group.id, kind)
|
||||
const legacyPrefix = `${group.id}:${kind}:thread:`
|
||||
return this.commitSessionState((state) => {
|
||||
const legacyKeys = new Set([
|
||||
key,
|
||||
...(taskId ? [this.sessionKey(group.id, kind, taskId)] : []),
|
||||
...state.messages.filter(message => message.groupId === group.id && message.role === 'user')
|
||||
.map(message => this.sessionKey(group.id, kind, message.id)),
|
||||
])
|
||||
const belongsToSession = candidate => legacyKeys.has(candidate)
|
||||
|| candidate.startsWith(legacyPrefix)
|
||||
|| (candidate.startsWith(`${group.id}:task:`) && candidate.endsWith(`:${kind}`))
|
||||
let changed = false
|
||||
for (const candidate of Object.keys(state.sessions)) {
|
||||
if (candidate !== key && !candidate.startsWith(legacyPrefix)) continue
|
||||
if (!belongsToSession(candidate)) continue
|
||||
delete state.sessions[candidate]
|
||||
changed = true
|
||||
}
|
||||
for (const candidate of Object.keys(state.sessionMeta)) {
|
||||
if (candidate !== key && !candidate.startsWith(legacyPrefix)) continue
|
||||
if (!belongsToSession(candidate)) continue
|
||||
delete state.sessionMeta[candidate]
|
||||
changed = true
|
||||
}
|
||||
if (kind === 'openclaw' && rotateOpenClaw) {
|
||||
const generation = randomUUID().replace(/[^a-zA-Z0-9]/g, '').slice(0, 12) || 'session'
|
||||
const provenance = createdSessionProvenance(group, cleanText(taskId, 120))
|
||||
state.sessions[key] = this.openClawSessionRef(group, generation, scopedTaskId)
|
||||
state.sessions[key] = this.openClawSessionRef(group, generation)
|
||||
state.sessionMeta[key] = normalizeSessionMeta(provenanceMeta(provenance))
|
||||
changed = true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
const { parseTaskDecision } = require('../collaboration/task-decision.cjs')
|
||||
|
||||
const v4NaturalDecisionMethods = {
|
||||
v4NaturalRouteDecision(decision, activeKinds) {
|
||||
const participants = Array.isArray(activeKinds) ? activeKinds : []
|
||||
if (decision == null) return { status: 'none', kinds: [] }
|
||||
let parsed
|
||||
try { parsed = parseTaskDecision(decision) }
|
||||
catch { return { status: 'invalid', kinds: [] } }
|
||||
const requested = parsed.nextKinds || []
|
||||
if (requested.some(kind => !participants.includes(kind))) return { status: 'invalid', kinds: [] }
|
||||
if (!requested.length) return { status: 'none', kinds: [] }
|
||||
return { status: 'valid', kinds: participants.filter(kind => requested.includes(kind)) }
|
||||
},
|
||||
|
||||
async v4NaturalRoundOutcome(group, controller, threadRootId, round, activeKinds) {
|
||||
const messages = this.v4NaturalDiscussionRoundMessages(group, controller, threadRootId, round)
|
||||
const owner = this.v4NaturalOwner(group, controller, threadRootId)
|
||||
const routes = messages.map(message => this.v4NaturalRouteDecision(
|
||||
message.trace?.context?.taskDecision, activeKinds,
|
||||
))
|
||||
if (routes.some(route => route.status === 'invalid')) {
|
||||
this.addMessage(group.id, 'system', 'Discussion stopped without a valid task completion decision.',
|
||||
'', threadRootId, { key: 'system.autoTaskDecisionMissing' })
|
||||
return { status: 'partial' }
|
||||
}
|
||||
// A peer's explicit blocker is a task outcome, not an empty routing choice.
|
||||
// Without this guard the delivery owner could complete the run while a
|
||||
// participant had already reported that the work was blocked.
|
||||
const peerBlocker = messages.find(message => {
|
||||
if (message.agentKind === owner) return false
|
||||
const status = message.trace?.context?.taskDecision?.status
|
||||
return status === 'blocked' || status === 'needs-human'
|
||||
})
|
||||
if (peerBlocker) {
|
||||
const decision = peerBlocker.trace?.context?.taskDecision
|
||||
this.addMessage(group.id, 'system', decision.reason, '', threadRootId, {
|
||||
key: decision.status === 'needs-human' ? 'system.autoTaskNeedsHuman' : 'system.autoTaskBlocked',
|
||||
params: { reason: decision.reason },
|
||||
})
|
||||
return { status: 'partial' }
|
||||
}
|
||||
const nextKinds = this.v4NaturalNextKinds(group, controller, threadRootId, round, activeKinds)
|
||||
if (nextKinds.length) return { nextKinds, ownerReview: false }
|
||||
if (!activeKinds.includes(owner)) return { status: 'partial' }
|
||||
const ownerMessage = messages.find(message => message.agentKind === owner)
|
||||
const decision = ownerMessage?.trace?.context?.taskDecision
|
||||
if (decision?.handoffTo && !activeKinds.includes(decision.handoffTo)) return { status: 'partial' }
|
||||
if (decision?.status === 'continue') return { nextKinds: [owner], ownerReview: false }
|
||||
const sawAllContributions = messages.length === 1
|
||||
|| (controller.discussionStyle === 'sequential' && messages.at(-1)?.agentKind === owner)
|
||||
if (!ownerMessage || !sawAllContributions) return { nextKinds: [owner], ownerReview: true }
|
||||
if (!decision) {
|
||||
this.addMessage(group.id, 'system', 'Discussion stopped without a valid task completion decision.',
|
||||
'', threadRootId, { key: 'system.autoTaskDecisionMissing' })
|
||||
return { status: 'partial' }
|
||||
}
|
||||
if (decision.status === 'completed') return { status: controller.failedKinds.length ? 'partial' : 'completed' }
|
||||
if (decision.status === 'needs-human' && this.requestTaskDecision) {
|
||||
const response = await this.requestTaskDecision(group, controller, ownerMessage)
|
||||
if (response?.status === 'approved') return { nextKinds: [owner], ownerReview: true }
|
||||
if (response?.status === 'rejected') {
|
||||
controller.stopReason = 'human_gate_rejected'
|
||||
return { status: 'stopped' }
|
||||
}
|
||||
}
|
||||
this.addMessage(group.id, 'system', decision.reason, '', threadRootId, {
|
||||
key: decision.status === 'needs-human' ? 'system.autoTaskNeedsHuman' : 'system.autoTaskBlocked',
|
||||
params: { reason: decision.reason },
|
||||
})
|
||||
return { status: 'partial' }
|
||||
},
|
||||
|
||||
v4NaturalNextKinds(group, controller, threadRootId, round, activeKinds) {
|
||||
const current = this.v4NaturalDiscussionRoundMessages(group, controller, threadRootId, round)
|
||||
const selected = new Set(current.flatMap(message => (
|
||||
this.v4NaturalRouteDecision(message.trace?.context?.taskDecision, activeKinds).kinds
|
||||
.filter(kind => kind !== message.agentKind)
|
||||
)))
|
||||
if (!selected.size) return []
|
||||
return activeKinds.filter(kind => selected.has(kind))
|
||||
},
|
||||
|
||||
v4NaturalOwner(group, controller, threadRootId) {
|
||||
let owner = controller.targetKinds[0] || ''
|
||||
for (const message of this.state().messages) {
|
||||
if (message.groupId !== group.id || message.threadRootId !== threadRootId
|
||||
|| message.role !== 'agent' || message.agentKind !== owner
|
||||
|| message.trace?.phase !== 'discussion'
|
||||
|| !this.v4NaturalMessageMatchesBinding(message, controller)) continue
|
||||
const decision = message.trace?.context?.taskDecision
|
||||
if (decision?.status === 'continue' && decision.handoffTo
|
||||
&& controller.targetKinds.includes(decision.handoffTo)) owner = decision.handoffTo
|
||||
}
|
||||
return owner
|
||||
},
|
||||
|
||||
v4NaturalDiscussionIsRepeating(group, controller, threadRootId, round, activeKinds) {
|
||||
const window = Math.max(4, activeKinds.length * 2)
|
||||
if (round < window + 2) return false
|
||||
const firstRound = round - window + 1
|
||||
const previous = new Map()
|
||||
const observedRounds = new Set()
|
||||
const messages = this.state().messages
|
||||
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
||||
const message = messages[index]
|
||||
const messageRound = Number(message.trace?.round) || 0
|
||||
if (message.groupId !== group.id || message.threadRootId !== threadRootId
|
||||
|| message.role !== 'agent' || message.trace?.phase !== 'discussion'
|
||||
|| message.trace?.runId !== controller.runId || messageRound < 2
|
||||
|| messageRound > round || !this.v4NaturalMessageMatchesBinding(message, controller)) continue
|
||||
const contribution = this.v4NaturalMessageContent(message)
|
||||
if (contribution.partial) return false
|
||||
const content = contribution.text
|
||||
.replace(/@[A-Za-z0-9][A-Za-z0-9_-]*/gu, '')
|
||||
.replace(/\s+/gu, ' ').trim()
|
||||
if (previous.has(message.agentKind) && previous.get(message.agentKind) !== content) return false
|
||||
if (messageRound >= firstRound) {
|
||||
observedRounds.add(messageRound)
|
||||
previous.set(message.agentKind, content)
|
||||
} else {
|
||||
previous.delete(message.agentKind)
|
||||
if (observedRounds.size === window && previous.size === 0) return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
|
||||
v4NaturalStopRepeatingDiscussion(group, controller, threadRootId, round, activeKinds) {
|
||||
if (!this.v4NaturalDiscussionIsRepeating(group, controller, threadRootId, round, activeKinds)) return false
|
||||
this.addMessage(
|
||||
group.id, 'system',
|
||||
'Automatic discussion stopped because repeated handoffs produced no new contribution.',
|
||||
'', threadRootId, { key: 'system.autoDiscussionStalled' },
|
||||
)
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
module.exports = { v4NaturalDecisionMethods }
|
||||
@@ -0,0 +1,100 @@
|
||||
const { terminalRunStatusForReason } = require('./local-workspace-inputs.cjs')
|
||||
const {
|
||||
normalizeFailure,
|
||||
} = require('../runs/failure-policy.cjs')
|
||||
|
||||
function authenticationFailureText(error) {
|
||||
return [
|
||||
error?.diagnostic,
|
||||
error?.message,
|
||||
error?.cause?.diagnostic,
|
||||
error?.cause?.message,
|
||||
].filter(Boolean).join('\n')
|
||||
}
|
||||
|
||||
function unauthorizedFailure(error) {
|
||||
return normalizeFailure(error).category === 'authentication'
|
||||
}
|
||||
|
||||
function hardBudgetFailure(error) {
|
||||
return error?.code === 'LOCAL_BUDGET_EXHAUSTED'
|
||||
|| error?.message === 'LOCAL_BUDGET_EXHAUSTED'
|
||||
}
|
||||
|
||||
function circuitBreakerFailure(error) {
|
||||
return error?.code === 'LOCAL_RUN_CIRCUIT_BREAKER'
|
||||
|| error?.message === 'LOCAL_RUN_CIRCUIT_BREAKER'
|
||||
}
|
||||
|
||||
function circuitBreakerError() {
|
||||
return Object.assign(new Error('LOCAL_RUN_CIRCUIT_BREAKER'), {
|
||||
code: 'LOCAL_RUN_CIRCUIT_BREAKER',
|
||||
})
|
||||
}
|
||||
|
||||
function authenticationFailureStatus(error) {
|
||||
const status = normalizeFailure(error).httpStatus
|
||||
if ([401, 403].includes(status)) return status
|
||||
const message = authenticationFailureText(error)
|
||||
if (/(?:\bHTTP\s*)?\b403\b|forbidden/i.test(message)) return 403
|
||||
return 401
|
||||
}
|
||||
|
||||
function sanitizedAuthenticationError(error) {
|
||||
const statusCode = authenticationFailureStatus(error)
|
||||
const sanitized = Object.assign(
|
||||
new Error(`HTTP ${statusCode}; authentication failed; Agent retained`),
|
||||
{
|
||||
code: 'LOCAL_AGENT_AUTH_REQUIRED',
|
||||
statusCode,
|
||||
failure: Object.freeze({
|
||||
code: 'LOCAL_AGENT_AUTH_REQUIRED',
|
||||
category: 'authentication',
|
||||
retryable: false,
|
||||
}),
|
||||
},
|
||||
)
|
||||
if (error?.runTrace) {
|
||||
Object.defineProperty(sanitized, 'runTrace', {
|
||||
value: error.runTrace,
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
})
|
||||
}
|
||||
return sanitized
|
||||
}
|
||||
|
||||
function abortableDelay(delayMs, signal) {
|
||||
if (!delayMs) return Promise.resolve()
|
||||
if (signal?.aborted) return Promise.reject(new Error('LOCAL_AGENT_EXECUTION_STOPPED'))
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener('abort', abortHandler)
|
||||
resolve()
|
||||
}, delayMs)
|
||||
const abortHandler = () => {
|
||||
clearTimeout(timer)
|
||||
reject(new Error('LOCAL_AGENT_EXECUTION_STOPPED'))
|
||||
}
|
||||
signal?.addEventListener('abort', abortHandler, { once: true })
|
||||
})
|
||||
}
|
||||
|
||||
function stalePermissionResumeFailure(error, resumedGate) {
|
||||
const code = String(error?.code || error?.message || '')
|
||||
return resumedGate?.type === 'permission'
|
||||
&& ['LOCAL_RUN_PERMISSION_RESUME_UNAVAILABLE', 'LOCAL_AGENT_SESSION_INVALID'].includes(code)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
abortableDelay,
|
||||
authenticationFailureStatus,
|
||||
authenticationFailureText,
|
||||
circuitBreakerError,
|
||||
circuitBreakerFailure,
|
||||
hardBudgetFailure,
|
||||
sanitizedAuthenticationError,
|
||||
stalePermissionResumeFailure,
|
||||
terminalRunStatusForReason,
|
||||
unauthorizedFailure,
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
const { createHash } = require('node:crypto')
|
||||
|
||||
const {
|
||||
coordinationRecoveryKinds,
|
||||
createWorkReceipt,
|
||||
hashValue,
|
||||
} = require('../collaboration/orchestration-v4-records.cjs')
|
||||
const { canonicalJson } = require('../collaboration/context-pack-records.cjs')
|
||||
|
||||
const v4OutcomeMethods = {
|
||||
v4LatestReceipt(receiptRecords, phase, agentKind = '') {
|
||||
return [...receiptRecords].reverse().find(record => (
|
||||
record?.receipt?.phase === phase
|
||||
&& (!agentKind || record.receipt.agentKind === agentKind)
|
||||
)) || null
|
||||
},
|
||||
|
||||
v4WorkState(workReceipts, coordinationPlan) {
|
||||
if (!coordinationPlan) throw new Error('LOCAL_RUN_V4_COORDINATION_PLAN_INVALID')
|
||||
const completed = new Map()
|
||||
for (const assignment of coordinationPlan.assignments) {
|
||||
const exactReceipt = (Array.isArray(workReceipts) ? workReceipts : []).find(candidate => (
|
||||
candidate?.planHash === coordinationPlan.planHash
|
||||
&& candidate.taskId === assignment.taskId
|
||||
&& candidate.ownerKind === assignment.ownerKind
|
||||
))
|
||||
if (!exactReceipt) continue
|
||||
const record = { receipt: exactReceipt.collaborationReceipt }
|
||||
if (!this.v4ReceiptReferencesComplete(record)
|
||||
|| exactReceipt.artifacts.some((binding) => {
|
||||
const identity = this.v4ArtifactIdentity(binding.artifactId)
|
||||
return identity.contentHash !== binding.contentHash
|
||||
|| canonicalJson(identity.artifact.contentRef) !== canonicalJson(binding.contentRef)
|
||||
})) {
|
||||
throw new Error('LOCAL_RUN_V4_WORK_RECEIPT_INVALID')
|
||||
}
|
||||
completed.set(assignment.taskId, exactReceipt)
|
||||
}
|
||||
const pending = coordinationPlan.assignments.filter(assignment => !completed.has(assignment.taskId))
|
||||
const ready = pending.filter(assignment => (
|
||||
assignment.dependsOn.every(taskId => completed.has(taskId))
|
||||
))
|
||||
return { completed, pending, ready }
|
||||
},
|
||||
|
||||
v4ArtifactIdentity(artifactId) {
|
||||
if (!this.outcomeStore || !this.outcomeStore.contentBlobStore) {
|
||||
throw new Error('LOCAL_RUN_V4_CANDIDATE_INVALID')
|
||||
}
|
||||
try {
|
||||
const artifact = this.outcomeStore.getArtifact(artifactId)
|
||||
if (!artifact?.contentRef || artifact.contentHash !== artifact.contentRef.hash) {
|
||||
throw new Error('LOCAL_RUN_V4_CANDIDATE_INVALID')
|
||||
}
|
||||
const bytes = this.outcomeStore.contentBlobStore.read(artifact.contentRef)
|
||||
const contentHash = createHash('sha256').update(bytes).digest('hex')
|
||||
if (contentHash !== artifact.contentHash) {
|
||||
throw new Error('LOCAL_RUN_V4_CANDIDATE_INVALID')
|
||||
}
|
||||
return {
|
||||
artifact,
|
||||
contentHash,
|
||||
content: artifact.contentRef?.mediaType === 'text/plain'
|
||||
? bytes.toString('utf8')
|
||||
: '',
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.message === 'LOCAL_RUN_V4_CANDIDATE_INVALID') throw error
|
||||
throw new Error('LOCAL_RUN_V4_CANDIDATE_INVALID')
|
||||
}
|
||||
},
|
||||
|
||||
v4CandidateIdentity(record) {
|
||||
const artifactId = record?.receipt?.artifactIds?.[0]
|
||||
if (typeof artifactId !== 'string') throw new Error('LOCAL_RUN_V4_CANDIDATE_INVALID')
|
||||
const { contentHash } = this.v4ArtifactIdentity(artifactId)
|
||||
return { artifactId, contentHash }
|
||||
},
|
||||
|
||||
v4EvidenceRecord(evidenceId, errorCode = 'LOCAL_RUN_V4_REFERENCE_INVALID') {
|
||||
try {
|
||||
const evidence = this.outcomeStore.getEvidence(evidenceId)
|
||||
const concrete = evidence.refs.some(reference => (
|
||||
reference.type === 'artifact'
|
||||
|| reference.type === 'evidence'
|
||||
|| reference.type === 'blob'
|
||||
|| (reference.type === 'location' && Boolean(reference.contentHash))
|
||||
))
|
||||
if (!concrete) throw new Error(errorCode)
|
||||
return evidence
|
||||
} catch (error) {
|
||||
if (error?.message === errorCode) throw error
|
||||
throw new Error(errorCode)
|
||||
}
|
||||
},
|
||||
|
||||
v4EvidenceSupportsArtifact(evidenceId, artifactId, contentHash, seen = new Set()) {
|
||||
if (seen.has(evidenceId)) return false
|
||||
seen.add(evidenceId)
|
||||
const evidence = this.v4EvidenceRecord(
|
||||
evidenceId, 'LOCAL_RUN_V4_REVIEW_FINDING_INVALID',
|
||||
)
|
||||
const artifactBound = evidence.subject?.type === 'artifact'
|
||||
&& evidence.subject.artifactId === artifactId
|
||||
|| evidence.refs.some(reference => (
|
||||
reference.type === 'artifact' && reference.artifactId === artifactId
|
||||
))
|
||||
const contentBound = evidence.refs.some(reference => (
|
||||
reference.type === 'blob' && reference.contentHash === contentHash
|
||||
))
|
||||
if (artifactBound && contentBound) return true
|
||||
return evidence.refs.some(reference => (
|
||||
reference.type === 'evidence'
|
||||
&& this.v4EvidenceSupportsArtifact(
|
||||
reference.evidenceId, artifactId, contentHash, seen,
|
||||
)
|
||||
))
|
||||
},
|
||||
|
||||
v4ReceiptReferencesComplete(record, expectedArtifactId = '', expectedProducer = null) {
|
||||
const receipt = record?.receipt
|
||||
if (!receipt || !['completed', 'accepted'].includes(receipt.status)
|
||||
|| !receipt.artifactIds?.length || !receipt.evidenceIds?.length) return false
|
||||
const artifacts = new Map()
|
||||
for (const artifactId of receipt.artifactIds) {
|
||||
const identity = this.v4ArtifactIdentity(artifactId)
|
||||
artifacts.set(artifactId, identity)
|
||||
}
|
||||
const evidences = receipt.evidenceIds.map(evidenceId => this.v4EvidenceRecord(evidenceId))
|
||||
if (expectedProducer) {
|
||||
const runId = String(expectedProducer.runId || '')
|
||||
const agentRunId = String(expectedProducer.agentRunId || '')
|
||||
const agentKind = String(expectedProducer.agentKind || '')
|
||||
const operationId = String(expectedProducer.operationId || '')
|
||||
if (!runId || !agentRunId || !agentKind || !operationId
|
||||
|| receipt.agentKind !== agentKind || receipt.operationId !== operationId) return false
|
||||
const evidenceBindings = evidences.map((evidence) => {
|
||||
const recorder = evidence.recordedBy || {}
|
||||
const recorderBound = recorder.kind === 'system'
|
||||
? recorder.actorId === 'meldwork-main'
|
||||
: recorder.kind === 'agent'
|
||||
&& recorder.runId === runId
|
||||
&& recorder.agentRunId === agentRunId
|
||||
&& recorder.agentKind === agentKind
|
||||
if (!recorderBound) return null
|
||||
const boundArtifactIds = new Set([...artifacts.entries()]
|
||||
.filter(([artifactId, identity]) => {
|
||||
const artifactBound = evidence.subject?.type === 'artifact'
|
||||
&& evidence.subject.artifactId === artifactId
|
||||
|| evidence.refs.some(reference => (
|
||||
reference.type === 'artifact' && reference.artifactId === artifactId
|
||||
))
|
||||
const contentBound = evidence.refs.some(reference => (
|
||||
reference.type === 'blob'
|
||||
&& reference.contentHash === identity.contentHash
|
||||
&& canonicalJson(reference.contentRef)
|
||||
=== canonicalJson(identity.artifact.contentRef)
|
||||
))
|
||||
return artifactBound && contentBound
|
||||
})
|
||||
.map(([artifactId]) => artifactId))
|
||||
if (recorder.kind === 'system' && !boundArtifactIds.size) return null
|
||||
return boundArtifactIds
|
||||
})
|
||||
if (evidenceBindings.some(binding => !binding)) return false
|
||||
return [...artifacts.entries()].every(([artifactId, identity]) => {
|
||||
const artifact = identity.artifact
|
||||
return artifact.producedBy?.runId === runId
|
||||
&& artifact.producedBy?.agentRunId === agentRunId
|
||||
&& artifact.producedBy?.agentKind === agentKind
|
||||
&& evidenceBindings.some(binding => binding.has(artifactId))
|
||||
})
|
||||
}
|
||||
const artifactId = expectedArtifactId || receipt.artifactIds[0]
|
||||
const identity = artifacts.get(artifactId)
|
||||
if (!identity) return false
|
||||
return evidences.some(evidence => {
|
||||
const artifactBound = evidence.subject?.type === 'artifact'
|
||||
&& evidence.subject.artifactId === artifactId
|
||||
|| evidence.refs.some(reference => (
|
||||
reference.type === 'artifact' && reference.artifactId === artifactId
|
||||
))
|
||||
const contentBound = evidence.refs.some(reference => (
|
||||
reference.type === 'blob' && reference.contentHash === identity.contentHash
|
||||
))
|
||||
return artifactBound && contentBound
|
||||
})
|
||||
},
|
||||
|
||||
v4TrustedSynthesisResult({
|
||||
controller, slots, activeAttempt, synthesisRecovery, coordinationPlan, snapshotHash,
|
||||
}) {
|
||||
try {
|
||||
const rankedKinds = coordinationRecoveryKinds(coordinationPlan)
|
||||
if (!activeAttempt || !synthesisRecovery || !coordinationPlan?.planHash
|
||||
|| coordinationPlan.snapshotHash !== snapshotHash
|
||||
|| synthesisRecovery.originalWriterKind !== coordinationPlan.finalizerKind
|
||||
|| synthesisRecovery.activeWriterKind !== activeAttempt.writerKind
|
||||
|| canonicalJson(synthesisRecovery.rankedKinds) !== canonicalJson(rankedKinds)
|
||||
|| synthesisRecovery.rankingFingerprint !== hashValue({
|
||||
planHash: coordinationPlan.planHash,
|
||||
rankedKinds,
|
||||
})) return false
|
||||
const slot = slots.find(candidate => candidate.slotId === activeAttempt.slotId)
|
||||
if (!slot || slot.agentKind !== activeAttempt.writerKind
|
||||
|| slot.operationId !== activeAttempt.operationId
|
||||
|| slot.snapshotHash !== snapshotHash) return false
|
||||
const records = Array.isArray(slot.resultRefs?.workflowOutcomeRefs)
|
||||
? slot.resultRefs.workflowOutcomeRefs
|
||||
: []
|
||||
const record = [...records].reverse().find(candidate => {
|
||||
const receipt = candidate?.receipt
|
||||
return receipt?.phase === 'synthesis'
|
||||
&& receipt.agentKind === activeAttempt.writerKind
|
||||
&& receipt.slotId === activeAttempt.slotId
|
||||
&& receipt.operationId === activeAttempt.operationId
|
||||
&& receipt.snapshotHash === snapshotHash
|
||||
&& ['completed', 'accepted'].includes(receipt.status)
|
||||
})
|
||||
const receipt = record?.receipt
|
||||
if (!receipt?.artifactIds?.length || !receipt.evidenceIds?.length
|
||||
|| canonicalJson(receipt.artifactIds)
|
||||
!== canonicalJson(slot.resultRefs?.artifactIds || [])
|
||||
|| canonicalJson(receipt.evidenceIds)
|
||||
!== canonicalJson(slot.resultRefs?.evidenceIds || [])) return false
|
||||
return receipt.artifactIds.every((artifactId) => {
|
||||
const { artifact, contentHash } = this.v4ArtifactIdentity(artifactId)
|
||||
if (artifact.producedBy?.runId !== controller.runId
|
||||
|| artifact.producedBy?.agentKind !== activeAttempt.writerKind) return false
|
||||
return receipt.evidenceIds.some((evidenceId) => {
|
||||
const evidence = this.v4EvidenceRecord(evidenceId)
|
||||
return evidence.recordedBy?.kind === 'system'
|
||||
&& evidence.recordedBy.actorId === 'meldwork-main'
|
||||
&& evidence.subject?.type === 'artifact'
|
||||
&& evidence.subject.artifactId === artifactId
|
||||
&& evidence.refs.some(reference => (
|
||||
reference.type === 'artifact' && reference.artifactId === artifactId
|
||||
))
|
||||
&& evidence.refs.some(reference => (
|
||||
reference.type === 'blob'
|
||||
&& reference.contentHash === contentHash
|
||||
&& canonicalJson(reference.contentRef) === canonicalJson(artifact.contentRef)
|
||||
))
|
||||
})
|
||||
})
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
},
|
||||
|
||||
v4ExactWorkReceipt(receiptRecord, assignment, slot, snapshotRecord, snapshotHash,
|
||||
coordinationPlan) {
|
||||
const receipt = receiptRecord?.receipt
|
||||
if (!receipt || !assignment || !slot || !snapshotRecord?.bodyHash
|
||||
|| !snapshotRecord?.contentRef || !coordinationPlan?.planHash) {
|
||||
throw new Error('LOCAL_RUN_V4_WORK_RECEIPT_INVALID')
|
||||
}
|
||||
const artifacts = receipt.artifactIds.map((artifactId) => {
|
||||
const { artifact, contentHash } = this.v4ArtifactIdentity(artifactId)
|
||||
return {
|
||||
artifactId,
|
||||
contentHash,
|
||||
contentRef: artifact.contentRef,
|
||||
}
|
||||
})
|
||||
return createWorkReceipt({
|
||||
snapshotHash,
|
||||
snapshotBodyHash: snapshotRecord.bodyHash,
|
||||
snapshotContentRef: snapshotRecord.contentRef,
|
||||
planHash: coordinationPlan.planHash,
|
||||
taskId: assignment.taskId,
|
||||
ownerKind: assignment.ownerKind,
|
||||
slotId: slot.slotId,
|
||||
operationId: slot.operationId,
|
||||
collaborationReceipt: receipt,
|
||||
artifacts,
|
||||
})
|
||||
},
|
||||
|
||||
v4ReviewFindings(input, options = {}) {
|
||||
const record = input?.record
|
||||
const receipt = record?.receipt
|
||||
const reviewedArtifactId = String(input?.reviewedArtifactId || '')
|
||||
const runId = String(options.runId || '')
|
||||
const required = options.required === true || record?.verdict === 'contradict'
|
||||
if (!receipt || !['challenge', 'verification'].includes(receipt.phase)
|
||||
|| !['support', 'contradict'].includes(record?.verdict)
|
||||
|| !reviewedArtifactId || !runId) {
|
||||
throw new Error('LOCAL_RUN_V4_REVIEW_FINDING_INVALID')
|
||||
}
|
||||
const findingIds = Array.isArray(receipt.findingIds) ? receipt.findingIds : []
|
||||
if (required && findingIds.length === 0) {
|
||||
throw new Error('LOCAL_RUN_V4_REVIEW_FINDING_INVALID')
|
||||
}
|
||||
const { artifact, contentHash } = this.v4ArtifactIdentity(reviewedArtifactId)
|
||||
const receiptEvidenceIds = Array.isArray(receipt.evidenceIds) ? receipt.evidenceIds : []
|
||||
const receiptEvidenceSet = new Set(receiptEvidenceIds)
|
||||
return findingIds.map((findingId) => {
|
||||
let finding
|
||||
try { finding = this.outcomeStore.getReviewerFinding(findingId) } catch {
|
||||
throw new Error('LOCAL_RUN_V4_REVIEW_FINDING_INVALID')
|
||||
}
|
||||
if (finding.artifactId !== reviewedArtifactId
|
||||
|| finding.relation !== record.verdict
|
||||
|| finding.reviewer?.kind !== 'agent'
|
||||
|| finding.reviewer.runId !== runId
|
||||
|| finding.reviewer.agentKind !== receipt.agentKind
|
||||
|| !finding.reviewer.agentRunId
|
||||
|| !finding.evidenceIds.length) {
|
||||
throw new Error('LOCAL_RUN_V4_REVIEW_FINDING_INVALID')
|
||||
}
|
||||
for (const evidenceId of finding.evidenceIds) {
|
||||
if (!receiptEvidenceSet.has(evidenceId) && receiptEvidenceIds.length !== 64) {
|
||||
throw new Error('LOCAL_RUN_V4_REVIEW_FINDING_INVALID')
|
||||
}
|
||||
const evidence = this.v4EvidenceRecord(
|
||||
evidenceId, 'LOCAL_RUN_V4_REVIEW_FINDING_INVALID',
|
||||
)
|
||||
const recorder = evidence.recordedBy || {}
|
||||
const directArtifactBound = evidence.subject?.type === 'artifact'
|
||||
&& evidence.subject.artifactId === reviewedArtifactId
|
||||
&& evidence.refs.some(reference => (
|
||||
reference.type === 'artifact' && reference.artifactId === reviewedArtifactId
|
||||
))
|
||||
const exactContentBound = evidence.refs.some(reference => (
|
||||
reference.type === 'blob'
|
||||
&& reference.contentHash === contentHash
|
||||
&& canonicalJson(reference.contentRef) === canonicalJson(artifact.contentRef)
|
||||
))
|
||||
if (evidence.kind !== 'review'
|
||||
|| recorder.kind !== 'agent'
|
||||
|| recorder.runId !== finding.reviewer.runId
|
||||
|| recorder.agentRunId !== finding.reviewer.agentRunId
|
||||
|| recorder.agentKind !== finding.reviewer.agentKind
|
||||
|| !directArtifactBound || !exactContentBound) {
|
||||
throw new Error('LOCAL_RUN_V4_REVIEW_FINDING_INVALID')
|
||||
}
|
||||
}
|
||||
return finding
|
||||
})
|
||||
},
|
||||
|
||||
v4ReviewReceiptComplete(input, options = {}) {
|
||||
const status = input?.record?.receipt?.status
|
||||
if (!['completed', 'accepted'].includes(status)) return false
|
||||
return this.v4ReviewFindings(input, { ...options, required: true }).length > 0
|
||||
},
|
||||
|
||||
v4IssueId(record, findingId) {
|
||||
return `issue-${hashValue({
|
||||
phase: record.receipt.phase,
|
||||
reviewerFindingId: findingId,
|
||||
})}`
|
||||
},
|
||||
|
||||
v4IssueFromFinding(record, finding) {
|
||||
const { contentHash } = this.v4ArtifactIdentity(finding.artifactId)
|
||||
return {
|
||||
id: this.v4IssueId(record, finding.reviewerFindingId),
|
||||
artifactId: finding.artifactId,
|
||||
findingId: finding.reviewerFindingId,
|
||||
summary: finding.summary,
|
||||
semanticKey: hashValue({
|
||||
phase: record.receipt.phase,
|
||||
candidateContentHash: contentHash,
|
||||
relation: finding.relation,
|
||||
reviewerKind: finding.reviewer.agentKind,
|
||||
summary: finding.summary,
|
||||
}),
|
||||
}
|
||||
},
|
||||
|
||||
v4IssuesFromReviews(inputs, options = {}) {
|
||||
const issues = new Map()
|
||||
for (const input of inputs) {
|
||||
const record = input?.record
|
||||
const findings = this.v4ReviewFindings(input, options)
|
||||
if (record.verdict !== 'contradict') continue
|
||||
for (const finding of findings) {
|
||||
const issue = this.v4IssueFromFinding(record, finding)
|
||||
issues.set(issue.id, issue)
|
||||
}
|
||||
}
|
||||
return [...issues.values()].sort((left, right) => left.id.localeCompare(right.id))
|
||||
},
|
||||
|
||||
v4CarriedIssues(receiptRecords, openIssueIds, options = {}) {
|
||||
const requested = Array.isArray(openIssueIds) ? openIssueIds : []
|
||||
if (new Set(requested).size !== requested.length) {
|
||||
throw new Error('LOCAL_RUN_V4_ISSUE_INVALID')
|
||||
}
|
||||
if (requested.length === 0) return []
|
||||
const requestedSet = new Set(requested)
|
||||
const durableIssues = new Map()
|
||||
try {
|
||||
for (const record of receiptRecords) {
|
||||
if (!['challenge', 'verification'].includes(record?.receipt?.phase)
|
||||
|| record.verdict !== 'contradict') continue
|
||||
const findingIds = Array.isArray(record.receipt.findingIds)
|
||||
? record.receipt.findingIds : []
|
||||
if (findingIds.length === 0) throw new Error('LOCAL_RUN_V4_ISSUE_INVALID')
|
||||
for (const findingId of findingIds) {
|
||||
const issueId = this.v4IssueId(record, findingId)
|
||||
if (!requestedSet.has(issueId)) continue
|
||||
const finding = this.outcomeStore.getReviewerFinding(findingId)
|
||||
const scopedRecord = {
|
||||
...record,
|
||||
receipt: { ...record.receipt, findingIds: [findingId] },
|
||||
}
|
||||
if (!this.v4ReviewReceiptComplete({
|
||||
record: scopedRecord,
|
||||
reviewedArtifactId: finding.artifactId,
|
||||
}, options)) throw new Error('LOCAL_RUN_V4_ISSUE_INVALID')
|
||||
const issues = this.v4IssuesFromReviews([{
|
||||
record: scopedRecord,
|
||||
reviewedArtifactId: finding.artifactId,
|
||||
}], options)
|
||||
for (const issue of issues) durableIssues.set(issue.id, issue)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
throw new Error('LOCAL_RUN_V4_ISSUE_INVALID')
|
||||
}
|
||||
return requested.map((issueId) => {
|
||||
const issue = durableIssues.get(issueId)
|
||||
if (!issue) throw new Error('LOCAL_RUN_V4_ISSUE_INVALID')
|
||||
return issue
|
||||
}).sort((left, right) => left.id.localeCompare(right.id))
|
||||
},
|
||||
|
||||
v4ResolveIssues(openIssues, resolvedIssueIds) {
|
||||
const issues = Array.isArray(openIssues) ? openIssues : []
|
||||
const openIds = issues.map(issue => issue?.id)
|
||||
const resolved = Array.isArray(resolvedIssueIds) ? resolvedIssueIds : []
|
||||
if (openIds.some(issueId => typeof issueId !== 'string')
|
||||
|| new Set(openIds).size !== openIds.length
|
||||
|| resolved.some(issueId => typeof issueId !== 'string')
|
||||
|| new Set(resolved).size !== resolved.length
|
||||
|| resolved.some(issueId => !openIds.includes(issueId))) {
|
||||
throw new Error('LOCAL_RUN_V4_RESOLUTION_INVALID')
|
||||
}
|
||||
const closed = new Set(resolved)
|
||||
return issues.filter(issue => !closed.has(issue.id))
|
||||
},
|
||||
|
||||
v4ReceiptForOperation(receiptRecords, phase, agentKind, operationId = '') {
|
||||
return [...receiptRecords].reverse().find(record => (
|
||||
record?.receipt?.phase === phase
|
||||
&& record.receipt.agentKind === agentKind
|
||||
&& (!operationId || record.receipt.operationId === operationId)
|
||||
)) || null
|
||||
},
|
||||
|
||||
v4RoundState(receiptRecords, targetKinds, writerKind, verificationKinds, options = {}) {
|
||||
const slots = Array.isArray(options.slots) ? options.slots : []
|
||||
const challengeBindings = Array.isArray(options.challengeBindings)
|
||||
? options.challengeBindings : []
|
||||
const coordinationSupportReceiptIds = new Set(
|
||||
options.coordinationPlan?.supportReceiptIds || [],
|
||||
)
|
||||
const challengeInputs = targetKinds.map((kind) => {
|
||||
const binding = challengeBindings.find(item => item.reviewerKind === kind)
|
||||
if (binding) {
|
||||
const record = this.v4ReceiptForOperation(
|
||||
receiptRecords, 'challenge', kind, binding.reviewerOperationId,
|
||||
)
|
||||
return record && binding.artifactIds?.[0]
|
||||
? { record, reviewedArtifactId: binding.artifactIds[0] }
|
||||
: null
|
||||
}
|
||||
const record = [...receiptRecords].reverse().find(item => (
|
||||
item?.receipt?.phase === 'challenge'
|
||||
&& item.receipt.agentKind === kind
|
||||
&& coordinationSupportReceiptIds.has(item.receipt.receiptId)
|
||||
))
|
||||
const findingId = record?.receipt?.findingIds?.[0]
|
||||
let reviewedArtifactId = ''
|
||||
try {
|
||||
reviewedArtifactId = findingId
|
||||
? this.outcomeStore.getReviewerFinding(findingId).artifactId
|
||||
: ''
|
||||
} catch {}
|
||||
return record && reviewedArtifactId ? { record, reviewedArtifactId } : null
|
||||
}).filter(Boolean)
|
||||
const priorIssues = this.v4CarriedIssues(
|
||||
receiptRecords,
|
||||
options.previousConvergence?.openIssueIds || [],
|
||||
{ runId: options.runId },
|
||||
)
|
||||
const challengeIssues = this.v4IssuesFromReviews(challengeInputs, { runId: options.runId })
|
||||
const issueMap = new Map(priorIssues.map(issue => [issue.id, issue]))
|
||||
for (const issue of challengeIssues) {
|
||||
const carried = [...issueMap.values()].some(existing => (
|
||||
existing.semanticKey === issue.semanticKey
|
||||
))
|
||||
if (!carried) issueMap.set(issue.id, issue)
|
||||
}
|
||||
|
||||
const writerSlot = slots.find(slot => slot.agentKind === writerKind)
|
||||
const synthesis = writerSlot && this.v4ReceiptForOperation(
|
||||
receiptRecords, 'synthesis', writerKind, writerSlot.operationId,
|
||||
)
|
||||
if (!synthesis) throw new Error('LOCAL_RUN_V4_CANDIDATE_INVALID')
|
||||
const candidate = this.v4CandidateIdentity(synthesis)
|
||||
if (!this.v4ReceiptReferencesComplete(synthesis, candidate.artifactId)) {
|
||||
throw new Error('LOCAL_RUN_V4_CANDIDATE_INVALID')
|
||||
}
|
||||
let openIssues = this.v4ResolveIssues(
|
||||
[...issueMap.values()], synthesis.resolvedIssueIds || [],
|
||||
)
|
||||
const verificationInputs = verificationKinds.map((kind) => {
|
||||
const slot = slots.find(candidateSlot => candidateSlot.agentKind === kind)
|
||||
const record = slot && this.v4ReceiptForOperation(
|
||||
receiptRecords, 'verification', kind, slot.operationId,
|
||||
)
|
||||
return record ? { record, reviewedArtifactId: candidate.artifactId } : null
|
||||
}).filter(Boolean)
|
||||
if (options.includeVerification === true) {
|
||||
const verificationIssues = this.v4IssuesFromReviews(
|
||||
verificationInputs, { runId: options.runId },
|
||||
)
|
||||
const nextIssues = new Map(openIssues.map(issue => [issue.id, issue]))
|
||||
for (const issue of verificationIssues) {
|
||||
const carried = [...nextIssues.values()].some(existing => (
|
||||
existing.semanticKey === issue.semanticKey
|
||||
))
|
||||
if (!carried) nextIssues.set(issue.id, issue)
|
||||
}
|
||||
openIssues = [...nextIssues.values()].sort((left, right) => left.id.localeCompare(right.id))
|
||||
}
|
||||
return {
|
||||
candidate,
|
||||
synthesis,
|
||||
challengeInputs,
|
||||
verificationInputs,
|
||||
openIssues,
|
||||
}
|
||||
},
|
||||
|
||||
v4NextConvergence(previous, candidate, openIssueIds, round, writerKind) {
|
||||
const { artifact, contentHash } = this.v4ArtifactIdentity(candidate?.artifactId)
|
||||
const sortedIssueIds = [...new Set(openIssueIds || [])].sort()
|
||||
if (contentHash !== candidate?.contentHash || artifact.producedBy.agentKind !== writerKind
|
||||
|| !Number.isSafeInteger(round) || round < 2
|
||||
|| sortedIssueIds.length !== (openIssueIds || []).length
|
||||
|| sortedIssueIds.some(issueId => !/^issue-[a-f0-9]{64}$/.test(issueId))) {
|
||||
throw new Error('LOCAL_RUN_V4_CONVERGENCE_INVALID')
|
||||
}
|
||||
const stateKey = hashValue({ candidateContentHash: contentHash, openIssueIds: sortedIssueIds })
|
||||
const stateChanged = !previous || previous.stateKey !== stateKey
|
||||
let consecutiveStableRounds = 1
|
||||
if (!stateChanged && previous.lastCompletedRound === round - 1) {
|
||||
const previousArtifact = this.v4ArtifactIdentity(previous.candidateArtifactId).artifact
|
||||
if (previousArtifact.producedBy.agentKind === writerKind) {
|
||||
consecutiveStableRounds = previous.consecutiveStableRounds + 1
|
||||
}
|
||||
}
|
||||
return {
|
||||
candidateArtifactId: candidate.artifactId,
|
||||
candidateContentHash: contentHash,
|
||||
openIssueIds: sortedIssueIds,
|
||||
stateKey,
|
||||
lastCompletedRound: round,
|
||||
consecutiveStableRounds,
|
||||
stateEpoch: stateChanged ? (previous?.stateEpoch || 0) + 1 : previous.stateEpoch,
|
||||
acknowledgedGateEpoch: previous?.acknowledgedGateEpoch || 0,
|
||||
}
|
||||
},
|
||||
|
||||
v4ShouldOpenStableGate(convergence, unlimitedRounds) {
|
||||
return unlimitedRounds === true
|
||||
&& convergence?.consecutiveStableRounds >= 2
|
||||
&& convergence.acknowledgedGateEpoch !== convergence.stateEpoch
|
||||
},
|
||||
|
||||
v4Acceptance(receiptRecords, targetKinds, writerKind, verificationKinds, options = {}) {
|
||||
const state = this.v4RoundState(
|
||||
receiptRecords, targetKinds, writerKind, verificationKinds,
|
||||
{ ...options, includeVerification: true },
|
||||
)
|
||||
const proposals = targetKinds.map(kind => (
|
||||
this.v4LatestReceipt(receiptRecords, 'proposal', kind)
|
||||
)).filter(Boolean)
|
||||
const workState = options.coordinationPlan
|
||||
? this.v4WorkState(options.workReceipts, options.coordinationPlan)
|
||||
: null
|
||||
const referencesComplete = proposals.length === targetKinds.length
|
||||
&& proposals.every(record => this.v4ReceiptReferencesComplete(record))
|
||||
&& (!workState || workState.completed.size === options.coordinationPlan.assignments.length)
|
||||
&& this.v4ReceiptReferencesComplete(state.synthesis, state.candidate.artifactId)
|
||||
&& state.challengeInputs.length === targetKinds.length
|
||||
&& state.challengeInputs.every(input => this.v4ReviewReceiptComplete(
|
||||
input, { runId: options.runId },
|
||||
))
|
||||
&& state.verificationInputs.length === verificationKinds.length
|
||||
&& state.verificationInputs.every(input => this.v4ReviewReceiptComplete(
|
||||
input, { runId: options.runId },
|
||||
))
|
||||
const allSupport = state.verificationInputs.length === verificationKinds.length
|
||||
&& state.verificationInputs.every(input => input.record.verdict === 'support')
|
||||
const requiredSlotsHealthy = targetKinds.every(kind => {
|
||||
if (options.coordinationPlan && kind !== writerKind
|
||||
&& !verificationKinds.includes(kind)) {
|
||||
const assignments = options.coordinationPlan.assignments.filter(candidate => (
|
||||
candidate.ownerKind === kind
|
||||
))
|
||||
return assignments.length > 0 && assignments.every(assignment => (
|
||||
workState?.completed.has(assignment.taskId)
|
||||
))
|
||||
}
|
||||
const slot = options.slots?.find(candidate => candidate.agentKind === kind)
|
||||
const requiredPhase = kind === writerKind
|
||||
? 'synthesis'
|
||||
: (verificationKinds.includes(kind)
|
||||
? 'verification'
|
||||
: (options.coordinationPlan ? 'work' : 'challenge'))
|
||||
return slot?.status === 'completed' && slot.phase === requiredPhase
|
||||
})
|
||||
return {
|
||||
accepted: Boolean(referencesComplete && allSupport && requiredSlotsHealthy
|
||||
&& state.openIssues.length === 0),
|
||||
candidateHash: state.candidate.contentHash,
|
||||
candidateArtifactId: state.candidate.artifactId,
|
||||
openIssueIds: state.openIssues.map(issue => issue.id),
|
||||
unresolved: state.openIssues,
|
||||
synthesis: state.synthesis,
|
||||
verifications: state.verificationInputs.map(input => input.record),
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
module.exports = { v4OutcomeMethods }
|
||||
@@ -26,6 +26,9 @@ const CONTINUATION_STABLE_CONTEXT_TEXT_LIMIT = 1400
|
||||
const CONTINUATION_RECENT_CONTEXT_TEXT_LIMIT = 4600
|
||||
const CURRENT_TASK_TEXT_LIMIT = 6000
|
||||
const V4_SNAPSHOT_HISTORY_LIMIT = 16
|
||||
const NATURAL_TRANSCRIPT_TEXT_LIMIT = 48000
|
||||
const NATURAL_TRANSCRIPT_ENTRY_LIMIT = 20000
|
||||
const NATURAL_TRANSCRIPT_OMISSION_NOTICE = 'This transcript is partial: some turns or parts of turns were omitted to fit the context budget. Omission is not evidence of agreement or completion. Ask peers to restate any missing evidence needed to judge the original task.'
|
||||
const V4_SNAPSHOT_FIELDS = [
|
||||
'group', 'history', 'messageId', 'phase', 'snapshotHash',
|
||||
'skillHintsByKind', 'targetKinds', 'taskId', 'taskText', 'version', 'writerKind',
|
||||
@@ -53,6 +56,50 @@ function unlimitedReviewContract(enabled = false) {
|
||||
return enabled ? UNLIMITED_REVIEW_CONTRACT : ''
|
||||
}
|
||||
|
||||
function packNaturalDiscussionTranscript(entries, options = {}) {
|
||||
const prefix = String(options.prefix || '')
|
||||
const latestByKind = new Map(entries.map((entry, index) => [entry.agentKind, index]))
|
||||
let excerpted = entries.some(entry => entry.partial === true)
|
||||
const completeBodies = new Map()
|
||||
const packed = packContextEntries(entries.map((entry, index) => {
|
||||
const heading = `Round ${Number(entry.round) || 0} - @${entry.agentKind}\n`
|
||||
let text = String(entry.text || '').trim()
|
||||
const limit = NATURAL_TRANSCRIPT_ENTRY_LIMIT - heading.length
|
||||
if (text.length > limit) {
|
||||
const marker = '\n[Middle of this turn omitted]\n'
|
||||
const edge = Math.floor((limit - marker.length) / 2)
|
||||
// Preserve closing requests as well as opening findings, without inventing a summary.
|
||||
const head = text.slice(0, edge).replace(/[\uD800-\uDBFF]$/u, '')
|
||||
const tail = text.slice(-edge).replace(/^[\uDC00-\uDFFF]/u, '')
|
||||
text = `${head}${marker}${tail}`
|
||||
excerpted = true
|
||||
} else if (!entry.partial) {
|
||||
completeBodies.set(entry.id, `${heading}${text}`)
|
||||
}
|
||||
return {
|
||||
id: entry.id,
|
||||
text: `${heading}${text}`,
|
||||
priority: index === entries.length - 1 ? 3
|
||||
: latestByKind.get(entry.agentKind) === index ? 2 : 1,
|
||||
}
|
||||
}), {
|
||||
budget: NATURAL_TRANSCRIPT_TEXT_LIMIT - NATURAL_TRANSCRIPT_OMISSION_NOTICE.length - prefix.length - 2,
|
||||
entryLimit: NATURAL_TRANSCRIPT_ENTRY_LIMIT,
|
||||
maxEntries: 100,
|
||||
})
|
||||
const text = [
|
||||
prefix,
|
||||
excerpted || packed.omittedCount ? NATURAL_TRANSCRIPT_OMISSION_NOTICE : '',
|
||||
packed.text,
|
||||
].filter(Boolean).join('\n')
|
||||
return options.withEntries ? {
|
||||
text,
|
||||
completeMessageIds: packed.sourceEntries.filter(entry => (
|
||||
completeBodies.get(entry.id) === entry.text
|
||||
)).map(entry => entry.id),
|
||||
} : text
|
||||
}
|
||||
|
||||
function v4Snapshot({
|
||||
state, group, taskId, targetKinds, message, skillHintsByKind,
|
||||
phase = 'proposal', writerKind = '',
|
||||
@@ -219,6 +266,7 @@ function validateV4SnapshotBody({
|
||||
|
||||
function v4Prompt({
|
||||
group, kind, phase, snapshot, role = 'proposal', receipt = true, skillHints = null,
|
||||
naturalResponse = false,
|
||||
}) {
|
||||
const history = Array.isArray(snapshot?.history) && snapshot.history.length
|
||||
? snapshot.history.map(item => [
|
||||
@@ -227,14 +275,23 @@ function v4Prompt({
|
||||
].join('\n')).join('\n')
|
||||
: '(none)'
|
||||
const selectedAgentCount = Array.isArray(snapshot?.targetKinds) ? snapshot.targetKinds.length : 0
|
||||
const requiredVerifierCount = Math.min(2, Math.max(0, selectedAgentCount - 1))
|
||||
const phaseInstruction = {
|
||||
proposal: 'Develop an independent proposal. State at least one capability, intended work item, and Artifact you will deliver, plus an explicit dependencies array (which may be empty). Do not rely on another Agent output from this batch.',
|
||||
challenge: `Discuss the proposals as peers and negotiate one shared responsibility graph. Every selected Agent must own at least one substantive work package, and an Agent may own multiple dependent work packages. The graph must include one finalizerKind owned by an integrator. It must name exactly ${requiredVerifierCount} distinct verifierKinds from the selected Agents; verifierKinds must not contain finalizerKind. taskId values must be unique; dependsOn may reference only other taskId values and must remain acyclic. inputRefs are exact displayed frozen Source IDs; artifactIds are existing immutable Artifact IDs; future outputs flow only through dependsOn. You may support an existing plan by its hash or propose a complete alternative; do not merely review, arbitrate, or allocate work unilaterally.`,
|
||||
work: 'Execute the agreed responsibility assigned to you. Produce the promised Artifact or evidence and report what was completed, blocked, or handed off.',
|
||||
synthesis: 'Assemble the agreed work products into one bounded deliverable for the user.',
|
||||
verification: 'Verify the proposed deliverable independently and report only material defects or acceptance.',
|
||||
}[phase] || 'Complete the assigned collaboration phase.'
|
||||
const requiredVerifierCount = Math.max(0, selectedAgentCount - 1)
|
||||
const phaseInstruction = naturalResponse
|
||||
? {
|
||||
proposal: 'Work independently on the user task and offer your own analysis, recommendations, and next steps.',
|
||||
discussion: 'Continue from the available peer responses. Add useful evidence, challenge weak assumptions, resolve disagreements where possible, and advance the shared result.',
|
||||
challenge: 'Review the available peer context as a subject-matter peer. Explain what you agree with, what is missing, and the clearest correction or direction.',
|
||||
work: 'Complete the responsibility assigned to you. Report useful work, evidence, blockers, or handoffs in your own words.',
|
||||
synthesis: 'Combine the available work into the clearest useful answer for the user. Resolve contradictions where possible and state remaining uncertainty plainly.',
|
||||
verification: 'Independently check the proposed answer or deliverable. Report material defects, risks, or acceptance in your own words.',
|
||||
}[phase] || 'Address the current collaboration task directly.'
|
||||
: {
|
||||
proposal: 'Develop an independent proposal. State at least one capability, intended work item, and Artifact you will deliver, plus an explicit dependencies array (which may be empty). Do not rely on another Agent output from this batch.',
|
||||
challenge: `Discuss the proposals as peers and negotiate one shared responsibility graph. Every selected Agent must own at least one substantive work package, and an Agent may own multiple dependent work packages. The graph must include one finalizerKind owned by an integrator. It must name exactly ${requiredVerifierCount} distinct verifierKinds from the selected Agents; verifierKinds must not contain finalizerKind. taskId values must be unique; dependsOn may reference only other taskId values and must remain acyclic. inputRefs are exact displayed frozen Source IDs; artifactIds are existing immutable Artifact IDs; future outputs flow only through dependsOn. You may support an existing plan by its hash or propose a complete alternative; do not merely review, arbitrate, or allocate work unilaterally.`,
|
||||
work: 'Execute the agreed responsibility assigned to you. Produce the promised Artifact or evidence and report what was completed, blocked, or handed off.',
|
||||
synthesis: 'Assemble the agreed work products into one bounded deliverable for the user.',
|
||||
verification: 'Verify the proposed deliverable independently and report only material defects or acceptance.',
|
||||
}[phase] || 'Complete the assigned collaboration phase.'
|
||||
const receiptShape = phase === 'proposal'
|
||||
? 'Receipt JSON shape: [[MELDWORK_COLLABORATION:{"summary":"...","capabilities":["..."],"intendedWork":["..."],"deliverables":["..."],"dependencies":[]}]]'
|
||||
: phase === 'challenge'
|
||||
@@ -244,10 +301,11 @@ function v4Prompt({
|
||||
: ['challenge', 'verification'].includes(phase)
|
||||
? 'Receipt JSON shape: [[MELDWORK_COLLABORATION:{"verdict":"support|contradict","summary":"..."}]]'
|
||||
: 'Receipt JSON shape: [[MELDWORK_COLLABORATION:{"summary":"...","resolvedIssueIds":[]}]]'
|
||||
const receiptContract = receipt
|
||||
? [
|
||||
const receiptContract = receipt && !naturalResponse
|
||||
? [
|
||||
'Return the user-facing answer first, then append exactly one structured receipt marker.',
|
||||
receiptShape,
|
||||
'Do not mention the receipt, Meldwork protocol, plan files, plan mode, ExitPlanMode, or whether this is a code task in the user-facing answer. Append nothing after the marker.',
|
||||
'The receipt summary must be concise, factual, and contain no credentials, paths, commands, or private reasoning.',
|
||||
].join('\n')
|
||||
: ''
|
||||
@@ -257,6 +315,24 @@ function v4Prompt({
|
||||
const frozenSkillHints = Array.isArray(skillHints)
|
||||
? skillHints
|
||||
: (snapshot?.skillHintsByKind || []).find(item => item?.kind === kind)?.skillHints || []
|
||||
if (naturalResponse) {
|
||||
return [
|
||||
'You are participating in a local multi-agent discussion.',
|
||||
`User task:\n${cleanText(snapshot?.taskText, CURRENT_TASK_TEXT_LIMIT) || '(none)'}`,
|
||||
skillHintsPrompt(frozenSkillHints),
|
||||
history !== '(none)' ? `Relevant prior context:\n${history}` : '',
|
||||
phaseInstruction,
|
||||
phase === 'proposal'
|
||||
? 'This invocation is read-only. Its deliverable is your initial analysis and proposed next actions. Return that contribution when ready; any workspace changes belong to a later invocation that explicitly grants write permission. Do not attempt or delegate writes from this invocation, or wait here for write permission.'
|
||||
: '',
|
||||
'Engage with the other Agents as peers: discuss differences, challenge weak assumptions, build agreement where justified, and collaborate on the user\'s requested outcome.',
|
||||
'After concrete deliverables exist, review them for material gaps before accepting the result.',
|
||||
phase === 'discussion'
|
||||
? 'Answer the user naturally in Markdown. Keep orchestration instructions out of the answer. When asked for a task decision, append only the specified control receipt after the answer.'
|
||||
: 'Answer the user naturally in Markdown. Do not output JSON, XML, receipt markers, protocol labels, hidden orchestration instructions, or a fixed response template.',
|
||||
'Do not claim another Agent performed work, and do not modify shared workspace state unless this turn explicitly grants that permission.',
|
||||
].filter(Boolean).join('\n\n')
|
||||
}
|
||||
return [
|
||||
'MELDWORK_V4_FROZEN_SNAPSHOT_V1',
|
||||
`Phase: ${phase}`,
|
||||
@@ -346,12 +422,8 @@ function unknownLegacySessionMeta(meta) {
|
||||
function resolveSessionState({
|
||||
state, group, kind, threadRootId = '', taskId = '', save,
|
||||
}) {
|
||||
const scopedTaskId = group.conversationType === 'direct'
|
||||
? ''
|
||||
: cleanText(taskId || threadRootId, 100)
|
||||
const currentTaskId = cleanText(taskId || threadRootId, 100)
|
||||
const key = sessionKey(group.id, kind, scopedTaskId)
|
||||
const globalKey = sessionKey(group.id, kind)
|
||||
const key = sessionKey(group.id, kind)
|
||||
const legacyPrefix = `${group.id}:${kind}:thread:`
|
||||
let stateChanged = false
|
||||
const validStoredRef = (candidateKey) => {
|
||||
@@ -369,7 +441,7 @@ function resolveSessionState({
|
||||
const legacyBase = `agent:main:desktop-meldwork-${legacyScope}-openclaw`
|
||||
if (candidate === legacyBase || candidate.startsWith(`${legacyBase}-`)) {
|
||||
const generation = candidate.slice(legacyBase.length).replace(/^-/, '')
|
||||
candidate = openClawSessionRef(group, generation, scopedTaskId)
|
||||
candidate = openClawSessionRef(group, generation)
|
||||
state.sessions[candidateKey] = candidate
|
||||
stateChanged = true
|
||||
}
|
||||
@@ -389,42 +461,41 @@ function resolveSessionState({
|
||||
return candidate
|
||||
}
|
||||
|
||||
const currentLegacyKey = scopedTaskId
|
||||
? `${legacyPrefix}${scopedTaskId}`
|
||||
: ''
|
||||
const legacyKeys = [...new Set([
|
||||
...(currentTaskId ? [sessionKey(group.id, kind, currentTaskId), `${legacyPrefix}${currentTaskId}`] : []),
|
||||
...[...(state.messages || [])].reverse()
|
||||
.filter(message => message.groupId === group.id && message.role === 'user')
|
||||
.flatMap(message => [sessionKey(group.id, kind, message.id), `${legacyPrefix}${message.id}`]),
|
||||
...Object.keys(state.sessions).reverse().filter(candidate => (
|
||||
candidate.startsWith(legacyPrefix)
|
||||
|| (candidate.startsWith(`${group.id}:task:`) && candidate.endsWith(`:${kind}`))
|
||||
)),
|
||||
])].filter(candidate => candidate !== key)
|
||||
let migration = ''
|
||||
let sessionReset = false
|
||||
let created = false
|
||||
let stored = validStoredRef(key)
|
||||
if (!stored && currentLegacyKey) {
|
||||
const legacyRef = validStoredRef(currentLegacyKey)
|
||||
if (legacyRef) {
|
||||
for (const legacyKey of legacyKeys) {
|
||||
const legacyRef = validStoredRef(legacyKey)
|
||||
if (!stored && legacyRef) {
|
||||
state.sessions[key] = legacyRef
|
||||
state.sessionMeta[key] = completeSessionMeta(
|
||||
state.sessionMeta[currentLegacyKey], 'task', scopedTaskId,
|
||||
)
|
||||
delete state.sessions[currentLegacyKey]
|
||||
delete state.sessionMeta[currentLegacyKey]
|
||||
const legacyMeta = normalizeSessionMeta(state.sessionMeta[legacyKey])
|
||||
state.sessionMeta[key] = ['task', 'conversation'].includes(legacyMeta.sessionScope)
|
||||
? normalizeSessionMeta({ ...legacyMeta, sessionScope: 'conversation' })
|
||||
: unknownLegacySessionMeta(legacyMeta)
|
||||
stored = legacyRef
|
||||
migration = 'migrated'
|
||||
stateChanged = true
|
||||
}
|
||||
}
|
||||
if (!stored && scopedTaskId && globalKey !== key) {
|
||||
// A conversation-scoped legacy Session has no trustworthy task provenance.
|
||||
// Reusing it for a new root can make the Agent continue an unrelated topic.
|
||||
validStoredRef(globalKey)
|
||||
if (Object.hasOwn(state.sessions, globalKey) || Object.hasOwn(state.sessionMeta, globalKey)) {
|
||||
delete state.sessions[globalKey]
|
||||
delete state.sessionMeta[globalKey]
|
||||
sessionReset = true
|
||||
if (Object.hasOwn(state.sessions, legacyKey) || Object.hasOwn(state.sessionMeta, legacyKey)) {
|
||||
delete state.sessions[legacyKey]
|
||||
delete state.sessionMeta[legacyKey]
|
||||
stateChanged = true
|
||||
}
|
||||
}
|
||||
if (!stored && kind === 'openclaw') {
|
||||
state.sessions[key] = openClawSessionRef(group, '', scopedTaskId)
|
||||
state.sessions[key] = openClawSessionRef(group)
|
||||
state.sessionMeta[key] = completeSessionMeta(
|
||||
state.sessionMeta[key], scopedTaskId ? 'task' : 'conversation', currentTaskId,
|
||||
state.sessionMeta[key], 'conversation', currentTaskId,
|
||||
)
|
||||
stateChanged = true
|
||||
stored = state.sessions[key]
|
||||
@@ -439,7 +510,7 @@ function resolveSessionState({
|
||||
if (stateChanged) save()
|
||||
const provenance = created || !stored
|
||||
? {
|
||||
scope: scopedTaskId ? 'task' : 'conversation',
|
||||
scope: 'conversation',
|
||||
reuse: false,
|
||||
origin: 'created',
|
||||
originTaskId: currentTaskId || null,
|
||||
@@ -463,7 +534,7 @@ function resolveSessionState({
|
||||
inheritedTaskIds: [...(meta.inheritedTaskIds || [])],
|
||||
completeness: meta.provenanceCompleteness || 'partial',
|
||||
}
|
||||
return { key, sessionRef: stored, sessionMeta: meta, provenance, sessionReset }
|
||||
return { key, sessionRef: stored, sessionMeta: meta, provenance, sessionReset: false }
|
||||
}
|
||||
|
||||
function resolveSessionRef(options) {
|
||||
@@ -570,12 +641,14 @@ function stableUserInstructions(state, groupId, threadRootId = '', contextOption
|
||||
function recentTranscriptEntries(state, groupId, afterAgentKind = '', contextOptions = {}) {
|
||||
const messages = scopedConversationMessages(state, groupId, contextOptions)
|
||||
let afterIndex = -1
|
||||
const afterMessageId = cleanText(contextOptions.afterMessageId, 100)
|
||||
if (afterMessageId) afterIndex = messages.findIndex(message => message.id === afterMessageId)
|
||||
if (afterAgentKind) {
|
||||
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
||||
const message = messages[index]
|
||||
if (message.agentKind === afterAgentKind
|
||||
&& (message.role === 'agent' || isTracedAgentTerminalMessage(message))) {
|
||||
afterIndex = index
|
||||
afterIndex = Math.max(afterIndex, index)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -622,11 +695,13 @@ function packedPromptContext({
|
||||
excludeResponseVersionRootId = '',
|
||||
focusUserMessageId = '',
|
||||
omitAgentThreadRootId = '',
|
||||
afterMessageId = '',
|
||||
}) {
|
||||
const contextOptions = {
|
||||
beforeMessageId,
|
||||
excludeResponseVersionRootId,
|
||||
focusUserMessageId,
|
||||
afterMessageId: cleanText(afterMessageId, 100),
|
||||
}
|
||||
const scopedMessages = scopedConversationMessages(state, groupId, contextOptions)
|
||||
const focusId = cleanText(focusUserMessageId, 100)
|
||||
@@ -718,6 +793,7 @@ function packedPromptContext({
|
||||
currentTaskText,
|
||||
latestUserLanguage: responseLanguageFromText(latestUserMessage?.content),
|
||||
latestUserMessageId: latestUserMessage?.id || '',
|
||||
latestMessageId: scopedMessages.at(-1)?.id || '',
|
||||
...bootstrapSelection,
|
||||
continuationSourceMessageIds: continuationSelection.sourceMessageIds,
|
||||
continuationSourceEntries: continuationSelection.sourceEntries,
|
||||
@@ -822,6 +898,7 @@ function promptFor({
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
packNaturalDiscussionTranscript,
|
||||
clearSessionState,
|
||||
openClawSessionRef,
|
||||
packedPromptContext,
|
||||
|
||||
@@ -3,6 +3,7 @@ const AGENT_LABELS = {
|
||||
hermes: 'Hermes',
|
||||
openclaw: 'OpenClaw',
|
||||
workbuddy: 'WorkBuddy',
|
||||
pi: 'Pi Agent',
|
||||
kimi: 'Kimi',
|
||||
mimo: 'MiMo',
|
||||
claude: 'Claude',
|
||||
@@ -12,6 +13,7 @@ const AGENT_LABELS = {
|
||||
opencodereview: 'OpenCodeReview',
|
||||
}
|
||||
const CUSTOM_AGENT_KIND = /^custom-[a-f0-9]{16}$/
|
||||
const CLOUD_AGENT_KIND = /^cloud-[a-f0-9]{24}$/
|
||||
const MAX_MESSAGE_TEXT_CHARS = 20000
|
||||
const MAX_SYSTEM_PARAM_TEXT_CHARS = 1000
|
||||
const STABLE_USER_TURNS_PER_EDGE = 3
|
||||
@@ -22,7 +24,10 @@ const RECENT_TRANSCRIPT_TEXT_LIMIT = 9000
|
||||
const SESSION_KEY = /^[A-Za-z0-9._:-]{1,240}$/
|
||||
|
||||
function isSupportedAgentKind(kind) {
|
||||
return Object.hasOwn(AGENT_LABELS, kind) || CUSTOM_AGENT_KIND.test(String(kind || ''))
|
||||
const normalized = String(kind || '')
|
||||
return Object.hasOwn(AGENT_LABELS, normalized)
|
||||
|| CUSTOM_AGENT_KIND.test(normalized)
|
||||
|| CLOUD_AGENT_KIND.test(normalized)
|
||||
}
|
||||
|
||||
function defaultAgentLabel(kind) {
|
||||
@@ -44,6 +49,7 @@ function cleanInline(value, limit = 80) {
|
||||
|
||||
module.exports = {
|
||||
AGENT_LABELS,
|
||||
CLOUD_AGENT_KIND,
|
||||
CUSTOM_AGENT_KIND,
|
||||
MAX_MESSAGE_TEXT_CHARS,
|
||||
MAX_SYSTEM_PARAM_TEXT_CHARS,
|
||||
|
||||
@@ -48,10 +48,31 @@ class LocalWorkspaceRunLedger {
|
||||
try { this.runLedger?.deleteGroup?.(record.groupId) } catch {}
|
||||
continue
|
||||
}
|
||||
for (const agentRun of Array.isArray(record.agentRuns) ? record.agentRuns : []) {
|
||||
const agentRuns = Array.isArray(record.agentRuns) ? record.agentRuns : []
|
||||
const latestAttemptByKind = new Map()
|
||||
for (const attempt of Array.isArray(record.attemptHistory) ? record.attemptHistory : []) {
|
||||
const previous = latestAttemptByKind.get(attempt.agentKind)
|
||||
if (!previous || attempt.sequence > previous.sequence) {
|
||||
latestAttemptByKind.set(attempt.agentKind, attempt)
|
||||
}
|
||||
}
|
||||
const latestTerminalFailureByKind = new Map()
|
||||
for (const agentRun of agentRuns) {
|
||||
if (['failed', 'timeout'].includes(String(agentRun?.status || '').toLowerCase())) {
|
||||
latestTerminalFailureByKind.set(agentRun.kind, agentRun.agentRunId)
|
||||
}
|
||||
}
|
||||
for (const agentRun of agentRuns) {
|
||||
const status = String(agentRun?.status || '').toLowerCase()
|
||||
if (!RECOVERABLE_AGENT_STATUSES.has(status)
|
||||
|| !isSupportedAgentKind(agentRun?.kind)) continue
|
||||
if (['failed', 'timeout'].includes(status)) {
|
||||
const latestAttempt = latestAttemptByKind.get(agentRun.kind)
|
||||
if (latestAttempt?.finalOutcome === 'succeeded'
|
||||
|| latestTerminalFailureByKind.get(agentRun.kind) !== agentRun.agentRunId) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
const output = cleanText(agentRun.output, DEFAULT_MAX_OUTPUT_CHARS)
|
||||
const trace = traceCapsuleFromAgentRun({
|
||||
...agentRun,
|
||||
|
||||
@@ -19,7 +19,6 @@ const {
|
||||
terminalRunStatusForReason,
|
||||
} = require('./local-workspace-inputs.cjs')
|
||||
const { MAX_RUN_AGENT_ATTEMPTS } = require('../runs/failure-policy.cjs')
|
||||
const { mediaGenerationRequest } = require('../media/media-generation-request.cjs')
|
||||
const { createTaskGraph } = require('../collaboration/task-graph-records.cjs')
|
||||
const { assertLocalSkillExecution } = require('../skills/local-skill-contract.cjs')
|
||||
const {
|
||||
@@ -45,6 +44,8 @@ const {
|
||||
validateV4SnapshotBody,
|
||||
} = require('./local-workspace-context.cjs')
|
||||
|
||||
const DISCUSSION_STYLES = new Set(['sequential', 'agent-led'])
|
||||
|
||||
function hardBudgetFailure(error) {
|
||||
return error?.code === 'LOCAL_BUDGET_EXHAUSTED'
|
||||
|| error?.message === 'LOCAL_BUDGET_EXHAUSTED'
|
||||
@@ -254,7 +255,6 @@ class LocalWorkspaceMessageSubmission {
|
||||
]))
|
||||
return {
|
||||
text,
|
||||
mediaRequest: mediaGenerationRequest(text),
|
||||
attachments,
|
||||
skillHintsByKind,
|
||||
skillHints: targetKinds.flatMap(kind => publicSkillHintsByKind.get(kind) || []),
|
||||
@@ -280,7 +280,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
minContextChars: Math.max(1, cleanText(input.text).length),
|
||||
})
|
||||
const targetKinds = routingDecision.selectedKinds
|
||||
if (mode === 'auto' && targetKinds.length < 2) throw new Error('LOCAL_AUTO_AGENT_COUNT')
|
||||
if (mode === 'auto' && !targetKinds.length) throw new Error('LOCAL_AUTO_AGENT_COUNT')
|
||||
if (input.mentionedAgentKinds != null && !Array.isArray(input.mentionedAgentKinds)) {
|
||||
throw new Error('LOCAL_MESSAGE_TARGET_REQUIRED')
|
||||
}
|
||||
@@ -337,15 +337,28 @@ class LocalWorkspaceMessageSubmission {
|
||||
if (regenerateMessageId && (mode !== 'manual' || targetKinds.length !== 1)) {
|
||||
throw new Error('LOCAL_MESSAGE_REGENERATION_INVALID')
|
||||
}
|
||||
const v4 = (mode === 'manual' || mode === 'auto')
|
||||
&& group.conversationType !== 'direct'
|
||||
&& (targetKinds.length > 1 || (mode === 'auto' && targetKinds.length === 1))
|
||||
&& !regenerateMessageId
|
||||
&& input.protocol !== 'legacy'
|
||||
&& this.v4Requested(input)
|
||||
const requestedDiscussionStyle = input.discussionStyle == null
|
||||
? ''
|
||||
: cleanInline(input.discussionStyle, 40)
|
||||
if (requestedDiscussionStyle && !DISCUSSION_STYLES.has(requestedDiscussionStyle)) {
|
||||
throw new Error('LOCAL_DISCUSSION_STYLE_INVALID')
|
||||
}
|
||||
if (requestedDiscussionStyle && (mode !== 'auto' || !v4)) {
|
||||
throw new Error('LOCAL_DISCUSSION_STYLE_UNSUPPORTED')
|
||||
}
|
||||
return {
|
||||
mode,
|
||||
targetKinds,
|
||||
v4: (mode === 'manual' || mode === 'auto')
|
||||
&& group.conversationType !== 'direct'
|
||||
&& targetKinds.length > 1
|
||||
&& !regenerateMessageId
|
||||
&& input.protocol !== 'legacy'
|
||||
&& this.v4Requested(input),
|
||||
v4,
|
||||
discussionStyle: mode === 'auto' && v4
|
||||
? (requestedDiscussionStyle || 'sequential')
|
||||
: '',
|
||||
unlimitedRounds,
|
||||
maxRounds,
|
||||
requestedThreadRootId,
|
||||
@@ -735,7 +748,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
}
|
||||
|
||||
async commitV4ManualBarrier({ group, controller, targetKinds, slots, snapshotRecord,
|
||||
batchId, writerKind }) {
|
||||
batchId, writerKind, allowStoppedCommit = false }) {
|
||||
const successfulSlots = slots.filter(slot => ['completed', 'partial'].includes(slot.status))
|
||||
const committedKinds = successfulSlots
|
||||
.filter(slot => slot.commitStatus === 'committed')
|
||||
@@ -777,7 +790,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
this.checkpointV4Manual(group, controller)
|
||||
|
||||
for (const slot of successfulSlots) {
|
||||
if (controller.signal.aborted) break
|
||||
if (controller.signal.aborted && !allowStoppedCommit) break
|
||||
const resultBody = this.loadV4ResultBody(slot)
|
||||
const workflowRecord = slot.resultRefs?.workflowOutcomeRefs?.find(item => (
|
||||
item?.receipt?.receiptId === slot.receiptId
|
||||
@@ -918,6 +931,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
singleWriterKind: writerKind || '',
|
||||
parallelGraph: true,
|
||||
deferMessage: true,
|
||||
allowMissingProposalReceipt: true,
|
||||
operationId: slot.operationId,
|
||||
onLeaseAcquired: (leaseState) => {
|
||||
if (leaseAcquired) return
|
||||
@@ -1112,9 +1126,13 @@ class LocalWorkspaceMessageSubmission {
|
||||
if (!controller.signal.aborted && slot.status === 'completed') continue
|
||||
const error = item.error || item.invocation?.error || new Error('LOCAL_AGENT_UNKNOWN_FAILURE')
|
||||
failures.push({ ...item, error })
|
||||
if (!controller.signal.aborted) this.recordAgentFailure(
|
||||
group.id, item.kind, error, threadRootId,
|
||||
)
|
||||
if (!controller.signal.aborted) {
|
||||
this.recordAgentFailure(group.id, item.kind, error, threadRootId)
|
||||
} else if (controller.stopReason === 'user'
|
||||
&& slot.agentRunId
|
||||
&& error?.runTrace?.agentRunId === slot.agentRunId) {
|
||||
this.recordAgentInterruption(group.id, item.kind, error, threadRootId, 'stopped')
|
||||
}
|
||||
}
|
||||
controller.completedKinds = targetKinds.filter(kind => {
|
||||
const status = slots.find(slot => slot.agentKind === kind)?.status
|
||||
@@ -1188,7 +1206,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
const successfulKinds = slots
|
||||
.filter(slot => ['completed', 'partial'].includes(slot.status))
|
||||
.map(slot => slot.agentKind)
|
||||
if (!controller.signal.aborted) {
|
||||
if (!controller.signal.aborted || controller.stopReason === 'user') {
|
||||
await this.commitV4ManualBarrier({
|
||||
group,
|
||||
controller,
|
||||
@@ -1197,6 +1215,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
snapshotRecord: frozenSnapshot.record,
|
||||
batchId,
|
||||
writerKind,
|
||||
allowStoppedCommit: controller.stopReason === 'user',
|
||||
})
|
||||
}
|
||||
return {
|
||||
@@ -1422,6 +1441,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
regenerateMessageId,
|
||||
routingDecision,
|
||||
taskGraph,
|
||||
discussionStyle,
|
||||
} = this.validateInput(group, input)
|
||||
const regeneration = this.resolveRegeneration(group, regenerateMessageId, targetKinds)
|
||||
const reservation = this.reserveRun(
|
||||
@@ -1433,6 +1453,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
unlimitedRounds,
|
||||
)
|
||||
reservation.v4 = v4
|
||||
reservation.discussionStyle = discussionStyle
|
||||
try {
|
||||
if (regeneration) reservation.responseVersionRootId = regeneration.responseVersionRootId
|
||||
this.configureRunBudget(reservation, input.budget || {})
|
||||
@@ -1581,7 +1602,6 @@ class LocalWorkspaceMessageSubmission {
|
||||
let activeKinds = [...targetKinds]
|
||||
const pendingKinds = [...targetKinds]
|
||||
const replacementInstructions = new Map()
|
||||
const mediaOwnerKind = prepared.mediaRequest ? targetKinds[0] : ''
|
||||
while (pendingKinds.length) {
|
||||
const kind = pendingKinds.shift()
|
||||
if (!activeKinds.includes(kind)) continue
|
||||
@@ -1613,7 +1633,6 @@ class LocalWorkspaceMessageSubmission {
|
||||
attachmentSnapshots: prepared.attachments,
|
||||
sessionThreadRootId: requestedThreadRootId || threadRootId,
|
||||
runtimeInstruction: replacementInstructions.get(kind) || '',
|
||||
mediaRequest: kind === mediaOwnerKind ? prepared.mediaRequest : null,
|
||||
responseVersionRootId: regeneration?.responseVersionRootId || '',
|
||||
regenerationInstruction: regeneration ? this.regenerationInstruction() : '',
|
||||
contextOptions: regeneration
|
||||
@@ -1758,7 +1777,7 @@ class LocalWorkspaceMessageSubmission {
|
||||
? normalizeTargetKinds(input.targetKinds)
|
||||
: group.agentKinds
|
||||
const targetKinds = [...new Set(requested.filter(kind => group.agentKinds.includes(kind)))]
|
||||
if (targetKinds.length < 2) throw new Error('LOCAL_AUTO_AGENT_COUNT')
|
||||
if (!targetKinds.length) throw new Error('LOCAL_AUTO_AGENT_COUNT')
|
||||
const unlimitedRounds = input.unlimitedRounds === true
|
||||
const maxRounds = unlimitedRounds
|
||||
? 0
|
||||
@@ -1791,6 +1810,18 @@ class LocalWorkspaceMessageSubmission {
|
||||
group.id, 'auto', targetKinds, threadRootId, maxRounds, unlimitedRounds,
|
||||
)
|
||||
reservation.v4 = input.protocol !== 'legacy' && this.v4Requested(input)
|
||||
const requestedDiscussionStyle = input.discussionStyle == null
|
||||
? ''
|
||||
: cleanInline(input.discussionStyle, 40)
|
||||
if (requestedDiscussionStyle && !DISCUSSION_STYLES.has(requestedDiscussionStyle)) {
|
||||
this.releasePreparation(group.id, reservation)
|
||||
throw new Error('LOCAL_DISCUSSION_STYLE_INVALID')
|
||||
}
|
||||
if (requestedDiscussionStyle && !reservation.v4) {
|
||||
this.releasePreparation(group.id, reservation)
|
||||
throw new Error('LOCAL_DISCUSSION_STYLE_UNSUPPORTED')
|
||||
}
|
||||
reservation.discussionStyle = requestedDiscussionStyle || 'sequential'
|
||||
try {
|
||||
this.configureRunBudget(reservation, input.budget || {})
|
||||
const contextPack = this.createContextPack({
|
||||
|
||||
@@ -18,6 +18,17 @@ class LocalWorkspaceRunMessages {
|
||||
this.addMessage = options.addMessage
|
||||
}
|
||||
|
||||
responseVersionRootId(groupId, kind, threadRootId, trace = null) {
|
||||
const traceRound = Number(trace?.round)
|
||||
const round = Number.isInteger(traceRound) && traceRound >= 0 ? traceRound : 1
|
||||
const phase = cleanText(trace?.phase, 40)
|
||||
|| cleanText(trace?.context?.phase, 40)
|
||||
|| 'response'
|
||||
return `response-${createHash('sha256').update(JSON.stringify([
|
||||
String(groupId || ''), String(threadRootId || ''), String(kind || ''), round, phase,
|
||||
])).digest('hex').slice(0, 48)}`
|
||||
}
|
||||
|
||||
recordFailure(groupId, kind, error, threadRootId, reportedFailures = null) {
|
||||
const label = this.agentLabel(kind)
|
||||
const reason = cleanText(error?.message || error, MAX_SYSTEM_PARAM_TEXT_CHARS)
|
||||
@@ -29,6 +40,8 @@ class LocalWorkspaceRunMessages {
|
||||
this.checkpointRun(groupId, controller)
|
||||
}
|
||||
const streamedConclusion = this.streamedConclusion(groupId, agentRunId)
|
||||
const trace = error?.runTrace || null
|
||||
const responseVersionRootId = this.responseVersionRootId(groupId, kind, threadRootId, trace)
|
||||
const hardBudget = reason === 'LOCAL_BUDGET_EXHAUSTED'
|
||||
&& error?.decision?.action === 'terminal'
|
||||
const content = terminalMessageContent(
|
||||
@@ -60,7 +73,7 @@ class LocalWorkspaceRunMessages {
|
||||
kind,
|
||||
threadRootId,
|
||||
system,
|
||||
{ trace: error?.runTrace },
|
||||
{ trace, responseVersionRootId },
|
||||
)
|
||||
}
|
||||
return { label, reason }
|
||||
@@ -90,6 +103,7 @@ class LocalWorkspaceRunMessages {
|
||||
}
|
||||
const interrupted = status === 'interrupted'
|
||||
const streamedConclusion = this.streamedConclusion(groupId, trace.agentRunId)
|
||||
const responseVersionRootId = this.responseVersionRootId(groupId, kind, threadRootId, trace)
|
||||
this.addMessage(
|
||||
groupId,
|
||||
'system',
|
||||
@@ -100,7 +114,7 @@ class LocalWorkspaceRunMessages {
|
||||
key: interrupted ? 'system.agentInterrupted' : 'system.agentStopped',
|
||||
params: { agent: label },
|
||||
},
|
||||
{ trace },
|
||||
{ trace, responseVersionRootId },
|
||||
)
|
||||
return trace
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ const {
|
||||
const AUTO_CONSENSUS_MARKER = /\[\[MELDWORK_CONSENSUS:(agree|continue)\]\]/gi
|
||||
const AUTO_FINAL_CONSENSUS_MARKER = /(?:^|\r?\n)[ \t]*\[\[MELDWORK_CONSENSUS:(agree|continue)\]\][ \t]*$/i
|
||||
const DEFAULT_RUN_SILENCE_WARNING_MS = 20 * 1000
|
||||
const DEFAULT_RUN_AGENT_TIMEOUT_MS = 15 * 60 * 1000
|
||||
const DEFAULT_RUN_AGENT_TIMEOUT_MS = 3 * 60 * 1000
|
||||
const DEFAULT_RUN_AGENT_TOOL_TIMEOUT_MS = 5 * 60 * 1000
|
||||
const DEFAULT_RUN_ABORT_GRACE_MS = 2500
|
||||
const DEFAULT_AUTO_ROUNDS = 6
|
||||
const MAX_AUTO_ROUNDS = 10
|
||||
@@ -191,6 +192,7 @@ module.exports = {
|
||||
DEFAULT_AUTO_ROUNDS,
|
||||
DEFAULT_RUN_ABORT_GRACE_MS,
|
||||
DEFAULT_RUN_AGENT_TIMEOUT_MS,
|
||||
DEFAULT_RUN_AGENT_TOOL_TIMEOUT_MS,
|
||||
DEFAULT_RUN_SILENCE_WARNING_MS,
|
||||
HERMES_WORKSPACE_ACP_ENABLED,
|
||||
RECOVERABLE_AGENT_STATUSES,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const { RUN_STATUSES } = require('../runs/run-ledger-records.cjs')
|
||||
const { normalizeSessionMeta } = require('../runs/run-harness.cjs')
|
||||
const {
|
||||
SESSION_KEY,
|
||||
@@ -19,7 +20,7 @@ const FAILED_AGENT_STATUSES = new Set(['failed', 'stopped', 'timeout'])
|
||||
const TERMINAL_PERSISTENCE_STATES = new Set(['pending', 'retrying', 'failed'])
|
||||
|
||||
const V4_PHASES = new Set([
|
||||
'prepare', 'dispatch', 'running', 'reconcile', 'proposal', 'challenge',
|
||||
'prepare', 'dispatch', 'running', 'reconcile', 'proposal', 'discussion', 'challenge',
|
||||
'coordination', 'work', 'synthesis', 'verification', 'commit', 'committed', 'completed',
|
||||
'human-gate', 'stopped', 'failed',
|
||||
])
|
||||
@@ -244,9 +245,7 @@ function saveWorkspaceState(storagePath, state) {
|
||||
fs.renameSync(tempPath, storagePath)
|
||||
}
|
||||
|
||||
function durableWaitingRunSnapshots({ state, runLedger, pendingGates, liveRunIds, liveGroupIds }) {
|
||||
let records = []
|
||||
try { records = runLedger?.list?.() || [] } catch { return [] }
|
||||
function durableWaitingRunSnapshots({ state, records, pendingGates, liveRunIds, liveGroupIds }) {
|
||||
const groupIds = new Set(state.groups.map(group => group.id))
|
||||
const pendingById = new Map(pendingGates.map(gate => [gate.gateId, gate]))
|
||||
const projectedGroupIds = new Set()
|
||||
@@ -319,6 +318,23 @@ function workspaceSnapshot({
|
||||
detectedAgents, state, preparingRuns, activeRuns, humanGateCoordinator, runLedger,
|
||||
workspaceRecovery,
|
||||
}) {
|
||||
let records = []
|
||||
try { records = runLedger?.list?.() || [] } catch { /* retain the visible workspace on ledger read failure */ }
|
||||
const groupIds = new Set(state.groups.map(group => group.id))
|
||||
const roots = new Map(state.messages.filter(message => message.role === 'user' && !message.threadRootId)
|
||||
.map(message => [message.id, message.groupId]))
|
||||
const latestOutcomes = new Map()
|
||||
for (const record of records) {
|
||||
if (!groupIds.has(record.groupId) || roots.get(record.threadRootId) !== record.groupId
|
||||
|| !RUN_STATUSES.has(record.status)) continue
|
||||
const previous = latestOutcomes.get(record.threadRootId)
|
||||
if (previous && previous.startedAt >= record.startedAt) continue
|
||||
latestOutcomes.set(record.threadRootId, {
|
||||
groupId: record.groupId, runId: record.runId, threadRootId: record.threadRootId,
|
||||
status: record.status, targetKinds: [...record.targetKinds],
|
||||
startedAt: record.startedAt, finishedAt: record.finishedAt || 0,
|
||||
})
|
||||
}
|
||||
const busyEntries = [
|
||||
...[...preparingRuns.entries()].map(entry => [...entry, 'preparing']),
|
||||
...[...activeRuns.entries()].map(entry => [...entry, 'running']),
|
||||
@@ -330,7 +346,7 @@ function workspaceSnapshot({
|
||||
const liveRunIds = new Set(runEntries.map(([, run]) => run.runId).filter(Boolean))
|
||||
const liveGroupIds = new Set(busyEntries.map(([groupId]) => groupId))
|
||||
const durableRunEntries = durableWaitingRunSnapshots({
|
||||
state, runLedger, pendingGates, liveRunIds, liveGroupIds,
|
||||
state, records, pendingGates, liveRunIds, liveGroupIds,
|
||||
})
|
||||
const liveRunEntries = runEntries.map(([groupId, run, phase]) => {
|
||||
const mode = run.mode === 'auto' ? 'auto' : 'manual'
|
||||
@@ -404,6 +420,7 @@ function workspaceSnapshot({
|
||||
])],
|
||||
humanGates: publicGates,
|
||||
runs: publicRuns,
|
||||
runOutcomes: [...latestOutcomes.values()],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ const { EventEmitter } = require('node:events')
|
||||
const { createHash, randomUUID } = require('node:crypto')
|
||||
const path = require('node:path')
|
||||
const { ContentBlobStore } = require('../attachments/content-blob-store.cjs')
|
||||
const { agentRuntimeCapabilities } = require('../agents/agent-runtime-contract.cjs')
|
||||
const { ContextPackStore } = require('../collaboration/context-pack-store.cjs')
|
||||
const { HumanGateCoordinator } = require('../gates/human-gate-coordinator.cjs')
|
||||
const { HumanGateStore } = require('../gates/human-gate-store.cjs')
|
||||
@@ -50,6 +51,9 @@ const {
|
||||
normalizeSessionRef,
|
||||
terminalRunStatusForReason,
|
||||
} = require('./local-workspace-inputs.cjs')
|
||||
const {
|
||||
DEFAULT_RUN_AGENT_TOOL_TIMEOUT_MS,
|
||||
} = require('./local-workspace-runtime-contracts.cjs')
|
||||
const { MAX_RUN_AGENT_ATTEMPTS } = require('../runs/failure-policy.cjs')
|
||||
const {
|
||||
loadWorkspaceState,
|
||||
@@ -63,6 +67,47 @@ const TERMINAL_RUN_STATUSES = new Set([
|
||||
'completed', 'partial', 'failed', 'stopped', 'timeout', 'round-limit', 'interrupted',
|
||||
'budget-exhausted', 'circuit-breaker',
|
||||
])
|
||||
const V4_VISIBLE_MESSAGE_PHASES = ['proposal', 'discussion', 'challenge', 'work', 'verification']
|
||||
|
||||
function naturalV4MessageBindingMatches(message, record, phase) {
|
||||
if (!record.orchestration?.discussionStyle || !['proposal', 'discussion'].includes(phase)) {
|
||||
return true
|
||||
}
|
||||
const round = Number(message?.trace?.round) || 0
|
||||
const slot = record.orchestration.slots?.find(candidate => (
|
||||
candidate.agentKind === message.agentKind
|
||||
))
|
||||
if (round < 1 || !slot?.slotId) return false
|
||||
const operationPhase = phase === 'discussion' ? `discussion:${round}` : phase
|
||||
const operationId = `operation-${createHash('sha256').update(JSON.stringify([
|
||||
record.runId,
|
||||
record.taskId,
|
||||
message.agentKind,
|
||||
slot.slotId,
|
||||
operationPhase,
|
||||
round,
|
||||
])).digest('hex')}`
|
||||
return message.trace?.context?.operationId === operationId
|
||||
&& message.trace?.context?.snapshotHash === record.orchestration.snapshotHash
|
||||
}
|
||||
|
||||
function isCommittedV4PhaseMessage(message, record) {
|
||||
const agentRunId = String(message?.trace?.agentRunId || '')
|
||||
if (message?.role !== 'agent' || message?.groupId !== record.groupId
|
||||
|| message?.trace?.runId !== record.runId || !message.agentKind || !agentRunId) {
|
||||
return false
|
||||
}
|
||||
return V4_VISIBLE_MESSAGE_PHASES.some((phase) => {
|
||||
if (message.id !== `message-${hashValue({
|
||||
agentKind: message.agentKind,
|
||||
agentRunId,
|
||||
phase,
|
||||
runId: record.runId,
|
||||
taskId: record.taskId,
|
||||
})}`) return false
|
||||
return naturalV4MessageBindingMatches(message, record, phase)
|
||||
})
|
||||
}
|
||||
|
||||
class LocalWorkspace extends EventEmitter {
|
||||
constructor(options) {
|
||||
@@ -70,7 +115,6 @@ class LocalWorkspace extends EventEmitter {
|
||||
this.storagePath = options.storagePath
|
||||
this.detectAgentsFn = options.detectAgents
|
||||
this.runAgentFn = options.runAgent
|
||||
this.generateMediaFn = options.generateMedia || null
|
||||
this.resolveAttachmentsFn = options.resolveAttachments || (async (attachments) => {
|
||||
if (attachments?.length) throw new Error('LOCAL_ATTACHMENT_STORAGE_UNAVAILABLE')
|
||||
return []
|
||||
@@ -97,6 +141,10 @@ class LocalWorkspace extends EventEmitter {
|
||||
&& options.runAgentTimeoutMs > 0
|
||||
? options.runAgentTimeoutMs
|
||||
: DEFAULT_RUN_AGENT_TIMEOUT_MS
|
||||
this.runAgentToolTimeoutMs = Number.isFinite(options.runAgentToolTimeoutMs)
|
||||
&& options.runAgentToolTimeoutMs > 0
|
||||
? options.runAgentToolTimeoutMs
|
||||
: DEFAULT_RUN_AGENT_TOOL_TIMEOUT_MS
|
||||
this.runAbortGraceMs = Number.isFinite(options.runAbortGraceMs)
|
||||
&& options.runAbortGraceMs > 0
|
||||
? options.runAbortGraceMs
|
||||
@@ -224,7 +272,10 @@ class LocalWorkspace extends EventEmitter {
|
||||
detectedAgents: () => this.detectedAgents,
|
||||
activeRuns: this.activeRuns,
|
||||
runAgentTimeoutMs: this.runAgentTimeoutMs,
|
||||
runAgentToolTimeoutMs: this.runAgentToolTimeoutMs,
|
||||
runAbortGraceMs: this.runAbortGraceMs,
|
||||
defaultYolo: options.defaultYolo,
|
||||
naturalAgentResponses: options.naturalAgentResponses,
|
||||
captureAgentOutputs: (...args) => this.captureAgentOutputsFn(...args),
|
||||
captureArtifactOutputs: (...args) => this.captureArtifactOutputsFn(...args),
|
||||
captureAgentOutcomeDescriptors: (...args) => (
|
||||
@@ -259,15 +310,19 @@ class LocalWorkspace extends EventEmitter {
|
||||
completeHumanGateContinuation: (...args) => this.completeHumanGateContinuation(...args),
|
||||
connectorRuntime: options.connectorRuntime,
|
||||
attachmentSupport: (...args) => this.attachmentSupportFn(...args),
|
||||
generateMedia: (...args) => this.generateMediaFn?.(...args),
|
||||
})
|
||||
this.autoRunner = new LocalWorkspaceAutoRunner({
|
||||
state: () => this.state,
|
||||
canWriteWorkspace: kind => agentRuntimeCapabilities(kind, {
|
||||
agent: this.detectedAgents.find(agent => agent.kind === kind),
|
||||
}).permissionModes.includes('workspace-write'),
|
||||
beginRun: (...args) => this.beginRun(...args),
|
||||
resolveAttachments: (...args) => this.resolveAttachments(...args),
|
||||
validateSkillSelections: (...args) => this.validateSkillSelectionsFn(...args),
|
||||
validateKnowledgeBaseSelections: (...args) => this.validateKnowledgeBaseSelectionsFn(...args),
|
||||
invokeAgent: (...args) => this.invokeAgent(...args),
|
||||
defaultYolo: options.defaultYolo,
|
||||
naturalAgentResponses: options.naturalAgentResponses,
|
||||
resetAgentSession: (...args) => this.resetAgentSession(...args),
|
||||
refreshAgents: () => this.refreshAgents(),
|
||||
consumeAgentControl: (...args) => this.runCoordinator.consumeAgentControl(...args),
|
||||
@@ -276,6 +331,7 @@ class LocalWorkspace extends EventEmitter {
|
||||
recordAgentFailure: (...args) => this.recordAgentFailure(...args),
|
||||
recordAgentInterruption: (...args) => this.recordAgentInterruption(...args),
|
||||
addMessage: (...args) => this.addMessage(...args),
|
||||
removeAgent: (...args) => this.conversations.removeAgent(...args),
|
||||
commitV4AgentMessage: input => this.commitV4AgentMessage(input),
|
||||
emitChanged: () => this.emitChanged(),
|
||||
finishRun: (...args) => this.finishRun(...args),
|
||||
@@ -285,6 +341,8 @@ class LocalWorkspace extends EventEmitter {
|
||||
hasRunLedger: () => Boolean(this.runLedger),
|
||||
requestHumanGate: (...args) => this.requestHumanGate(...args),
|
||||
completeHumanGateContinuation: (...args) => this.completeHumanGateContinuation(...args),
|
||||
requestTaskDecision: (...args) => this.requestV4TaskDecision(...args),
|
||||
taskDecisionResponses: runId => this.v4TaskDecisionResponses(runId),
|
||||
retryContract: kind => ({
|
||||
idempotencyMode: this.detectedAgents.find(agent => agent.kind === kind)?.idempotencyMode
|
||||
=== 'durable'
|
||||
@@ -397,7 +455,9 @@ class LocalWorkspace extends EventEmitter {
|
||||
? [durable.orchestration.candidateCommit.messageId] : []),
|
||||
])
|
||||
const retainedMessages = this.state.messages.filter(message => (
|
||||
message.trace?.runId !== durable.runId || allowedMessageIds.has(message.id)
|
||||
message.trace?.runId !== durable.runId
|
||||
|| allowedMessageIds.has(message.id)
|
||||
|| isCommittedV4PhaseMessage(message, durable)
|
||||
))
|
||||
if (retainedMessages.length !== this.state.messages.length) {
|
||||
this.state.messages = retainedMessages
|
||||
@@ -443,7 +503,7 @@ class LocalWorkspace extends EventEmitter {
|
||||
const commitState = orchestration?.commitState
|
||||
const candidateCommit = orchestration?.candidateCommit
|
||||
const resumablePhase = [
|
||||
'proposal', 'challenge', 'coordination', 'work', 'synthesis', 'verification',
|
||||
'proposal', 'discussion', 'challenge', 'coordination', 'work', 'synthesis', 'verification',
|
||||
].includes(orchestration?.phase)
|
||||
const resumableCommit = ['commit', 'committed', 'completed'].includes(orchestration?.phase)
|
||||
&& ['committing', 'committed'].includes(commitState?.status)
|
||||
@@ -603,6 +663,10 @@ class LocalWorkspace extends EventEmitter {
|
||||
const finalStatus = await this.autoRunner.resume(group, durable, controller)
|
||||
await this.finishRun(group.id, controller, finalStatus)
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) {
|
||||
await this.finishRun(group.id, controller, terminalRunStatusForReason(controller.stopReason))
|
||||
return
|
||||
}
|
||||
controller.stopReason = String(error?.message || 'LOCAL_RUN_CONTINUATION_INVALID')
|
||||
await this.finishRun(group.id, controller, 'failed')
|
||||
}
|
||||
@@ -742,7 +806,7 @@ class LocalWorkspace extends EventEmitter {
|
||||
const invocationFields = ['phase', 'slotId', 'operationId', 'snapshotHash']
|
||||
const invocationFieldCount = invocationFields.filter(field => Object.hasOwn(input, field)).length
|
||||
if (invocationFieldCount > 0
|
||||
&& (input.resumeKind !== 'agent_slot'
|
||||
&& (!['agent_slot', 'v4_task_decision'].includes(input.resumeKind)
|
||||
|| invocationFieldCount !== invocationFields.length)) {
|
||||
throw new Error('LOCAL_RUN_CONTINUATION_INVALID')
|
||||
}
|
||||
@@ -1077,6 +1141,103 @@ class LocalWorkspace extends EventEmitter {
|
||||
return { ...match, state: continuation.state }
|
||||
}
|
||||
|
||||
v4TaskDecisionSource(durable, gate, request) {
|
||||
if (durable?.mode !== 'auto' || durable.orchestration?.version !== 4
|
||||
|| gate.type !== 'input' || gate.runId !== durable.runId
|
||||
|| !request || Object.keys(request).length !== 7
|
||||
|| request.source !== 'task-decision' || request.phase !== 'discussion'
|
||||
|| request.snapshotHash !== durable.orchestration.snapshotHash) return null
|
||||
const sources = durable.agentRuns.filter(attempt => (
|
||||
attempt.agentRunId === gate.agentRunId && attempt.kind === gate.agentKind
|
||||
&& attempt.status === 'completed' && attempt.round === request.round
|
||||
&& attempt.context?.operationId === request.operationId
|
||||
&& attempt.context?.snapshotHash === request.snapshotHash
|
||||
&& attempt.context?.taskDecision?.status === 'needs-human'
|
||||
&& hashValue(attempt.context.taskDecision) === request.decisionHash
|
||||
))
|
||||
if (sources.length !== 1 || request.operationId !== this.autoRunner.v4OperationId(
|
||||
durable, gate.agentKind, `discussion:${request.round}`, request.slotId, request.round,
|
||||
)) return null
|
||||
return sources[0]
|
||||
}
|
||||
|
||||
canResumeV4TaskDecision(durable, gate, request) {
|
||||
const source = this.v4TaskDecisionSource(durable, gate, request)
|
||||
const continuation = durable.continuation
|
||||
const cursor = durable.orchestration
|
||||
const group = this.state.groups.find(item => item.id === durable.groupId)
|
||||
const slot = cursor?.slots.find(item => item.slotId === request?.slotId)
|
||||
return Boolean(source && group && gate.options.length === 2
|
||||
&& gate.options[0].optionId === 'respond' && gate.options[0].kind === 'respond'
|
||||
&& gate.options[1].optionId === 'cancel' && gate.options[1].kind === 'reject'
|
||||
&& continuation?.resumeKind === 'v4_task_decision'
|
||||
&& cursor.phase === 'discussion' && cursor.round === request.round
|
||||
&& durable.currentRound === request.round && continuation.round === request.round
|
||||
&& continuation.slotId === request.slotId
|
||||
&& continuation.operationId === request.operationId
|
||||
&& continuation.snapshotHash === request.snapshotHash
|
||||
&& slot?.agentRunId === source.agentRunId && slot.agentKind === source.kind
|
||||
&& slot.operationId === request.operationId && slot.commitStatus === 'committed'
|
||||
&& this.autoRunner.v4NaturalOwner(group, durable, durable.threadRootId) === source.kind)
|
||||
}
|
||||
|
||||
v4TaskDecisionResponses(runId) {
|
||||
const durable = this.runLedger?.get?.(runId)
|
||||
if (!durable) return []
|
||||
return this.humanGateStore.list({ runId }).flatMap(item => {
|
||||
if (item.type !== 'input' || item.status !== 'approved') return []
|
||||
try {
|
||||
const gate = this.humanGateStore.get(item.gateId)
|
||||
const request = this.humanGateStore.request(item.gateId)
|
||||
const source = this.v4TaskDecisionSource(durable, gate, request)
|
||||
return source && gate.decision?.response ? [{
|
||||
id: gate.gateId, round: source.round, agentKind: 'human',
|
||||
text: gate.decision.response,
|
||||
}] : []
|
||||
} catch { return [] }
|
||||
})
|
||||
}
|
||||
|
||||
async requestV4TaskDecision(group, controller, message) {
|
||||
const durable = this.runLedger?.get?.(controller.runId)
|
||||
if (!durable) return null
|
||||
const source = durable.agentRuns.find(attempt => (
|
||||
attempt.agentRunId === message.trace?.agentRunId && attempt.kind === message.agentKind
|
||||
))
|
||||
const slot = durable.orchestration?.slots.find(item => item.agentRunId === source?.agentRunId)
|
||||
if (!source || !slot || source.context?.taskDecision?.status !== 'needs-human'
|
||||
|| slot.commitStatus !== 'committed') throw new Error('LOCAL_RUN_CONTINUATION_INVALID')
|
||||
const request = {
|
||||
source: 'task-decision', phase: 'discussion', round: source.round,
|
||||
slotId: slot.slotId, operationId: slot.operationId,
|
||||
snapshotHash: durable.orchestration.snapshotHash,
|
||||
decisionHash: hashValue(source.context.taskDecision),
|
||||
}
|
||||
const decision = await this.requestHumanGate({
|
||||
type: 'input', runId: durable.runId, agentRunId: source.agentRunId, agentKind: source.kind,
|
||||
createdAt: new Date(slot.finishedAt).toISOString(),
|
||||
summary: source.context.taskDecision.reason,
|
||||
options: [
|
||||
{ optionId: 'respond', name: 'Respond', kind: 'respond' },
|
||||
{ optionId: 'cancel', name: 'Cancel', kind: 'reject' },
|
||||
],
|
||||
request,
|
||||
}, {
|
||||
signal: controller.signal,
|
||||
preserveOnAbort: () => controller.stopReason === 'shutdown',
|
||||
continuation: {
|
||||
resumeKind: 'v4_task_decision', agentRunId: source.agentRunId, agentKind: source.kind,
|
||||
round: source.round, phase: 'discussion', slotId: slot.slotId,
|
||||
operationId: slot.operationId, snapshotHash: durable.orchestration.snapshotHash,
|
||||
},
|
||||
})
|
||||
if (this.completeHumanGateContinuation(durable.runId, decision.gateId,
|
||||
decision.status === 'approved' ? 'completed' : 'cancelled') !== true) {
|
||||
throw new Error('LOCAL_RUN_PERSIST_FAILED')
|
||||
}
|
||||
return decision
|
||||
}
|
||||
|
||||
async requestHumanGate(input, options = {}) {
|
||||
const runId = String(input?.runId || '')
|
||||
const previous = this.humanGateWaitTails.get(runId) || Promise.resolve()
|
||||
@@ -1184,6 +1345,11 @@ class LocalWorkspace extends EventEmitter {
|
||||
if (continuation.state !== 'pending' && gate.status === 'pending') return false
|
||||
try {
|
||||
const request = this.humanGateStore.request(gate.gateId)
|
||||
if (continuation.resumeKind === 'v4_task_decision') {
|
||||
const pack = this.contextPackStore.get(runRecord.contextPackId)
|
||||
return pack.taskId === runRecord.taskId
|
||||
&& this.canResumeV4TaskDecision(runRecord, gate, request)
|
||||
}
|
||||
const connectorBound = gate.type === 'input' || request?.source === 'connector'
|
||||
if (connectorBound && (
|
||||
continuation.requestId !== request.requestId
|
||||
@@ -1404,7 +1570,7 @@ class LocalWorkspace extends EventEmitter {
|
||||
if (durable?.mode !== 'auto' || continuation?.resumeKind !== 'agent_slot'
|
||||
|| cursor?.version !== 4 || cursor.workflow !== 'auto'
|
||||
|| cursor.template !== 'discussion'
|
||||
|| !['proposal', 'challenge', 'work', 'synthesis', 'verification'].includes(phase)
|
||||
|| !['proposal', 'discussion', 'challenge', 'work', 'synthesis', 'verification'].includes(phase)
|
||||
|| !['budget', 'permission', 'retry', 'input'].includes(gate?.type)
|
||||
|| gate.runId !== durable.runId || gate.agentRunId !== continuation.agentRunId
|
||||
|| gate.agentKind !== continuation.agentKind
|
||||
@@ -1439,7 +1605,7 @@ class LocalWorkspace extends EventEmitter {
|
||||
|| (slot.resultRefs?.workflowOutcomeRefs || []).some(item => (
|
||||
item?.receipt?.phase === phase && item.receipt.operationId === slot.operationId
|
||||
))) return false
|
||||
let operationPhase = phase
|
||||
let operationPhase = phase === 'discussion' ? `discussion:${cursor.round}` : phase
|
||||
if (phase === 'work') {
|
||||
const matchingAssignments = cursor.coordinationPlan?.assignments?.filter(item => (
|
||||
item.ownerKind === slot.agentKind && item.taskId
|
||||
@@ -1477,6 +1643,7 @@ class LocalWorkspace extends EventEmitter {
|
||||
}
|
||||
return slot.operationId === this.autoRunner.v4OperationId(
|
||||
controller, slot.agentKind, operationPhase, slot.slotId,
|
||||
...(phase === 'discussion' ? [cursor.round] : []),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1695,6 +1862,11 @@ class LocalWorkspace extends EventEmitter {
|
||||
try {
|
||||
controller = this.runCoordinator.resume(durable)
|
||||
const group = this.getGroup(durable.groupId)
|
||||
if (durable.continuation.resumeKind === 'v4_task_decision') {
|
||||
const finalStatus = await this.autoRunner.resume(group, durable, controller)
|
||||
await this.finishRun(durable.groupId, controller, finalStatus)
|
||||
return
|
||||
}
|
||||
const resumableManual = this.canResumeManualOrchestration(durable)
|
||||
const resumableAuto = this.canResumeAutoOrchestration(durable)
|
||||
const resumableV4ManualSlot = this.canResumeV4ManualAgentSlot(durable, gate)
|
||||
@@ -2342,26 +2514,47 @@ class LocalWorkspace extends EventEmitter {
|
||||
}
|
||||
|
||||
persistSessionState(key, sessionRef, meta) {
|
||||
const canonicalKey = this.canonicalConversationSessionKey(key)
|
||||
const nextRef = normalizeSessionRef(sessionRef)
|
||||
if (!SESSION_KEY.test(String(key || '')) || !nextRef) return false
|
||||
const hadSession = Object.hasOwn(this.state.sessions, key)
|
||||
const hadMeta = Object.hasOwn(this.state.sessionMeta, key)
|
||||
const previousSession = this.state.sessions[key]
|
||||
const previousMeta = this.state.sessionMeta[key]
|
||||
this.state.sessions[key] = nextRef
|
||||
this.state.sessionMeta[key] = normalizeSessionMeta(meta)
|
||||
if (!SESSION_KEY.test(String(canonicalKey || '')) || !nextRef) return false
|
||||
const hadSession = Object.hasOwn(this.state.sessions, canonicalKey)
|
||||
const hadMeta = Object.hasOwn(this.state.sessionMeta, canonicalKey)
|
||||
const hadLegacySession = Object.hasOwn(this.state.sessions, key)
|
||||
const hadLegacyMeta = Object.hasOwn(this.state.sessionMeta, key)
|
||||
const previousLegacySession = this.state.sessions[key]
|
||||
const previousLegacyMeta = this.state.sessionMeta[key]
|
||||
const previousSession = this.state.sessions[canonicalKey]
|
||||
const previousMeta = this.state.sessionMeta[canonicalKey]
|
||||
this.state.sessions[canonicalKey] = nextRef
|
||||
this.state.sessionMeta[canonicalKey] = normalizeSessionMeta(meta)
|
||||
if (canonicalKey !== key) {
|
||||
delete this.state.sessions[key]
|
||||
delete this.state.sessionMeta[key]
|
||||
}
|
||||
try {
|
||||
this.save()
|
||||
} catch (error) {
|
||||
if (hadSession) this.state.sessions[key] = previousSession
|
||||
else delete this.state.sessions[key]
|
||||
if (hadMeta) this.state.sessionMeta[key] = previousMeta
|
||||
else delete this.state.sessionMeta[key]
|
||||
if (hadSession) this.state.sessions[canonicalKey] = previousSession
|
||||
else delete this.state.sessions[canonicalKey]
|
||||
if (hadMeta) this.state.sessionMeta[canonicalKey] = previousMeta
|
||||
else delete this.state.sessionMeta[canonicalKey]
|
||||
if (canonicalKey !== key) {
|
||||
if (hadLegacySession) this.state.sessions[key] = previousLegacySession
|
||||
else delete this.state.sessions[key]
|
||||
if (hadLegacyMeta) this.state.sessionMeta[key] = previousLegacyMeta
|
||||
else delete this.state.sessionMeta[key]
|
||||
}
|
||||
throw error
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
canonicalConversationSessionKey(key) {
|
||||
const value = String(key || '')
|
||||
const match = value.match(/^([^:]+):task:[^:]+:([^:]+)$/)
|
||||
return match ? `${match[1]}:${match[2]}` : value
|
||||
}
|
||||
|
||||
persistSessionRef(key, sessionRef) {
|
||||
const next = normalizeSessionRef(sessionRef)
|
||||
if (!SESSION_KEY.test(String(key || '')) || !next || next === this.state.sessions[key]) return false
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Desktop Tests
|
||||
|
||||
Desktop tests mirror the source domains under `desktop/src`. Keep a test next to
|
||||
the domain it verifies, and put reusable fixtures or process harnesses in
|
||||
`test/support` rather than copying them into individual suites.
|
||||
|
||||
The test runner discovers `*.test.cjs` recursively. Use a focused suite while
|
||||
iterating, then run the complete suite before delivery:
|
||||
|
||||
```sh
|
||||
npm run test:agents
|
||||
npm run test:runs
|
||||
npm run test:workspace
|
||||
npm test
|
||||
```
|
||||
|
||||
Suite selection is defined in `scripts/test-discovery.cjs`. Add a new domain to
|
||||
`TEST_SUITES` when it needs an independent, repeatable test command.
|
||||
@@ -62,6 +62,15 @@ test('keeps unidentified versions distinct from verified incompatibility', () =>
|
||||
})
|
||||
})
|
||||
|
||||
test('accepts the verified Pi Agent release', () => {
|
||||
assert.deepEqual(assessAgentVersion('pi', '0.84.2'), {
|
||||
resolvedVersion: '0.84.2',
|
||||
supportedVersionRange: '0.84.2',
|
||||
compatibilityState: 'compatible',
|
||||
incompatibilityReason: '',
|
||||
})
|
||||
})
|
||||
|
||||
test('accepts inclusive release ranges and rejects unvalidated versions', () => {
|
||||
for (const [kind, contract] of Object.entries(AGENT_COMPATIBILITY)) {
|
||||
const supported = contract.exactVersion
|
||||
@@ -78,6 +87,7 @@ test('accepts inclusive release ranges and rejects unvalidated versions', () =>
|
||||
['codex', '0.146.0-alpha.9.3'],
|
||||
['hermes', '0.19.1-beta.1'],
|
||||
['openclaw', '2026.7.1'],
|
||||
['pi', '0.2.0'],
|
||||
['gemini', '0.53.2'],
|
||||
['opencodereview', '1.8.7'],
|
||||
]) {
|
||||
@@ -92,9 +102,9 @@ test('accepts inclusive release ranges and rejects unvalidated versions', () =>
|
||||
|
||||
test('defines required capability probes for every supported connector', () => {
|
||||
assert.deepEqual(Object.keys(AGENT_COMPATIBILITY).sort(), [
|
||||
'claude', 'codex', 'gemini', 'hermes', 'kimi', 'mimo', 'openclaw',
|
||||
'claude', 'codex', 'gemini', 'hermes', 'kimi', 'mimo', 'openclaw', 'pi',
|
||||
'opencode', 'opencodereview', 'qwen', 'workbuddy',
|
||||
])
|
||||
].sort())
|
||||
for (const kind of Object.keys(AGENT_COMPATIBILITY)) {
|
||||
assert.ok(capabilityProbes(kind).length > 0, kind)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ const {
|
||||
normalizeExternalRunRef,
|
||||
outcomeForAcpStopReason,
|
||||
requireTerminalAgentResult,
|
||||
terminalAuthenticationDiagnostic,
|
||||
} = require('../../src/agents/agent-runtime-contract.cjs')
|
||||
const { ALLOWED_KINDS } = require('../../src/agents/cli/cli-discovery.cjs')
|
||||
|
||||
@@ -98,3 +99,31 @@ test('failed and cancelled outcomes do not become successful results', () => {
|
||||
&& error.failure.category === 'cancellation',
|
||||
)
|
||||
})
|
||||
|
||||
test('short terminal HTTP credential diagnostics cannot become successful results', () => {
|
||||
const diagnostic = 'HTTP 401: Invalid token (request id: request-1)'
|
||||
assert.equal(terminalAuthenticationDiagnostic(diagnostic), diagnostic)
|
||||
assert.equal(
|
||||
terminalAuthenticationDiagnostic('HTTP 403: Forbidden'),
|
||||
'HTTP 403: Forbidden',
|
||||
)
|
||||
assert.throws(
|
||||
() => requireTerminalAgentResult({ outcome: 'completed', text: diagnostic }),
|
||||
error => error.message === 'LOCAL_AGENT_AUTH_REQUIRED'
|
||||
&& error.failure.category === 'authentication'
|
||||
&& error.diagnostic === diagnostic,
|
||||
)
|
||||
assert.equal(terminalAuthenticationDiagnostic(
|
||||
'When an API returns HTTP 401: Invalid token, refresh the configured credential.',
|
||||
), '')
|
||||
})
|
||||
|
||||
test('successful explanations of authentication errors remain successful', () => {
|
||||
for (const text of [
|
||||
'HTTP 401: Unauthorized means the request needs valid credentials.',
|
||||
'HTTP 403: Forbidden is the expected response in this test.',
|
||||
'HTTP 401: Invalid token can be reproduced with the following test.',
|
||||
]) {
|
||||
assert.equal(requireTerminalAgentResult({ outcome: 'completed', text }).text, text)
|
||||
}
|
||||
})
|
||||
@@ -19,6 +19,7 @@ const {
|
||||
parseMimoOutput,
|
||||
parseOpenCodeOutput,
|
||||
parseOpenCodeReviewOutput,
|
||||
parsePiOutput,
|
||||
parseWorkBuddyOutput,
|
||||
prepareCommand,
|
||||
readHermesFinalResponse,
|
||||
@@ -151,7 +152,7 @@ test('WorkBuddy uses non-interactive output and resumes its native session', ()
|
||||
assert.deepEqual(spec.args, [
|
||||
'--print', '--output-format', 'stream-json', '--include-partial-messages',
|
||||
'--permission-mode', 'plan',
|
||||
'--max-turns', '20', '--resume', 'workbuddy-session',
|
||||
'--max-turns', '8', '--resume', 'workbuddy-session',
|
||||
])
|
||||
assert.equal(spec.eventTransport, 'stream-json')
|
||||
})
|
||||
@@ -1032,6 +1033,26 @@ test('Claude uses partial stream JSON and resumes its native session', () => {
|
||||
assert.equal(spec.promptArg, true)
|
||||
})
|
||||
|
||||
test('Claude selected Provider overrides native cloud selection without credentials in argv', () => {
|
||||
const spec = invocation('claude', '/tmp/claude', '/tmp/work', 'native-session', {
|
||||
provider: { id: 'anthropic', model: 'selected-model', baseUrl: 'https://selected.example' },
|
||||
env: { ANTHROPIC_API_KEY: 'selected-secret-key' },
|
||||
})
|
||||
const settings = JSON.parse(spec.args[spec.args.indexOf('--settings') + 1])
|
||||
assert.equal(settings.env.ANTHROPIC_BASE_URL, 'https://selected.example')
|
||||
assert.equal(settings.env.ANTHROPIC_API_KEY, '')
|
||||
assert.equal(settings.env.ANTHROPIC_AUTH_TOKEN, '')
|
||||
assert.equal(settings.env.CLAUDE_CODE_OAUTH_TOKEN, '')
|
||||
assert.equal(settings.env.ANTHROPIC_CUSTOM_HEADERS, '')
|
||||
assert.match(settings.apiKeyHelper, /MELDWORK_PROVIDER_API_KEY/)
|
||||
for (const flag of ['BEDROCK', 'VERTEX', 'FOUNDRY', 'MANTLE']) {
|
||||
assert.equal(settings.env[`CLAUDE_CODE_USE_${flag}`], '0')
|
||||
}
|
||||
assert.equal(spec.args[spec.args.indexOf('--model') + 1], 'selected-model')
|
||||
assert.equal(spec.args[spec.args.indexOf('--resume') + 1], 'native-session')
|
||||
assert.equal(JSON.stringify(spec.args).includes('selected-secret-key'), false)
|
||||
})
|
||||
|
||||
test('MiMo uses ACP by default and declares its JSON setup fallback', () => {
|
||||
const spec = invocation('mimo', '/tmp/mimo', '/tmp/work', 'mimo-session', {
|
||||
sandbox: 'workspace-write',
|
||||
@@ -1062,6 +1083,110 @@ test('MiMo JSON output returns final text and session id', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('Pi uses the current non-interactive JSON mode and resumes by session id', () => {
|
||||
const readOnly = invocation('pi', '/tmp/pi', '/tmp/work', 'pi-session', {
|
||||
provider: { id: 'zgci', model: 'glm' },
|
||||
})
|
||||
assert.deepEqual(readOnly.args, [
|
||||
'--mode', 'json', '--print', '--no-approve', '--tools', 'read,grep,find,ls', '--session', 'pi-session',
|
||||
])
|
||||
assert.equal(readOnly.promptArg, true)
|
||||
assert.equal(readOnly.eventTransport, 'json')
|
||||
|
||||
const writable = invocation('pi', '/tmp/pi', '/tmp/work', '', {
|
||||
sandbox: 'workspace-write',
|
||||
})
|
||||
assert.deepEqual(writable.args, ['--mode', 'json', '--print', '--approve'])
|
||||
})
|
||||
|
||||
test('Pi JSON output returns final text and session id from current CLI events', () => {
|
||||
const raw = [
|
||||
JSON.stringify({
|
||||
type: 'session',
|
||||
id: '01a03794-ae3f-72ea-9efd-cd2cd16d88a1',
|
||||
cwd: '/tmp/work',
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'message_update',
|
||||
assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: 'Pi ' },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'message_update',
|
||||
assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: 'reply' },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'message_end',
|
||||
message: {
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', text: 'Pi reply' }],
|
||||
stopReason: 'stop',
|
||||
},
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'turn_end',
|
||||
message: { role: 'assistant', stopReason: 'stop' },
|
||||
}),
|
||||
JSON.stringify({ type: 'agent_settled' }),
|
||||
].join('\n')
|
||||
assert.deepEqual(parsePiOutput(raw), {
|
||||
text: 'Pi reply',
|
||||
sessionRef: '01a03794-ae3f-72ea-9efd-cd2cd16d88a1',
|
||||
})
|
||||
assert.deepEqual(profileOutput('pi', raw), {
|
||||
text: 'Pi reply',
|
||||
sessionRef: '01a03794-ae3f-72ea-9efd-cd2cd16d88a1',
|
||||
outcome: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
test('Pi ignores user/tool echoes and tool ids while preserving the assistant answer and native session', () => {
|
||||
const raw = [
|
||||
{ type: 'session', id: 'pi-persistent-session' },
|
||||
{ type: 'message_end', message: { role: 'user', content: [{ type: 'text', text: 'Private input' }] } },
|
||||
{ type: 'tool_execution_end', id: 'unrelated-tool-id' },
|
||||
{ type: 'message_end', message: { role: 'toolResult', content: [{ type: 'text', text: 'Tool noise' }] } },
|
||||
{ type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: 'Actual answer' } },
|
||||
{ type: 'turn_end', message: { role: 'assistant', stopReason: 'stop' } },
|
||||
{ type: 'agent_end', messages: [{ role: 'assistant', stopReason: 'stop' }] },
|
||||
{ type: 'agent_settled' },
|
||||
].map(event => JSON.stringify(event)).join('\n')
|
||||
assert.deepEqual(parsePiOutput(raw), { text: 'Actual answer', sessionRef: 'pi-persistent-session' })
|
||||
assert.deepEqual(profileOutput('pi', raw), {
|
||||
text: 'Actual answer', sessionRef: 'pi-persistent-session', outcome: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
test('Pi agent_end preserves failed, cancelled and incomplete assistant outcomes', () => {
|
||||
for (const [stopReason, outcome] of [['error', 'failed'], ['aborted', 'cancelled'], ['length', 'partial']]) {
|
||||
const raw = [
|
||||
{ type: 'session', id: 'pi-terminal-session' },
|
||||
{ type: 'message_end', message: { role: 'user', content: [{ type: 'text', text: 'Do not echo me' }] } },
|
||||
{ type: 'turn_end', message: { role: 'assistant', stopReason } },
|
||||
{ type: 'agent_end', messages: [{ role: 'assistant', stopReason }] },
|
||||
{ type: 'agent_settled' },
|
||||
].map(event => JSON.stringify(event)).join('\n')
|
||||
const result = profileOutput('pi', raw)
|
||||
assert.equal(result.outcome, outcome, stopReason)
|
||||
assert.equal(result.text, '', stopReason)
|
||||
assert.equal(parsePiOutput(raw).text, '', stopReason)
|
||||
}
|
||||
})
|
||||
|
||||
test('Pi clears a recoverable attempt failure after its internal retry completes', () => {
|
||||
const raw = [
|
||||
{ type: 'session', id: 'pi-retry-session' },
|
||||
{ type: 'turn_end', message: { role: 'assistant', stopReason: 'error' } },
|
||||
{ type: 'agent_end', messages: [{ role: 'assistant', stopReason: 'error' }], willRetry: true },
|
||||
{ type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: 'Recovered answer' } },
|
||||
{ type: 'turn_end', message: { role: 'assistant', stopReason: 'stop' } },
|
||||
{ type: 'agent_end', messages: [{ role: 'assistant', stopReason: 'stop' }], willRetry: false },
|
||||
{ type: 'agent_settled' },
|
||||
].map(event => JSON.stringify(event)).join('\n')
|
||||
assert.deepEqual(profileOutput('pi', raw), {
|
||||
text: 'Recovered answer', sessionRef: 'pi-retry-session', outcome: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
test('Claude and Qwen stream JSON output returns the final reply and session id', () => {
|
||||
for (const kind of ['claude', 'qwen']) {
|
||||
const raw = [
|
||||
@@ -1596,6 +1721,21 @@ test('every supported built-in Agent produces an explicit completion outcome', (
|
||||
part: { type: 'step-finish', reason: 'stop' },
|
||||
}),
|
||||
].join('\n'),
|
||||
pi: [
|
||||
JSON.stringify({ type: 'session', version: 3, id: 'pi-session' }),
|
||||
JSON.stringify({
|
||||
type: 'message_update',
|
||||
assistantMessageEvent: { type: 'text_delta', contentIndex: 1, delta: 'Pi Agent reply' },
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: 'message_end',
|
||||
message: {
|
||||
role: 'assistant', content: [{ type: 'text', text: 'Pi Agent reply' }],
|
||||
stopReason: 'stop', rawStopReason: 'stop',
|
||||
},
|
||||
}),
|
||||
JSON.stringify({ type: 'turn_end', stopReason: 'stop' }),
|
||||
].join('\n'),
|
||||
claude: JSON.stringify({
|
||||
type: 'result', result: 'Claude reply', session_id: 'claude-session',
|
||||
}),
|
||||
@@ -1635,6 +1775,185 @@ test('every supported built-in Agent produces an explicit completion outcome', (
|
||||
}
|
||||
})
|
||||
|
||||
test('structured result output keeps the terminal result after an earlier recoverable error', () => {
|
||||
for (const [kind, resultText] of [
|
||||
['claude', 'Claude completed after recovering'],
|
||||
['workbuddy', 'WorkBuddy completed after recovering'],
|
||||
['qwen', 'Qwen completed after recovering'],
|
||||
]) {
|
||||
const result = profileOutput(kind, [
|
||||
JSON.stringify({ type: 'error', error: { message: 'tool attempt failed' } }),
|
||||
JSON.stringify({
|
||||
type: 'result',
|
||||
result: resultText,
|
||||
session_id: `${kind}-session`,
|
||||
}),
|
||||
].join('\n'))
|
||||
assert.equal(result.outcome, 'completed', kind)
|
||||
assert.equal(result.text, resultText, kind)
|
||||
}
|
||||
})
|
||||
|
||||
test('a Claude terminal result settles even when the native process forgets to exit', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-claude-terminal-hang-'))
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
const cli = executable(directory, 'claude-terminal-hang.cjs', `
|
||||
process.stdout.write(JSON.stringify({ type: 'result', result: 'Claude finished', session_id: 'claude-terminal-session' }) + '\\n')
|
||||
setInterval(() => {}, 1000)
|
||||
`)
|
||||
const startedAt = Date.now()
|
||||
const result = await runAgent(
|
||||
{ kind: 'claude', executable: cli, name: 'Claude' },
|
||||
'hello',
|
||||
directory,
|
||||
)
|
||||
assert.equal(result.outcome, 'completed')
|
||||
assert.equal(result.text, 'Claude finished')
|
||||
assert.equal(result.sessionRef, 'claude-terminal-session')
|
||||
assert.ok(Date.now() - startedAt < 5000)
|
||||
})
|
||||
|
||||
test('Pi removes only the recognizable internal collaboration prompt echo', () => {
|
||||
const raw = [
|
||||
JSON.stringify({ type: 'session', version: 3, id: 'pi-prompt-session' }),
|
||||
JSON.stringify({
|
||||
type: 'message_update',
|
||||
assistantMessageEvent: {
|
||||
type: 'text_delta',
|
||||
delta: 'You are participating in a local multi-agent discussion.\nUser task: sync skills\nAnswer the user naturally in Markdown.\nHere is the actual answer.',
|
||||
},
|
||||
}),
|
||||
JSON.stringify({ type: 'agent_end' }),
|
||||
].join('\n')
|
||||
const result = profileOutput('pi', raw)
|
||||
assert.equal(result.text, 'Here is the actual answer.')
|
||||
assert.equal(result.outcome, 'completed')
|
||||
})
|
||||
|
||||
test('runAgent strips an exact Meldwork direct-chat prompt echo before persisting the answer', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-prompt-echo-'))
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
const prompt = [
|
||||
'You are participating in the local "Pi Agent" conversation as Pi Agent.',
|
||||
'Current user task (authoritative):',
|
||||
'hey',
|
||||
].join('\n')
|
||||
const cli = executable(directory, 'pi-prompt-echo.cjs', `
|
||||
const prompt = process.argv.at(-1)
|
||||
process.stdout.write(JSON.stringify({ type: 'session', id: 'pi-prompt-echo-session' }) + '\\n')
|
||||
process.stdout.write(JSON.stringify({
|
||||
type: 'message_update',
|
||||
assistantMessageEvent: { type: 'text_delta', delta: prompt + 'Hey! What can I help you with today?' },
|
||||
}) + '\\n')
|
||||
process.stdout.write(JSON.stringify({ type: 'agent_end' }) + '\\n')
|
||||
`)
|
||||
const result = await runAgent(
|
||||
{ kind: 'pi', executable: cli, name: 'Pi Agent' },
|
||||
prompt,
|
||||
directory,
|
||||
)
|
||||
assert.equal(result.text, 'Hey! What can I help you with today?')
|
||||
assert.equal(result.outcome, 'completed')
|
||||
})
|
||||
|
||||
test('runAgent strips a full long multi-agent prompt echo from Pi output', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-pi-group-echo-'))
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
const prompt = [
|
||||
'You are participating in a local multi-agent discussion.',
|
||||
'',
|
||||
'Your role this turn is worker.',
|
||||
'',
|
||||
'The current collaboration phase is proposal.',
|
||||
'',
|
||||
'User task:',
|
||||
'Share a short proposal.',
|
||||
'',
|
||||
'Answer the user naturally in Markdown. Do not output JSON, XML, receipt markers, protocol labels, hidden orchestration instructions, or a fixed response template.',
|
||||
'',
|
||||
'Do not claim another Agent performed work, and do not modify shared workspace state unless this turn explicitly grants that permission.',
|
||||
].join('\n')
|
||||
const cli = executable(directory, 'pi-group-prompt-echo.cjs', `
|
||||
const prompt = ${JSON.stringify(prompt)}
|
||||
process.stdout.write(JSON.stringify({ type: 'session', id: 'pi-group-echo-session' }) + '\\n')
|
||||
process.stdout.write(JSON.stringify({
|
||||
type: 'message_update',
|
||||
assistantMessageEvent: { type: 'text_delta', delta: prompt + '\\n\\nProposal: keep the shared task state explicit.' },
|
||||
}) + '\\n')
|
||||
process.stdout.write(JSON.stringify({ type: 'agent_end' }) + '\\n')
|
||||
`)
|
||||
const result = await runAgent(
|
||||
{ kind: 'pi', executable: cli, name: 'Pi Agent' },
|
||||
prompt,
|
||||
directory,
|
||||
)
|
||||
assert.equal(result.text, 'Proposal: keep the shared task state explicit.')
|
||||
assert.equal(result.outcome, 'completed')
|
||||
})
|
||||
|
||||
test('Pi keeps running after a tool turn until its agent loop ends', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-pi-tool-turn-'))
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
const cli = executable(directory, 'pi-tool-turn.cjs', `
|
||||
const send = value => process.stdout.write(JSON.stringify(value) + '\\n')
|
||||
send({ type: 'session', id: 'pi-tool-turn-session' })
|
||||
send({ type: 'message_update', assistantMessageEvent: {
|
||||
type: 'text_delta', delta: 'Preparing evidence. ',
|
||||
} })
|
||||
send({ type: 'turn_end', message: { role: 'assistant', stopReason: 'toolUse' } })
|
||||
setTimeout(() => {
|
||||
send({ type: 'message_update', assistantMessageEvent: {
|
||||
type: 'text_delta', delta: 'Final answer.',
|
||||
} })
|
||||
send({ type: 'agent_end', messages: [{ role: 'assistant', stopReason: 'stop' }] })
|
||||
}, 400)
|
||||
`)
|
||||
|
||||
const result = await runAgent(
|
||||
{ kind: 'pi', executable: cli, name: 'Pi Agent' },
|
||||
'research the current market',
|
||||
directory,
|
||||
)
|
||||
assert.deepEqual(result, {
|
||||
text: 'Preparing evidence. Final answer.',
|
||||
sessionRef: 'pi-tool-turn-session',
|
||||
outcome: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
test('runAgent strips partial Pi protocol and Harness record echoes', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-pi-partial-echo-'))
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
const prompt = 'Continue the current group discussion using the Harness context below.'
|
||||
const cli = executable(directory, 'pi-partial-prompt-echo.cjs', `
|
||||
process.stdout.write(JSON.stringify({ type: 'session', id: 'pi-partial-echo-session' }) + '\\n')
|
||||
process.stdout.write(JSON.stringify({
|
||||
type: 'message_update',
|
||||
assistantMessageEvent: { type: 'text_delta', delta: [
|
||||
'Do not output JSON, XML, receipt markers, protocol labels, hidden orchestration instructions, or a fixed response template.',
|
||||
'',
|
||||
'Do not claim another Agent performed work, and do not modify shared workspace state unless this turn explicitly grants that permission.',
|
||||
'',
|
||||
'A useful conclusion.',
|
||||
'',
|
||||
'Selected records from completed phases:',
|
||||
'MELDWORK_V4_COLLABORATION_PACKAGE_V1',
|
||||
'[index] hermes',
|
||||
'Artifact: artifact-123',
|
||||
'[proposal] agent=claude Completed the proposal phase. Continue with the next step.',
|
||||
].join('\\n') },
|
||||
}) + '\\n')
|
||||
process.stdout.write(JSON.stringify({ type: 'agent_end' }) + '\\n')
|
||||
`)
|
||||
const result = await runAgent(
|
||||
{ kind: 'pi', executable: cli, name: 'Pi Agent' },
|
||||
prompt,
|
||||
directory,
|
||||
)
|
||||
assert.equal(result.text, 'A useful conclusion.\n\nContinue with the next step.')
|
||||
assert.equal(result.outcome, 'completed')
|
||||
})
|
||||
|
||||
test('recorded fixtures cover every supported built-in output schema', () => {
|
||||
const manifest = JSON.parse(fs.readFileSync(
|
||||
path.join(OUTPUT_FIXTURE_DIRECTORY, 'manifest.json'),
|
||||
@@ -1652,6 +1971,7 @@ test('recorded fixtures cover every supported built-in output schema', () => {
|
||||
workbuddy: 'WorkBuddy fixture reply',
|
||||
kimi: 'Kimi fixture reply',
|
||||
mimo: 'MiMo fixture reply',
|
||||
pi: 'Pi Agent fixture reply',
|
||||
claude: 'Claude fixture reply',
|
||||
gemini: 'Gemini fixture reply',
|
||||
opencode: 'OpenCode fixture reply',
|
||||
@@ -1807,6 +2127,44 @@ test('supported local CLIs run in the selected workdir and return native session
|
||||
}
|
||||
})
|
||||
|
||||
test('Pi runs in JSON mode and selects approval flags from the sandbox', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-pi-invocation-'))
|
||||
const workdir = fs.realpathSync(directory)
|
||||
const argvFile = path.join(directory, 'pi-argv.json')
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
const cli = executable(directory, 'pi-argv.cjs', `
|
||||
const fs = require('node:fs')
|
||||
fs.writeFileSync(${JSON.stringify(argvFile)}, JSON.stringify(process.argv.slice(2)))
|
||||
process.stdout.write(JSON.stringify({ type: 'session', version: 3, id: 'pi-session' }) + '\\n')
|
||||
process.stdout.write(JSON.stringify({
|
||||
type: 'message_update',
|
||||
assistantMessageEvent: { type: 'text_delta', contentIndex: 1, delta: process.cwd() },
|
||||
}) + '\\n')
|
||||
process.stdout.write(JSON.stringify({ type: 'turn_end', stopReason: 'stop' }) + '\\n')
|
||||
`)
|
||||
|
||||
for (const sandbox of ['workspace-write', 'read-only']) {
|
||||
fs.writeFileSync(argvFile, '')
|
||||
const result = await runAgent(
|
||||
{ kind: 'pi', executable: cli, name: 'pi' },
|
||||
'hello',
|
||||
workdir,
|
||||
{ sandbox, sessionRef: 'pi-native-session' },
|
||||
)
|
||||
const argv = JSON.parse(fs.readFileSync(argvFile, 'utf8'))
|
||||
assert.equal(result.text, workdir, sandbox)
|
||||
assert.equal(result.sessionRef, 'pi-session', sandbox)
|
||||
assert.ok(argv.includes('--mode'), sandbox)
|
||||
assert.ok(argv.includes('json'), sandbox)
|
||||
assert.ok(argv.includes('--print'), sandbox)
|
||||
assert.ok(argv.includes('--session'), sandbox)
|
||||
assert.ok(argv.includes('pi-native-session'), sandbox)
|
||||
assert.ok(argv.indexOf('--mode') < argv.indexOf('--print'), sandbox)
|
||||
assert.ok(argv.includes(sandbox === 'workspace-write' ? '--approve' : '--no-approve'), sandbox)
|
||||
assert.equal(argv.includes(sandbox === 'workspace-write' ? '--no-approve' : '--approve'), false, sandbox)
|
||||
}
|
||||
})
|
||||
|
||||
test('every conversational built-in Agent emits its answer through the shared runtime event contract', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-agent-events-'))
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
|
||||
@@ -5,6 +5,7 @@ const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const { EventEmitter } = require('node:events')
|
||||
const { PassThrough } = require('node:stream')
|
||||
const { probeAgentCapabilities } = require('../../../src/agents/cli/cli-discovery.cjs')
|
||||
const {
|
||||
detectAgents,
|
||||
imageAttachmentLimit,
|
||||
@@ -37,6 +38,93 @@ test('search path includes common user CLI locations', () => {
|
||||
assert.match(searchPath(), /\.mimocode\/bin/)
|
||||
})
|
||||
|
||||
test('capability timeouts retry once and remain inconclusive when both attempts time out', async () => {
|
||||
for (const recover of [true, false]) {
|
||||
const timeouts = []
|
||||
const result = await probeAgentCapabilities('pi', '/test/timeout-pi', {
|
||||
env: {},
|
||||
execFileFn: async (_command, _args, options) => {
|
||||
timeouts.push(options.timeout)
|
||||
if (!recover || timeouts.length === 1) {
|
||||
throw Object.assign(new Error('timeout'), { killed: true })
|
||||
}
|
||||
return { stdout: argsForProbe(_command, _args) }
|
||||
},
|
||||
})
|
||||
assert.deepEqual(timeouts, [8000, 16000])
|
||||
assert.equal(result.compatibilityState, recover ? 'compatible' : 'unknown')
|
||||
if (!recover) assert.equal(result.incompatibilityReason, 'LOCAL_AGENT_CAPABILITY_PROBE_TIMEOUT')
|
||||
}
|
||||
})
|
||||
|
||||
function argsForProbe(_command, args) {
|
||||
return args.includes('--mode')
|
||||
? '{"type":"session","id":"probe-session"}'
|
||||
: '--mode json --print --session --tools --approve --no-approve'
|
||||
}
|
||||
|
||||
test('only unchanged recently verified executables survive inconclusive capability probes', async () => {
|
||||
const executable = '/test/cached-workbuddy'
|
||||
let identity = 1
|
||||
let mode = 'success'
|
||||
const options = {
|
||||
env: {}, version: '2.115.0',
|
||||
statFn: () => ({ dev: 1, ino: identity, size: 100, mtimeMs: 1, ctimeMs: 1 }),
|
||||
execFileFn: async () => {
|
||||
if (mode === 'timeout') throw Object.assign(new Error('timeout'), { code: 'ETIMEDOUT' })
|
||||
return { stdout: mode === 'success'
|
||||
? '--print --output-format --permission-mode --max-turns --resume json plan acceptEdits'
|
||||
: 'different CLI help' }
|
||||
},
|
||||
}
|
||||
assert.equal((await probeAgentCapabilities('workbuddy', executable, options)).compatibilityState, 'compatible')
|
||||
mode = 'timeout'
|
||||
assert.equal((await probeAgentCapabilities('workbuddy', executable, options)).compatibilityState, 'compatible')
|
||||
identity = 2
|
||||
assert.equal((await probeAgentCapabilities('workbuddy', executable, options)).compatibilityState, 'unknown')
|
||||
identity = 1
|
||||
options.version = '2.132.0'
|
||||
assert.equal((await probeAgentCapabilities('workbuddy', executable, options)).compatibilityState, 'unknown')
|
||||
options.version = '2.115.0'
|
||||
mode = 'incompatible'
|
||||
assert.equal((await probeAgentCapabilities('workbuddy', executable, options)).compatibilityState, 'incompatible')
|
||||
mode = 'timeout'
|
||||
assert.equal((await probeAgentCapabilities('workbuddy', executable, options)).compatibilityState, 'unknown')
|
||||
})
|
||||
|
||||
test('Agent detection does not promote an inconclusive capability check to compatible', async () => {
|
||||
const [agent] = await detectAgents({
|
||||
env: {},
|
||||
resolveExecutableFn: async kind => kind === 'pi' ? '/test/cold-pi' : null,
|
||||
execFileFn: async (_command, args) => {
|
||||
if (args[0] === '--version') return { stdout: '0.84.2' }
|
||||
throw Object.assign(new Error('timeout'), { killed: true })
|
||||
},
|
||||
})
|
||||
assert.equal(agent.kind, 'pi')
|
||||
assert.equal(agent.compatibilityState, 'unknown')
|
||||
assert.equal(agent.incompatibilityReason, 'LOCAL_AGENT_CAPABILITY_PROBE_TIMEOUT')
|
||||
})
|
||||
|
||||
test('Pi detection rejects same-name programs and CLIs missing required permission controls', async () => {
|
||||
for (const [name, help, expected] of [
|
||||
['unrelated', 'Pi help: calculate digits of pi', 'incompatible'],
|
||||
['no-permission-controls', '--mode json --print --session --tools', 'incompatible'],
|
||||
['required-protocol', '--mode json --print --session --tools --approve --no-approve', 'compatible'],
|
||||
]) {
|
||||
const [agent] = await detectAgents({
|
||||
env: {},
|
||||
resolveExecutableFn: async kind => kind === 'pi' ? `/test/pi-${name}/pi` : null,
|
||||
execFileFn: async (_command, args) => ({ stdout: args[0] === '--version' ? '0.84.2' : help }),
|
||||
})
|
||||
assert.equal(agent.kind, 'pi')
|
||||
assert.equal(agent.compatibilityState, expected, name)
|
||||
if (expected === 'incompatible') {
|
||||
assert.equal(agent.incompatibilityReason, 'LOCAL_AGENT_REQUIRED_CAPABILITY_MISSING', name)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('Agent discovery scans independent Agent kinds concurrently', async () => {
|
||||
const started = []
|
||||
let release
|
||||
@@ -55,7 +143,7 @@ test('Agent discovery scans independent Agent kinds concurrently', async () => {
|
||||
const startedBeforeRelease = started.length
|
||||
release()
|
||||
assert.deepEqual(await detection, [])
|
||||
assert.equal(startedBeforeRelease, 11)
|
||||
assert.equal(startedBeforeRelease, 12)
|
||||
})
|
||||
|
||||
test('Hermes capability and ACP checks run concurrently without changing the result', async () => {
|
||||
@@ -874,6 +962,9 @@ test('Agent detection passes only allowlisted system environment to version comm
|
||||
PATH: '/custom/bin',
|
||||
MELDWORK_PRIVATE_VALUE: 'desktop-private-value',
|
||||
OPENAI_API_KEY: 'provider-secret',
|
||||
https_proxy: 'http://proxy.example:3128',
|
||||
NO_PROXY: 'localhost,127.0.0.1',
|
||||
REQUESTS_CA_BUNDLE: '/certs/company.pem',
|
||||
},
|
||||
resolveExecutableFn: async kind => kind === 'kimi' ? '/tmp/kimi' : null,
|
||||
execFileFn: async (_command, args, options) => {
|
||||
@@ -897,10 +988,13 @@ test('Agent detection passes only allowlisted system environment to version comm
|
||||
assert.match(env.PATH, /\/custom\/bin/)
|
||||
assert.equal(env.MELDWORK_PRIVATE_VALUE, undefined)
|
||||
assert.equal(env.OPENAI_API_KEY, undefined)
|
||||
assert.equal(env.https_proxy, 'http://proxy.example:3128')
|
||||
assert.equal(env.NO_PROXY, 'localhost,127.0.0.1')
|
||||
assert.equal(env.REQUESTS_CA_BUNDLE, '/certs/company.pem')
|
||||
}
|
||||
})
|
||||
|
||||
test('Agent detection excludes executable shims that cannot report a version', async () => {
|
||||
test('Agent detection retains a broken installation with unavailable capabilities', async () => {
|
||||
const found = await detectAgents({
|
||||
platform: 'darwin',
|
||||
env: {},
|
||||
@@ -908,7 +1002,24 @@ test('Agent detection excludes executable shims that cannot report a version', a
|
||||
execFileFn: async () => { throw new Error('broken shim') },
|
||||
})
|
||||
|
||||
assert.deepEqual(found, [])
|
||||
assert.equal(found.length, 1)
|
||||
assert.equal(found[0].kind, 'codex')
|
||||
assert.equal(found[0].compatibilityState, 'incompatible')
|
||||
assert.equal(found[0].incompatibilityReason, 'LOCAL_AGENT_REQUIRED_CAPABILITY_MISSING')
|
||||
})
|
||||
|
||||
test('Agent detection uses capability evidence when the version command fails', async () => {
|
||||
const found = await detectAgents({
|
||||
env: { CODEX_HOME: '/tmp/custom-codex' },
|
||||
resolveExecutableFn: async kind => kind === 'codex' ? '/tmp/codex' : null,
|
||||
execFileFn: async (_command, args, options) => {
|
||||
assert.equal(options.env.CODEX_HOME, '/tmp/custom-codex')
|
||||
if (args[0] === '--version') throw Object.assign(new Error('timeout'), { killed: true })
|
||||
return { stdout: '--json --sandbox --skip-git-repo-check --image read-only workspace-write' }
|
||||
},
|
||||
})
|
||||
assert.equal(found.length, 1)
|
||||
assert.equal(found[0].compatibilityState, 'compatible')
|
||||
})
|
||||
|
||||
test('runAgent hides executable paths from spawn failures', async () => {
|
||||
@@ -979,6 +1090,31 @@ setInterval(() => {}, 1000)
|
||||
await waitForExit(pid)
|
||||
})
|
||||
|
||||
test('runAgent converts a closed stdin pipe into a bounded send failure', async () => {
|
||||
const child = new EventEmitter()
|
||||
child.stdin = new PassThrough()
|
||||
child.stdout = new PassThrough()
|
||||
child.stderr = new PassThrough()
|
||||
let killed = false
|
||||
child.kill = () => {
|
||||
if (killed) return true
|
||||
killed = true
|
||||
process.nextTick(() => child.emit('close', 1, 'SIGTERM'))
|
||||
return true
|
||||
}
|
||||
process.nextTick(() => child.stdin.destroy(new Error('write EPIPE')))
|
||||
|
||||
await assert.rejects(
|
||||
runAgent(
|
||||
{ kind: 'codex', executable: '/tmp/codex', name: 'Codex' },
|
||||
'send this reliably',
|
||||
os.tmpdir(),
|
||||
{ spawnFn: () => child },
|
||||
),
|
||||
error => error?.message === 'LOCAL_AGENT_SEND_FAILED',
|
||||
)
|
||||
})
|
||||
|
||||
test('runAgent cancellation closes pipes inherited by a descendant process', {
|
||||
skip: process.platform === 'win32',
|
||||
}, async (t) => {
|
||||
|
||||
@@ -15,6 +15,7 @@ const {
|
||||
parseKimiOutput,
|
||||
parseMimoOutput,
|
||||
parseOpenCodeOutput,
|
||||
parsePiOutput,
|
||||
parseWorkBuddyOutput,
|
||||
prepareCommand,
|
||||
readHermesFinalResponse,
|
||||
@@ -495,6 +496,31 @@ finish()
|
||||
), result.text)
|
||||
})
|
||||
|
||||
test('structured terminal output is kept when a CLI exits non-zero after producing a result', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-cli-result-before-exit-'))
|
||||
const cli = executable(directory, 'result-before-exit.cjs', `
|
||||
process.stdout.write(JSON.stringify({
|
||||
type: 'result', subtype: 'success', is_error: false,
|
||||
result: 'completed before cleanup failure', session_id: 'result-before-exit-session',
|
||||
}) + '\\n')
|
||||
process.exitCode = 1
|
||||
`)
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
|
||||
const events = []
|
||||
const result = await runAgent(
|
||||
{ kind: 'workbuddy', executable: cli, name: 'WorkBuddy' },
|
||||
'hello',
|
||||
directory,
|
||||
{ onEvent: event => events.push(event) },
|
||||
)
|
||||
|
||||
assert.equal(result.outcome, 'completed')
|
||||
assert.equal(result.text, 'completed before cleanup failure')
|
||||
assert.equal(result.sessionRef, 'result-before-exit-session')
|
||||
assert.equal(events.some(event => event.type === 'answer_delta'), true)
|
||||
})
|
||||
|
||||
test('Gemini profile state retains one real tool lifecycle id and summary', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-gemini-profile-state-'))
|
||||
const cli = executable(directory, 'gemini-profile-state.cjs', `
|
||||
@@ -1169,6 +1195,39 @@ input.on('line', (line) => {
|
||||
assert.equal(answerEvents.at(-1).replace, true)
|
||||
})
|
||||
|
||||
test('a reused ACP session that refuses before any output is recoverable as stale', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-acp-stale-refusal-'))
|
||||
const cli = executable(directory, 'acp-stale-refusal.cjs', `
|
||||
const readline = require('node:readline')
|
||||
const input = readline.createInterface({ input: process.stdin })
|
||||
const send = value => process.stdout.write(JSON.stringify(value) + '\\n')
|
||||
input.on('close', () => process.exit(0))
|
||||
input.on('line', line => {
|
||||
const message = JSON.parse(line)
|
||||
if (message.method === 'initialize') {
|
||||
send({ jsonrpc: '2.0', id: message.id, result: { protocolVersion: 1 } })
|
||||
} else if (message.method === 'session/resume') {
|
||||
send({ jsonrpc: '2.0', id: message.id, result: {} })
|
||||
} else if (message.method === 'session/set_mode') {
|
||||
send({ jsonrpc: '2.0', id: message.id, result: {} })
|
||||
} else if (message.method === 'session/prompt') {
|
||||
send({ jsonrpc: '2.0', id: message.id, result: { stopReason: 'refusal' } })
|
||||
}
|
||||
})
|
||||
`)
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }))
|
||||
|
||||
await assert.rejects(
|
||||
runAgent(
|
||||
{ kind: 'hermes', executable: cli, name: 'Hermes' },
|
||||
'continue the group task',
|
||||
directory,
|
||||
{ sessionRef: 'stale-session', sessionTransport: 'acp', hermesAcpAvailable: true },
|
||||
),
|
||||
error => error.message === 'LOCAL_AGENT_SESSION_INVALID',
|
||||
)
|
||||
})
|
||||
|
||||
test('ACP terminal stop reasons preserve exact outcome and failure semantics', async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-acp-stop-reasons-'))
|
||||
const cli = executable(directory, 'acp-stop-reasons.cjs', `
|
||||
@@ -1521,6 +1580,18 @@ test('Hermes receives selected Skill snapshots through the prompt without native
|
||||
assert.deepEqual(acpSpec.args, ['acp'])
|
||||
})
|
||||
|
||||
test('Pi uses non-interactive JSON flags and keeps provider settings out of arguments', () => {
|
||||
const spec = invocation('pi', '/tmp/pi', '/tmp', 'pi-session-123', {
|
||||
provider: { id: 'zgci', model: 'glm' },
|
||||
})
|
||||
assert.deepEqual(spec.args, [
|
||||
'--mode', 'json', '--print', '--no-approve', '--tools', 'read,grep,find,ls', '--session', 'pi-session-123',
|
||||
])
|
||||
assert.equal(spec.promptArg, true)
|
||||
assert.equal(spec.eventTransport, 'json')
|
||||
assert.equal(typeof parsePiOutput, 'function')
|
||||
})
|
||||
|
||||
test('Hermes forwards one image and rejects additional images instead of dropping them', () => {
|
||||
const first = path.resolve('diagram-one.png')
|
||||
const second = path.resolve('diagram-two.png')
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const http = require('node:http')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
const { execFile } = require('node:child_process')
|
||||
const { promisify } = require('node:util')
|
||||
const test = require('node:test')
|
||||
const { invocation, runAgent } = require('../../../src/agents/cli/cli-adapters.cjs')
|
||||
const { providerOptionsFor } = require('../../../src/providers/provider-options.cjs')
|
||||
|
||||
test('Claude credential helper reads a secret as data without shell expansion', {
|
||||
skip: process.platform === 'win32',
|
||||
}, async () => {
|
||||
const secret = 'test-$(exit 37)-`exit 38`-"quoted"-$HOME-&-secret'
|
||||
const spec = invocation('claude', '/tmp/claude', '/tmp', '', {
|
||||
provider: { id: 'anthropic', model: 'test-model', baseUrl: 'https://example.com' },
|
||||
platform: 'linux',
|
||||
})
|
||||
const settings = JSON.parse(spec.args[spec.args.indexOf('--settings') + 1])
|
||||
const result = await promisify(execFile)('/bin/sh', ['-c', settings.apiKeyHelper], {
|
||||
env: { MELDWORK_PROVIDER_API_KEY: secret }, timeout: 5000,
|
||||
})
|
||||
assert.equal(result.stdout, secret)
|
||||
assert.equal(JSON.stringify(spec.args).includes(secret), false)
|
||||
})
|
||||
|
||||
test('Claude Windows credential helper does not interpolate the key into cmd syntax', () => {
|
||||
const spec = invocation('claude', 'C:\\claude.exe', 'C:\\work', '', {
|
||||
provider: { id: 'anthropic', model: 'test-model' }, platform: 'win32',
|
||||
})
|
||||
const settings = JSON.parse(spec.args[spec.args.indexOf('--settings') + 1])
|
||||
assert.match(settings.apiKeyHelper, /GetEnvironmentVariable\('MELDWORK_PROVIDER_API_KEY'\)/)
|
||||
assert.doesNotMatch(settings.apiKeyHelper, /%MELDWORK_PROVIDER_API_KEY%/)
|
||||
})
|
||||
|
||||
test('native Claude uses the selected Provider despite conflicting native settings', {
|
||||
skip: !process.env.MELDWORK_TEST_CLAUDE_EXECUTABLE,
|
||||
timeout: 40000,
|
||||
}, async (t) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-claude-provider-'))
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }))
|
||||
const requests = []
|
||||
const selectedKey = 'selected-validation-key'
|
||||
async function endpoint(label) {
|
||||
const server = http.createServer((req, res) => {
|
||||
req.resume()
|
||||
if (req.method === 'HEAD') { res.writeHead(200); res.end(); return }
|
||||
requests.push({ label, selectedKey: req.headers['x-api-key'] === selectedKey
|
||||
|| req.headers.authorization === `Bearer ${selectedKey}` })
|
||||
res.writeHead(200, { 'Content-Type': 'text/event-stream' })
|
||||
for (const event of [
|
||||
{ type: 'message_start', message: {
|
||||
id: 'msg_local', type: 'message', role: 'assistant', model: 'claude-sonnet-4-6',
|
||||
content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 0 },
|
||||
} },
|
||||
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
|
||||
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'LOCAL_PROVIDER_OK' } },
|
||||
{ type: 'content_block_stop', index: 0 },
|
||||
{ type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } },
|
||||
{ type: 'message_stop' },
|
||||
]) res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
|
||||
res.end()
|
||||
})
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
|
||||
t.after(() => new Promise(resolve => { server.close(resolve); server.closeAllConnections() }))
|
||||
return `http://127.0.0.1:${server.address().port}`
|
||||
}
|
||||
const selected = await endpoint('selected')
|
||||
const native = await endpoint('native')
|
||||
const config = path.join(root, '.claude')
|
||||
fs.mkdirSync(config)
|
||||
const filename = path.join(config, 'settings.json')
|
||||
const settings = JSON.stringify({
|
||||
apiKeyHelper: 'exit 39', permissions: { deny: ['Bash(*)'] },
|
||||
env: {
|
||||
CLAUDE_CODE_USE_BEDROCK: '1', ANTHROPIC_BASE_URL: native,
|
||||
ANTHROPIC_API_KEY: 'native-validation-key', ANTHROPIC_AUTH_TOKEN: 'native-validation-token',
|
||||
ANTHROPIC_CUSTOM_HEADERS: 'Authorization: Bearer native-header-token',
|
||||
},
|
||||
})
|
||||
fs.writeFileSync(filename, settings)
|
||||
const options = providerOptionsFor('claude', {
|
||||
OPENAI_API_KEY: selectedKey, OPENAI_BASE_URL: selected, OPENAI_MODEL: 'claude-sonnet-4-6',
|
||||
})
|
||||
const events = []
|
||||
const result = await runAgent({ kind: 'claude', executable: process.env.MELDWORK_TEST_CLAUDE_EXECUTABLE },
|
||||
'Reply with OK. Do not use tools.', root, {
|
||||
...options, signal: AbortSignal.timeout(25000), onEvent: event => events.push(event),
|
||||
env: {
|
||||
...options.env, HOME: root, USERPROFILE: root, CLAUDE_CONFIG_DIR: config,
|
||||
XDG_CONFIG_HOME: root, XDG_DATA_HOME: root, XDG_STATE_HOME: root, XDG_CACHE_HOME: root,
|
||||
HTTP_PROXY: '', HTTPS_PROXY: '', ALL_PROXY: '', http_proxy: '', https_proxy: '', all_proxy: '',
|
||||
NO_PROXY: '*', no_proxy: '*', CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
|
||||
},
|
||||
})
|
||||
assert.equal(result.text, 'LOCAL_PROVIDER_OK')
|
||||
assert.ok(requests.length > 0)
|
||||
assert.ok(requests.every(request => request.label === 'selected' && request.selectedKey))
|
||||
assert.equal(fs.readFileSync(filename, 'utf8'), settings)
|
||||
assert.equal(JSON.stringify(events).includes(selectedKey), false)
|
||||
})
|
||||
@@ -46,6 +46,11 @@ const PROFILE_EXPECTATIONS = {
|
||||
source: 'stdout', answerMode: 'delta', tools: { start: false, update: false, result: false },
|
||||
plan: false, reasoning: false, session: true, terminal: true,
|
||||
},
|
||||
pi: {
|
||||
profileId: 'pi-json-events-v2', protocol: 'pi-json', framing: 'jsonl',
|
||||
source: 'stdout', answerMode: 'delta', tools: { start: true, update: true, result: true },
|
||||
plan: false, reasoning: true, session: true, terminal: true,
|
||||
},
|
||||
claude: {
|
||||
profileId: 'anthropic-stream-json-v1', protocol: 'anthropic-stream-json', framing: 'jsonl',
|
||||
source: 'stdout', answerMode: 'delta', tools: { start: true, update: true, result: true },
|
||||
@@ -128,6 +133,7 @@ test('every built-in invocation transport resolves its reusable profile and capa
|
||||
kind: 'mimo', options: { invocationTransport: 'json' },
|
||||
profileId: 'mimo-json-events-v1', limited: true,
|
||||
},
|
||||
{ kind: 'pi', profileId: 'pi-json-events-v2', limited: false },
|
||||
{ kind: 'claude', profileId: 'anthropic-stream-json-v1', limited: false },
|
||||
{ kind: 'gemini', profileId: 'gemini-stream-json-v1', limited: false },
|
||||
{ kind: 'opencode', profileId: 'acp-jsonrpc-v1', limited: false },
|
||||
|
||||
@@ -51,9 +51,15 @@ input.on('line', (line) => {
|
||||
} else if (message.method === 'session/prompt') {
|
||||
promptCount += 1
|
||||
if (resumed) {
|
||||
const prompt = message.params?.prompt?.[0]?.text || ''
|
||||
update(sessionId, {
|
||||
sessionUpdate: 'agent_message_chunk',
|
||||
content: { type: 'text', text: 'HTTP 401: Invalid token' },
|
||||
content: {
|
||||
type: 'text',
|
||||
text: prompt === 'auth prompt'
|
||||
? 'HTTP 401: Invalid token (request id: request-1)'
|
||||
: 'resumed turn',
|
||||
},
|
||||
})
|
||||
send({ jsonrpc: '2.0', id: message.id, result: { stopReason: 'end_turn' } })
|
||||
return
|
||||
@@ -120,12 +126,22 @@ input.on('line', (line) => {
|
||||
assert.equal(typeof adapters.shutdownAcpSessionRuntime, 'function')
|
||||
await adapters.shutdownAcpSessionRuntime()
|
||||
await within(readWhenReady(stoppedFile))
|
||||
await assert.rejects(() => adapters.runAgent(agent, 'stale prompt', directory, {
|
||||
const resumed = await adapters.runAgent(agent, 'resumed prompt', directory, {
|
||||
acpPersistenceKey: 'workspace:hermes:direct',
|
||||
sessionRef: first.sessionRef,
|
||||
sessionTransport: 'acp',
|
||||
env: { MELDWORK_TEST_SPAWN_COUNT_FILE: spawnCountFile },
|
||||
}), { message: 'LOCAL_AGENT_SESSION_INVALID' })
|
||||
})
|
||||
assert.equal(resumed.text, 'resumed turn')
|
||||
assert.equal(resumed.sessionRef, first.sessionRef)
|
||||
assert.equal(fs.readFileSync(spawnCountFile, 'utf8'), '2')
|
||||
await assert.rejects(() => adapters.runAgent(agent, 'auth prompt', directory, {
|
||||
acpPersistenceKey: 'workspace:hermes:direct',
|
||||
sessionRef: first.sessionRef,
|
||||
sessionTransport: 'acp',
|
||||
env: { MELDWORK_TEST_SPAWN_COUNT_FILE: spawnCountFile },
|
||||
}), error => error.message === 'LOCAL_AGENT_AUTH_REQUIRED'
|
||||
&& error.failure?.category === 'authentication')
|
||||
})
|
||||
|
||||
test('ACP closes a start-only tool with the partial terminal outcome', async (t) => {
|
||||
@@ -623,6 +639,8 @@ input.on('line', (line) => {
|
||||
},
|
||||
})
|
||||
const events = []
|
||||
let receivedStream
|
||||
const streamReceived = new Promise(resolve => { receivedStream = resolve })
|
||||
let resolved = false
|
||||
resultPromise = adapters.runAgent(
|
||||
{ kind: 'openclaw', executable: cli, name: 'OpenClaw' },
|
||||
@@ -631,7 +649,10 @@ input.on('line', (line) => {
|
||||
{
|
||||
...runtime,
|
||||
sessionRef: stableSessionRef,
|
||||
onEvent: event => events.push(event),
|
||||
onEvent: event => {
|
||||
events.push(event)
|
||||
if (events.length === 5) receivedStream()
|
||||
},
|
||||
},
|
||||
).then((result) => {
|
||||
resolved = true
|
||||
@@ -639,6 +660,8 @@ input.on('line', (line) => {
|
||||
})
|
||||
|
||||
await within(readWhenReady(readyFile))
|
||||
// The child's file write does not guarantee the parent has consumed stdout.
|
||||
await within(streamReceived)
|
||||
assert.equal(resolved, false)
|
||||
assert.deepEqual(events.map(event => event.type), [
|
||||
'tool_start', 'tool_update', 'tool_result_summary',
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const { execFile } = require('node:child_process')
|
||||
const { promisify } = require('node:util')
|
||||
const { networkEnvironment } = require('../../../src/agents/cli/cli-network-environment.cjs')
|
||||
const { systemChildEnvironment } = require('../../../src/agents/cli/cli-discovery.cjs')
|
||||
const { childEnvironment } = require('../../../src/agents/cli/cli-process-support.cjs')
|
||||
const { resolveNativeShellEnvironment, resolveNativeCredentialState } = require('../../../src/agents/local-agent-readiness.cjs')
|
||||
const { redactChildSecrets, createRuntimeEventEmitter } = require('../../../src/agents/cli/cli-runtime-event-sanitizer.cjs')
|
||||
|
||||
test('network configuration preserves POSIX proxy case and explicit empty overrides without runtime injection', () => {
|
||||
const source = {
|
||||
HTTP_PROXY: 'http://upper.example:8080', http_proxy: 'http://lower.example:8081',
|
||||
HTTPS_PROXY: '', NO_PROXY: 'localhost,127.0.0.1,::1', no_proxy: '',
|
||||
NODE_EXTRA_CA_CERTS: '/certs/company.pem', REQUESTS_CA_BUNDLE: '/certs/python.pem',
|
||||
NODE_USE_ENV_PROXY: '1', NODE_OPTIONS: '--require=/untrusted.cjs',
|
||||
NODE_TLS_REJECT_UNAUTHORIZED: '0', OPENAI_API_KEY: 'unrelated-secret',
|
||||
}
|
||||
const expected = { ...source }
|
||||
for (const key of ['NODE_OPTIONS', 'NODE_TLS_REJECT_UNAUTHORIZED', 'OPENAI_API_KEY']) delete expected[key]
|
||||
assert.deepEqual(networkEnvironment(source, 'darwin'), expected)
|
||||
const child = systemChildEnvironment(source, 'darwin')
|
||||
for (const [key, value] of Object.entries(expected)) assert.equal(child[key], value)
|
||||
assert.equal(child.NODE_OPTIONS, undefined)
|
||||
assert.equal(child.NODE_TLS_REJECT_UNAUTHORIZED, undefined)
|
||||
assert.equal(child.OPENAI_API_KEY, undefined)
|
||||
assert.deepEqual(networkEnvironment({ Https_Proxy: 'http://windows.example:8080' }, 'win32'), {
|
||||
HTTPS_PROXY: 'http://windows.example:8080',
|
||||
})
|
||||
})
|
||||
|
||||
test('login shell proxy and CA settings survive credential probes and actual child construction', { skip: process.platform === 'win32' }, async () => {
|
||||
const source = {
|
||||
PATH: '/usr/bin:/bin', HTTPS_PROXY: 'http://inherited.example:8080',
|
||||
http_proxy: 'http://shell.example:3128', NO_PROXY: 'localhost,127.0.0.1',
|
||||
NODE_EXTRA_CA_CERTS: '/certs/trusted.pem',
|
||||
}
|
||||
const shell = await resolveNativeShellEnvironment({
|
||||
cache: false, platform: 'linux', shell: '/bin/sh', home: '/tmp/meldwork-network-test', env: source,
|
||||
execFileFn: async (_file, args, options) => {
|
||||
assert.equal(options.env.http_proxy, source.http_proxy)
|
||||
return promisify(execFile)('/bin/sh', ['-c', `HTTPS_PROXY=''; export HTTPS_PROXY\n${args[1]}`], {
|
||||
env: { ...options.env, NODE_OPTIONS: 'must-not-be-returned' },
|
||||
})
|
||||
},
|
||||
})
|
||||
assert.equal(shell.env.HTTPS_PROXY, '')
|
||||
assert.equal(shell.env.NODE_OPTIONS, undefined)
|
||||
for (const key of ['http_proxy', 'NO_PROXY', 'NODE_EXTRA_CA_CERTS']) assert.equal(shell.env[key], source[key])
|
||||
let probed = false
|
||||
await resolveNativeCredentialState('claude', {
|
||||
executable: '/tmp/claude-network-test', home: '/tmp/meldwork-network-test', env: shell.env,
|
||||
execFileFn: async (_file, _args, options) => {
|
||||
probed = true
|
||||
assert.equal(options.env.http_proxy, source.http_proxy)
|
||||
assert.equal(options.env.HTTPS_PROXY, '')
|
||||
return { stdout: '{"loggedIn":true}', stderr: '' }
|
||||
},
|
||||
})
|
||||
assert.equal(probed, true)
|
||||
const env = childEnvironment({ kind: 'claude' }, '/tmp/workspace', {
|
||||
env: networkEnvironment(shell.env), sandbox: 'read-only',
|
||||
}, 'linux')
|
||||
assert.equal(env.http_proxy, source.http_proxy)
|
||||
assert.equal(env.HTTPS_PROXY, '')
|
||||
assert.equal(env.NODE_EXTRA_CA_CERTS, source.NODE_EXTRA_CA_CERTS)
|
||||
})
|
||||
|
||||
test('proxy credentials are redacted in diagnostics and across every streamed split', () => {
|
||||
const proxy = 'http://proxy-user:proxy%[email protected]:3128'
|
||||
const env = { https_proxy: proxy }
|
||||
const values = [proxy, 'proxy-user:proxy%40password', 'proxy-user:proxy@password',
|
||||
'proxy%40password', 'proxy@password', Buffer.from('proxy-user:proxy@password').toString('base64')]
|
||||
for (const value of values) {
|
||||
assert.equal(redactChildSecrets(`Connection failed: ${value}`, env), 'Connection failed: [redacted]')
|
||||
for (let split = 1; split < value.length; split += 1) {
|
||||
const emitted = []
|
||||
const events = createRuntimeEventEmitter({ onEvent: event => emitted.push(event) }, env)
|
||||
events.emit({ type: 'answer_delta', status: 'running', delta: `Connection failed: ${value.slice(0, split)}` })
|
||||
events.emit({ type: 'answer_delta', status: 'running', delta: `${value.slice(split)}. Retry later.` })
|
||||
events.emitFinalAnswer(`Connection failed: ${value}. Retry later.`)
|
||||
const delivered = emitted.filter(event => event.type === 'answer_delta').map(event => event.delta).join('')
|
||||
assert.equal(delivered.includes(value), false, `split ${split}`)
|
||||
assert.match(delivered, /\[redacted\]/)
|
||||
}
|
||||
}
|
||||
assert.equal(redactChildSecrets('https://public.example', { HTTPS_PROXY: 'https://public.example' }), 'https://public.example')
|
||||
assert.equal(redactChildSecrets('Bad proxy: user:private-password@', { HTTP_PROXY: 'user:private-password@' }), 'Bad proxy: [redacted]')
|
||||
})
|
||||
@@ -4,9 +4,49 @@ const fs = require('node:fs')
|
||||
const os = require('node:os')
|
||||
const path = require('node:path')
|
||||
|
||||
const { childEnvironment } = require('../../../src/agents/cli/cli-process-support.cjs')
|
||||
const { childEnvironment, failedAgentProcessError } = require('../../../src/agents/cli/cli-process-support.cjs')
|
||||
const { managedOpenClawOptions } = require('../../../src/agents/cli/openclaw-runtime.cjs')
|
||||
|
||||
test('local Agent child environments keep supported runtime settings but reject process injection', () => {
|
||||
const env = childEnvironment(
|
||||
{ kind: 'pi' }, '/tmp/workspace', {
|
||||
env: {
|
||||
OPENAI_BASE_URL: 'https://provider.example/v1',
|
||||
HTTPS_PROXY: 'http://proxy.example:3128',
|
||||
GITHUB_TOKEN: 'unrelated-secret',
|
||||
NODE_OPTIONS: '--require=/tmp/injected.js',
|
||||
DYLD_INSERT_LIBRARIES: '/tmp/injected.dylib',
|
||||
},
|
||||
}, 'darwin',
|
||||
)
|
||||
assert.equal(env.OPENAI_BASE_URL, 'https://provider.example/v1')
|
||||
assert.equal(env.HTTPS_PROXY, 'http://proxy.example:3128')
|
||||
assert.equal(Object.hasOwn(env, 'GITHUB_TOKEN'), false)
|
||||
assert.equal(Object.hasOwn(env, 'NODE_OPTIONS'), false)
|
||||
assert.equal(Object.hasOwn(env, 'DYLD_INSERT_LIBRARIES'), false)
|
||||
})
|
||||
|
||||
test('process diagnostics require explicit authentication failure evidence', () => {
|
||||
for (const diagnostic of [
|
||||
'EACCES: permission denied opening auth-service.ts',
|
||||
'Cannot find module credential-parser',
|
||||
'Model configuration failed: connection timed out',
|
||||
'Failed to download documentation: HTTP 403 Forbidden',
|
||||
]) {
|
||||
assert.equal(failedAgentProcessError(diagnostic).code, 'LOCAL_AGENT_PROCESS_FAILED')
|
||||
}
|
||||
for (const diagnostic of [
|
||||
'Invalid API key',
|
||||
'Authentication failed',
|
||||
'Please log in before continuing',
|
||||
'Select an auth type first.',
|
||||
'HTTP 401: Unauthorized',
|
||||
'认证失败,请重新登录',
|
||||
]) {
|
||||
assert.equal(failedAgentProcessError(diagnostic).code, 'LOCAL_AGENT_AUTH_REQUIRED')
|
||||
}
|
||||
})
|
||||
|
||||
test('OpenClaw child environment keeps only its guarded runtime and selected credential', (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'meldwork-openclaw-child-env-'))
|
||||
const workdir = path.join(directory, 'workspace')
|
||||
@@ -46,6 +86,9 @@ test('OpenClaw child environment keeps only its guarded runtime and selected cre
|
||||
...runtime,
|
||||
env: {
|
||||
...runtime.env,
|
||||
https_proxy: 'http://proxy.example:3128',
|
||||
NO_PROXY: 'localhost,127.0.0.1,::1',
|
||||
NODE_EXTRA_CA_CERTS: '/certs/company.pem',
|
||||
MELDWORK_OPENCLAW_NATIVE_API_KEY: 'wrong-openclaw-key',
|
||||
GITHUB_TOKEN: 'caller-secret',
|
||||
ANTHROPIC_API_KEY: 'caller-anthropic-secret',
|
||||
@@ -56,6 +99,9 @@ test('OpenClaw child environment keeps only its guarded runtime and selected cre
|
||||
)
|
||||
|
||||
assert.equal(env.MELDWORK_OPENCLAW_API_KEY, 'selected-openclaw-key')
|
||||
assert.equal(env.https_proxy, 'http://proxy.example:3128')
|
||||
assert.equal(env.NO_PROXY, 'localhost,127.0.0.1,::1')
|
||||
assert.equal(env.NODE_EXTRA_CA_CERTS, '/certs/company.pem')
|
||||
assert.equal(env.OPENCLAW_GATEWAY_TOKEN, runtime.env.OPENCLAW_GATEWAY_TOKEN)
|
||||
assert.equal(env.OPENCLAW_DISABLE_BONJOUR, '1')
|
||||
assert.equal(Object.hasOwn(env, 'MELDWORK_OPENCLAW_NATIVE_API_KEY'), false)
|
||||
|
||||
@@ -51,6 +51,15 @@ const STREAMING_FIXTURES = [
|
||||
file: 'mimo.jsonl',
|
||||
expectedTypes: ['answer_delta'],
|
||||
},
|
||||
{
|
||||
kind: 'pi',
|
||||
agent: 'Pi Agent',
|
||||
version: '0.84.2',
|
||||
protocol: 'pi-json',
|
||||
evidence: 'captured-fixture',
|
||||
file: 'pi.jsonl',
|
||||
expectedTypes: ['reasoning_summary', 'reasoning_summary', 'reasoning_summary', 'answer_delta'],
|
||||
},
|
||||
{
|
||||
kind: 'opencode',
|
||||
agent: 'OpenCode',
|
||||
@@ -518,6 +527,22 @@ test('terminal reconciliation never reconstructs an exact 8-byte child secret',
|
||||
}
|
||||
})
|
||||
|
||||
test('AWS access keys are redacted across every streaming boundary', () => {
|
||||
const secret = 'AKIATESTACCESSKEY1234'
|
||||
for (let split = 1; split < secret.length; split += 1) {
|
||||
const emitted = []
|
||||
const runtimeEvents = createRuntimeEventEmitter(
|
||||
{ onEvent: event => emitted.push(event) }, { AWS_ACCESS_KEY_ID: secret },
|
||||
)
|
||||
runtimeEvents.emit({ type: 'answer_delta', status: 'running', delta: secret.slice(0, split) })
|
||||
runtimeEvents.emit({ type: 'answer_delta', status: 'running', delta: secret.slice(split) })
|
||||
runtimeEvents.emitFinalAnswer(secret)
|
||||
assert.equal(JSON.stringify(emitted).includes(secret), false)
|
||||
assert.equal(emitted.filter(event => event.type === 'answer_delta')
|
||||
.map(event => event.delta).join('').includes(secret), false)
|
||||
}
|
||||
})
|
||||
|
||||
test('runtime answer delivery reconciles empty and incomplete deltas with the terminal answer', () => {
|
||||
for (const deltas of [[], [''], ['authoritative ']]) {
|
||||
const emitted = []
|
||||
@@ -640,7 +665,7 @@ test('profile capabilities produce connector-limited warnings without Agent-kind
|
||||
}
|
||||
|
||||
const complete = [
|
||||
['codex'], ['hermes'], ['openclaw'], ['kimi'], ['claude'], ['qwen'], ['gemini'],
|
||||
['codex'], ['hermes'], ['openclaw'], ['pi', { transport: 'acp' }], ['kimi'], ['claude'], ['qwen'], ['gemini'],
|
||||
['workbuddy', { transport: 'stream-json' }],
|
||||
]
|
||||
for (const [kind, options] of complete) {
|
||||
|
||||