File size: 177,528 Bytes
f0634fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 | import { getMaxListeners } from 'node:events';
import { type ToolCall } from '#human/llm/message';
import { emptyUsage } from '#human/llm/usage';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { IDisposable } from '#/_base/di/lifecycle';
import { Event } from '#/_base/event';
import { IAgentProfileService } from '#/index';
import { IAgentLLMRequesterService } from '#/agent/llmRequester/llmRequester';
import type { ModelRequestTiming } from '#/llm-adapter/model/model-requester';
import { APIProviderRateLimitError } from '#/llm-adapter/contract/errors';
import type { ContextMessage, PromptOrigin } from '#/agent/contextMemory/types';
import type { LoopRecordedEvent } from '#/agent/contextMemory/loopEventFold';
import { IAgentGoalService } from '#/features/goal/goalService';
import { IAgentLoopService, type Turn } from '#/agent/loop/loop';
import { createActor } from '#human/xstate2';
import { createAgentMachine } from '#human/agent/machine';
import { agentContextOf } from '#/agent/scopeContext/scopeContext';
import type { AgentContext } from '#/agent/agentContext/agentContext';
import {
IAgentLifecycleService,
type AgentScopeCreatedEvent,
} from '#/session/agentLifecycle/agentLifecycle';
import {
AssistantDelta,
ThinkingDelta,
TurnStarted,
TurnStepInterrupted,
TurnStepStarted,
} from '#/agent/loop/turnEvents';
import { TurnEnded } from '#/agent/loop/turnOps';
import type { ExecutableTool } from '#/tool/toolContract';
import { IAgentToolRegistryService } from '#/agent/toolRegistry/toolRegistry';
import { IAgentToolExecutorService } from '#/agent/toolExecutor/toolExecutor';
import { IEventBus } from '#/app/event/eventBus';
import { ITelemetryService } from '#/app/telemetry/telemetry';
import { isUserCancellation, userCancellationReason } from '#/_base/utils/abort';
import {
agentService,
createTestAgent,
InMemoryWireRecordPersistence,
permissionModeServices,
requesterFromGenerateFn,
sessionService,
wireRecordPersistenceServices,
type TestAgentContext,
type TestAgentOptions,
} from '../../harness';
import { recordingTelemetry, type TelemetryRecord } from '../../app/telemetry/stubs';
import { submitPromptTurn } from './stubs';
type GenerateFn = NonNullable<TestAgentOptions['generate']>;
describe('Agent loop', () => {
let ctx: TestAgentContext;
let loop: IAgentLoopService;
let profile: IAgentProfileService;
beforeEach(async () => {
ctx = createTestAgent();
await ctx.restorePersisted();
loop = ctx.get(IAgentLoopService);
profile = ctx.get(IAgentProfileService);
});
afterEach(async () => {
try {
await ctx.expectResumeMatches();
} finally {
await ctx.dispose();
}
});
it('runs a text-only agent turn from prompt to completion', async () => {
profile.update({ activeToolNames: [] });
ctx.mockNextResponse(
{ type: 'think', think: '<think-1>' },
{ type: 'text', text: '<text-1>' },
{ type: 'think', think: '' },
{ type: 'text', text: '<text-2>' },
);
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
expect(await ctx.untilTurnEnd()).toMatchInlineSnapshot(`
[wire] tools.set_active_tools { "agentId": "main", "names": [], "time": "<time>" }
[emit] prompt.submitted { "time": "<time>", "agentId": "main", "promptId": "<msg-1>", "userMessageId": "<msg-1>", "status": "running", "content": [ { "type": "text", "text": "Hello" } ], "createdAt": "<time>" }
[wire] turn.prompt { "agentId": "main", "input": [ { "type": "text", "text": "Hello" } ], "origin": { "kind": "user" }, "promptId": "<msg-1>", "turnId": 0, "time": "<time>" }
[emit] turn.started { "time": "<time>", "agentId": "main", "turnId": 0, "promptId": "<msg-1>", "origin": { "kind": "user" }, "prompt": "Hello" }
[emit] context.spliced { "time": "<time>", "agentId": "main", "start": 0, "deleteCount": 0, "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Hello" } ], "id": "<msg-1>", "toolCalls": [], "origin": { "kind": "user" } } ] }
[emit] prompt.started { "time": "<time>", "agentId": "main", "promptId": "<msg-1>" }
[wire] context.append_message { "agentId": "main", "message": { "role": "user", "content": [ { "type": "text", "text": "Hello" } ], "id": "<msg-1>", "toolCalls": [], "origin": { "kind": "user" } }, "time": "<time>" }
[wire] agent.message.appended { "message": { "message": { "role": "user", "content": [ { "type": "text", "text": "Hello" } ] }, "meta": { "source": "input", "promptId": "<msg-1>", "origin": { "kind": "user" }, "tracked": true, "createdAt": "<time>", "userMessageId": "<msg-1>" } }, "time": "<time>", "kind": "event" }
[wire] agent.turn.started { "turnId": 0, "queueItemId": "<msg-1>", "time": "<time>", "kind": "event" }
[wire] plugin.session_start { "agentId": "main", "content": null, "time": "<time>" }
[emit] turn.step.started { "time": "<time>", "agentId": "main", "turnId": 0, "step": 1, "stepId": "<uuid-1>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "step.begin", "uuid": "<uuid-1>", "turnId": "0", "step": 1 }, "time": "<time>" }
[emit] thinking.delta { "time": "<time>", "agentId": "main", "turnId": 0, "delta": "<think-1>" }
[wire] llm.tools_snapshot { "agentId": "main", "hash": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945", "tools": [], "time": "<time>" }
[emit] assistant.delta { "time": "<time>", "agentId": "main", "turnId": 0, "delta": "<text-1>" }
[emit] thinking.delta { "time": "<time>", "agentId": "main", "turnId": 0, "delta": "" }
[wire] llm.request { "agentId": "main", "kind": "loop", "provider": "openai", "model": "mock-model", "modelAlias": "mock-model", "thinkingEffort": "off", "maxTokens": 1000000, "toolSelect": false, "systemPromptHash": "ec9c34379c88babbc468ef2f3e0e08cd2f422c8c4a910664fb8bb394d703a575", "toolsHash": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945", "messageCount": 1, "turnStep": "0.1", "time": "<time>" }
[emit] assistant.delta { "time": "<time>", "agentId": "main", "turnId": 0, "delta": "<text-2>" }
[wire] usage.record { "agentId": "main", "model": "mock-model", "usage": { "inputOther": 3, "output": 10, "inputCacheRead": 0, "inputCacheCreation": 0 }, "usageScope": "turn", "time": "<time>" }
[emit] agent.status.updated { "time": "<time>", "agentId": "main", "usage": { "byModel": { "mock-model": { "inputOther": 3, "output": 10, "inputCacheRead": 0, "inputCacheCreation": 0 } }, "total": { "inputOther": 3, "output": 10, "inputCacheRead": 0, "inputCacheCreation": 0 }, "currentTurn": { "inputOther": 3, "output": 10, "inputCacheRead": 0, "inputCacheCreation": 0 } } }
[wire] token_counting.measured { "agentId": "main", "length": 2, "tokens": 13, "time": "<time>" }
[emit] agent.status.updated { "time": "<time>", "agentId": "main", "contextTokens": 13 }
[emit] turn.step.completed { "time": "<time>", "agentId": "main", "turnId": 0, "step": 1, "stepId": "<uuid-1>", "usage": { "inputOther": 3, "output": 10, "inputCacheRead": 0, "inputCacheCreation": 0 }, "finishReason": "end_turn", "providerFinishReason": "completed", "rawFinishReason": "stop" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "content.part", "uuid": "<uuid-2>", "turnId": "0", "step": 1, "stepUuid": "<uuid-1>", "part": { "type": "think", "think": "<think-1>" } }, "time": "<time>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "content.part", "uuid": "<uuid-3>", "turnId": "0", "step": 1, "stepUuid": "<uuid-1>", "part": { "type": "text", "text": "<text-1><text-2>" } }, "time": "<time>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "step.end", "uuid": "<uuid-1>", "turnId": "0", "step": 1, "finishReason": "end_turn", "usage": { "inputOther": 3, "output": 10, "inputCacheRead": 0, "inputCacheCreation": 0 }, "messageId": "mock-1", "providerFinishReason": "completed", "rawFinishReason": "stop" }, "time": "<time>" }
[wire] agent.message.appended { "message": { "message": { "role": "assistant", "content": [ { "type": "think", "think": "<think-1>" }, { "type": "text", "text": "<text-1><text-2>" } ], "toolCalls": [] }, "meta": { "model": { "provider": "agent-loop", "model": "agent-loop" }, "source": "llm", "usage": { "inputOther": 3, "output": 10, "inputCacheRead": 0, "inputCacheCreation": 0 }, "finish": { "finishReason": "completed", "rawFinishReason": "stop" }, "messageId": "mock-1" } }, "time": "<time>", "kind": "event" }
[wire] agent.turn.ended { "turnId": 0, "outcome": "done", "time": "<time>", "kind": "event" }
[wire] turn.ended { "agentId": "main", "turnId": 0, "reason": "completed", "time": "<time>" }
[emit] turn.ended { "time": "<time>", "agentId": "main", "turnId": 0, "reason": "completed" }
`);
expect(ctx.lastLlmInput()).toMatchInlineSnapshot(`
system: <system-prompt>
tools: []
messages:
user: text "Hello"
`);
});
it('persists a turn.ended wire record with the end reason and duration', async () => {
profile.update({ activeToolNames: [] });
ctx.mockNextResponse({ type: 'text', text: 'done' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await ctx.untilTurnEnd();
const record = (await ctx.persistedWireRecords()).find((entry) => entry.type === 'turn.ended');
expect(record).toMatchObject({ turnId: 0, reason: 'completed' });
expect(record?.['durationMs']).toEqual(expect.any(Number));
expect(record?.['time']).toEqual(expect.any(Number));
});
it('restores the engine turn clock from the machine journal on resume', async () => {
profile.update({ activeToolNames: [] });
ctx.mockNextResponse({ type: 'text', text: 'first answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'first prompt' }] });
await ctx.untilTurnEnd();
const records = await ctx.persistedWireRecords();
expect(records.some((record) => record.type === 'agent.turn.ended')).toBe(true);
const resumed = createTestAgent(
wireRecordPersistenceServices(new InMemoryWireRecordPersistence(records)),
);
try {
await resumed.restorePersisted();
const turnIds: number[] = [];
const subscription = resumed
.get(IEventBus)
.subscribe(TurnStarted, (event) => turnIds.push(event.turnId));
resumed.mockNextResponse({ type: 'text', text: 'second answer' });
await resumed.rpc.prompt({ input: [{ type: 'text', text: 'second prompt' }] });
await resumed.untilTurnEnd();
subscription.dispose();
expect(turnIds).toEqual([1]);
const persisted = await resumed.persistedWireRecords();
expect(
persisted
.filter((record) => record.type === 'agent.turn.ended')
.map((record) => record['turnId']),
).toEqual([0, 1]);
} finally {
await resumed.dispose();
}
});
it('fails the turn after a filtered step completes', async () => {
ctx.mockNextProviderResponse({
parts: [{ type: 'text', text: 'blocked' }],
finishReason: 'filtered',
});
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
expect(await ctx.untilTurnEnd()).toMatchInlineSnapshot(`
[emit] prompt.submitted { "time": "<time>", "agentId": "main", "promptId": "<msg-1>", "userMessageId": "<msg-1>", "status": "running", "content": [ { "type": "text", "text": "Hello" } ], "createdAt": "<time>" }
[wire] turn.prompt { "agentId": "main", "input": [ { "type": "text", "text": "Hello" } ], "origin": { "kind": "user" }, "promptId": "<msg-1>", "turnId": 0, "time": "<time>" }
[emit] turn.started { "time": "<time>", "agentId": "main", "turnId": 0, "promptId": "<msg-1>", "origin": { "kind": "user" }, "prompt": "Hello" }
[emit] context.spliced { "time": "<time>", "agentId": "main", "start": 0, "deleteCount": 0, "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Hello" } ], "id": "<msg-1>", "toolCalls": [], "origin": { "kind": "user" } } ] }
[emit] prompt.started { "time": "<time>", "agentId": "main", "promptId": "<msg-1>" }
[wire] context.append_message { "agentId": "main", "message": { "role": "user", "content": [ { "type": "text", "text": "Hello" } ], "id": "<msg-1>", "toolCalls": [], "origin": { "kind": "user" } }, "time": "<time>" }
[wire] agent.message.appended { "message": { "message": { "role": "user", "content": [ { "type": "text", "text": "Hello" } ] }, "meta": { "source": "input", "promptId": "<msg-1>", "origin": { "kind": "user" }, "tracked": true, "createdAt": "<time>", "userMessageId": "<msg-1>" } }, "time": "<time>", "kind": "event" }
[wire] agent.turn.started { "turnId": 0, "queueItemId": "<msg-1>", "time": "<time>", "kind": "event" }
[wire] plugin.session_start { "agentId": "main", "content": null, "time": "<time>" }
[emit] turn.step.started { "time": "<time>", "agentId": "main", "turnId": 0, "step": 1, "stepId": "<uuid-1>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "step.begin", "uuid": "<uuid-1>", "turnId": "0", "step": 1 }, "time": "<time>" }
[emit] assistant.delta { "time": "<time>", "agentId": "main", "turnId": 0, "delta": "blocked" }
[wire] llm.tools_snapshot { "agentId": "main", "hash": "d0f052e43d5697d7ed9cbd7208499a7907c68e615869f36109b6f9b7252a61c7", "tools": [ { "name": "Agent", "description": "Launch a subagent to handle a task. The subagent runs as a same-process loop instance with its own context and wire file. Delegating also keeps the bulk of intermediate file contents out of your own context — you get a conclusion back instead of a pile of dumps.\\n\\nWriting the prompt:\\n- The subagent starts with zero context — it has not seen this conversation. Brief it like a colleague who just walked into the room: state the goal, list what you already know, hand over the specifics.\\n- Lookups (read this file, run that test): put the exact path or command in the prompt. The subagent should not have to search for things you already know.\\n- Investigations (figure out X, find why Y): give the question, not prescribed steps — fixed steps become dead weight when the premise is wrong.\\n- Do not delegate understanding. If the task hinges on a file path or line number, find it yourself first and write it into the prompt.\\n\\nUsage notes:\\n- When the task continues earlier work a subagent already did, prefer resuming that agent (pass its \`resume\` id) over spawning a fresh instance — the resumed agent keeps its prior context.\\n- A subagent's result is only visible to you, not to the user. When the user needs to see what a subagent produced, summarize the relevant parts yourself in your own reply.\\n\\nWhen NOT to use Agent: skip delegation for trivial work you can do directly — reading a file whose path you already know, searching a small known set of files, or any task that takes only a step or two. Delegation has a context-handoff cost; it pays off only when the task is substantial enough to outweigh it.\\n\\nOnce a subagent is running, leave that scope to it: do not redo its searches or reads in parallel, and do not abandon it midway and finish the job manually. Both undo the context savings the delegation was meant to buy.\\n\\n\\nWhen \`run_in_background=true\`, the subagent runs detached from this turn. The completion arrives in a later turn as a synthetic user-role message containing its result — you do not need to poll, sleep, or check on its progress. Continue with other work or respond to the user. Never fabricate or predict what the result will say.\\n\\nDefault to a foreground subagent (omit \`run_in_background\`) when your next step needs its result — foreground hands the result straight back. Reach for \`run_in_background=true\` only when you have other work to do while it runs and do not need its result to proceed. Never launch in the background and then immediately wait on it (by polling \`TaskOutput\`, sleeping, or otherwise): that just blocks the turn for no benefit — run it in the foreground instead.\\n\\n\\nAvailable agent types (pass via subagent_type):\\n- plan: Read-only implementation planning and architecture design. Use this agent when the parent agent needs a step-by-step implementation plan, key file identification, and architectural trade-off analysis before code changes are made.\\n Tools: Read, ReadMediaFile, Glob, Grep, WebSearch, FetchURL\\n- coder: General software engineering agent — the only subagent type with file-editing tools; use it for any delegated task that must modify code. Use this agent for non-trivial software engineering work that may require reading files, editing code, running commands, and returning a compact but technically complete summary to the parent agent.\\n Tools: Bash, CronCreate, CronDelete, CronList, Edit, EnterPlanMode, ExitPlanMode, Glob, Grep, Read, ReadMediaFile, Skill, TaskList, TaskOutput, TaskStop, TodoList, WaitFor, WebSearch, FetchURL, Write, mcp__*\\n- explore: Fast codebase exploration with prompt-enforced read-only behavior. Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (e.g. \\"src/**/*.yaml\\"), search code for keywords (e.g. \\"database connection\\"), or answer questions about the codebase (e.g. \\"how does the auth module work?\\"). When calling this agent, specify the desired thoroughness level: \\"quick\\" for basic searches, \\"medium\\" for moderate exploration, or \\"thorough\\" for comprehensive analysis across multiple locations and naming conventions. Use this agent for any read-only exploration that will clearly require more than 3 search queries. Prefer launching multiple explore agents concurrently when investigating independent questions.\\n Tools: Bash, Read, ReadMediaFile, Glob, Grep, WebSearch, FetchURL", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "prompt": { "type": "string", "description": "Full task prompt for the subagent" }, "description": { "type": "string", "description": "Short task description (3-5 words) for UI display" }, "subagent_type": { "description": "One of the available agent types (see \\"Available agent types\\" in this tool description). Defaults to \\"coder\\" when omitted.", "type": "string" }, "resume": { "description": "Optional agent ID to resume instead of creating a new instance. When set, do not also pass subagent_type — the resumed agent keeps its own type, and supplying both is rejected.", "type": "string" }, "run_in_background": { "description": "If true, return immediately without waiting for completion. Prefer false unless the task can run independently and there is a clear benefit to not waiting.", "type": "boolean" } }, "required": [ "prompt", "description" ], "additionalProperties": false } }, { "name": "AgentSwarm", "description": "Launch multiple subagents from one prompt template, existing agent resumes, or both.\\n\\nUse AgentSwarm when many subagents should run the same kind of task over different inputs. The placeholder is exactly \`{{item}}\`. For example, with \`prompt_template\` set to \`Review {{item}} for likely regressions.\` and \`items\` set to \`[\\"src/a.ts\\", \\"src/b.ts\\"]\`, AgentSwarm launches two new subagents with those two concrete prompts. For a few differently-shaped tasks, make separate \`Agent\` calls in one message instead.\\n\\nUse \`resume_agent_ids\` to continue subagents that already exist from earlier work, such as ones that failed or timed out: map each agent id to the prompt for that resumed subagent (usually \`continue\` if no extra information is needed). You may combine \`resume_agent_ids\` with \`items\` in the same call to resume existing subagents and launch new ones. Do not duplicate resumed work in \`items\`.\\n\\nEach of these is enforced — a violation is rejected before any subagent starts: provide at least 2 \`items\` unless you pass \`resume_agent_ids\`; whenever \`items\` are present, \`prompt_template\` is required and must contain \`{{item}}\`; and the filled-in prompts must be distinct (two items that expand to the same prompt are rejected).\\n\\nUse enough subagents to keep the work focused and parallel. AgentSwarm supports up to 128 subagents, and launches are queued automatically, so it is safe to split large tasks into many clear, independent items.\\n\\nIf \`AgentSwarm\` is called, that call must be the only tool call in the response.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "description": { "type": "string", "minLength": 1, "description": "Short description for the whole swarm." }, "subagent_type": { "description": "Subagent type used for every new subagent spawned from items; defaults to coder when omitted. Resumed subagents always keep their original type, so passing subagent_type together with resume_agent_ids is allowed — it only affects the item-based spawns.", "type": "string", "minLength": 1 }, "prompt_template": { "description": "Prompt template for each subagent. The {{item}} placeholder is replaced with each item value.", "type": "string", "minLength": 1 }, "items": { "description": "Values used to fill {{item}}. Each item launches one new subagent.", "maxItems": 128, "type": "array", "items": { "type": "string", "minLength": 1 } }, "resume_agent_ids": { "description": "Map of existing subagent agent_id to the prompt used to resume that subagent. These resumed subagents are launched before new item-based subagents.", "type": "object", "propertyNames": { "type": "string", "minLength": 1 }, "additionalProperties": { "type": "string", "minLength": 1 } } }, "required": [ "description" ], "additionalProperties": false } }, { "name": "AskUserQuestion", "description": "Use this tool when you need to ask the user questions with structured options during execution. This allows you to:\\n1. Collect user preferences or requirements before proceeding\\n2. Resolve ambiguous or underspecified instructions\\n3. Let the user decide between implementation approaches as you work\\n4. Present concrete options when multiple valid directions exist\\n\\n**When NOT to use:**\\n- When you can infer the answer from context — be decisive and proceed\\n- Trivial decisions that don't materially affect the outcome\\n\\nOverusing this tool interrupts the user's flow. Only use it when the user's input genuinely changes your next action.\\n\\n**Usage notes:**\\n- Users always have an \\"Other\\" option for custom input — don't create one yourself\\n- Use multi_select to allow multiple answers to be selected for a question\\n- Keep option labels concise (1-5 words), use descriptions for trade-offs and details\\n- Each question should have 2-4 meaningful, distinct options\\n- Question texts must be unique across the call, and option labels must be unique within each question\\n- You can ask 1-4 questions at a time; group related questions to minimize interruptions\\n- If you recommend a specific option, list it first and append \\"(Recommended)\\" to its label\\n- The result is JSON with an \`answers\` object keyed by question text; each value is the chosen option's label (comma-separated labels for multi_select, or the user's own words if they picked \\"Other\\"); if \`answers\` is empty and a \`note\` says the user dismissed it, they chose not to answer — do not treat this as selecting the recommended option; decide based on context and do not re-ask the same question\\n- Set background=true when you can keep working without the answer. This starts a background question task and returns a task_id immediately. The answer arrives automatically in a later turn — you do not need to poll, sleep, or check on it. Continue with other work; never fabricate or predict the answer.", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "questions": { "minItems": 1, "maxItems": 4, "type": "array", "items": { "type": "object", "properties": { "question": { "type": "string", "minLength": 1, "description": "A specific, actionable question. End with '?'." }, "header": { "default": "", "description": "Short category tag (max 12 chars, e.g. 'Auth', 'Style').", "type": "string" }, "options": { "minItems": 2, "maxItems": 4, "type": "array", "items": { "type": "object", "properties": { "label": { "type": "string", "minLength": 1, "description": "Concise display text (1-5 words). If recommended, append '(Recommended)'." }, "description": { "default": "", "description": "Brief explanation of trade-offs or implications.", "type": "string" } }, "required": [ "label" ], "additionalProperties": false }, "description": "2-4 meaningful, distinct options. Do NOT include an 'Other' option — the system adds one automatically." }, "multi_select": { "default": false, "description": "Whether the user can select multiple options.", "type": "boolean" } }, "required": [ "question", "options" ], "additionalProperties": false }, "description": "The questions to ask the user (1-4 questions)." }, "background": { "default": false, "description": "Set true to ask in the background and return immediately with a background task_id; you are notified automatically when the user answers — do not poll with TaskOutput while the question is pending.", "type": "boolean" } }, "required": [ "questions" ], "additionalProperties": false } }, { "name": "Bash", "description": "Execute a \`bash\` command. Use this for shell semantics — pipes, env, processes, git, package managers, build/test runners, anything genuinely interactive or multi-step.\\n\\n**Translate these to a dedicated tool instead:**\\n- \`cat\` / \`head\` / \`tail\` (known path) → \`Read\`\\n- \`sed\` / \`awk\` (in-place edit) → \`Edit\`\\n- \`echo > file\` / \`cat <<EOF\` → \`Write\`\\n- \`find\` / recursive \`ls\` to locate files by name pattern → \`Glob\` (plain \`ls <known-directory>\` is fine for listing a directory)\\n- \`grep\` / \`rg\` (search file contents) → \`Grep\`\\n- \`echo\` / \`printf\` (talk to the user) → just output text directly\\n\\nThe dedicated tools render in the per-tool permission UI and keep raw stdout out of the conversation; that is why they are worth reaching for whenever one fits.\\n\\n**Output:**\\nThe stdout and stderr will be combined and returned as a string. The output may be truncated if it is too long. If the command exits non-zero, the output ends with a \`Command failed with exit code: N\` line; a command killed by its timeout or interrupted by the user ends with its own message instead.\\n\\nIf \`run_in_background=true\`, the command will be started as a background task and this tool will return a task ID instead of waiting for command completion. When doing that, you must provide a short \`description\`. Background commands default to a 600s timeout and \`timeout\` is capped at 86400s; set \`disable_timeout=true\` only when the task should run without a timeout. You will be automatically notified when the task completes. After starting one, default to returning control to the user instead of immediately waiting on it. Use \`TaskOutput\` only for a non-blocking status/output snapshot — do not wait on a task you just launched, since its completion arrives automatically. Use \`TaskStop\` only if the task must be cancelled. If a human user wants to inspect background tasks themselves, point them to the background-task panel.\\n\\n**Guidelines for safety and security:**\\n- Each shell tool call will be executed in a fresh shell environment. The shell variables, current working directory changes, and the shell history is not preserved between calls. To run a command in a particular directory, pass the \`cwd\` argument (or use absolute paths) rather than relying on a \`cd\` from an earlier call.\\n- The tool call will return after the command is finished. You shall not use this tool to execute an interactive command or a command that may run forever. For possibly long-running foreground commands, set the \`timeout\` argument in seconds. Foreground commands default to 60s and allow up to 300s. When a foreground command hits its timeout it is moved to the background instead of being killed, and you will be automatically notified when it completes. The user can also move a running foreground command to the background at any time.\\n- Avoid using \`..\` to access files or directories outside of the working directory.\\n- Avoid modifying files outside of the working directory unless explicitly instructed to do so.\\n- Never run commands that require superuser privileges unless explicitly instructed to do so.\\n- Run git-mutating commands such as \`git commit\`, \`git push\`, \`git reset\`, and \`git rebase\` only when the user asks for them.\\n\\n**Guidelines for efficiency:**\\n- Use \`&&\` to chain commands that genuinely depend on each other, e.g. \`npm install && npm test\`. Independent read-only commands (separate \`git show\`, \`ls\`, or status checks) should be issued as separate parallel Bash calls in one response, not chained into a single call — chaining serializes their execution and mixes their output. Do not stitch outputs together with \`echo\` separators.\\n- Use \`;\` to run commands sequentially regardless of success/failure\\n- Use \`||\` for conditional execution (run second command only if first fails)\\n- Use pipe operations (\`|\`) and redirections (\`>\`, \`>>\`) to chain input and output between commands\\n- Always quote file paths containing spaces with double quotes (e.g., cd \\"/path with spaces/\\")\\n- Compose multi-step logic in a single call with \`if\` / \`case\` / \`for\` / \`while\` control flows.\\n- Prefer \`run_in_background=true\` for long-running builds, tests, watchers, or servers when you need the conversation to continue before the command finishes.\\n\\n**Commands available:**\\nThe following common command categories are usually available. Availability still depends on the host, so when in doubt run \`which <command>\` first to confirm a command exists before relying on it.\\n- Navigation and inspection: \`ls\`, \`pwd\`, \`cd\`, \`stat\`, \`file\`, \`du\`, \`df\`, \`tree\`\\n- File and directory management: \`cp\`, \`mv\`, \`rm\`, \`mkdir\`, \`touch\`, \`ln\`, \`chmod\`, \`chown\`\\n- Text and data processing: \`wc\`, \`sort\`, \`uniq\`, \`cut\`, \`tr\`, \`diff\`, \`xargs\`\\n- Archives and compression: \`tar\`, \`gzip\`, \`gunzip\`, \`zip\`, \`unzip\`\\n- Networking and transfer: \`curl\`, \`wget\`, \`ping\`, \`ssh\`, \`scp\`\\n- Version control: \`git\`; for GitHub-hosted work (PRs, issues, CI runs, API queries) prefer the \`gh\` CLI when installed — it carries the user's GitHub auth and can return structured JSON\\n- Process and system: \`ps\`, \`kill\`, \`top\`, \`env\`, \`date\`, \`uname\`, \`whoami\`\\n- Language and package toolchains: \`node\`, \`npm\`, \`pnpm\`, \`yarn\`, \`python\`, \`pip\` (use whichever the project actually relies on)\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "command": { "type": "string", "minLength": 1, "description": "The command to execute." }, "cwd": { "description": "The working directory in which to run the command. When omitted, the command runs in the session's working directory.", "type": "string" }, "timeout": { "default": 60, "description": "Optional timeout in seconds for the command to execute. Foreground default 60s, max 300s. Background default 600s, max 86400s. Ignored for background commands when disable_timeout=true.", "type": "integer", "exclusiveMinimum": 0, "maximum": 9007199254740991 }, "description": { "description": "A short description for the background task. Required when run_in_background is true.", "type": "string" }, "run_in_background": { "description": "Whether to run the command as a background task.", "type": "boolean" }, "disable_timeout": { "description": "If true, do not apply a timeout to the command. Only applies when run_in_background is true.", "type": "boolean" } }, "required": [ "command" ], "additionalProperties": false } }, { "name": "CreateGoal", "description": "Create a durable, structured goal that the runtime will pursue across multiple turns.\\n\\nCall \`CreateGoal\` only when:\\n\\n- the user explicitly asks you to start a goal or work autonomously toward an outcome, or\\n- a host goal-intake prompt asks you to create one.\\n\\nDo NOT create a goal for greetings, ordinary questions, or vague requests that lack a\\nverifiable completion condition. A goal needs a checkable end state.\\n\\nWhen the request is vague, ask the user for the missing completion criterion before creating\\nthe goal. If the user clearly insists after you warn them that the wording is vague or risky,\\nrespect that and create the goal.\\n\\nInclude a \`completionCriterion\` when the user provides one, or when it can be stated without\\ninventing new requirements. Keep \`objective\` concise; reference long task descriptions by file\\npath rather than pasting them.\\n\\nCreating a goal fails if one already exists, so use \`replace: true\` only when the user explicitly\\nwants to abandon the current goal and start a new one.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "objective": { "type": "string", "minLength": 1, "description": "The objective to pursue. Must have a verifiable end state." }, "completionCriterion": { "description": "How to verify the goal is complete. Include when the user provides one.", "type": "string" }, "replace": { "description": "Replace an existing active, paused, or blocked goal instead of failing.", "type": "boolean" } }, "required": [ "objective" ], "additionalProperties": false } }, { "name": "CronCreate", "description": "Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders.\\n\\nUses standard 5-field cron in the user's local timezone: minute hour day-of-month month day-of-week. \`0 9 * * *\` means 9am local — no timezone conversion needed.\\n\\n## One-shot tasks (recurring: false)\\n\\nFor \\"remind me at X\\" or \\"at <time>, do Y\\" requests — fire once then auto-delete.\\nPin minute/hour/day-of-month/month to specific values:\\n \\"remind me at 2:30pm today to check the deploy\\" → cron: \\"30 14 <today_dom> <today_month> *\\", recurring: false\\n \\"tomorrow morning, run the smoke test\\" → cron: \\"57 8 <tomorrow_dom> <tomorrow_month> *\\", recurring: false\\n\\nOne-shots are best for near-term reminders. A task only fires while its session is still alive (see Session lifetime below), so favor near times — within hours or a few days — rather than scheduling weeks or months ahead.\\n\\n## Recurring jobs (recurring: true, the default)\\n\\nFor \\"every N minutes\\" / \\"every hour\\" / \\"weekdays at 9am\\" requests:\\n \\"*/5 * * * *\\" (every 5 min), \\"0 * * * *\\" (hourly), \\"0 9 * * 1-5\\" (weekdays at 9am local)\\n\\n## Avoid the :00 and :30 minute marks when the task allows it\\n\\nEvery user who asks for \\"9am\\" gets \`0 9\`, and every user who asks for \\"hourly\\" gets \`0 *\` — which means requests from across the planet land on the API at the same instant. When the user's request is approximate, pick a minute that is NOT 0 or 30:\\n \\"every morning around 9\\" → \\"57 8 * * *\\" or \\"3 9 * * *\\" (not \\"0 9 * * *\\")\\n \\"hourly\\" → \\"7 * * * *\\" (not \\"0 * * * *\\")\\n \\"in an hour or so, remind me to...\\" → pick whatever minute you land on, don't round\\n\\nOnly use minute 0 or 30 when the user names that exact time and clearly means it (\\"at 9:00 sharp\\", \\"at half past\\", coordinating with a meeting). When in doubt, nudge a few minutes early or late — the user will not notice, and the fleet will.\\n\\n## Coalesce semantics\\n\\nFires are delivered only while the session is idle: a fire that comes due during an active turn is held and delivered at the next idle moment, never injected mid-turn.\\n\\nIf the scheduler slept past multiple ideal fire times (laptop closed, long-running turn, etc.), only **one** fire is delivered when it wakes up. The origin carries \`coalescedCount\` showing how many ideal fires were collapsed into this single delivery. You should treat \`coalescedCount > 1\` as \\"I missed some checks; only the latest state matters\\" rather than running the prompt that many times.\\n\\n## Cron-fire envelope\\n\\nWhen a cron task fires, the prompt you scheduled is re-injected wrapped in an XML envelope that exposes the fire context:\\n\\n\`\`\`\\n<cron-fire jobId=\\"...\\" cron=\\"...\\" recurring=\\"true|false\\" coalescedCount=\\"N\\" stale=\\"true|false\\">\\n<prompt>\\nyour original prompt text, verbatim\\n</prompt>\\n</cron-fire>\\n\`\`\`\\n\\nThe envelope is parseable. Use \`coalescedCount > 1\` to know multiple ideal fires were collapsed into a single delivery (treat as \\"only the latest state matters\\"), and \`stale=\\"true\\"\` as a cue that the task is past its 7-day threshold.\\n\\n## 7-day stale behavior\\n\\nRecurring tasks that have been alive for more than 7 days fire one\\nfinal time with \`stale: true\` on the envelope, and the system then\\nauto-deletes the task. The flag is the model's notice that this is\\nthe last delivery. If the schedule is still wanted, call \`CronCreate\`\\nagain with the same \`cron\` and \`prompt\` — that resets \`createdAt\` and\\nstarts a fresh 7-day window. One-shot tasks are never marked stale.\\n\\n## Jitter behavior\\n\\nAnti-herd jitter is applied deterministically per task id:\\n - Recurring: ideal fire time is shifted **forward** by an offset ≤ min(10% of the cron period, 15 minutes). A \`*/5 * * * *\` task can drift up to 30s; a \`0 9 * * *\` task can drift up to 15 minutes.\\n - One-shot: only when the ideal fire lands on \`:00\` or \`:30\` of the hour, the fire is pulled **earlier** by ≤ 90 seconds. Other minutes pass through unchanged.\\n\\n## One-shot vs recurring — when to pick which\\n\\nUse \`recurring: false\` for \\"remind me at X\\" style requests, single deadlines, \\"in N minutes do Y\\", and any task that should not repeat. Use \`recurring: true\` for periodic polling (CI status, build watchers, scheduled reports), workday rituals, and anything the user explicitly described as recurring.\\n\\n## Session lifetime\\n\\nCron tasks live in the current session. When you exit, they\\nare persisted under the session homedir; resuming the same session\\nreloads them and the scheduler resumes from each task's \`createdAt\`. Fire times that fell during the offline window are\\ncollapsed into a single delivery via \`coalescedCount\` (and recurring\\ntasks past their 7-day window arrive with \`stale: true\` as their final\\ndelivery).\\n\\nTasks do **not** carry over into a brand-new session — they are scoped\\nto the resumed session id, not to the working directory.\\n\\n## Limits\\n\\nA session holds at most 50 live cron tasks; creating one beyond that is rejected. (The \`prompt\` body is also capped — see its parameter description.) Expressions that never fire within the next 5 years (e.g. \`0 0 31 2 *\`, an impossible date) are rejected at create time.\\n\\n## Returned fields\\n\\n\`id\` (ULID), \`cron\` (the normalized expression), \`humanSchedule\` (English summary), \`recurring\`,\\n\`nextFireAt\` (local ISO timestamp with numeric offset, or null). \`id\` is needed by \`CronDelete\`.\\n\\n## Tell the user how to cancel or modify\\n\\nAfter successfully creating a task, proactively tell the user how they can cancel or modify it later. Users have no direct \`/cron\` command or self-service UI to manage reminders themselves; they must ask the model to make changes (e.g. \\"cancel my 9am reminder\\" or \\"change my daily check to 10am\\"). Include the task \`id\` in your message so the user can reference it.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "cron": { "type": "string", "description": "5-field cron expression in local time: \\"M H DoM Mon DoW\\" (e.g. \\"*/5 * * * *\\" = every 5 minutes; \\"30 14 28 2 *\\" = Feb 28 at 2:30pm local — a pinned date like this repeats yearly unless you also pass recurring: false)." }, "prompt": { "type": "string", "minLength": 1, "maxLength": 8192, "description": "The prompt to enqueue at each fire time. Limited to 8 KiB (UTF-8)." }, "recurring": { "default": true, "description": "true (default) = fire on every cron match until deleted or auto-expired after 7 days. false = fire once at the next match, then auto-delete. Use false for \\"remind me at X\\" one-shot requests with pinned minute/hour/dom/month.", "type": "boolean" } }, "required": [ "cron", "prompt" ], "additionalProperties": false } }, { "name": "CronDelete", "description": "Cancel a scheduled cron job by id.\\n\\nUse this tool to remove a cron task previously scheduled with\\n\`CronCreate\`. The \`id\` is the ULID value returned by \`CronCreate\`, or\\nshown in the \`id:\` column of \`CronList\` — quote it verbatim, no\\nprefix.\\n\\nBehaviour by task kind:\\n\\n- **Recurring task** (\`recurring: true\`): stops all future fires\\n immediately. The scheduler picks up the deletion on its next tick.\\n- **One-shot task** (\`recurring: false\`): cancels the pending fire if\\n it has not happened yet. One-shots that have already fired\\n auto-delete themselves, so calling \`CronDelete\` on a fired one-shot\\n returns \\"no cron job with id ...\\".\\n\\nNot-found is reported as an error (not a silent no-op) so you can\\ncorrect yourself — typically by calling \`CronList\` to see which ids\\nare actually live, rather than re-trying with the same stale id.\\n\\nRefresh pattern (use when you want a stale recurring schedule to\\ncontinue):\\n\\nStale recurring tasks are auto-deleted by the system after their final\\nfire — there is nothing for \`CronDelete\` to remove at that point. To\\nkeep the schedule running, just call \`CronCreate\` with the same \`cron\`\\nand \`prompt\`. Use \`CronList\`'s \`prompt\` field to recall the original\\ntext after a context compaction.\\n\\n\`CronDelete\` remains the right call when you want to cancel a task\\nthat is still live (recurring not yet stale, or a one-shot still\\npending).\\n\\nGuidelines:\\n\\n- Users have no direct \`/cron\` command or self-service UI to delete\\n tasks themselves; they must ask the model to cancel a reminder.\\n When deleting on behalf of a user, confirm the action and report\\n the result plainly.\\n- Cron deletion is irreversible — there is no undo. If you delete the\\n wrong task, you must re-create it with \`CronCreate\`.\\n- If the model is unsure which id is current (e.g. after a context\\n compaction), call \`CronList\` first rather than guessing.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "id": { "type": "string", "description": "The cron job id (ULID) returned by CronCreate / CronList." } }, "required": [ "id" ], "additionalProperties": false } }, { "name": "CronList", "description": "List all cron jobs currently scheduled in this session.\\n\\nUse this tool to see every pending cron task — both recurring jobs and\\none-shot reminders — that you (or the user) have scheduled with\\n\`CronCreate\`. The output is the entry point for inspecting scheduled\\nwork: it returns a stable id, the original cron expression, a human\\nrendering, the next post-jitter fire time, the recurring flag, the\\ntask's age in days, and a stale indicator.\\n\\nEach record carries:\\n\\n- \`id\` — the task id (a ULID). Pass this to \`CronDelete\` to remove the\\n task, or quote it in user-facing messages when asking for\\n confirmation.\\n- \`cron\` — the verbatim 5-field cron expression as scheduled.\\n- \`humanSchedule\` — plain-English rendering (e.g. \`every 5 minutes\`).\\n- \`prompt\` — the scheduled prompt text, JSON-encoded so embedded\\n newlines stay on one line. Truncated to 200 UTF-8 bytes with\\n \`…(truncated)\` if longer. Use this to recall what a task is for\\n after a context compaction, and as the source for the\\n \`CronCreate\` refresh ritual.\\n- \`nextFireAt\` — local ISO timestamp with an explicit numeric offset\\n for the next fire **after jitter has been applied**. The actual fire\\n may land slightly before or after a round \`:00\` / \`:30\` minute mark\\n due to herd-avoidance jitter; this is the value the scheduler will\\n compare against, so it reflects what will really happen. \`null\` if\\n the expression has no fire in the next 5 years (should not happen\\n for tasks created through \`CronCreate\`, which validates).\\n- \`recurring\` — \`true\` for cadenced jobs, \`false\` for one-shots.\\n- \`ageDays\` — \`(now - createdAt) / day\`, two decimal places. Useful\\n when deciding whether a long-running cron is still relevant.\\n- \`stale\` — \`true\` when a recurring task is older than 7 days. The\\n system **auto-deletes the task after this fire** to bound session\\n lifetime; the \`stale: true\` flag is the model's notice that this is\\n the final delivery. To resume the same schedule, call \`CronCreate\`\\n again with the original \`cron\` and \`prompt\` (the \`prompt\` row above\\n carries it for exactly this purpose). One-shots are never marked\\n stale — they fire at most once by construction.\\n\\nGuidelines:\\n\\n- This tool is read-only and never mutates state, so it is always\\n safe to call (including in plan mode).\\n- Users cannot directly manage cron tasks themselves; if they want to\\n cancel or modify a schedule, route the request through the model\\n (i.e. call \`CronDelete\` or \`CronCreate\` on their behalf).\\n- The empty case returns \`cron_jobs: 0\\\\nNo cron jobs scheduled.\`. Cron\\n tasks survive a resume of the same session but do not bleed into new\\n sessions.\\n- After a context compaction, or whenever you are unsure which cron\\n jobs are live, call this tool to re-enumerate them rather than\\n guessing ids from earlier in the conversation.\\n- Records are separated by a line containing just \`---\`, in the\\n insertion order they were scheduled.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": {}, "additionalProperties": false } }, { "name": "Edit", "description": "Perform exact replacements in existing files.\\n\\n- Edit is mandatory for every incremental change, especially small edits. DO NOT use Write or Bash \`sed\`.\\n- Read the target file before every Edit. DO NOT call Edit from memory, stale context, or a guessed \`old_string\`.\\n- Take \`old_string\` and \`new_string\` from the Read output view.\\n- Drop the line-number prefix and tab; match only file content.\\n- \`old_string\` must be unique unless \`replace_all\` is set.\\n- If \`old_string\` is ambiguous, add surrounding context. Use \`replace_all\` only when every occurrence should change — for example, renaming a symbol throughout the file.\\n- Multiple Edit calls may run in one response only when they do not target the same file.\\n- DO NOT issue consecutive Edit calls on the same file. A previous Edit can invalidate a later Edit's \`old_string\`, causing \`old_string not found\`. Read the file again before the next Edit.\\n- A write lock serializes same-file edits in response order, but serialization does not make stale \`old_string\` valid.\\n- For pure CRLF files, Read shows LF; use LF in \`old_string\` and \`new_string\`, and Edit writes CRLF back.\\n- For mixed endings or lone carriage returns, Read shows carriage returns as \\\\r; include actual \\\\r escapes in those positions.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "path": { "type": "string", "description": "Path to the text file to edit. Relative paths resolve against the working directory; a path outside the working directory must be absolute." }, "old_string": { "type": "string", "minLength": 1, "description": "Exact content to replace from the Read output view, without the line-number prefix. Use LF for pure CRLF files; use actual \\\\r escapes where Read shows \\\\r." }, "new_string": { "type": "string", "description": "Replacement text in the same Read output view. LF is written back as CRLF only for pure CRLF files." }, "replace_all": { "description": "Set true only when every occurrence of old_string should be replaced.", "type": "boolean" } }, "required": [ "path", "old_string", "new_string" ], "additionalProperties": false } }, { "name": "EnterPlanMode", "description": "Use this tool proactively when you're about to start a non-trivial implementation task.\\nGetting user sign-off on your approach via ExitPlanMode before writing code prevents wasted effort.\\n\\nUse it when ANY of these conditions apply:\\n\\n1. New Feature Implementation - e.g. \\"Add a caching layer to the API\\"\\n2. Multiple Valid Approaches - e.g. \\"Optimize database queries\\" (indexing vs rewrite vs caching)\\n3. Code Modifications - e.g. \\"Refactor auth module to support OAuth\\"\\n4. Architectural Decisions - e.g. \\"Add WebSocket support\\"\\n5. Multi-File Changes - involves more than 2-3 files\\n6. Unclear Requirements - need exploration to understand scope\\n7. User Preferences Matter - if user input would materially change the implementation approach, use EnterPlanMode to structure the decision\\n\\nPermission mode notes:\\n- EnterPlanMode enters plan mode automatically without an approval prompt in all permission modes.\\n- In yolo and manual modes, ExitPlanMode still presents the plan to the user for approval.\\n- In auto permission mode, do not use AskUserQuestion; make the best decision from available context.\\n- In auto permission mode, ExitPlanMode exits plan mode without asking the user.\\n- Use EnterPlanMode only when planning itself adds value.\\n\\nWhen NOT to use:\\n- Single-line or few-line fixes (typos, obvious bugs, small tweaks)\\n- User gave very specific, detailed instructions\\n- Pure research/exploration tasks\\n\\nOnce you are in plan mode, a reminder walks you through the workflow (explore → design → write the plan file → \`ExitPlanMode\`) and enforces read-only access. For non-trivial tasks where you are unsure of the codebase structure or relevant code paths, use \`Agent(subagent_type=\\"explore\\")\` to investigate first when the \`Agent\` tool is available.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": {}, "additionalProperties": false } }, { "name": "ExitPlanMode", "description": "Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.\\n\\n## How This Tool Works\\n- You should have already written your plan to the plan file specified in the plan mode reminder.\\n- This tool does NOT take the plan content as a parameter - it reads the plan from the file you wrote.\\n- The user will see the contents of your plan file when they review it. In auto permission mode, the tool reads the file and exits plan mode without asking the user.\\n\\n## When to Use\\nOnly use this tool for tasks that require planning implementation steps. For research tasks (searching files, reading code, understanding the codebase), do NOT use this tool.\\n\\n## What a good plan contains\\nList specific, verifiable steps grounded in the actual codebase — real files, functions, and commands, in a sensible order. Each step should be concrete enough to act on and to check. Avoid vague filler like \\"improve performance\\" or \\"add tests\\"; say what to change and where.\\n\\n## Multiple Approaches\\nIf your plan offers multiple alternative approaches, pass them via the \`options\` parameter so the user can choose which one to execute — see the \`options\` parameter for the format, count, and reserved labels. In yolo and manual modes the user sees all options alongside the host's Reject and Revise controls.\\n\\n## Before Using\\n- In auto permission mode, do NOT use AskUserQuestion; make the best decision from available context.\\n- In auto permission mode, this tool exits plan mode without asking the user.\\n- In yolo and manual modes, this tool still presents the plan to the user for approval.\\n- If auto permission mode is not active and you have unresolved questions, use AskUserQuestion first.\\n- If auto permission mode is not active and you have multiple approaches and haven't narrowed down yet, consider using AskUserQuestion first to let the user choose, then write a plan for the chosen approach only.\\n- Once your plan is finalized, use THIS tool to request approval.\\n- Do NOT use AskUserQuestion to ask \\"Is this plan OK?\\" or \\"Should I proceed?\\" - that is exactly what ExitPlanMode does.\\n- If rejected, revise based on feedback and call ExitPlanMode again.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "options": { "description": "When the plan contains multiple alternative approaches, list them here so the user can choose which one to execute. Provide up to 3 options; 2-3 distinct approaches work best when the plan offers a real choice. Passing a single option is allowed and is equivalent to a plain plan approval. Each option represents a distinct approach from the plan. Do not use \\"Reject\\", \\"Revise\\", \\"Approve\\", or \\"Reject and Exit\\" as labels.", "minItems": 1, "maxItems": 3, "type": "array", "items": { "type": "object", "properties": { "label": { "type": "string", "minLength": 1, "maxLength": 80, "description": "Short name for this option (1-8 words). Append \\"(Recommended)\\" if you recommend this option." }, "description": { "default": "", "description": "Brief summary of this approach and its trade-offs.", "type": "string" } }, "required": [ "label" ], "additionalProperties": false } } }, "additionalProperties": false } }, { "name": "FetchURL", "description": "Fetch content from a URL. The content is returned either as the main text extracted from the page, or as the full response body verbatim; a note at the top of the result states which of the two you received, so you can judge how complete it is. Use this when you need to read a specific web page.\\n\\nOnly fully-formed public \`http\`/\`https\` URLs are supported; other schemes and private or loopback addresses are not fetched. Very large pages may be truncated or refused. The fetch carries no login or session for the target site, so pages behind authentication (private repositories, internal dashboards) return a login page or an error instead of the real content — if the text you get back looks like a generic landing or sign-in page, treat that as the login wall, not the answer, and reach the content through a credentialed route (an authenticated CLI or MCP tool) instead.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "url": { "type": "string", "description": "The URL to fetch content from." } }, "required": [ "url" ], "additionalProperties": false } }, { "name": "GetGoal", "description": "Read the current goal: its objective, completion criterion, status, and budgets (turns, tokens,\\ntime, and how much of each remains). When the goal has stopped, it also reports the terminal reason.\\n\\nUse \`GetGoal\` before deciding whether to continue working, report completion, report a blocker,\\nor respect a pause. It returns \`{ \\"goal\\": null }\` when there is no current goal.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": {}, "additionalProperties": false } }, { "name": "Glob", "description": "Find files by glob pattern, sorted by modification time (most recent first).\\n\\nPowered by ripgrep. Respects \`.gitignore\`, \`.ignore\`, and \`.rgignore\` by default — set \`include_ignored\` to also match ignored files (e.g. build outputs, \`node_modules\`). Sensitive files (such as \`.env\`) are always filtered out. Matches are files only — directories themselves are never listed; to find a directory, glob for a file inside it (e.g. \`**/fixtures/**\`).\\n\\nGood patterns:\\n- \`*.ts\` — all files matching an extension, at any depth below the search root (a bare pattern without \`/\` matches recursively)\\n- \`src/*.ts\` — files directly inside \`src/\` (one level, not recursive)\\n- \`src/**/*.ts\` — recursive walk with a subdirectory anchor and extension\\n- \`**/*.py\` — recursive walk from the search root for an extension\\n- \`*.{ts,tsx}\` — brace expansion is supported\\n- \`{src,test}/**/*.ts\` — cartesian brace expansion is supported too\\n\\nResults default to 100 matching paths. Use \`offset\` (default 0) and \`head_limit\` (default 100) to page through results. When more matches are available, the result gives the next offset; keep the other search arguments unchanged. Set \`head_limit=0\` to remove the match-count limit. Pages still stay within the character retention limit, including notices: when it is reached, only complete paths are returned, with the next offset for continuation. Large pages are saved to a file with a path for Read.\\n\\nEach call searches the current filesystem again; pagination is not a snapshot, and file changes can shift results between pages. To collect a large list, use \`head_limit=0\`, read any saved output, and follow continuation offsets if the character limit is reached. Search timeouts, traversal errors, and output capture limits can still produce partial results; the result reports these limits, and pagination cannot recover paths that were never collected. Narrow the search and retry when it is incomplete.\\n\\nLarge-directory caveat — avoid recursing into dependency / build output even with an anchor, especially when \`include_ignored\` is set:\\n- \`node_modules/**/*.js\`, \`.venv/**/*.py\`, \`__pycache__/**\`, \`target/**\` can produce thousands of results and waste search time and context. Prefer specific subpaths like \`node_modules/react/src/**/*.js\` unless you need a complete listing.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "pattern": { "type": "string", "description": "Glob pattern to match files." }, "head_limit": { "description": "Maximum number of matching paths to return after offset. Defaults to 100. Pass 0 to remove the match-count limit. The character limit still applies: large pages are saved for Read, and a continuation offset is provided when more paths remain. Search time and output capture limits still apply.", "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "offset": { "description": "Number of matching paths to skip. Defaults to 0. Each call searches the current filesystem again; changes can shift results between pages.", "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "path": { "description": "Directory to search. Accepts an absolute path, or a path relative to the current working directory. Defaults to the current working directory.", "type": "string" }, "include_ignored": { "description": "Also match files excluded by ignore files such as \`.gitignore\`, \`.ignore\`, and \`.rgignore\` (for example \`node_modules\` or build outputs). Sensitive files (such as \`.env\`) remain filtered out for safety. VCS metadata directories (\`.git\` and similar) are always skipped, even when this is true. Defaults to false.", "type": "boolean" }, "include_dirs": { "description": "Deprecated and ignored. Results are always files-only — directories are never listed. Accepted only so older calls that still pass this flag are not rejected by parameter validation.", "type": "boolean" } }, "required": [ "pattern" ], "additionalProperties": false } }, { "name": "Grep", "description": "Search file contents using regular expressions (powered by ripgrep).\\n\\nUse Grep when the task is to find unknown content or unknown file locations. Do not use shell \`grep\` or \`rg\` directly; this tool applies workspace path policy, output limits, and sensitive-file filtering.\\nALWAYS use Grep tool instead of running \`grep\` or \`rg\` from a shell — direct shell calls bypass workspace policy, output limits, and sensitive-file filtering.\\nIf you already know a concrete file path and need to inspect its contents, use Read directly instead.\\n\\nWrite patterns in ripgrep regex syntax, which differs from POSIX \`grep\` syntax. For example, braces are special, so escape them as \`\\\\{\` to match a literal \`{\`.\\n\\nHidden files (dotfiles such as \`.gitlab-ci.yml\` or \`.eslintrc.json\`) are searched by default. To also search files excluded by \`.gitignore\` (such as \`node_modules\` or build outputs), set \`include_ignored\` to \`true\`. Sensitive files (such as \`.env\`) are always skipped for safety, even when \`include_ignored\` is \`true\`.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "pattern": { "type": "string", "description": "Regular expression to search for." }, "path": { "description": "File or directory to search. Accepts an absolute path, or a path relative to the current working directory. Omit to search the current working directory. Use Read instead when you already know a concrete file path and need its contents.", "type": "string" }, "glob": { "description": "Optional glob filter for which files to search, e.g. \`*.ts\`. Matched against each file's full absolute path, so a path-anchored pattern like \`src/**/*.ts\` silently matches nothing — use a basename pattern (\`*.ts\`), or anchor with \`**/\` (\`**/src/**/*.ts\`). To scope the search to a directory, use \`path\` instead.", "type": "string" }, "type": { "description": "Optional ripgrep file type filter, such as ts or py. Prefer this over \`glob\` when filtering by language or file kind: it is more efficient and less error-prone than an equivalent glob pattern.", "type": "string" }, "output_mode": { "description": "Shape of the result. \`content\` shows matching lines (honors \`-A\`, \`-B\`, \`-C\`, \`-n\`, and \`head_limit\`); \`files_with_matches\` shows only the paths of files that contain a match, most-recently-modified first (honors \`head_limit\`); \`count_matches\` shows per-file match counts as \`path:count\` lines, preceded by an aggregate total line. Defaults to \`files_with_matches\`.", "type": "string", "enum": [ "content", "files_with_matches", "count_matches" ] }, "-i": { "description": "Perform a case-insensitive search. Defaults to false.", "type": "boolean" }, "-n": { "description": "Prefix each matching line with its line number. Applies only when \`output_mode\` is \`content\`. Defaults to true.", "type": "boolean" }, "-A": { "description": "Number of lines to show after each match. Applies only when \`output_mode\` is \`content\`.", "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "-B": { "description": "Number of lines to show before each match. Applies only when \`output_mode\` is \`content\`.", "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "-C": { "description": "Number of lines to show before and after each match. Applies only when \`output_mode\` is \`content\`; takes precedence over \`-A\` and \`-B\`.", "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "head_limit": { "description": "Limit output to the first N lines/entries after offset. Defaults to 250. Pass 0 for unlimited.", "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "offset": { "description": "Number of leading lines/entries to skip before applying \`head_limit\`. Use it together with \`head_limit\` to page through large result sets. Defaults to 0.", "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "multiline": { "description": "Enable multiline matching, where the pattern can span line boundaries and \`.\` also matches newlines. Defaults to false.", "type": "boolean" }, "include_ignored": { "description": "Also search files excluded by ignore files such as \`.gitignore\`, \`.ignore\`, and \`.rgignore\` (for example \`node_modules\` or build outputs). Sensitive files (such as \`.env\`) remain filtered out for safety. VCS metadata directories (\`.git\` and similar) are always skipped, even when this is true. Defaults to false.", "type": "boolean" } }, "required": [ "pattern" ], "additionalProperties": false } }, { "name": "Read", "description": "Read a text file from the local filesystem.\\n\\nThe path may be a \`kimi-file://\` attachment reference. Its bytes come from the current session's storage, independently of the workspace runtime. Next Read keeps the reference so pagination also works after a fork. For a binary attachment, the error includes a server-local path when available; a converter must be able to access that filesystem. ReadMediaFile accepts the same reference for images and videos.\\n\\nIf the user provides a concrete file path to a text file, call Read directly. Do not \`Glob\`, \`ls\`, or otherwise pre-check known text file paths; missing or invalid file paths return errors you can handle. Do not use Read for directories; use \`ls\` via Bash for a known directory, or Glob when you need files matching a name pattern (Glob lists files only, never directories). Use \`Grep\` only when the task is to search for unknown content or locations.\\n\\nWhen you need several files, prefer to read them in parallel: emit multiple \`Read\` calls in a single response instead of reading one file per turn.\\n\\n- Relative paths resolve against the working directory; a path outside the working directory must be absolute.\\n- Returns text within \`max_chars\`, including line numbers and the status block, preferring complete lines. The configured default is 100000 characters; calls can request up to 500000. Characters use JavaScript string length, not UTF-8 bytes or tokens. Read results are not spilled or shortened again by the general tool-output limit.\\n- Omit \`n_lines\` to read toward the end of the file. There is no fixed line-count cap. When the task requires the full text of a large file, request a larger \`max_chars\`, up to 500000, in the first call.\\n- Page larger files with \`line_offset\` (1-based start line) and \`n_lines\`. If the result is incomplete, copy the \`Next Read\` arguments in the status block to continue without gaps or overlaps. Do not answer from a partial page when the task requires the remaining content.\\n- If a single line cannot fit on its own page, Read returns a fragment and reports its column range. Continue on the same line with the supplied \`column_offset\`; do not insert a newline between fragments of one source line. A partial line still counts toward the remaining \`n_lines\` until its ending is returned.\\n- \`column_offset\` is a zero-based position in the first line's displayed text, excluding its line-number prefix. It is supported only for forward reads. Offsets past the line or inside a Unicode surrogate pair return an error. Continuation refers to the current file contents; start a new read if the file changed.\\n- Kimi Code agent event logs (\`wire.jsonl\` under the sessions directory) follow the same character budget; locate a record with Grep, read it with \`n_lines=1\`, and follow \`Next Read\` to retrieve every fragment of a long record.\\n- Sensitive files (\`.env\` files, credential stores, SSH private keys, and similar secrets) are refused to protect secrets; do not attempt to read them. Templates and public keys are exempt: \`.env.example\` / \`.env.sample\` / \`.env.template\` and public SSH keys such as \`id_rsa.pub\` read normally.\\n- UTF-8 text files are read directly. UTF-16 LE/BE text files (with or without a BOM) are detected automatically and checked with strict decoding first. If malformed sequences are found, Read returns readable text with U+FFFD replacements and a lossy-decoding warning on every page; do not treat this view as exact original text. The status block notes the detected encoding, and Edit/Write on such a file still expect UTF-8 — convert its encoding first (e.g. with \`iconv\`). Other encodings (e.g. GBK), binary files, and files containing NUL bytes are refused.\\n- Negative \`line_offset\` reads from the end of the file (for example, -100 reads the last 100 lines). If the requested tail range exceeds the character budget, the newest complete lines in that range are returned first; \`Next Read\` covers the omitted earlier range. If no complete line fits, Read reports this and supplies forward \`Next Read\` arguments for the entire unread range. Omit \`column_offset\` when using a negative \`line_offset\`.\\n- Output format: \`<line-number>\\\\t<content>\` per line.\\n- A \`<system>...</system>\` status block is appended after the file content. It reports the actual returned range, total lines, effective character budget, whether the requested range is complete, and whether EOF was reached. The block is not part of the file itself.\\n- Pure CRLF files are displayed with LF line endings; \`Edit\` matches this output and preserves CRLF when writing back.\\n- Mixed or lone carriage-return line endings are shown as \`\\\\r\` and require exact \`Edit.old_string\` escapes.\\n- After a successful \`Edit\`/\`Write\`, do not re-read solely to prove the write landed. When the task depends on an exact file, API, or output shape, inspect the final external contract before finishing.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "path": { "type": "string", "description": "Path to a text file or a kimi-file:// attachment reference in the current session. Relative filesystem paths resolve against the working directory; a path outside the working directory must be absolute. Directories are not supported; use \`ls\` via Bash for a known directory, or Glob for pattern search." }, "line_offset": { "description": "The line number to start reading from. Omit to start at line 1. Negative values read from the end of the file (for example, -100 reads the last 100 lines).", "anyOf": [ { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, { "type": "integer", "minimum": -9007199254740991, "exclusiveMaximum": 0 } ] }, "column_offset": { "description": "Zero-based character offset within the first line of a forward read, excluding its line-number prefix. Uses JavaScript string length in the displayed text. Copy continuation arguments from the previous result to resume a long line.", "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "n_lines": { "description": "The number of lines to read. Omit to read toward the end of the file. Results are bounded by max_chars, with continuation arguments when the requested range is incomplete.", "type": "integer", "exclusiveMinimum": 0, "maximum": 9007199254740991 }, "max_chars": { "description": "Maximum characters in the returned text, including line numbers and status. Omit for the configured default; requests above the configured maximum are capped.", "type": "integer", "exclusiveMinimum": 0, "maximum": 9007199254740991 } }, "required": [ "path" ], "additionalProperties": false } }, { "name": "SetGoalBudget", "description": "Set a hard budget limit for the current goal.\\n\\nUse this only when the user clearly gives a runtime limit, such as:\\n\\n- \\"stop after 20 turns\\"\\n- \\"use no more than 500k tokens\\"\\n- \\"finish within 30 minutes\\"\\n\\nDo not invent limits. Do not call this for vague wording such as \\"spend some time\\" or\\n\\"try to be quick\\".\\n\\nIf the user gives a compound time, convert it to one supported unit before calling this tool.\\nFor example, \\"2 hours and 3 minutes\\" can be set as \`value: 123, unit: \\"minutes\\"\`.\\n\\nA time budget must be at least 1 second and convert to a finite number of milliseconds.\\nThere is no upper duration limit. Turn and token budgets must be positive and are rounded\\nto the nearest whole number (minimum 1).\\n\\nSupported units:\\n\\n- \`turns\`\\n- \`tokens\`\\n- \`milliseconds\`\\n- \`seconds\`\\n- \`minutes\`\\n- \`hours\`\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "value": { "type": "number", "exclusiveMinimum": 0, "description": "The positive numeric budget value." }, "unit": { "type": "string", "enum": [ "turns", "tokens", "milliseconds", "seconds", "minutes", "hours" ] } }, "required": [ "value", "unit" ], "additionalProperties": false } }, { "name": "Skill", "description": "Invoke a registered skill from the current skill listing. BLOCKING REQUIREMENT: when a skill from the listing matches the user's request, you MUST call this tool (not free-form text). Do not re-invoke a skill to repeat work already done: if a \`<skill-loaded>\` block for it with the same \`args\` is already present in the conversation, follow those instructions directly instead of calling the tool again. Do call the tool again when you need the skill with different arguments — the loaded block was expanded with the earlier \`args\` and will not reflect new inputs.", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "skill": { "type": "string", "description": "The exact name of the skill to invoke, spelled as it appears in the current skill listing (e.g. \\"commit\\", \\"pdf\\")." }, "args": { "description": "Optional argument string for the skill, written like a command line (e.g. \`-m \\"fix bug\\"\`, \`123\`, a file path). It is split on whitespace (quotes group a token) and expanded into the skill's placeholders ($NAME, $1, $ARGUMENTS); if the skill body has no placeholders, the whole string is still appended as a trailing \`ARGUMENTS:\` line. Omit it only when there is nothing to pass.", "type": "string" } }, "required": [ "skill" ], "additionalProperties": false } }, { "name": "TaskList", "description": "List background tasks and their current status.\\n\\nUse this tool to discover which background tasks exist and where each one\\nstands. It is the entry point for inspecting background work: it returns a\\ntask ID, status, and description for every task it reports, plus the command,\\nPID, and (once finished) exit code for shell tasks, and a stop reason for any\\ntask that ended early.\\n\\nGuidelines:\\n\\n- After a context compaction, or whenever you are unsure which background\\n tasks are running or what their task IDs are, call this tool to\\n re-enumerate them instead of guessing a task ID.\\n- Prefer the default \`active_only=true\`, which lists only non-terminal tasks.\\n Pass \`active_only=false\` only when you specifically need to see tasks that\\n have already finished. With \`active_only=false\` the result may also include\\n \`lost\` tasks — tasks left over from a previous process that can no longer be\\n inspected or controlled; treat them as already terminated.\\n- \`limit\` caps how many tasks are returned. It accepts a value between 1 and\\n 100 and defaults to 20 when omitted.\\n- This tool only lists tasks; it does not return their output. Use it first\\n to locate the task ID you need, then call \`TaskOutput\` with that ID to read\\n the task's output and details.\\n- This tool is read-only and does not change any state, so it is always safe\\n to call, including in plan mode.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "active_only": { "default": true, "description": "Whether to list only non-terminal background tasks.", "type": "boolean" }, "limit": { "default": 20, "description": "Maximum number of tasks to return.", "type": "integer", "minimum": 1, "maximum": 100 } }, "additionalProperties": false } }, { "name": "TaskOutput", "description": "Retrieve a snapshot of a running or completed background task.\\n\\nUse this after \`Bash(run_in_background=true)\`, \`Agent(run_in_background=true)\`, or \`AskUserQuestion(background=true)\` to check progress, or to read the output of a task that has already completed.\\n\\nGuidelines:\\n- Prefer relying on automatic completion notifications. Use this tool only when you need task output before the automatic notification arrives.\\n- This tool is always non-blocking: it returns the current status/output snapshot immediately and never waits for the task to finish.\\n- Do not use TaskOutput to wait for a result you need before continuing — if your next step depends on the task's result, run that task in the foreground instead. TaskOutput is for a deliberate progress check you will act on without blocking, not a way to sit and wait for a background task you just launched.\\n- This tool returns structured task metadata, a fixed-size output preview, and an output_path for the full log.\\n- For a terminal task, the metadata also explains why it ended. A shell command that runs to completion reports \`status: completed\` on a zero exit, or \`status: failed\` with its non-zero \`exit_code\` — judge that failure from the \`exit_code\`, because a plain command failure carries no \`stop_reason\` and no \`terminal_reason\`. \`terminal_reason\` is a categorical label emitted only when the end is not an ordinary exit: \`timed_out\` when the deadline aborted it, \`stopped\` when it was explicitly stopped, or \`failed\` when it errored without producing an exit code; the \`stopped\` and \`failed\` cases also carry a human-readable \`stop_reason\`. A task that finished on its own with a clean exit carries neither \`stop_reason\` nor \`terminal_reason\`.\\n- The full, never-truncated log is always available at output_path; use the \`Read\` tool with that path to page through it, whether or not the preview was truncated.\\n- This tool works with the generic background task system and should remain the primary read path for future task types, not just bash.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "task_id": { "type": "string", "description": "The background task ID to inspect." } }, "required": [ "task_id" ], "additionalProperties": false } }, { "name": "TaskStop", "description": "Stop a running background task.\\n\\nOnly use this when a task must genuinely be cancelled — for a task that is\\nfinishing normally, wait for its completion notification or inspect it with\\n\`TaskOutput\` instead of stopping it.\\n\\nGuidelines:\\n- This is a general-purpose stop capability for any background task. It is not\\n a bash-specific kill.\\n- Stopping a task is destructive: it may leave partial side effects behind.\\n Use it with care.\\n- If the task has already finished, this tool simply returns its current\\n status.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "task_id": { "type": "string", "description": "The background task ID to stop." }, "reason": { "default": "Stopped by TaskStop", "description": "Short reason recorded when the task is stopped.", "type": "string" } }, "required": [ "task_id" ], "additionalProperties": false } }, { "name": "TodoList", "description": "Use this tool to maintain a structured TODO list as you work through a multi-step task. Use it proactively and often when progress tracking helps the current work. This is especially useful in long-running investigations and implementation tasks with several tool calls; in plan mode, write the plan to the plan file rather than tracking it here.\\n\\n**When to use:**\\n- Multi-step tasks that span several tool calls\\n- Tracking investigation progress across a large codebase search\\n- Planning a sequence of edits before making them\\n- After receiving new multi-step instructions, capture the requirements as todos\\n- Before starting a tracked task, mark exactly one item as \`in_progress\`\\n- Immediately after finishing a tracked task, mark it \`done\`; do not batch completions at the end\\n\\n**When NOT to use:**\\n- Single-shot answers that complete in one or two tool calls\\n- Trivial requests where tracking adds no clarity\\n- Purely conversational or informational replies\\n\\n**Avoid churn:**\\n- Do not re-call this tool when nothing meaningful has changed since the last call — update the list only after real progress.\\n- When unsure of the current state, call query mode first (omit \`todos\`) to check the list before deciding what to update.\\n- If no available tool can move any task forward, tell the user where you are stuck instead of repeatedly re-ordering the same todos.\\n\\n**How to use:**\\n- Call with \`todos: [...]\` to replace the full list. Statuses: pending / in_progress / done.\\n- Call with no \`todos\` argument to retrieve the current list without changing it.\\n- Call with \`todos: []\` to clear the list.\\n- Keep titles short and actionable (e.g. \\"Read session-control.ts\\", \\"Add planMode flag to TurnManager\\").\\n- Update statuses as you make progress.\\n- When work is underway, keep exactly one task \`in_progress\`.\\n- Only mark a task \`done\` when it is fully accomplished.\\n- Never mark a task \`done\` if tests are failing, implementation is partial, unresolved errors remain, or required files/dependencies could not be found.\\n- If you encounter a blocker, keep the blocked task \`in_progress\` or add a new pending task describing what must be resolved.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "todos": { "description": "The updated todo list. Omit to read the current todo list without making changes. Pass an empty array to clear the list.", "type": "array", "items": { "type": "object", "properties": { "title": { "type": "string", "minLength": 1, "description": "Short, actionable title for the todo." }, "status": { "type": "string", "enum": [ "pending", "in_progress", "done" ], "description": "Current status of the todo." } }, "required": [ "title", "status" ], "additionalProperties": false } } }, "additionalProperties": false } }, { "name": "UpdateGoal", "description": "Set the status of the current goal. This is how you resume, complete, or block an autonomous goal.\\n\\n- \`active\` — resume a paused or blocked goal when the user explicitly asks you to work on that goal.\\n- \`complete\` — the objective is satisfied and any stated validation has passed. The goal ends and a completion summary is recorded. Before using this, verify the current state against the actual objective and every explicit requirement. Treat weak or indirect evidence as not complete. Do not use \`complete\` merely because a budget is nearly exhausted or you want to stop.\\n- \`blocked\` — a genuine impasse prevents useful progress: an external condition, required user input, missing credentials or permissions, a persistent technical failure, or an impossible, unsafe, or contradictory objective. For non-terminal blockers, do not use \`blocked\` the first time you hit the blocker. The same blocking condition must repeat for at least 3 consecutive goal turns before you call \`blocked\`, counting the original/user-triggered turn and automatic continuations. If a previously blocked goal is resumed, treat the resumed run as a fresh blocked audit. If the objective itself is impossible, unsafe, or contradictory, call \`blocked\` in the same turn instead of running more goal turns. Do not use \`blocked\` because the work is large, hard, slow, uncertain, incomplete, still needs validation, would benefit from clarification, or needs more goal turns. Once the 3-turn threshold is met and you cannot make meaningful progress without user input or an external-state change, call \`blocked\` instead of leaving the goal active.\\n\\nMost active goal turns should not call this tool. If you complete one useful slice of work and material work remains, end the turn normally without calling UpdateGoal; the runtime will prompt you to continue in the next goal turn. Call \`complete\` only when all required work is done, any stated validation has passed, and there is no useful next action. Do not call \`complete\` after only producing a plan, summary, first pass, or partial result. Call \`blocked\` only after the blocked audit threshold is met. If you call \`blocked\`, you will be prompted to explain the blocker in your next message. Setting the status is the machine-readable signal; the completion summary or blocker explanation is yours to write in the following message.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "status": { "type": "string", "enum": [ "active", "complete", "blocked" ], "description": "The lifecycle status to set for the current goal. Use \`blocked\` for impossible, unsafe, or contradictory objectives, or after the same non-terminal blocking condition repeats for at least 3 consecutive goal turns." } }, "required": [ "status" ], "additionalProperties": false } }, { "name": "WaitFor", "description": "Wait for background tasks to finish without ending the current turn.\\n\\nUse this when your next step depends on the result of a running background task (a sub-agent, a background bash command, or a background AskUserQuestion). The call suspends inside the current turn until the task finishes or the timeout elapses, then returns the outcome so you can keep working in the same turn. While waiting, no LLM requests are made.\\n\\nGuidelines:\\n\\n- Do not call WaitFor right after dispatching work whose result you do not need yet — finished background tasks notify you automatically. WaitFor is for the moment you genuinely cannot proceed without a result.\\n- \`timeout\` is required, in seconds, capped at 600. To wait longer, call WaitFor again; waking up periodically also lets you re-evaluate the situation.\\n- A timeout is not an error: the result lists the tasks that are still running, and you decide whether to wait again or do other work meanwhile.\\n- Without \`task_id\`, the wait ends as soon as any background task that was running at call time finishes. Tasks started during the wait are not covered by it; their completion arrives via the usual automatic notification.\\n- With \`task_id\`, the wait ends when that task finishes. An unknown \`task_id\` is an error; a task that has already finished returns immediately.\\n- When no background tasks are running, WaitFor returns immediately without waiting.\\n- When the wait ends because a task finished, the result also lists other tasks that finished during the wait window, so failures surface with context.\\n- Waiting has no side effects on the waited tasks: WaitFor never stops a task, and interrupting the wait (for example, a user interruption) leaves every task running.\\n- A finished task's result is delivered exactly once: tasks reported by WaitFor do not also produce an automatic completion notification.\\n- You can only wait for background tasks started by this agent; task IDs belonging to other agents are unknown here.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "timeout": { "type": "integer", "exclusiveMinimum": 0, "maximum": 600, "description": "Maximum time to wait, in seconds (1-600). A timeout is not an error: the tool returns the tasks that are still running, and you can call it again to keep waiting." }, "task_id": { "description": "The background task ID to wait for. When omitted, the wait ends as soon as any background task that was running at call time finishes.", "type": "string" } }, "required": [ "timeout" ], "additionalProperties": false } }, { "name": "Write", "description": "Create, append to, or replace a file entirely.\\n\\n- Missing parent directories are created automatically (like \`mkdir(parents=True, exist_ok=True)\`).\\n- Mode defaults to overwrite; append adds content at EOF without adding a newline.\\n- Write is NOT ALLOWED for incremental changes to existing files, including trivial, one-line, quick, or cosmetic edits. Use Edit instead.\\n- Use Write only when the file does not exist, you intend a complete replacement, or the new contents have little continuity with the old contents.\\n- Do not create unsolicited documentation files (\`*.md\` write-ups, \`README\`s, summaries) just because a task finished — write one only when the user asks for it, or when a task or project instruction requires it (e.g. the plan-mode plan file, created with Write when plan mode directs you to, or a changeset the repo mandates).\\n- Read before overwriting an existing file.\\n- Write ignores the Read/Edit line-number view. NEVER include line prefixes.\\n- Write outputs content literally, including supplied line endings: \\\\n stays LF, \\\\r\\\\n stays CRLF.\\n- For new content too large for one call, overwrite the first chunk, then append subsequent chunks. Never chunk Write to modify an existing file.\\n", "parameters": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "path": { "type": "string", "description": "Path to the file to create, append to, or completely overwrite. Relative paths resolve against the working directory; a path outside the working directory must be absolute. Missing parent directories are created automatically." }, "content": { "type": "string", "description": "Raw full file content to write exactly as provided. This does not use the Read/Edit text view." }, "mode": { "description": "Write mode. Defaults to overwrite. append adds content to the end exactly as provided and does not add a newline.", "type": "string", "enum": [ "overwrite", "append" ] } }, "required": [ "path", "content" ], "additionalProperties": false } } ], "time": "<time>" }
[wire] llm.request { "agentId": "main", "kind": "loop", "provider": "openai", "model": "mock-model", "modelAlias": "mock-model", "thinkingEffort": "off", "maxTokens": 1000000, "toolSelect": false, "systemPromptHash": "ec9c34379c88babbc468ef2f3e0e08cd2f422c8c4a910664fb8bb394d703a575", "toolsHash": "d0f052e43d5697d7ed9cbd7208499a7907c68e615869f36109b6f9b7252a61c7", "messageCount": 1, "turnStep": "0.1", "time": "<time>" }
[emit] agent.status.updated { "time": "<time>", "agentId": "main", "usage": { "byModel": { "mock-model": { "inputOther": 3, "output": 5, "inputCacheRead": 0, "inputCacheCreation": 0 } }, "total": { "inputOther": 3, "output": 5, "inputCacheRead": 0, "inputCacheCreation": 0 }, "currentTurn": { "inputOther": 3, "output": 5, "inputCacheRead": 0, "inputCacheCreation": 0 } } }
[emit] agent.status.updated { "time": "<time>", "agentId": "main", "contextTokens": 8 }
[wire] usage.record { "agentId": "main", "model": "mock-model", "usage": { "inputOther": 3, "output": 5, "inputCacheRead": 0, "inputCacheCreation": 0 }, "usageScope": "turn", "time": "<time>" }
[emit] turn.step.completed { "time": "<time>", "agentId": "main", "turnId": 0, "step": 1, "stepId": "<uuid-1>", "usage": { "inputOther": 3, "output": 5, "inputCacheRead": 0, "inputCacheCreation": 0 }, "finishReason": "filtered", "providerFinishReason": "filtered", "rawFinishReason": "filtered" }
[wire] token_counting.measured { "agentId": "main", "length": 2, "tokens": 8, "time": "<time>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "content.part", "uuid": "<uuid-2>", "turnId": "0", "step": 1, "stepUuid": "<uuid-1>", "part": { "type": "text", "text": "blocked" } }, "time": "<time>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "step.end", "uuid": "<uuid-1>", "turnId": "0", "step": 1, "finishReason": "filtered", "usage": { "inputOther": 3, "output": 5, "inputCacheRead": 0, "inputCacheCreation": 0 }, "messageId": "mock-1", "providerFinishReason": "filtered", "rawFinishReason": "filtered" }, "time": "<time>" }
[wire] agent.message.appended { "message": { "message": { "role": "assistant", "content": [ { "type": "text", "text": "blocked" } ], "toolCalls": [] }, "meta": { "model": { "provider": "agent-loop", "model": "agent-loop" }, "source": "llm", "usage": { "inputOther": 3, "output": 5, "inputCacheRead": 0, "inputCacheCreation": 0 }, "finish": { "finishReason": "filtered", "rawFinishReason": "filtered" }, "messageId": "mock-1" } }, "time": "<time>", "kind": "event" }
[wire] agent.turn.ended { "turnId": 0, "outcome": "done", "time": "<time>", "kind": "event" }
[wire] turn.ended { "agentId": "main", "turnId": 0, "reason": "failed", "error": { "code": "provider.filtered", "message": "Provider safety policy blocked the response.", "name": "ProviderFilteredError", "details": { "finishReason": "filtered" }, "retryable": false }, "time": "<time>" }
[emit] turn.ended { "time": "<time>", "agentId": "main", "turnId": 0, "reason": "failed", "error": { "code": "provider.filtered", "message": "Provider safety policy blocked the response.", "name": "ProviderFilteredError", "details": { "finishReason": "filtered" }, "retryable": false }, "interruptReason": "filtered" }
`);
const stepCompleted = ctx.allEvents.find(
(event) => event.type === '[rpc]' && event.event === 'turn.step.completed',
);
expect(stepCompleted?.args).toMatchObject({
finishReason: 'filtered',
});
});
it('marks a completed turn as truncated when the provider stops at max tokens', async () => {
profile.update({ activeToolNames: [] });
ctx.mockNextProviderResponse({
parts: [{ type: 'text', text: 'partial answer' }],
finishReason: 'truncated',
rawFinishReason: 'length',
});
const { turn } = submitTurn(loop, 'Hello');
expect(turn).toBeDefined();
await ctx.untilTurnEnd();
await expect(turn.result).resolves.toEqual({
type: 'completed',
steps: 1,
truncated: true,
});
const stepCompleted = ctx.allEvents.find(
(event) => event.type === '[rpc]' && event.event === 'turn.step.completed',
);
expect(stepCompleted?.args).toMatchObject({
finishReason: 'max_tokens',
providerFinishReason: 'truncated',
rawFinishReason: 'length',
});
const turnEnded = ctx.allEvents.find(
(event) => event.type === '[rpc]' && event.event === 'turn.ended',
);
expect(turnEnded?.args).toMatchObject({ reason: 'completed' });
});
it('stops the turn when provider reports tool_calls without any tool call structure', async () => {
profile.update({ activeToolNames: [] });
ctx.mockNextProviderResponse({
parts: [{ type: 'text', text: 'done' }],
finishReason: 'tool_calls',
});
const { turn } = submitTurn(loop, 'Hello');
expect(turn).toBeDefined();
await ctx.untilTurnEnd();
await expect(turn.result).resolves.toEqual({
type: 'completed',
steps: 1,
truncated: false,
});
const stepCompleted = ctx.allEvents.find(
(event) => event.type === '[rpc]' && event.event === 'turn.step.completed',
);
expect(stepCompleted?.args).toMatchObject({
finishReason: 'other',
providerFinishReason: 'tool_calls',
rawFinishReason: 'tool_calls',
});
});
it('lets a loop error handler recover a non-context loop error by retrying', async () => {
profile.update({ activeToolNames: [] });
const workTool: ExecutableTool = {
name: 'Work',
description: 'Pretend to work.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
resolveExecution: () => ({
approvalRule: 'Work',
execute: async () => ({ output: 'should never run' }),
}),
};
ctx.get(IAgentToolRegistryService).register(workTool);
const seenErrors: Array<{ readonly step: number | undefined; readonly message: string }> = [];
loop.registerLoopErrorHandler({
id: 'test-recover-generate-error',
match: () => true,
handle: async (hookCtx) => {
seenErrors.push({
step: hookCtx.step,
message: hookCtx.error instanceof Error ? hookCtx.error.message : String(hookCtx.error),
});
if (seenErrors.length === 1) {
ctx.mockNextResponse({ type: 'text', text: 'Recovered.' });
hookCtx.retry();
return true;
}
return undefined;
},
});
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await ctx.untilTurnEnd();
expect(seenErrors).toEqual([
{ step: 1, message: 'Unexpected generate call #1' },
]);
expect(ctx.allEvents).toContainEqual(
expect.objectContaining({
event: 'turn.ended',
args: expect.objectContaining({ reason: 'completed' }),
}),
);
profile.update({ activeToolNames: ['Work'] });
const beforeExecuteError = new Error('beforeExecute blew up');
const subscription = ctx.get(IAgentToolExecutorService).onBeforeExecuteTool(() => {
throw beforeExecuteError;
});
ctx.mockNextResponse(
{ type: 'text', text: 'working' },
{ type: 'function', id: 'call-work-1', name: 'Work', arguments: '{}' },
);
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'use the tool' }] });
await ctx.untilTurnEnd();
subscription.dispose();
expect(seenErrors).toEqual([
{ step: 1, message: 'Unexpected generate call #1' },
{ step: 1, message: 'beforeExecute blew up' },
]);
expect(ctx.allEvents).toContainEqual(
expect.objectContaining({
event: 'turn.ended',
args: expect.objectContaining({
reason: 'failed',
error: expect.objectContaining({ message: 'beforeExecute blew up' }),
}),
}),
);
expect(ctx.allEvents).toContainEqual(
expect.objectContaining({
type: '[wire]',
event: 'context.append_loop_event',
args: expect.objectContaining({
event: expect.objectContaining({ type: 'step.end', finishReason: 'error' }),
}),
}),
);
expect(
ctx.allEvents.filter(
(entry) =>
entry.type === '[wire]' &&
entry.event === 'context.append_loop_event' &&
(entry.args as { event?: { type?: string } }).event?.type === 'tool.result',
),
).toHaveLength(0);
expect(ctx.llmCalls).toHaveLength(2);
});
it('reports an untyped LLM error message without an internal-code prefix', async () => {
profile.update({ activeToolNames: [] });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await ctx.untilTurnEnd();
expect(ctx.allEvents).toContainEqual(
expect.objectContaining({
event: 'turn.step.interrupted',
args: expect.objectContaining({
reason: 'error',
message: 'Unexpected generate call #1',
}),
}),
);
});
it('appends streamed partial content to the wire when the request fails mid-stream', async () => {
profile.update({ activeToolNames: [] });
ctx.mockNextProviderResponse({
parts: [{ type: 'text', text: 'partial before error' }],
error: new Error('stream broke mid-flight'),
});
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await ctx.untilTurnEnd();
expect(ctx.allEvents).toContainEqual(
expect.objectContaining({
type: '[wire]',
event: 'context.append_loop_event',
args: expect.objectContaining({
event: expect.objectContaining({
type: 'content.part',
part: { type: 'text', text: 'partial before error' },
}),
}),
}),
);
expect(ctx.allEvents).toContainEqual(
expect.objectContaining({
event: 'turn.step.interrupted',
args: expect.objectContaining({ reason: 'error', message: 'stream broke mid-flight' }),
}),
);
});
it('does not run loop error handlers for aborted turns', async () => {
let called = false;
loop.registerLoopErrorHandler({
id: 'test-abort-not-recoverable',
match: () => {
called = true;
return true;
},
handle: async () => undefined,
});
const { turn } = submitTurn(loop, 'go');
turn.cancel(new Error('stop'));
const result = await turn.result;
expect(result.type).toBe('cancelled');
expect(called).toBe(false);
});
it('fails with the error handler error when recovery throws', async () => {
const recoveryError = new Error('recovery failed');
loop.registerLoopErrorHandler({
id: 'test-throw-recovery-error',
match: () => true,
handle: async () => {
throw recoveryError;
},
});
const { turn } = submitTurn(loop, 'go');
const result = await turn.result;
expect(result.type).toBe('failed');
if (result.type === 'failed') {
expect(result.error).toBe(recoveryError);
}
});
it('runs an agent turn through registered tool approval and execution', async () => {
const lookupCall: ToolCall = {
type: 'function',
id: 'call_lookup',
name: 'Lookup',
arguments: '{"query":"moon"}',
};
const lookupTool: ExecutableTool<{ query: string }> = {
name: 'Lookup',
description: 'Look up a short test value.',
parameters: {
type: 'object',
properties: {
query: { type: 'string' },
},
required: ['query'],
additionalProperties: false,
},
resolveExecution: () => ({
approvalRule: 'Lookup',
execute: async () => ({ output: 'lookup-result' }),
}),
};
profile.update({ activeToolNames: ['Lookup'] });
ctx.get(IAgentToolRegistryService).register(lookupTool);
ctx.mockNextResponse({ type: 'text', text: 'I will look it up.' }, lookupCall);
await ctx.rpc.prompt({
input: [{ type: 'text', text: 'Look up moon' }],
});
ctx.mockNextResponse({ type: 'text', text: 'The lookup result is lookup-result.' });
expect(await ctx.untilApproval(true)).toMatchInlineSnapshot(`
[wire] tools.set_active_tools { "agentId": "main", "names": [ "Lookup" ], "time": "<time>" }
[emit] prompt.submitted { "time": "<time>", "agentId": "main", "promptId": "<msg-1>", "userMessageId": "<msg-1>", "status": "running", "content": [ { "type": "text", "text": "Look up moon" } ], "createdAt": "<time>" }
[wire] turn.prompt { "agentId": "main", "input": [ { "type": "text", "text": "Look up moon" } ], "origin": { "kind": "user" }, "promptId": "<msg-1>", "turnId": 0, "time": "<time>" }
[emit] turn.started { "time": "<time>", "agentId": "main", "turnId": 0, "promptId": "<msg-1>", "origin": { "kind": "user" }, "prompt": "Look up moon" }
[emit] context.spliced { "time": "<time>", "agentId": "main", "start": 0, "deleteCount": 0, "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Look up moon" } ], "id": "<msg-1>", "toolCalls": [], "origin": { "kind": "user" } } ] }
[emit] prompt.started { "time": "<time>", "agentId": "main", "promptId": "<msg-1>" }
[wire] context.append_message { "agentId": "main", "message": { "role": "user", "content": [ { "type": "text", "text": "Look up moon" } ], "id": "<msg-1>", "toolCalls": [], "origin": { "kind": "user" } }, "time": "<time>" }
[wire] agent.message.appended { "message": { "message": { "role": "user", "content": [ { "type": "text", "text": "Look up moon" } ] }, "meta": { "source": "input", "promptId": "<msg-1>", "origin": { "kind": "user" }, "tracked": true, "createdAt": "<time>", "userMessageId": "<msg-1>" } }, "time": "<time>", "kind": "event" }
[wire] agent.turn.started { "turnId": 0, "queueItemId": "<msg-1>", "time": "<time>", "kind": "event" }
[wire] plugin.session_start { "agentId": "main", "content": null, "time": "<time>" }
[emit] turn.step.started { "time": "<time>", "agentId": "main", "turnId": 0, "step": 1, "stepId": "<uuid-1>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "step.begin", "uuid": "<uuid-1>", "turnId": "0", "step": 1 }, "time": "<time>" }
[emit] assistant.delta { "time": "<time>", "agentId": "main", "turnId": 0, "delta": "I will look it up." }
[wire] llm.tools_snapshot { "agentId": "main", "hash": "3bfeb22e61431247933e79f6ab94e7ca14a127f899bc87e7bbd22594ba9cdb66", "tools": [ { "name": "Lookup", "description": "Look up a short test value.", "parameters": { "type": "object", "properties": { "query": { "type": "string" } }, "required": [ "query" ], "additionalProperties": false } } ], "time": "<time>" }
[emit] tool.call.delta { "time": "<time>", "agentId": "main", "turnId": 0, "toolCallId": "call_lookup", "name": "Lookup", "argumentsPart": "{\\"query\\":\\"moon\\"}" }
[wire] llm.request { "agentId": "main", "kind": "loop", "provider": "openai", "model": "mock-model", "modelAlias": "mock-model", "thinkingEffort": "off", "maxTokens": 1000000, "toolSelect": false, "systemPromptHash": "ec9c34379c88babbc468ef2f3e0e08cd2f422c8c4a910664fb8bb394d703a575", "toolsHash": "3bfeb22e61431247933e79f6ab94e7ca14a127f899bc87e7bbd22594ba9cdb66", "messageCount": 1, "turnStep": "0.1", "time": "<time>" }
[emit] agent.status.updated { "time": "<time>", "agentId": "main", "usage": { "byModel": { "mock-model": { "inputOther": 4, "output": 16, "inputCacheRead": 0, "inputCacheCreation": 0 } }, "total": { "inputOther": 4, "output": 16, "inputCacheRead": 0, "inputCacheCreation": 0 }, "currentTurn": { "inputOther": 4, "output": 16, "inputCacheRead": 0, "inputCacheCreation": 0 } } }
[emit] agent.status.updated { "time": "<time>", "agentId": "main", "contextTokens": 20 }
[wire] usage.record { "agentId": "main", "model": "mock-model", "usage": { "inputOther": 4, "output": 16, "inputCacheRead": 0, "inputCacheCreation": 0 }, "usageScope": "turn", "time": "<time>" }
[wire] token_counting.measured { "agentId": "main", "length": 2, "tokens": 20, "time": "<time>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "content.part", "uuid": "<uuid-2>", "turnId": "0", "step": 1, "stepUuid": "<uuid-1>", "part": { "type": "text", "text": "I will look it up." } }, "time": "<time>" }
[emit] permission.approval.requested { "time": "<time>", "id": "<approval-1>", "sessionId": "test-session", "agentId": "main", "turnId": 0, "toolCallId": "call_lookup", "toolName": "Lookup", "action": "Approve Lookup", "display": { "kind": "generic", "summary": "Approve Lookup", "detail": { "query": "moon" } }, "toolInput": { "query": "moon" } }
[wire] interaction.request { "agentId": "main", "id": "<approval-1>", "kind": "approval", "toolCallId": "call_lookup", "request": { "id": "<approval-1>", "sessionId": "test-session", "agentId": "main", "turnId": 0, "toolCallId": "call_lookup", "toolName": "Lookup", "action": "Approve Lookup", "display": { "kind": "generic", "summary": "Approve Lookup", "detail": { "query": "moon" } } }, "time": "<time>" }
[emit] requestApproval { "id": "<approval-1>", "turnId": 0, "toolCallId": "call_lookup", "toolName": "Lookup", "action": "Approve Lookup", "display": { "kind": "generic", "summary": "Approve Lookup", "detail": { "query": "moon" } } }
`);
expect(ctx.lastLlmInput()).toMatchInlineSnapshot(`
system: <system-prompt>
tools: Lookup
messages:
user: text "Look up moon"
`);
expect(await ctx.untilTurnEnd()).toMatchInlineSnapshot(`
[wire] interaction.resolved { "agentId": "main", "id": "<approval-1>", "response": { "decision": "approved", "selectedLabel": "approve" }, "time": "<time>" }
[emit] permission.approval.resolved { "time": "<time>", "id": "<approval-1>", "sessionId": "test-session", "agentId": "main", "turnId": 0, "toolCallId": "call_lookup", "toolName": "Lookup", "action": "Approve Lookup", "display": { "kind": "generic", "summary": "Approve Lookup", "detail": { "query": "moon" } }, "toolInput": { "query": "moon" }, "decision": "approved", "selectedLabel": "approve" }
[wire] permission.record_approval_result { "turnId": 0, "toolCallId": "call_lookup", "toolName": "Lookup", "action": "Approve Lookup", "result": { "decision": "approved", "selectedLabel": "approve" }, "agentId": "main", "time": "<time>" }
[emit] tool.call.started { "time": "<time>", "agentId": "main", "turnId": 0, "toolCallId": "call_lookup", "name": "Lookup", "args": { "query": "moon" } }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "tool.call", "uuid": "<uuid-3>", "turnId": "0", "step": 1, "stepUuid": "<uuid-1>", "toolCallId": "call_lookup", "name": "Lookup", "args": { "query": "moon" } }, "time": "<time>" }
[emit] tool.result { "time": "<time>", "agentId": "main", "turnId": 0, "toolCallId": "call_lookup", "output": "lookup-result" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "tool.result", "parentUuid": "<uuid-3>", "toolCallId": "call_lookup", "result": { "output": "lookup-result" } }, "time": "<time>" }
[emit] turn.step.completed { "time": "<time>", "agentId": "main", "turnId": 0, "step": 1, "stepId": "<uuid-1>", "usage": { "inputOther": 4, "output": 16, "inputCacheRead": 0, "inputCacheCreation": 0 }, "finishReason": "tool_use", "providerFinishReason": "tool_calls", "rawFinishReason": "tool_calls" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "step.end", "uuid": "<uuid-1>", "turnId": "0", "step": 1, "finishReason": "tool_use", "usage": { "inputOther": 4, "output": 16, "inputCacheRead": 0, "inputCacheCreation": 0 }, "messageId": "mock-1", "providerFinishReason": "tool_calls", "rawFinishReason": "tool_calls" }, "time": "<time>" }
[emit] turn.step.started { "time": "<time>", "agentId": "main", "turnId": 0, "step": 2, "stepId": "<uuid-4>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "step.begin", "uuid": "<uuid-4>", "turnId": "0", "step": 2 }, "time": "<time>" }
[emit] assistant.delta { "time": "<time>", "agentId": "main", "turnId": 0, "delta": "The lookup result is lookup-result." }
[wire] llm.request { "agentId": "main", "kind": "loop", "provider": "openai", "model": "mock-model", "modelAlias": "mock-model", "thinkingEffort": "off", "maxTokens": 1000000, "toolSelect": false, "systemPromptHash": "ec9c34379c88babbc468ef2f3e0e08cd2f422c8c4a910664fb8bb394d703a575", "toolsHash": "3bfeb22e61431247933e79f6ab94e7ca14a127f899bc87e7bbd22594ba9cdb66", "messageCount": 3, "turnStep": "0.2", "time": "<time>" }
[wire] usage.record { "agentId": "main", "model": "mock-model", "usage": { "inputOther": 25, "output": 12, "inputCacheRead": 0, "inputCacheCreation": 0 }, "usageScope": "turn", "time": "<time>" }
[emit] agent.status.updated { "time": "<time>", "agentId": "main", "usage": { "byModel": { "mock-model": { "inputOther": 29, "output": 28, "inputCacheRead": 0, "inputCacheCreation": 0 } }, "total": { "inputOther": 29, "output": 28, "inputCacheRead": 0, "inputCacheCreation": 0 }, "currentTurn": { "inputOther": 29, "output": 28, "inputCacheRead": 0, "inputCacheCreation": 0 } } }
[wire] token_counting.measured { "agentId": "main", "length": 4, "tokens": 37, "time": "<time>" }
[emit] agent.status.updated { "time": "<time>", "agentId": "main", "contextTokens": 37 }
[emit] turn.step.completed { "time": "<time>", "agentId": "main", "turnId": 0, "step": 2, "stepId": "<uuid-4>", "usage": { "inputOther": 25, "output": 12, "inputCacheRead": 0, "inputCacheCreation": 0 }, "finishReason": "end_turn", "providerFinishReason": "completed", "rawFinishReason": "stop" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "content.part", "uuid": "<uuid-5>", "turnId": "0", "step": 2, "stepUuid": "<uuid-4>", "part": { "type": "text", "text": "The lookup result is lookup-result." } }, "time": "<time>" }
[wire] context.append_loop_event { "agentId": "main", "event": { "type": "step.end", "uuid": "<uuid-4>", "turnId": "0", "step": 2, "finishReason": "end_turn", "usage": { "inputOther": 25, "output": 12, "inputCacheRead": 0, "inputCacheCreation": 0 }, "messageId": "mock-2", "providerFinishReason": "completed", "rawFinishReason": "stop" }, "time": "<time>" }
[wire] agent.message.appended { "message": { "message": { "role": "assistant", "content": [ { "type": "text", "text": "I will look it up." } ], "toolCalls": [ { "type": "function", "id": "call_lookup", "name": "Lookup", "arguments": "{\\"query\\":\\"moon\\"}" } ] }, "meta": { "model": { "provider": "agent-loop", "model": "agent-loop" }, "source": "llm", "usage": { "inputOther": 4, "output": 16, "inputCacheRead": 0, "inputCacheCreation": 0 }, "finish": { "finishReason": "tool_calls", "rawFinishReason": "tool_calls" }, "messageId": "mock-1" } }, "time": "<time>", "kind": "event" }
[wire] agent.message.appended { "message": { "message": { "role": "tool", "content": [ { "type": "text", "text": "lookup-result" } ], "toolCallId": "call_lookup" }, "meta": { "source": "tool" } }, "time": "<time>", "kind": "event" }
[wire] agent.message.appended { "message": { "message": { "role": "assistant", "content": [ { "type": "text", "text": "The lookup result is lookup-result." } ], "toolCalls": [] }, "meta": { "model": { "provider": "agent-loop", "model": "agent-loop" }, "source": "llm", "usage": { "inputOther": 25, "output": 12, "inputCacheRead": 0, "inputCacheCreation": 0 }, "finish": { "finishReason": "completed", "rawFinishReason": "stop" }, "messageId": "mock-2" } }, "time": "<time>", "kind": "event" }
[wire] agent.turn.ended { "turnId": 0, "outcome": "done", "time": "<time>", "kind": "event" }
[wire] turn.ended { "agentId": "main", "turnId": 0, "reason": "completed", "time": "<time>" }
[emit] turn.ended { "time": "<time>", "agentId": "main", "turnId": 0, "reason": "completed" }
`);
expect(ctx.lastLlmInput()).toMatchInlineSnapshot(`
messages:
<last>
assistant: text "I will look it up." calls call_lookup:Lookup { "query": "moon" }
tool[call_lookup]: text "lookup-result"
`);
});
it('does not abort sibling tools when a parallel batch tool completes first', async () => {
const local = createTestAgent(permissionModeServices('yolo'));
const slowGate = deferred();
try {
const slowStarted = deferred();
let slowSawAbort: boolean | undefined;
const fastTool: ExecutableTool = {
name: 'Fast',
description: 'Return immediately.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
resolveExecution: () => ({
approvalRule: 'Fast',
execute: async () => ({ output: 'fast result' }),
}),
};
const slowTool: ExecutableTool = {
name: 'Slow',
description: 'Wait on a gate before returning.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
resolveExecution: () => ({
approvalRule: 'Slow',
execute: async ({ signal }) => {
slowStarted.resolve();
await slowGate.promise;
slowSawAbort = signal.aborted;
return { output: 'slow result' };
},
}),
};
local.get(IAgentProfileService).update({ activeToolNames: ['Fast', 'Slow'] });
local.get(IAgentToolRegistryService).register(fastTool);
local.get(IAgentToolRegistryService).register(slowTool);
local.mockNextResponse(
{ type: 'text', text: 'working' },
{ type: 'function', id: 'call-fast-1', name: 'Fast', arguments: '{}' },
{ type: 'function', id: 'call-slow-1', name: 'Slow', arguments: '{}' },
);
local.mockNextResponse({ type: 'text', text: 'all done' });
const toolResults = (): Array<Extract<LoopRecordedEvent, { type: 'tool.result' }>> =>
local.allEvents
.filter(
(entry) => entry.type === '[wire]' && entry.event === 'context.append_loop_event',
)
.map((entry) => (entry.args as { event: LoopRecordedEvent }).event)
.filter(
(event): event is Extract<LoopRecordedEvent, { type: 'tool.result' }> =>
event.type === 'tool.result',
);
const { turn } = submitTurn(local.get(IAgentLoopService), 'use both tools');
await slowStarted.promise;
await vi.waitFor(() => {
expect(toolResults().some((event) => event.toolCallId === 'call-fast-1')).toBe(true);
});
slowGate.resolve();
await expect(turn.result).resolves.toMatchObject({ type: 'completed' });
expect(slowSawAbort).toBe(false);
expect(toolResults().map((event) => event.toolCallId).toSorted()).toEqual([
'call-fast-1',
'call-slow-1',
]);
await local.expectResumeMatches();
} finally {
slowGate.resolve();
await local.dispose();
}
});
it('forwards the cancellation reason to the signals of running tools', async () => {
const local = createTestAgent(permissionModeServices('yolo'));
try {
const started = deferred();
const signals: AbortSignal[] = [];
const hangTool: ExecutableTool = {
name: 'Hang',
description: 'Wait until aborted.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
resolveExecution: () => ({
approvalRule: 'Hang',
execute: ({ signal }) => {
signals.push(signal);
started.resolve();
return new Promise((_, reject) => {
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
});
},
}),
};
local.get(IAgentProfileService).update({ activeToolNames: ['Hang'] });
local.get(IAgentToolRegistryService).register(hangTool);
local.mockNextResponse(
{ type: 'text', text: 'working' },
{ type: 'function', id: 'call-hang-1', name: 'Hang', arguments: '{}' },
);
const loop = local.get(IAgentLoopService);
const { turn } = submitTurn(loop, 'hang until cancelled');
await started.promise;
expect(loop.cancel()).toBe(true);
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
expect(signals).toHaveLength(1);
expect(signals[0]?.aborted).toBe(true);
expect(isUserCancellation(signals[0]?.reason)).toBe(true);
} finally {
await local.dispose();
}
});
it('preserves tool call extras (Gemini thought_signature) through to context', async () => {
const sigCall: ToolCall = {
type: 'function',
id: 'call_sig',
name: 'Lookup',
arguments: '{"query":"moon"}',
extras: { thought_signature_b64: 'c2lnbmF0dXJl' },
};
const lookupTool: ExecutableTool<{ query: string }> = {
name: 'Lookup',
description: 'Look up a short test value.',
parameters: {
type: 'object',
properties: {
query: { type: 'string' },
},
required: ['query'],
additionalProperties: false,
},
resolveExecution: () => ({
approvalRule: 'Lookup',
execute: async () => ({ output: 'lookup-result' }),
}),
};
profile.update({ activeToolNames: ['Lookup'] });
ctx.get(IAgentToolRegistryService).register(lookupTool);
ctx.mockNextResponse({ type: 'text', text: 'I will look it up.' }, sigCall);
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Look up moon' }] });
ctx.mockNextResponse({ type: 'text', text: 'The lookup result is lookup-result.' });
await ctx.untilApproval(true);
await ctx.untilTurnEnd();
const assistant = ctx.contextData().history.find((m) => m.role === 'assistant');
expect(assistant?.toolCalls[0]?.extras).toEqual({ thought_signature_b64: 'c2lnbmF0dXJl' });
});
it('lets non-external stop hooks continue a turn more than once', async () => {
profile.update({ activeToolNames: [] });
let continuations = 0;
loop.hooks.onDidFinishStep.register('test-repeat-stop-continuation', async (hookCtx, next) => {
if (continuations < 2) {
continuations += 1;
loop.notify({
message: {
role: 'user',
content: [{ type: 'text', text: `continue ${continuations}` }],
toolCalls: [],
origin: { kind: 'system_trigger', name: 'stop_hook' },
},
});
return;
}
await next();
});
ctx.mockNextResponse({ type: 'text', text: 'First answer.' });
ctx.mockNextProviderResponse({ error: new APIProviderRateLimitError('slow down', null, 1) });
ctx.mockNextResponse({ type: 'text', text: 'Second answer.' });
ctx.mockNextResponse({ type: 'text', text: 'Third answer.' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'hello' }] });
await ctx.untilTurnEnd();
expect(continuations).toBe(2);
expect(ctx.llmCalls).toHaveLength(4);
const startedSteps = ctx.allEvents
.filter((event) => event.type === '[rpc]' && event.event === 'turn.step.started')
.map((event) => (event.args as { step: number }).step);
expect(startedSteps).toEqual([1, 2, 3, 4]);
const retryingSteps = ctx.allEvents
.filter((event) => event.type === '[rpc]' && event.event === 'turn.step.retrying')
.map((event) => (event.args as { step: number }).step);
expect(retryingSteps).toEqual([2]);
expect(ctx.contextData().history).toContainEqual(
expect.objectContaining({
role: 'user',
content: [{ type: 'text', text: 'continue 1' }],
origin: { kind: 'system_trigger', name: 'stop_hook' },
}),
);
expect(ctx.contextData().history).toContainEqual(
expect.objectContaining({
role: 'user',
content: [{ type: 'text', text: 'continue 2' }],
origin: { kind: 'system_trigger', name: 'stop_hook' },
}),
);
});
it('raises the abort-listener ceiling on the step signal for parallel tool bursts', async () => {
profile.update({ activeToolNames: [] });
let observed = 0;
loop.hooks.onDidFinishStep.register('test-step-signal-listener-ceiling', async (hookCtx, next) => {
observed = getMaxListeners(hookCtx.signal);
await next();
});
ctx.mockNextResponse({ type: 'text', text: 'answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'hello' }] });
await ctx.untilTurnEnd();
expect(observed).toBe(64);
});
it('ends the turn when an afterStep hook sets stopTurn even though the model requested tool calls', async () => {
const lookupCall: ToolCall = {
type: 'function',
id: 'call_lookup',
name: 'Lookup',
arguments: '{"query":"moon"}',
};
const lookupTool: ExecutableTool<{ query: string }> = {
name: 'Lookup',
description: 'Look up a short test value.',
parameters: {
type: 'object',
properties: {
query: { type: 'string' },
},
required: ['query'],
additionalProperties: false,
},
resolveExecution: () => ({
approvalRule: 'Lookup',
execute: async () => ({ output: 'lookup-result' }),
}),
};
profile.update({ activeToolNames: ['Lookup'] });
ctx.get(IAgentToolRegistryService).register(lookupTool);
loop.hooks.onDidFinishStep.register('test-stop-turn', async (hookCtx, next) => {
hookCtx.stopTurn = true;
await next();
});
ctx.mockNextResponse({ type: 'text', text: 'I will look it up.' }, lookupCall);
ctx.mockNextResponse({ type: 'text', text: 'This step should not run.' });
const { turn } = submitTurn(loop, 'Look up moon');
await ctx.untilApproval(true);
await ctx.untilTurnEnd();
expect(ctx.llmCalls).toHaveLength(1);
await expect(turn!.result).resolves.toEqual({
type: 'completed',
steps: 1,
truncated: false,
});
});
it('lets stopTurn take precedence over a queued continuation request', async () => {
profile.update({ activeToolNames: [] });
loop.hooks.onDidFinishStep.register('test-continue-like-stop-hook', async (hookCtx, next) => {
loop.notify();
await next();
});
loop.hooks.onDidFinishStep.register('test-hard-stop', async (hookCtx, next) => {
hookCtx.stopTurn = true;
await next();
});
ctx.mockNextResponse({ type: 'text', text: 'First answer.' });
ctx.mockNextResponse({ type: 'text', text: 'This continuation should not run.' });
const { turn } = submitTurn(loop, 'hello');
await ctx.untilTurnEnd();
expect(ctx.llmCalls).toHaveLength(1);
await expect(turn!.result).resolves.toEqual({
type: 'completed',
steps: 1,
truncated: false,
});
});
it('carries a tool stopTurnReason into the completed turn result and turn.ended', async () => {
const stopCall: ToolCall = {
type: 'function',
id: 'call_stop',
name: 'Stopper',
arguments: '{}',
};
const stopperTool: ExecutableTool<Record<string, never>> = {
name: 'Stopper',
description: 'Stops the turn with a reason.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
resolveExecution: () => ({
approvalRule: 'Stopper',
execute: async () => ({ output: 'stopped', stopTurn: true, stopTurnReason: 'demo_reason' }),
}),
};
profile.update({ activeToolNames: ['Stopper'] });
ctx.get(IAgentToolRegistryService).register(stopperTool);
ctx.mockNextResponse({ type: 'text', text: 'Stopping.' }, stopCall);
ctx.mockNextResponse({ type: 'text', text: 'This step should not run.' });
const { turn } = submitTurn(loop, 'stop');
await ctx.untilApproval(true);
await ctx.untilTurnEnd();
expect(ctx.llmCalls).toHaveLength(1);
await expect(turn!.result).resolves.toEqual({
type: 'completed',
steps: 1,
truncated: false,
stopReason: 'demo_reason',
});
const turnEnded = ctx.allEvents.find(
(event) => event.type === '[rpc]' && event.event === 'turn.ended',
);
expect(turnEnded?.args).toMatchObject({ reason: 'completed', stopReason: 'demo_reason' });
const record = (await ctx.persistedWireRecords()).find((entry) => entry.type === 'turn.ended');
expect(record).toMatchObject({ turnId: 0, reason: 'completed', stopReason: 'demo_reason' });
});
it('queues consecutive nextTurn requests in FIFO order without overlapping turns', async () => {
const events: string[] = [];
const subscription = ctx.get(IEventBus).subscribe((event) => {
if (event instanceof TurnStarted || event instanceof TurnEnded) {
events.push(`${event.type}:${event.turnId}`);
}
});
ctx.mockNextResponse({ type: 'text', text: 'one' });
ctx.mockNextResponse({ type: 'text', text: 'two' });
ctx.mockNextResponse({ type: 'text', text: 'three' });
const first = submitTurn(loop, 'first').turn;
const second = submitTurn(loop, 'second').turn;
const third = submitTurn(loop, 'third').turn;
loop.notify();
await Promise.all([first.result, second.result, third.result]);
subscription.dispose();
await expect(first.result).resolves.toMatchObject({ type: 'completed' });
await expect(second.result).resolves.toMatchObject({ type: 'completed' });
await expect(third.result).resolves.toMatchObject({ type: 'completed' });
expect(events).toEqual([
'turn.started:0',
'turn.ended:0',
'turn.started:1',
'turn.ended:1',
'turn.started:2',
'turn.ended:2',
]);
expect(ctx.llmCalls).toHaveLength(3);
});
it('refuses a quiescence lease while a turn is active without cancelling it', async () => {
let started!: () => void;
const activeStarted = new Promise<void>((resolve) => {
started = resolve;
});
let release!: () => void;
const canFinish = new Promise<void>((resolve) => {
release = resolve;
});
const hook = loop.hooks.onWillBeginStep.register('test-quiescence', async (_hookCtx, next) => {
started();
await canFinish;
await next();
});
const active = submitTurn(loop, 'active').turn;
await activeStarted;
expect(loop.tryAcquireQuiescence()).toBeUndefined();
expect(active.signal.aborted).toBe(false);
hook.dispose();
ctx.mockNextResponse({ type: 'text', text: 'completed normally' });
release();
await expect(active.result).resolves.toMatchObject({ type: 'completed' });
});
it('holds new admissions until an idle quiescence lease is released', async () => {
const lease = loop.tryAcquireQuiescence();
expect(lease).toBeDefined();
expect(loop.tryAcquireQuiescence()).toBeUndefined();
const held = submitTurn(loop, 'held').turn;
let started = false;
const subscription = ctx.get(IEventBus).subscribe(TurnStarted, () => {
started = true;
});
await Promise.resolve();
expect(started).toBe(false);
expect(held.state).toBe('queued');
expect(loop.snapshot()).toMatchObject({ state: 'idle', hasPendingRequests: true });
ctx.mockNextResponse({ type: 'text', text: 'after undo' });
lease?.dispose();
await expect(held.result).resolves.toMatchObject({ type: 'completed' });
subscription.dispose();
const parked = createTestAgent(sessionService(IAgentLifecycleService, parkedLifecycleStub()));
try {
const parkedLoop = parked.get(IAgentLoopService);
const early = submitTurn(parkedLoop, 'early').turn;
expect(parkedLoop.snapshot()).toMatchObject({ state: 'idle', hasPendingRequests: true });
expect(parked.llmCalls).toHaveLength(0);
const earlyQueueId = parkedLoop.snapshot().queue[0]!.meta!.promptId!;
expect(parkedLoop.cancel({ promptId: earlyQueueId }, new Error('not wanted'))).toBe(true);
await expect(early.result).resolves.toMatchObject({ type: 'cancelled' });
const real = submitTurn(parkedLoop, 'real').turn;
let nudgeConsumed = 0;
parkedLoop.notify({
message: { role: 'user', content: [{ type: 'text', text: 'nudge text' }], toolCalls: [] },
onConsume: () => {
nudgeConsumed += 1;
},
});
parked.mockNextResponse({ type: 'text', text: 'real answer' });
const parkedRef = attachParkedEngine(parkedLoop);
try {
await expect(real.result).resolves.toMatchObject({ type: 'completed' });
expect(nudgeConsumed).toBe(1);
expect(parked.llmCalls).toHaveLength(1);
expect(parked.contextData().history).toContainEqual(
expect.objectContaining({
content: [{ type: 'text', text: 'nudge text' }],
}),
);
} finally {
parkedRef.stop();
}
} finally {
await parked.dispose();
}
});
it('can abort an admission while quiescence holds it', async () => {
const lease = loop.tryAcquireQuiescence();
expect(lease).toBeDefined();
const held = submitTurn(loop, 'held').turn;
const resumed = submitTurn(loop, 'resumed').turn;
expect(held.cancel()).toBe(true);
await expect(held.result).resolves.toMatchObject({ type: 'cancelled', steps: 0 });
expect(loop.snapshot().hasPendingRequests).toBe(true);
ctx.mockNextResponse({ type: 'text', text: 'resumed answer' });
lease?.dispose();
await expect(resumed.result).resolves.toMatchObject({ type: 'completed', steps: 1 });
expect(loop.snapshot().hasPendingRequests).toBe(false);
expect(loop.snapshot().state).toBe('idle');
});
it('cancels an in-flight turn while its queued turn continues afterwards', async () => {
let releaseRunning!: () => void;
const running = new Promise<void>((resolve) => {
releaseRunning = resolve;
});
let stepStarted!: () => void;
const started = new Promise<void>((resolve) => {
stepStarted = resolve;
});
let armed = true;
loop.hooks.onWillBeginStep.register('test-turn-cancel-mid-step', async (hookCtx, next) => {
if (armed) {
armed = false;
stepStarted();
await Promise.race([
running,
new Promise<void>((_, reject) => {
hookCtx.signal.addEventListener('abort', () => reject(hookCtx.signal.reason), { once: true });
}),
]);
}
await next();
});
ctx.mockNextResponse({ type: 'text', text: 'after cancellation' });
const turn = submitTurn(loop, 'start').turn;
const queued = submitTurn(loop, 'next').turn;
await started;
expect(turn.cancel(new Error('skip this turn'))).toBe(true);
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
releaseRunning();
await expect(queued.result).resolves.toMatchObject({ type: 'completed', steps: 1 });
expect(queued.state).toBe('completed');
expect(ctx.llmCalls).toHaveLength(1);
});
it('disposes active and queued turns with all turns settled and never pumps again', async () => {
let stepStarted!: () => void;
const started = new Promise<void>((resolve) => {
stepStarted = resolve;
});
loop.hooks.onWillBeginStep.register('test-dispose-loop', async (hookCtx, next) => {
stepStarted();
await new Promise<void>((_, reject) => {
hookCtx.signal.addEventListener('abort', () => reject(hookCtx.signal.reason), { once: true });
});
await next();
});
const active = submitTurn(loop, 'active').turn;
const queued = submitTurn(loop, 'queued').turn;
const queuedExtra = submitTurn(loop, 'queued-extra').turn;
await started;
(loop as IAgentLoopService & { dispose(): void }).dispose();
await expect(active.result).resolves.toMatchObject({ type: 'cancelled' });
await expect(queued.result).resolves.toMatchObject({ type: 'cancelled', steps: 0 });
await expect(queuedExtra.result).resolves.toMatchObject({ type: 'cancelled', steps: 0 });
expect(active.state).toBe('cancelled');
expect(queued.state).toBe('cancelled');
expect(ctx.llmCalls).toHaveLength(0);
expect(() => submitTurn(loop, 'rejected')).toThrow();
});
it('cancels a queued turn without starting or materializing its initial request', async () => {
const started: number[] = [];
const subscription = ctx.get(IEventBus).subscribe(TurnStarted, (event) => {
started.push(event.turnId);
});
ctx.mockNextResponse({ type: 'text', text: 'one' });
ctx.mockNextResponse({ type: 'text', text: 'three' });
const first = submitTurn(loop, 'first').turn;
const cancelledTurn = submitTurn(loop, 'cancelled').turn;
const third = submitTurn(loop, 'third').turn;
expect(cancelledTurn.cancel()).toBe(true);
await expect(cancelledTurn.result).resolves.toMatchObject({ type: 'cancelled', steps: 0 });
await Promise.all([first.result, third.result]);
subscription.dispose();
expect(started).toEqual([0, 1]);
expect(ctx.contextData().history).not.toContainEqual(
expect.objectContaining({ content: [{ type: 'text', text: 'cancelled' }] }),
);
});
it('omits the turn.started prompt for system-triggered turns', async () => {
const prompts: Array<string | undefined> = [];
const subscription = ctx.get(IEventBus).subscribe(TurnStarted, (event) => {
prompts.push(event.prompt);
});
ctx.mockNextResponse({ type: 'text', text: 'continued' });
ctx.mockNextResponse({ type: 'text', text: 'hi there' });
const system = submitPromptTurn(loop, {
message: { role: 'user', content: [{ type: 'text', text: 'continue the goal' }] },
meta: { origin: { kind: 'system_trigger', name: 'goal_continuation' } as PromptOrigin },
}).turn;
await system.result;
const user = submitTurn(loop, 'hi').turn;
await user.result;
subscription.dispose();
expect(prompts).toEqual([undefined, 'hi']);
});
it('carries the turn.started prompt for subagent system triggers', async () => {
const prompts: Array<string | undefined> = [];
const subscription = ctx.get(IEventBus).subscribe(TurnStarted, (event) => {
prompts.push(event.prompt);
});
ctx.mockNextResponse({ type: 'text', text: 'scanned' });
const subagent = submitPromptTurn(loop, {
message: { role: 'user', content: [{ type: 'text', text: 'scan the repo' }] },
meta: { origin: { kind: 'system_trigger', name: 'subagent' } as PromptOrigin },
}).turn;
await subagent.result;
subscription.dispose();
expect(prompts).toEqual(['scan the repo']);
});
it('carries kimi-file prompt attachments on turn.started, falling back to the URL file id', async () => {
const payloads: Array<TurnStarted['promptAttachments']> = [];
const subscription = ctx.get(IEventBus).subscribe(TurnStarted, (event) => {
payloads.push(event.promptAttachments);
});
ctx.mockNextResponse({ type: 'text', text: 'seen' });
const turn = submitPromptTurn(loop, { message: {
role: 'user',
content: [
{ type: 'image_url', imageUrl: { url: 'kimi-file://file_1', id: 'file_1', name: 'photo.png' } },
{ type: 'video_url', videoUrl: { url: 'kimi-file://file_2', id: 'file_2', name: 'clip.mp4' } },
{ type: 'image_url', imageUrl: { url: 'kimi-file://file_3' } },
{ type: 'image_url', imageUrl: { url: 'kimi-file://file_4', id: 'other' } },
{ type: 'image_url', imageUrl: { url: 'https://example.com/no-id.png' } },
{ type: 'image_url', imageUrl: { url: 'ms://provider-blob', id: 'prov_1' } },
{ type: 'text', text: 'look' },
],
}, meta: { origin: { kind: 'user' } } }).turn;
await turn.result;
subscription.dispose();
expect(payloads).toEqual([
[
{ kind: 'image', fileId: 'file_1', name: 'photo.png' },
{ kind: 'video', fileId: 'file_2', name: 'clip.mp4' },
{ kind: 'image', fileId: 'file_3' },
],
]);
});
it('carries origin file attachments on turn.started promptAttachments', async () => {
const payloads: Array<TurnStarted['promptAttachments']> = [];
const subscription = ctx.get(IEventBus).subscribe(TurnStarted, (event) => {
payloads.push(event.promptAttachments);
});
ctx.mockNextResponse({ type: 'text', text: 'seen' });
const turn = submitPromptTurn(loop, { message: {
role: 'user',
content: [
{ type: 'image_url', imageUrl: { url: 'kimi-file://file_1', id: 'file_1' } },
{ type: 'text', text: 'summarize' },
],
}, meta: { origin: {
kind: 'user',
attachments: [
{
name: 'report.pdf',
mediaType: 'application/pdf',
size: 42,
path: '/data/report.pdf',
},
],
} as PromptOrigin } }).turn;
await turn.result;
subscription.dispose();
expect(payloads).toEqual([
[
{ kind: 'image', fileId: 'file_1' },
{
kind: 'file',
name: 'report.pdf',
mediaType: 'application/pdf',
size: 42,
path: '/data/report.pdf',
},
],
]);
});
it('carries skill activation file attachments on turn.started promptAttachments', async () => {
const payloads: Array<TurnStarted['promptAttachments']> = [];
const subscription = ctx.get(IEventBus).subscribe(TurnStarted, (event) => {
payloads.push(event.promptAttachments);
});
ctx.mockNextResponse({ type: 'text', text: 'seen' });
const turn = submitPromptTurn(loop, { message: {
role: 'user',
content: [{ type: 'text', text: 'User activated the skill "check".' }],
}, meta: { origin: {
kind: 'skill_activation',
activationId: 'act_1',
skillName: 'check',
trigger: 'user-slash',
attachments: [
{
name: 'note.txt',
mediaType: 'text/plain',
size: 21,
path: '/data/note.txt',
},
],
} as PromptOrigin } }).turn;
await turn.result;
subscription.dispose();
expect(payloads).toEqual([
[{ kind: 'file', name: 'note.txt', mediaType: 'text/plain', size: 21, path: '/data/note.txt' }],
]);
});
});
describe('turn telemetry', () => {
it('emits turn_started and turn_ended with mode and protocol on completion', async () => {
const records: TelemetryRecord[] = [];
const local = createTestAgent({ telemetry: recordingTelemetry(records) });
try {
local.get(IAgentProfileService).update({ activeToolNames: [] });
local.mockNextResponse({ type: 'text', text: 'hi' });
await local.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await local.untilTurnEnd();
expect(records).toContainEqual({
event: 'turn_started',
properties: {
turn_id: 0,
agent_id: 'main',
mode: 'agent',
model: 'mock-model',
provider_type: 'kimi',
protocol: 'openai',
thinking_effort: 'off',
},
});
expect(records).toContainEqual({
event: 'turn_ended',
properties: expect.objectContaining({
turn_id: 0,
reason: 'completed',
duration_ms: expect.any(Number),
mode: 'agent',
provider_type: 'kimi',
protocol: 'openai',
thinking_effort: 'off',
}),
});
expect(records.some((record) => record.event === 'turn_interrupted')).toBe(false);
} finally {
await local.dispose();
}
});
it('keeps turn telemetry aligned with the request config across pre-step changes', async () => {
const records: TelemetryRecord[] = [];
const local = createTestAgent({ telemetry: recordingTelemetry(records) });
try {
const localLoop = local.get(IAgentLoopService);
const localProfile = local.get(IAgentProfileService);
local.configure({
modelCapabilities: {
image_in: false,
video_in: false,
audio_in: false,
thinking: true,
tool_use: true,
max_context_tokens: 1_000_000,
},
});
localProfile.update({ activeToolNames: [] });
localProfile.setThinking('on');
localLoop.hooks.onWillBeginStep.register('test-change-thinking', async (_ctx, next) => {
localProfile.setThinking('off');
await next();
});
local.mockNextResponse({ type: 'text', text: 'hi' });
await local.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await local.untilTurnEnd();
const request = local.allEvents.find(
(event) => event.type === '[wire]' && event.event === 'llm.request',
);
expect(request?.args).toMatchObject({ thinkingEffort: 'on' });
expect(records).toContainEqual({
event: 'turn_started',
properties: expect.objectContaining({ turn_id: 0, thinking_effort: 'on' }),
});
expect(records).toContainEqual({
event: 'turn_ended',
properties: expect.objectContaining({ turn_id: 0, thinking_effort: 'on' }),
});
} finally {
await local.dispose();
}
});
it('attaches the latest request trace id to turn_ended', async () => {
const records: TelemetryRecord[] = [];
const local = createTestAgent({ telemetry: recordingTelemetry(records) });
try {
local.get(IAgentProfileService).update({ activeToolNames: [] });
local.mockNextProviderResponse({
parts: [{ type: 'text', text: 'hi' }],
traceId: 'trace-turn-1',
});
await local.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await local.untilTurnEnd();
expect(records).toContainEqual({
event: 'turn_ended',
properties: expect.objectContaining({
turn_id: 0,
reason: 'completed',
trace_id: 'trace-turn-1',
}),
});
} finally {
await local.dispose();
}
});
it('clears the ambient trace id when the turn ends', async () => {
const records: TelemetryRecord[] = [];
const local = createTestAgent({ telemetry: recordingTelemetry(records) });
try {
local.get(IAgentProfileService).update({ activeToolNames: [] });
local.mockNextProviderResponse({
parts: [{ type: 'text', text: 'hi' }],
traceId: 'trace-turn-clear',
});
await local.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await local.untilTurnEnd();
expect(local.get(ITelemetryService).getContext()['trace_id']).toBeUndefined();
} finally {
await local.dispose();
}
});
it('does not reuse the previous step trace when a step hook fails before a request', async () => {
const records: TelemetryRecord[] = [];
const local = createTestAgent({ telemetry: recordingTelemetry(records) });
try {
const localLoop = local.get(IAgentLoopService);
local.get(IAgentProfileService).update({ activeToolNames: [] });
localLoop.hooks.onDidFinishStep.register('test-continue-after-first-step', async (hookCtx, next) => {
if (hookCtx.step === 1) {
localLoop.notify();
return;
}
await next();
});
localLoop.hooks.onWillBeginStep.register('test-fail-before-second-request', async (hookCtx, next) => {
if (hookCtx.step === 2) throw new Error('before step failed');
await next();
});
local.mockNextProviderResponse({
parts: [{ type: 'text', text: 'first' }],
traceId: 'trace-step-1',
});
await local.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await local.untilTurnEnd();
expect(local.llmCalls).toHaveLength(1);
expect(records.find((record) => record.event === 'turn_interrupted')?.properties?.['trace_id']).toBeUndefined();
expect(records.find((record) => record.event === 'turn_ended')?.properties?.['trace_id']).toBeUndefined();
} finally {
await local.dispose();
}
});
it('emits turn_interrupted with interrupt_reason filtered and turn_ended failed', async () => {
const records: TelemetryRecord[] = [];
const local = createTestAgent({ telemetry: recordingTelemetry(records) });
try {
local.mockNextProviderResponse({
parts: [{ type: 'text', text: 'blocked' }],
finishReason: 'filtered',
traceId: 'trace-turn-2',
});
await local.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await local.untilTurnEnd();
expect(records).toContainEqual({
event: 'turn_interrupted',
properties: expect.objectContaining({
turn_id: 0,
at_step: 1,
mode: 'agent',
interrupt_reason: 'filtered',
provider_type: 'kimi',
protocol: 'openai',
trace_id: 'trace-turn-2',
}),
});
expect(records).toContainEqual({
event: 'turn_ended',
properties: expect.objectContaining({
turn_id: 0,
reason: 'failed',
mode: 'agent',
error_type: 'provider.filtered',
trace_id: 'trace-turn-2',
}),
});
} finally {
await local.dispose();
}
});
it('emits turn_ended with error_type for an uncoded failure', async () => {
const records: TelemetryRecord[] = [];
const local = createTestAgent({ telemetry: recordingTelemetry(records) });
try {
const workTool: ExecutableTool = {
name: 'Work',
description: 'Pretend to work.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
resolveExecution: () => ({
approvalRule: 'Work',
execute: async () => ({ output: 'should never run' }),
}),
};
local.get(IAgentToolRegistryService).register(workTool);
local.get(IAgentProfileService).update({ activeToolNames: ['Work'] });
const subscription = local.get(IAgentToolExecutorService).onBeforeExecuteTool(() => {
throw new Error('beforeExecute blew up');
});
local.mockNextResponse(
{ type: 'text', text: 'working' },
{ type: 'function', id: 'call-work-1', name: 'Work', arguments: '{}' },
);
await local.rpc.prompt({ input: [{ type: 'text', text: 'use the tool' }] });
await local.untilTurnEnd();
subscription.dispose();
expect(records).toContainEqual({
event: 'turn_ended',
properties: expect.objectContaining({
turn_id: 0,
reason: 'failed',
error_type: 'internal',
}),
});
} finally {
await local.dispose();
}
});
it.each([
['user_cancelled', () => userCancellationReason()],
['aborted', () => new Error('stop')],
] as const)(
'emits turn_interrupted with interrupt_reason %s on cancellation',
async (expected, makeReason) => {
const records: TelemetryRecord[] = [];
const local = createTestAgent({ telemetry: recordingTelemetry(records) });
try {
const localLoop = local.get(IAgentLoopService);
let stepStarted!: () => void;
const started = new Promise<void>((resolve) => {
stepStarted = resolve;
});
localLoop.hooks.onWillBeginStep.register('test-hang', async (hookCtx, next) => {
stepStarted();
await new Promise<void>((_, reject) => {
hookCtx.signal.addEventListener('abort', () => reject(hookCtx.signal.reason), {
once: true,
});
});
await next();
});
const turn = submitTurn(localLoop, 'hang').turn;
await started;
localLoop.cancel({ turnId: turn.id }, makeReason());
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
expect(records).toContainEqual({
event: 'turn_interrupted',
properties: expect.objectContaining({ turn_id: 0, interrupt_reason: expected, mode: 'agent' }),
});
expect(records).toContainEqual({
event: 'turn_ended',
properties: expect.objectContaining({ reason: 'cancelled' }),
});
} finally {
await local.dispose();
}
},
);
});
describe('interruption reminder', () => {
let ctx: TestAgentContext;
let loop: IAgentLoopService;
beforeEach(async () => {
ctx = createTestAgent();
loop = ctx.get(IAgentLoopService);
await ctx.restorePersisted();
});
afterEach(async () => {
try {
await ctx.expectResumeMatches();
} finally {
await ctx.dispose();
}
});
function cancelOnFirstDelta(): IDisposable {
return ctx.get(IEventBus).subscribe(AssistantDelta, () => {
loop.cancel();
});
}
function remindersIn(target: TestAgentContext): ContextMessage[] {
return target.contextData().history.filter(
(message) =>
message.origin?.kind === 'injection' && message.origin.variant === 'interruption',
);
}
function interruptionReminders(): ContextMessage[] {
return remindersIn(ctx);
}
function contentPartRecordsIn(target: TestAgentContext): number {
return target.allEvents.filter(
(entry) =>
entry.type === '[wire]' &&
entry.event === 'context.append_loop_event' &&
(entry.args as { event?: { type?: string } }).event?.type === 'content.part',
).length;
}
it('preserves the partial stream and appends one reminder at the cancellation event point', async () => {
ctx.mockNextResponse({ type: 'text', text: 'partial answer' }, { type: 'text', text: ' more' });
const subscription = cancelOnFirstDelta();
const turn = submitTurn(loop, 'Hello').turn;
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
subscription.dispose();
expect(ctx.contextData().history.slice(0, 2)).toEqual([
expect.objectContaining({ role: 'user', content: [{ type: 'text', text: 'Hello' }] }),
{
role: 'assistant',
content: [{ type: 'text', text: 'partial answer' }],
toolCalls: [],
partial: true,
},
]);
expect(interruptionReminders()).toHaveLength(1);
const cancelRecord = ctx.allEvents.find(
(entry) => entry.type === '[wire]' && entry.event === 'turn.cancel',
);
expect(cancelRecord?.args).toMatchObject({
turnId: 0,
target: 'active',
reason: 'user_cancelled',
});
const turnEnded = ctx.allEvents.find(
(entry) => entry.type === '[rpc]' && entry.event === 'turn.ended',
);
expect(turnEnded?.args).toMatchObject({
reason: 'cancelled',
interruptReason: 'user_cancelled',
});
expect(contentPartRecordsIn(ctx)).toBe(1);
ctx.mockNextResponse({ type: 'text', text: 'second answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Next' }] });
await ctx.untilTurnEnd();
expect(interruptionReminders()).toHaveLength(1);
expect(interruptionReminders()[0]!.content).toEqual([
{
type: 'text',
text: '<system-reminder>\nThe previous turn was interrupted by the user before completion; any partial output shown above is incomplete. The user\'s next message continues the conversation.\n</system-reminder>',
},
]);
expect(ctx.contextData().history.indexOf(interruptionReminders()[0]!)).toBe(2);
});
it('writes one active cancellation when cancel repeats before the turn settles', async () => {
ctx.mockNextResponse({ type: 'text', text: 'partial answer' }, { type: 'text', text: ' more' });
const results: boolean[] = [];
let cancelled = false;
const subscription = ctx.get(IEventBus).subscribe(AssistantDelta, () => {
if (cancelled) return;
cancelled = true;
results.push(loop.cancel(), loop.cancel());
});
const turn = submitTurn(loop, 'Hello').turn;
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
subscription.dispose();
expect(results).toEqual([true, true]);
expect(
ctx.allEvents.filter(
(entry) => entry.type === '[wire]' && entry.event === 'turn.cancel',
),
).toHaveLength(1);
ctx.mockNextResponse({ type: 'text', text: 'second answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Next' }] });
await ctx.untilTurnEnd();
expect(interruptionReminders()).toHaveLength(1);
});
it('preserves the partial stream but appends no reminder on programmatic abort', async () => {
ctx.mockNextResponse({ type: 'text', text: 'partial answer' }, { type: 'text', text: ' more' });
const subscription = ctx.get(IEventBus).subscribe(AssistantDelta, () => {
loop.cancel(undefined, new Error('stop'));
});
const turn = submitTurn(loop, 'Hello').turn;
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
subscription.dispose();
expect(ctx.contextData().history).toContainEqual({
role: 'assistant',
content: [{ type: 'text', text: 'partial answer' }],
toolCalls: [],
partial: true,
});
expect(interruptionReminders()).toHaveLength(0);
const cancelRecord = ctx.allEvents.find(
(entry) => entry.type === '[wire]' && entry.event === 'turn.cancel',
);
expect(cancelRecord?.args).toMatchObject({ target: 'active', reason: 'aborted' });
const turnEnded = ctx.allEvents.find(
(entry) => entry.type === '[rpc]' && entry.event === 'turn.ended',
);
expect(turnEnded?.args).toMatchObject({ reason: 'cancelled', interruptReason: 'aborted' });
});
it('does not stack a second reminder without an intervening message', async () => {
ctx.mockNextResponse({ type: 'text', text: 'partial answer' });
const subscription = cancelOnFirstDelta();
const turn = submitTurn(loop, 'Hello').turn;
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
subscription.dispose();
expect(interruptionReminders()).toHaveLength(1);
ctx.get(IEventBus).publish(
new TurnEnded({ agentId: 'main',
turnId: 99,
reason: 'cancelled',
interruptReason: 'user_cancelled',
}),
);
ctx.mockNextResponse({ type: 'text', text: 'second answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Next' }] });
await ctx.untilTurnEnd();
expect(interruptionReminders()).toHaveLength(1);
});
it('appends no reminder when a queued turn is user-cancelled before starting', async () => {
let release!: () => void;
let armed = true;
let signalEntered!: () => void;
const entered = new Promise<void>((resolve) => {
signalEntered = resolve;
});
loop.hooks.onWillBeginStep.register('test-hang-queued-cancel', async (hookCtx, next) => {
if (armed) {
armed = false;
signalEntered();
await new Promise<void>((resolve) => {
release = resolve;
});
}
await next();
});
ctx.mockNextResponse({ type: 'text', text: 'unreached' });
const active = submitTurn(loop, 'active').turn;
const queued = submitTurn(loop, 'queued').turn;
expect(queued.cancel()).toBe(true);
await expect(queued.result).resolves.toMatchObject({ type: 'cancelled', steps: 0 });
await entered;
release();
loop.cancel({ turnId: active.id });
await expect(active.result).resolves.toMatchObject({ type: 'cancelled' });
expect(interruptionReminders()).toHaveLength(1);
ctx.mockNextResponse({ type: 'text', text: 'second answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Next' }] });
await ctx.untilTurnEnd();
expect(interruptionReminders()).toHaveLength(1);
});
it('sends the partial output and reminder in the next atomic step', async () => {
ctx.mockNextResponse({ type: 'text', text: 'partial answer' }, { type: 'text', text: ' more' });
const subscription = cancelOnFirstDelta();
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await ctx.untilTurnEnd();
subscription.dispose();
ctx.llmInputs();
ctx.mockNextResponse({ type: 'text', text: 'second answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Next' }] });
await ctx.untilTurnEnd();
expect(ctx.lastLlmInput()).toMatchInlineSnapshot(`
messages:
<last>
assistant: text "partial answer"
user: text "<system-reminder>\\nThe previous turn was interrupted by the user before completion; any partial output shown above is incomplete. The user's next message continues the conversation.\\n</system-reminder>"
user: text "Next"
`);
});
it('undo removes the event-point interruption with its cancelled turn', async () => {
ctx.mockNextResponse({ type: 'text', text: 'partial answer' });
const subscription = cancelOnFirstDelta();
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Hello' }] });
await ctx.untilTurnEnd();
subscription.dispose();
expect(interruptionReminders()).toHaveLength(1);
await ctx.undoHistory(1);
expect(
ctx.contextData().history.map((message) => ({
role: message.role,
origin: message.origin,
})),
).toEqual([
{
role: 'user',
origin: { kind: 'injection', variant: 'interruption', ownerPromptId: undefined },
},
]);
ctx.mockNextResponse({ type: 'text', text: 'second answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Next' }] });
await ctx.untilTurnEnd();
expect(interruptionReminders()).toHaveLength(1);
});
it('drops unsigned thinking but keeps signed thinking on user cancel', async () => {
ctx.mockNextResponse({ type: 'think', think: 'pondering' }, { type: 'text', text: 'answer' });
const subscription = ctx.get(IEventBus).subscribe(ThinkingDelta, () => {
loop.cancel();
});
const turn = submitTurn(loop, 'Hello').turn;
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
subscription.dispose();
const thinkParts = ctx
.contextData()
.history.flatMap((message) => message.content)
.filter((part) => part.type === 'think');
expect(thinkParts).toEqual([]);
expect(interruptionReminders()).toHaveLength(1);
ctx.mockNextResponse(
{ type: 'think', think: 'seg', encrypted: 'sig' },
{ type: 'text', text: 'partial answer' },
);
const second = ctx.get(IEventBus).subscribe(AssistantDelta, () => {
loop.cancel();
});
const secondTurn = submitTurn(loop, 'Again').turn;
await expect(secondTurn.result).resolves.toMatchObject({ type: 'cancelled' });
second.dispose();
expect(ctx.contextData().history).toContainEqual({
role: 'assistant',
content: [
{ type: 'think', think: 'seg', encrypted: 'sig' },
{ type: 'text', text: 'partial answer' },
],
toolCalls: [],
partial: true,
});
});
it('records no partial content when the stream only produced whitespace', async () => {
ctx.mockNextResponse({ type: 'text', text: ' ' }, { type: 'text', text: 'answer' });
const subscription = cancelOnFirstDelta();
const turn = submitTurn(loop, 'Hello').turn;
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
subscription.dispose();
expect(contentPartRecordsIn(ctx)).toBe(0);
expect(ctx.contextData().history.slice(0, 2)).toEqual([
expect.objectContaining({ role: 'user' }),
{ role: 'assistant', content: [], toolCalls: [], partial: true },
]);
expect(interruptionReminders()).toHaveLength(1);
});
it('does not stack a second reminder around a vacuous retry turn', async () => {
ctx.mockNextResponse({ type: 'text', text: 'partial answer' });
const first = cancelOnFirstDelta();
const firstTurn = submitTurn(loop, 'Hello').turn;
await expect(firstTurn.result).resolves.toMatchObject({ type: 'cancelled' });
first.dispose();
expect(interruptionReminders()).toHaveLength(1);
ctx.mockNextResponse({ type: 'text', text: 'retried answer' });
const onStepStarted = ctx.get(IEventBus).subscribe(TurnStepStarted, () => {
loop.cancel();
});
const retryTurn = submitPromptTurn(loop, {
message: { role: 'user', content: [] },
meta: { origin: { kind: 'retry' } },
}).turn;
await expect(retryTurn.result).resolves.toMatchObject({ type: 'cancelled' });
onStepStarted.dispose();
expect(interruptionReminders()).toHaveLength(1);
ctx.mockNextResponse({ type: 'text', text: 'third answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'Next' }] });
await ctx.untilTurnEnd();
expect(interruptionReminders()).toHaveLength(1);
});
it('renders a new interruption reminder after an intervening completed turn', async () => {
ctx.mockNextResponse({ type: 'text', text: 'first partial answer' });
const first = cancelOnFirstDelta();
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'first prompt' }] });
await ctx.untilTurnEnd();
first.dispose();
ctx.mockNextResponse({ type: 'text', text: 'completed answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'completed prompt' }] });
await ctx.untilTurnEnd();
expect(interruptionReminders()).toHaveLength(1);
ctx.mockNextResponse({ type: 'text', text: 'second partial answer' });
const second = cancelOnFirstDelta();
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'second prompt' }] });
await ctx.untilTurnEnd();
second.dispose();
ctx.mockNextResponse({ type: 'text', text: 'final answer' });
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'final prompt' }] });
await ctx.untilTurnEnd();
expect(interruptionReminders()).toHaveLength(2);
});
it('does not duplicate recorded content when cancelled during tool execution', async () => {
const local = createTestAgent(permissionModeServices('yolo'));
const releaseSlowTool = deferred();
try {
const slowToolStarted = registerAbortableWorkTool(local, releaseSlowTool.promise);
const localLoop = local.get(IAgentLoopService);
local.mockNextResponse(
{ type: 'text', text: 'working' },
{ type: 'function', id: 'call-work-1', name: 'Work', arguments: '{}' },
);
local.mockNextResponse(
{ type: 'text', text: 'still working' },
{ type: 'function', id: 'call-work-2', name: 'Work', arguments: '{}' },
);
const turn = submitTurn(localLoop, 'do work').turn;
await slowToolStarted.promise;
localLoop.cancel({ turnId: turn.id });
localLoop.cancel({ turnId: turn.id });
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled' });
expect(contentPartRecordsIn(local)).toBe(2);
expect(remindersIn(local)).toHaveLength(1);
const loopEvents = local.allEvents
.filter((entry) => entry.type === '[wire]' && entry.event === 'context.append_loop_event')
.map((entry) => (entry.args as { event: LoopRecordedEvent }).event);
const toolCalls = loopEvents.filter((event) => event.type === 'tool.call');
const toolResults = loopEvents.filter((event) => event.type === 'tool.result');
for (const call of toolCalls) {
expect(
toolResults.some(
(result) => result.toolCallId === call.toolCallId && result.parentUuid === call.uuid,
),
).toBe(true);
}
expect(toolResults.filter((event) => event.toolCallId === 'call-work-2')).toEqual([
expect.objectContaining({
result: {
output:
'The user manually interrupted "Work" (and anything else running at the same time). This was a deliberate user action, not a system error, timeout, or capacity limit. Do not retry automatically or guess at the cause — wait for the user\'s next instruction.',
isError: true,
},
}),
]);
local.mockNextResponse({ type: 'text', text: 'follow-up answer' });
await local.rpc.prompt({ input: [{ type: 'text', text: 'again' }] });
await local.untilTurnEnd();
const history = local.contextData().history;
expect(remindersIn(local)).toHaveLength(1);
const reminderIndex = history.indexOf(remindersIn(local)[0]!);
expect(history.slice(0, reminderIndex).some((message) => message.role === 'tool')).toBe(true);
expect(history[reminderIndex + 1]).toMatchObject({
role: 'user',
content: [{ type: 'text', text: 'again' }],
});
await local.expectResumeMatches();
} finally {
releaseSlowTool.resolve();
await local.dispose();
}
});
});
describe('step timing split propagation', () => {
it('carries the split from the llmRequester timing event to the turn.step.completed protocol event', async () => {
const ctx = createTestAgent(agentService(IAgentLLMRequesterService, createTimingRequester()));
try {
await ctx.rpc.prompt({ input: [{ type: 'text', text: 'hello' }] });
await ctx.untilTurnEnd();
const stepCompleted = ctx.allEvents.find(
(event) => event.type === '[rpc]' && event.event === 'turn.step.completed',
);
expect(stepCompleted?.args).toMatchObject({
llmFirstTokenLatencyMs: 100,
llmStreamDurationMs: 200,
llmRequestBuildMs: 30,
llmServerFirstTokenMs: 70,
llmServerDecodeMs: 150,
llmClientConsumeMs: 50,
llmClientBlockedMs: 20,
});
} finally {
await ctx.dispose();
}
});
});
describe('aborted step tool execution', () => {
it('accounts model usage when the step is aborted during tool execution', async () => {
const ctx = createTestAgent(
{ generate: createAbortedStepGenerate() },
permissionModeServices('yolo'),
);
await ctx.restorePersisted();
try {
const slowToolStarted = registerAbortableWorkTool(ctx);
const goals = ctx.get(IAgentGoalService);
await goals.createGoal({ objective: 'finish the task' });
await goals.setBudgetLimits({ budgetLimits: { tokenBudget: 60 } });
ctx.get(IEventBus).publish(new TurnStarted({ agentId: 'main', turnId: 1, origin: { kind: 'user' } }));
const loopService = ctx.get(IAgentLoopService);
const { turn } = submitTurn(loopService, 'work');
await slowToolStarted.promise;
turn.cancel(new Error('cancelled by test'));
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled', steps: 2 });
expect(ctx.usage.status()).toMatchObject({
total: {
inputOther: 107,
output: 61,
inputCacheRead: 0,
inputCacheCreation: 0,
},
currentTurn: {
inputOther: 107,
output: 61,
inputCacheRead: 0,
inputCacheCreation: 0,
},
});
expect(goals.getGoal().goal).toMatchObject({
status: 'blocked',
tokensUsed: 61,
budget: { tokenBudgetReached: true },
});
} finally {
await ctx.dispose();
}
});
it('includes the programmatic abort reason when a tool execution is interrupted', async () => {
const ctx = createTestAgent(
{ generate: createAbortedStepGenerate() },
permissionModeServices('yolo'),
);
let interrupted: { readonly reason: string; readonly message?: string } | undefined;
const subscription = ctx
.get(IEventBus)
.subscribe(TurnStepInterrupted, (event) => {
interrupted = event;
});
try {
const slowToolStarted = registerAbortableWorkTool(ctx);
const loopService = ctx.get(IAgentLoopService);
const { turn } = submitTurn(loopService, 'work');
await slowToolStarted.promise;
turn.cancel(new Error('Tool execution timed out'));
await expect(turn.result).resolves.toMatchObject({ type: 'cancelled', steps: 2 });
expect(interrupted).toMatchObject({
reason: 'aborted',
message: 'Tool execution timed out',
});
} finally {
subscription.dispose();
await ctx.dispose();
}
});
it('settles a message-less notification when credential resolution rejects before the first request', async () => {
const rejectingCredentials = () => ({
resolve: () => Promise.reject(new Error('OAuth login required')),
});
const requester: IAgentLLMRequesterService = {
_serviceBrand: undefined,
prepareTurnConfig: () => ({ thinkingEffort: 'off' }),
currentCredentialProvider: rejectingCredentials,
credentialProviderForTurn: rejectingCredentials,
async request() {
throw new Error('request must not run');
},
start() {
throw new Error('request must not run');
},
};
const ctx = createTestAgent(agentService(IAgentLLMRequesterService, requester));
try {
const loopService = ctx.get(IAgentLoopService);
const handle = loopService.notify();
await loopService.settled();
expect(handle.dropped).toBe(false);
} finally {
await ctx.dispose();
}
});
});
function submitTurn(loop: IAgentLoopService, text: string): { readonly turn: Turn } {
return submitPromptTurn(loop, {
message: { role: 'user', content: [{ type: 'text', text }] },
meta: { origin: { kind: 'user' } },
});
}
function parkedLifecycleStub(): IAgentLifecycleService {
return {
_serviceBrand: undefined,
onDidCreate: Event.None as Event<AgentContext>,
onDidCreateScope: Event.None as Event<AgentScopeCreatedEvent>,
onWillClose: Event.None as Event<AgentContext>,
onDidClose: Event.None as Event<AgentContext>,
create: () => Promise.reject(new Error('parked lifecycle stub')),
fork: () => Promise.reject(new Error('parked lifecycle stub')),
get: () => undefined,
list: () => [],
broadcastPermissionMode: () => {},
remove: () => Promise.resolve(),
handleOf: () => undefined,
adopt: (handle) => agentContextOf(handle),
};
}
function attachParkedEngine(loop: IAgentLoopService) {
const bundle = loop.buildAttachBundle();
const ref = createActor(createAgentMachine({}), {
input: {
request: bundle.request,
scopeFactory: () =>
Promise.resolve({
store: bundle.store,
turnLogic: bundle.turnLogic,
toolLogic: bundle.toolLogic,
tools: bundle.tools,
request: bundle.request,
}),
},
});
ref.start();
loop.attachEngine(ref, bundle);
return ref;
}
function createTimingRequester(): IAgentLLMRequesterService {
const timing: ModelRequestTiming = {
firstTokenLatencyMs: 100,
streamDurationMs: 200,
requestBuildMs: 30,
serverFirstTokenMs: 70,
serverDecodeMs: 150,
clientConsumeMs: 50,
clientBlockedMs: 20,
};
const requester: IAgentLLMRequesterService = {
_serviceBrand: undefined,
prepareTurnConfig: () => ({ thinkingEffort: 'off' }),
currentCredentialProvider: () => undefined,
credentialProviderForTurn: () => undefined,
async request(_overrides, onPart = () => {}) {
await onPart({ type: 'text', text: 'answer' });
return {
message: {
role: 'assistant',
content: [{ type: 'text', text: 'answer' }],
toolCalls: [],
},
usage: emptyUsage(),
model: 'mock-model',
timing,
};
},
start(overrides, onPart, signal) {
return { trace: { traceId: undefined }, result: this.request(overrides, onPart, signal) };
},
};
return requester;
}
function createAbortedStepGenerate(): GenerateFn {
const usages = [
{ inputOther: 100, output: 50, inputCacheRead: 0, inputCacheCreation: 0 },
{ inputOther: 7, output: 11, inputCacheRead: 0, inputCacheCreation: 0 },
];
let requestIndex = 0;
return requesterFromGenerateFn(async () => {
const usage = usages[requestIndex];
if (usage === undefined) throw new Error('Unexpected model request');
requestIndex += 1;
return {
id: `response-${String(requestIndex)}`,
message: {
role: 'assistant',
content: [],
toolCalls: [
{
type: 'function',
id: `call-work-${String(requestIndex)}`,
name: 'Work',
arguments: '{}',
},
],
},
usage,
finishReason: 'tool_calls',
rawFinishReason: 'tool_calls',
};
});
}
function registerAbortableWorkTool(
ctx: TestAgentContext,
ignoreAbortGate?: Promise<void>,
): ReturnType<typeof deferred> {
const slowToolStarted = deferred();
let executions = 0;
const tool: ExecutableTool = {
name: 'Work',
description: 'Run one fast operation and one cancellable operation.',
parameters: { type: 'object', properties: {}, additionalProperties: false },
resolveExecution: () => ({
approvalRule: 'Work',
accesses: [],
execute: async ({ signal }) => {
executions += 1;
if (executions === 1) return { output: 'first step complete' };
slowToolStarted.resolve();
if (ignoreAbortGate !== undefined) {
await ignoreAbortGate;
return { output: 'second step late result' };
}
if (!signal.aborted) {
await new Promise<void>((resolve) => {
signal.addEventListener(
'abort',
() => {
resolve();
},
{ once: true },
);
});
}
return { output: 'second step cancelled' };
},
}),
};
ctx.get(IAgentProfileService).update({ activeToolNames: ['Work'] });
ctx.get(IAgentToolRegistryService).register(tool);
return slowToolStarted;
}
function deferred(): { readonly promise: Promise<void>; readonly resolve: () => void } {
let resolve!: () => void;
const promise = new Promise<void>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
}
|