File size: 147,016 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 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 | # Server API
The local server started by `kimi web` exposes two programmatic surfaces: a REST API (`/api/v1`, plus `/api/v2/sessions` and `/api/v2/mcp`) and a WebSocket event stream (`/api/v1/ws`). This page is the protocol reference for both. For how to start the server and its command-line options, see the [kimi command](./kimi-command.md#kimi-web) reference; for an end-to-end walkthrough, see [Drive a session over the API](#drive-a-session-over-the-api) below.
This page is a curated, human-readable reference: it documents every endpoint's parameters, request bodies, and response shapes below. The precise machine-readable schema of every endpoint is owned by the server's live specification documents: `GET /openapi.json` (OpenAPI) and `GET /asyncapi.json` (AsyncAPI), both generated from the same validation schemas the server enforces at runtime. Both require authentication; when this page and the live spec ever disagree, the live spec wins.
::: warning
The REST and WebSocket APIs described on this page are experimental: interface stability is not guaranteed, and endpoints, fields, and event types may change in any release. When integrating, rely on the `/openapi.json` and `/asyncapi.json` documents served by your version.
:::
## Conventions
### Address
The default address is `http://127.0.0.1:58627`. When the port is taken, the server retries with the next port (up to 100 times); use `--port` / `--host` to change the bind. Multiple instances can coexist under the same home directory; running instances register under `~/.kimi-code/server/instances/`.
### Authentication
All `/api/*` paths (including `/openapi.json` and `/asyncapi.json`) require the bearer token, except:
- `OPTIONS` preflight requests
- `GET /api/v1/healthz` (liveness probe)
- Static web assets (non-`/api/` paths)
How to carry it: REST uses the `Authorization: Bearer <token>` header; the WebSocket upgrade accepts the same header or the subprotocol `kimi-code.bearer.<token>`. Token generation and rotation are covered in [Using Kimi Code in the browser: Getting started](../guides/web.md#getting-started).
Failed authentication returns HTTP 401 with envelope code `40101`. On non-loopback binds, a source that fails authentication 10 times within 60 seconds is banned for 60 seconds, during which every request gets HTTP 429 (code `42901`).
### Response envelope
Every JSON response is wrapped in a uniform envelope:
```json
{
"code": 0,
"msg": "success",
"data": {},
"request_id": "01JZX4A6E7M8V0R3Q0N2K2M5Q9"
}
```
- `code`: the business outcome; `0` means success. See the error-code bands below.
- `data`: the payload on success. Note that some "error" envelopes also carry a non-null `data` β for example, resolving an already-resolved approval returns `40902` with `data.resolved` set to `false` β so clients should check `code` first, then `data`.
- `request_id`: a ULID for this request. Clients may supply one via the `X-Request-Id` header; invalid values are regenerated by the server.
The HTTP status is almost always 200; the business outcome lives in `code`. Exceptions:
| Situation | HTTP status |
| --- | --- |
| Authentication failure / rate limit | 401 / 429 |
| Provider created, provider catalog imported | 201 |
| Provider deleted | 204 |
| Binary/streaming endpoints | 206 (Range) / 304 (ETag unchanged) where supported β capabilities differ per endpoint, see [Binary and streaming endpoints](#binary-and-streaming-endpoints) |
| `GET /api/v1/files/{file_id}` download errors | real 404 / 500 (still carrying an envelope body) |
The 201 responses still carry the standard envelope (`code` 0) β only the status line follows the REST convention for resource creation. A 204 response has no body by definition, so a successful delete is reported by the status code itself.
### Error codes
Error codes are grouped by band:
| Band | Meaning | Examples |
| --- | --- | --- |
| `0` | Success | |
| `400xx` | Bad request | `40001` validation failed (`details` lists each field), `40003` provider is OAuth-managed |
| `401xx` | Auth and readiness | `40101` unauthorized, `40110` no provider configured, `40113` model not resolved |
| `404xx` | Not found | `40401` session, `40408` MCP server, `40409` file path |
| `409xx` | State conflict | `40901` session busy, `40902` approval already resolved, `40922` page conditions mismatch `page_token` |
| `410xx` | Expired | `41001` approval timed out, `41002` question timed out, `41003` temporary file expired |
| `413xx` | Size or boundary exceeded | `41302` file read over 10 MB, `41304` path escapes the session directory |
| `429xx` | Rate limited | `42901` auth-failure ban, `42902` too many fs watches |
| `500xx` | Server internal error | `50001` uncaught exception, `50003` persistence failure |
| `6xxxx` / `7xxxx` / `8xxxx` | Tool runtime / LLM provider / MCP passthrough errors; `msg` carries the upstream text | |
### Pagination
List endpoints come in two styles:
- **Cursor style**: `before_id` / `after_id` (mutually exclusive) plus `page_size` (1β100), responding with `{ items, has_more }`. Used by the session list, message list, transcript, and others.
- **`page_token`**: an opaque token (bound to a fingerprint of the query conditions), used by `POST /api/v1/search` and `GET /api/v2/sessions`. Changing any query condition mid-pagination invalidates the token: v2 returns `40922`, search returns `40001`. `GET /api/v2/sessions` also offers a stateless `page` page-number mode as an alternative.
## Drive a session over the API
The minimal flow with curl: check the server β create a session β subscribe to events β submit a prompt β read history back. The examples assume the server runs at the default address and the token is stored in the shell variable `TOKEN`.
1. Check server status:
```sh
curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:58627/api/v1/meta
```
Every JSON response is wrapped in a uniform envelope β `{ "code": 0, "msg": "success", "data": ..., "request_id": "..." }`. The business outcome lives in `code` (`0` means success); the HTTP status only reports transport-level results.
2. Create a session; `metadata.cwd` sets the working directory:
```sh
curl -s -X POST http://127.0.0.1:58627/api/v1/sessions \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"metadata": {"cwd": "/path/to/project"}}'
```
The returned `data.id` (shaped like `session_...`) is the session id used by every subsequent request.
3. Connect to the WebSocket and subscribe to session events. Any WebSocket client works; below is a dependency-free Node.js script (Node.js 22+ ships a built-in `WebSocket` client):
```js
// subscribe.mjs β usage: TOKEN=... node subscribe.mjs session_...
const ws = new WebSocket('ws://127.0.0.1:58627/api/v1/ws', [
`kimi-code.bearer.${process.env.TOKEN}`,
]);
ws.onmessage = (e) => console.log(e.data);
ws.onopen = () =>
ws.send(
JSON.stringify({
type: 'subscribe',
id: '1',
payload: { session_ids: [process.argv[2]] },
}),
);
```
4. Submit a prompt:
```sh
curl -s -X POST http://127.0.0.1:58627/api/v1/sessions/<session_id>/prompts \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"content": [{"type": "text", "text": "Introduce this repository in one sentence"}]}'
```
The subscriber sees, in order: `turn.started` (turn begins) β `assistant.delta` (streaming text increments) β `tool.call.started` / `tool.result` when tool calls happen β `turn.ended` (turn finishes).
5. Read history back over REST at any time:
```sh
curl -s -H "Authorization: Bearer $TOKEN" \
"http://127.0.0.1:58627/api/v1/sessions/<session_id>/messages?page_size=20"
```
## REST endpoints
Endpoints are grouped by resource below. A `:{action}` suffix in a path is the action convention β POST to `path:action` on a single resource for non-CRUD operations (such as `:fork` and `:archive` on a session).
### Server and metadata
| Method and path | Description |
| --- | --- |
| `GET /api/v1/healthz` | Liveness probe; auth-exempt |
| `GET /api/v1/meta` | Server version, capability map, `server_id`, experimental flags |
| `POST /api/v1/shutdown` | Graceful shutdown (replies 200 first); mounted only on loopback binds |
#### `GET /api/v1/healthz`
Liveness probe for scripts and process supervisors. It is the one `/api` endpoint exempt from the bearer token (see [Authentication](#authentication)) and answers without touching config or the engine.
On success, `data` is `{ "ok": true }`.
#### `GET /api/v1/meta`
Returns this instance's identity and capability map. Most fields are frozen at boot; `experimental_flags` and `features` are resolved per request, so a flag flip or a failed feature shows up in the next response.
On success, `data` carries:
| Field | Type | Description |
| --- | --- | --- |
| `server_version` | string | Server version |
| `capabilities` | object | Capability map β `websocket`, `file_upload`, `fs_query`, `mcp`, `tasks`, `terminal`, all always `true` |
| `server_id` | string | Unique id of this server instance |
| `started_at` | string | Boot time, ISO 8601 |
| `open_in_apps` | array | Host apps usable as `open-in` targets (`finder` / `cursor` / `vscode` / `iterm` / `terminal`); currently always empty |
| `dangerous_bypass_auth` | boolean | Whether the server was started with `--dangerous-bypass-auth` (clients may skip the token prompt) |
| `backend` | string | Engine backend, `v1` or `v2`; always `v2` for this server |
| `web_title` | string | Custom browser tab title from `--web-title`; omitted when unset |
| `experimental_flags` | object | Experimental flag id β enabled, resolved at request time |
| `features` | array | Engine features as `{ name, state, meta }`; `state` is `Pending` / `Activating` / `Active` / `Unloading` / `Failed` |
#### `POST /api/v1/shutdown`
Asks the server to shut down gracefully. The reply is sent first and the shutdown runs immediately after, so the caller can trust the response it received. The route is mounted only on loopback binds β on a non-loopback bind it is not registered at all (requests hit a 404) unless the server was started with `--allow-remote-shutdown`.
On success, `data` is `{ "ok": true }`.
### Login and usage
These endpoints drive the managed Kimi OAuth login lifecycle and expose account-level information. The managed provider is named `managed:kimi-code`; the optional `provider` parameter on every endpoint below defaults to it.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/auth` | Auth snapshot |
| `POST /api/v1/oauth/login` | Start the OAuth device-code login flow |
| `GET /api/v1/oauth/login` | Poll the login flow state |
| `DELETE /api/v1/oauth/login` | Cancel a pending login flow |
| `POST /api/v1/oauth/logout` | Log out the managed provider |
| `GET /api/v1/oauth/usage` | Plan quota and booster wallet |
| `GET /api/v1/oauth/userinfo` | Account profile |
| `GET /api/v1/oauth/region` | Resolve the client region (`mainland-cn` / `global`) |
#### `GET /api/v1/auth`
Auth snapshot: whether the default model resolves to a usable provider configuration, plus the managed provider's login state. `models_ready` is `true` when the global `default_model` alias exists in the model table and resolves to a configured provider β including providerless flat models carrying their own `base_url` and models injected through `KIMI_MODEL_*` environment variables. It does not verify credentials, so a prompt can still fail afterwards with `40111` / `40112`.
On success, `data` carries `models_ready` (boolean), `providers_count` (number of configured providers), and `managed_provider` (`null`, or `{ name, status }` with `status` one of `authenticated` / `expired` / `revoked` / `unauthenticated`). The global default model alias itself is read from `GET /api/v1/config` (`default_model`), not from this endpoint.
#### `POST /api/v1/oauth/login`
Starts an OAuth device-code login flow for the managed provider; starting a new flow aborts any pending flow for the same provider. When the account is already authenticated, no user interaction is needed and the response reports `authenticated` immediately.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider` | body | string | Managed provider name. Default `managed:kimi-code` |
| `region` | body | string | `mainland-cn` or `global`; overrides the region resolution described under `GET /api/v1/oauth/region` for this flow |
On success, `data` has one of two shapes. A pending flow β `{ flow_id, provider, status: "pending", verification_uri, verification_uri_complete, user_code, expires_in, interval, expires_at }`: open `verification_uri_complete` (or `verification_uri` and enter `user_code`), then poll `GET /api/v1/oauth/login` every `interval` seconds until the flow resolves or `expires_at` passes (`expires_in` is the same deadline in seconds). The already-authenticated fast path β `{ flow_id, provider, status: "authenticated" }`.
#### `GET /api/v1/oauth/login`
Polls the login flow state for a provider. Returns `null` when no flow has been started.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider` | query | string | Managed provider name. Default `managed:kimi-code` |
On success, `data` is `null` or a flow snapshot: `{ flow_id, provider, status, verification_uri, verification_uri_complete, user_code, expires_in, expires_at, interval }`, where `status` is `pending` / `authenticated` / `denied` / `expired` / `cancelled`. Once the flow leaves `pending`, `resolved_at` records when it reached its terminal state and `error_message` describes a failed flow.
#### `DELETE /api/v1/oauth/login`
Cancels the pending login flow for a provider. When no flow is pending, the call is a no-op that reports the last known state.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider` | query | string | Managed provider name. Default `managed:kimi-code` |
On success, `data` is `{ cancelled, status }`: `cancelled` is `true` only when a `pending` flow was actually aborted, and `status` is the flow state after the call.
#### `POST /api/v1/oauth/logout`
Logs out the managed provider: discards the stored OAuth credential, aborts any pending login flow, and removes the managed provider from the configuration. OAuth-managed providers reject manual edit and delete (see `PUT` / `DELETE /api/v1/providers/{provider_id}` below), so log out first to remove one.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider` | body | string | Managed provider name. Default `managed:kimi-code` |
On success, `data` is `{ logged_out: true, provider }`.
#### `GET /api/v1/oauth/usage`
Plan quota and booster wallet of the managed account, fetched live from the account service. An upstream failure does not fail the envelope β it comes back in-band with `kind: "error"`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider` | query | string | Managed provider name. Default `managed:kimi-code` |
On success, `data` is `{ kind: "ok", quota }` or `{ kind: "error", message, status? }`, where `status` is the upstream HTTP status when one exists. In the `ok` shape, `quota` is `{ usages, extraUsage }`: `usages` carries one `{ usedRatio, resetAt? }` entry per quota window the account has β `limit5h`, `limit7d`, `monthTotal`, `monthCode` β with `usedRatio` as a 0β1 float and `resetAt` as an RFC3339 reset timestamp, and clients render whichever entries are present; `extraUsage` (nullable) is the pay-as-you-go wallet: `{ balanceCents, totalCents, monthlyChargeLimitEnabled, monthlyChargeLimitCents, monthlyUsedCents, currency }`.
#### `GET /api/v1/oauth/userinfo`
Profile of the managed account, with the same in-band `kind: "error"` convention as `GET /api/v1/oauth/usage`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider` | query | string | Managed provider name. Default `managed:kimi-code` |
On success, `data` is `{ kind: "ok", userInfo }` or `{ kind: "error", message, status? }`. `userInfo` always carries `userId`, `nickname`, `status`, `region`, `userLevel`, `userLevelName`, `domain`, and `domainName`, and may add `globalId`, `bio`, `avatar`, `username`, `email`, `phone` (`{ countryCode, number }`), `createdTime`, and `lastLoginTime`.
#### `GET /api/v1/oauth/region`
Resolves which Kimi region this client belongs to. The answer is derived locally, not probed over the network: an OAuth host pinned by environment or config wins first, then the configured OAuth key, then the region marker file in the home directory; the default is `mainland-cn`.
On success, `data` is `{ region }` with `region` one of `mainland-cn` / `global`.
### Config
| Method and path | Description |
| --- | --- |
| `GET /api/v1/config` | Read the global config (secret fields redacted) |
| `POST /api/v1/config` | Merge-patch the config; broadcasts `event.config.changed` |
#### `GET /api/v1/config`
Returns the resolved global configuration β the effective result of `config.toml` plus overlays. Secrets are redacted: each provider reports only `has_api_key`, never the stored key.
On success, `data` is the config object; its fields mirror the top-level domains documented under [Top-level fields](../configuration/config-files.md#top-level-fields):
| Field | Type | Description |
| --- | --- | --- |
| `providers` | object | Map of provider id β `{ type, base_url?, default_model?, has_api_key }` |
| `default_provider` | string | Global default provider id |
| `default_model` | string | Global default model alias |
| `models` | object | Map of model alias β model record |
| `thinking` | object | Default parameters for Thinking mode |
| `plan_mode` | boolean | Plan mode flag |
| `yolo` | boolean | Derived: `true` when `default_permission_mode` is `yolo` |
| `default_permission_mode` | string | Default permission mode for new sessions |
| `default_plan_mode` | boolean | Whether new sessions start in Plan mode |
| `permission` | object | Initial permission rules |
| `hooks` | array | Lifecycle hooks |
| `services` | object | Built-in external service configuration |
| `merge_all_available_skills` | boolean | Whether to merge Agent Skills from all available directories |
| `extra_skill_dirs` | array | Extra skill search directories |
| `loop_control` | object | Agent loop control parameters |
| `background` | object | Background task runtime parameters |
| `subagent` | object | Subagent configuration |
| `secondary_model` | object | Secondary model pool for subagents |
| `experimental` | object | Experimental flag id β enabled |
| `telemetry` | boolean | Whether anonymous telemetry is enabled |
| `raw` | object | Raw parsed `config.toml` content, unmodeled fields included |
#### `POST /api/v1/config`
Merge-patches the global configuration: each top-level domain in the body is deep-merged into that domain, and domains absent from the body are left untouched. Setting `yolo` to `true` is shorthand for `default_permission_mode: "yolo"`; a rejected patch (invalid value or persistence failure) returns `40001` with the underlying message.
Every config change β a successful update through this endpoint, an external edit of `config.toml`, or a server-side write such as an OAuth login refresh β is broadcast as the global `event.config.changed` event. Changes inside a short window are merged into one event carrying the affected domain names in `changedFields` (camelCase config domains, for example `defaultModel`) and the full current config projection in `config` (same shape as the `GET /api/v1/config` response).
The body is a partial config object β any subset of the response domains above except `raw`, all optional:
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `providers` | body | object | Map of provider id β provider table |
| `default_provider` | body | string | Global default provider id |
| `default_model` | body | string | Global default model alias |
| `models` | body | object | Map of model alias β model record |
| `thinking` | body | object | Default parameters for Thinking mode |
| `plan_mode` | body | boolean | Plan mode flag |
| `yolo` | body | boolean | `true` maps to `default_permission_mode: "yolo"`; `false` is ignored |
| `default_permission_mode` | body | string | `manual` / `yolo` / `auto` |
| `default_plan_mode` | body | boolean | Whether new sessions start in Plan mode |
| `permission` | body | object | Initial permission rules |
| `hooks` | body | array | Lifecycle hooks |
| `services` | body | object | Built-in external service configuration |
| `merge_all_available_skills` | body | boolean | Whether to merge Agent Skills from all available directories |
| `extra_skill_dirs` | body | array | Extra skill search directories |
| `loop_control` | body | object | Agent loop control parameters |
| `background` | body | object | Background task runtime parameters |
| `subagent` | body | object | Subagent configuration |
| `secondary_model` | body | object | Secondary model pool for subagents |
| `experimental` | body | object | Experimental flag id β enabled |
| `telemetry` | body | boolean | Whether anonymous telemetry is enabled |
On success, `data` is the full updated config in the same shape as `GET /api/v1/config`.
### Models and providers
These endpoints manage the two halves of model configuration β the [providers](../configuration/providers.md) table and the model-alias table of `config.toml` β plus a server-proxied models.dev directory for one-shot imports. A model alias id is the exact configured alias key: aliases created through the provider-management endpoints take the form `provider_id/model` (for example `my-provider/kimi-for-coding`), while a bare model-table key such as `turbo` is used as-is; anywhere the API takes a `model_id`, including the global `default_model`, it means this alias id. An unsupported action on a `:{action}` route returns `40001`.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/models` | List configured model aliases |
| `POST /api/v1/models/{model_id}:set_default` | Set the global default model |
| `GET /api/v1/providers` | List providers |
| `POST /api/v1/providers` | Create a provider (201) |
| `GET /api/v1/providers/{provider_id}` | Read a provider (reveals the stored key) |
| `PUT /api/v1/providers/{provider_id}` | Replace a provider |
| `DELETE /api/v1/providers/{provider_id}` | Delete a provider (204) |
| `POST /api/v1/providers/{provider_id}:refresh` | Refresh one provider's model metadata |
| `POST /api/v1/providers:{action}` | Collection actions: `refresh` / `refresh_oauth` / `import_catalog` / `import_registry` |
| `GET /api/v1/catalog/providers` | Browse the models.dev directory (server-proxied) |
| `GET /api/v1/catalog/providers/{catalog_id}` | Read one directory entry |
#### `GET /api/v1/models`
Lists every configured model alias across all providers.
On success, `data.items` is an array of `{ provider, model, display_name?, max_context_size, capabilities?, support_efforts?, default_effort? }`: `model` is the alias id (`provider_id/model` for provider-managed aliases, otherwise the bare key), `provider` the owning provider id, `max_context_size` the context window in tokens, and `capabilities` / `support_efforts` / `default_effort` describe capability flags and Thinking-mode effort support.
#### `POST /api/v1/models/{model_id}:set_default`
Sets the global `default_model` to an existing alias. `model_id` is the exact configured alias key β for a bare key like `turbo` the call is `POST /api/v1/models/turbo:set_default`; URL-encode the id when it contains `/`, as in `POST /api/v1/models/my-provider%2Fkimi-for-coding:set_default`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `model_id` | path | string | **Required.** The exact configured model alias key; URL-encode it when it contains `/` |
On success, `data` is `{ default_model, model }` β the alias now in effect and its catalog item (same shape as a `GET /api/v1/models` item).
- `40001`: malformed or unsupported action suffix in the path
- `40413`: no model alias with that id
#### `GET /api/v1/providers`
Lists every configured provider with its credential and model-discovery state, without revealing any key. This is the provider item shape referenced by the other provider endpoints.
On success, `data.items` is an array of:
| Field | Type | Description |
| --- | --- | --- |
| `id` | string | Provider id |
| `type` | string | Wire protocol: `kimi` / `openai` / `openai_responses` / `anthropic` / `google-genai` / `vertexai` |
| `base_url` | string | API base URL, when set |
| `default_model` | string | The provider's default model alias, when set |
| `has_api_key` | boolean | Whether a credential is stored |
| `status` | string | `connected` when an API key or cached OAuth token exists, `unconfigured` otherwise (`error` is reserved in the schema) |
| `models` | array | The provider's model alias ids |
#### `POST /api/v1/providers`
Creates a provider and its model aliases in one save; the reply is HTTP 201 with the standard envelope. When no global `default_model` is configured at all (fresh setup), it is seeded with the new provider's `default_model` (or first model); an existing default is never modified.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `id` | body | string | **Required.** Provider id β letters, digits, `-`, `_`, and spaces; must start with a letter or digit |
| `type` | body | string | **Required.** Wire protocol: `kimi` / `openai` / `openai_responses` / `anthropic` / `google-genai` / `vertexai` |
| `api_key` | body | string | API key, stored in `config.toml` |
| `base_url` | body | string | API base URL; must not contain an environment variable placeholder (`${...}`) |
| `default_model` | body | string | The provider's default model; must be one of `models[].model` |
| `models` | body | array | **Required.** At least one entry, no duplicate `model` values; entry shape below |
Each `models[]` entry declares one alias whose id becomes `id/model`:
| Field | Type | Description |
| --- | --- | --- |
| `model` | string | **Required.** Upstream model name |
| `max_context_size` | integer | **Required.** Context window in tokens, β₯ 1 |
| `display_name` | string | Display name |
| `capabilities` | array | Capability flags such as `thinking` or `image_in` |
| `max_output_size` | integer | Max output tokens, β₯ 1 |
| `support_efforts` | array | Supported Thinking-mode effort levels |
| `adaptive_thinking` | boolean | Adaptive thinking toggle |
On success, `data` is the created provider item (same shape as a `GET /api/v1/providers` item).
- `40921`: a provider with this `id` already exists
#### `GET /api/v1/providers/{provider_id}`
Reads one provider. Unlike the list route, the response reveals the stored `api_key` when one is set, so a local edit form can prefill β keep this in mind when exposing the port.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider_id` | path | string | **Required.** Provider id |
On success, `data` is the provider item plus `api_key` when a key is stored.
- `40412`: provider not found
#### `PUT /api/v1/providers/{provider_id}`
Replaces a provider in one save: `type`, `base_url`, and the model list are rewritten, and the provider's aliases are rebuilt from `models` β aliases no longer listed disappear from `config.toml`, while other providers' aliases are untouched. `api_key` is tri-state: omitted keeps the stored key, `""` clears it, any other value replaces it. Beyond the `new_id` rename migration, the global default pointers are never modified.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider_id` | path | string | **Required.** Current provider id |
| `new_id` | body | string | Rename the provider; the providers key, model aliases, `default_provider`, a `default_model` pointing at an old alias, and the subagent secondary-model pool all migrate. Same id rules as `POST /api/v1/providers` |
| `type` | body | string | **Required.** Wire protocol: `kimi` / `openai` / `openai_responses` / `anthropic` / `google-genai` / `vertexai` |
| `api_key` | body | string | Tri-state, see above |
| `base_url` | body | string | API base URL; must not contain an environment variable placeholder (`${...}`) |
| `default_model` | body | string | The provider's default model; must be one of `models[].model` |
| `models` | body | array | **Required.** At least one entry, no duplicate `model` values; same entry shape as `POST /api/v1/providers` |
On success, `data` is `{ provider }` with the saved provider item.
- `40001`: a renamed alias id would collide with another provider's alias
- `40003`: provider is OAuth-managed β log out via `POST /api/v1/oauth/logout` instead
- `40412`: provider not found
- `40921`: `new_id` is already taken
#### `DELETE /api/v1/providers/{provider_id}`
Deletes a provider and all of its model aliases; the subagent secondary-model pool is cascaded. The global `default_provider` / `default_model` pointers are left untouched, even when they point at the deleted provider β they are the user's settings, not this endpoint's to garbage-collect.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider_id` | path | string | **Required.** Provider id |
On success the server answers 204 with no body β the status line itself reports the delete (see [Response envelope](#response-envelope)).
- `40003`: provider is OAuth-managed β log out via `POST /api/v1/oauth/logout` instead
- `40412`: provider not found
#### `POST /api/v1/providers/{provider_id}:refresh`
Re-discovers one provider's model metadata from its upstream source and rewrites the provider's aliases. Providers with a static model source are reported `unchanged` without any network call. When at least one provider's aliases change, the server broadcasts the global `event.model_catalog.changed` event.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `provider_id` | path | string | **Required.** Provider id |
On success, `data` is a refresh report: `changed` is an array of `{ provider_id, provider_name, added, removed }` (added/removed alias counts), `unchanged` is an array of provider ids with no diff, and `failed` is an array of `{ provider, reason }`.
- `40001`: malformed or unsupported action suffix in the path
- `40412`: provider not found
#### `POST /api/v1/providers:refresh`
Refreshes model metadata for every provider. The body is optional and ignored.
On success, `data` is the same refresh report as `POST /api/v1/providers/{provider_id}:refresh` (`changed` / `unchanged` / `failed`).
#### `POST /api/v1/providers:refresh_oauth`
Same refresh as `POST /api/v1/providers:refresh`, limited to OAuth-backed providers. The body is optional and ignored.
On success, `data` is the refresh report (`changed` / `unchanged` / `failed`).
#### `POST /api/v1/providers:import_catalog`
Imports one models.dev directory entry as a configured provider; the reply is HTTP 201 with the standard envelope. The wire protocol and endpoint come from the catalog resolution, and every catalogued model is written as an alias. Importing an id that already exists is a refresh β the provider entry and its aliases are rewritten from the catalog, and an omitted `api_key` keeps the stored key. The global default pointers are never modified, except that `default_model` is seeded from the first imported model when none is configured at all.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `catalog_id` | body | string | **Required.** Directory entry id from `GET /api/v1/catalog/providers` |
| `id` | body | string | Override the catalog id as the local provider id. Same id rules as `POST /api/v1/providers` |
| `api_key` | body | string | API key for the imported provider |
| `base_url` | body | string | Override the catalog-resolved endpoint; required when the entry's `needs_base_url` is `true` |
On success, `data` is `{ provider, models_imported }` β the provider item and the number of aliases written.
- `40001`: `catalog_id` missing or another body validation failure
- `40003`: the target provider exists and is OAuth-managed
- `40004`: the entry cannot be imported (rejected, requires a `base_url`, has no importable models, or its id is unusable as a provider id)
- `40417`: no directory entry with that `catalog_id`
- `50004`: the models.dev directory is unavailable
#### `POST /api/v1/providers:import_registry`
Imports a models.dev-shaped private registry β an `api.json` URL plus an optional Bearer key β as configured providers; the reply is HTTP 201 with the standard envelope. Every listed provider is written with a `source` record so scheduled refreshes rediscover it. Re-importing the same URL removes providers that disappeared upstream β the URL is the registry's stable identity, so rotating the key is safe. The global default pointers follow the same rules as `:import_catalog`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `url` | body | string | **Required.** URL of the registry's `api.json` |
| `api_key` | body | string | Bearer key for the registry; when omitted, the key from the previous import of the same URL is reused |
On success, `data` is `{ providers, models_imported }` β an array of provider items and the total number of aliases written.
- `40001`: `url` missing or another body validation failure
- `40003`: a listed provider exists and is OAuth-managed
- `40005`: the registry cannot be fetched or parsed, or lists no importable providers
#### `GET /api/v1/catalog/providers`
Browses the models.dev directory, proxied by the server with a 10-minute in-memory cache and a built-in snapshot fallback. Items keep the upstream directory order. Entries the server cannot import carry `rejected: true` with a machine-readable `reject_reason`; entries with `needs_base_url: true` require a base URL at import time.
On success, `data.items` is an array of `{ id, name, wire_type, guessed, needs_base_url, rejected, reject_reason, env_key, models }`: `wire_type` is the resolved protocol (nullable, same enum as a provider `type`), `guessed` marks a heuristic resolution, `env_key` is the upstream's conventional API-key environment variable (nullable), and `models` is an array of `{ id, name?, max_context_size, capabilities?, reasoning }`.
- `50004`: the directory is unavailable (both the live fetch and the built-in snapshot failed)
#### `GET /api/v1/catalog/providers/{catalog_id}`
Reads one models.dev directory entry by catalog id β the same item shape as `GET /api/v1/catalog/providers`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `catalog_id` | path | string | **Required.** Directory entry id |
On success, `data` is the directory entry (same shape as a `GET /api/v1/catalog/providers` item).
- `40417`: no directory entry with that `catalog_id`
- `50004`: the directory is unavailable
### Sessions
These endpoints create, list, and inspect sessions, drive session-level actions (fork, compact, undo, and friends), and read per-session rollups. Most of them return a session in the wire shape documented once under [The session object](#the-session-object); non-CRUD operations use the `:{action}` convention described above.
| Method and path | Description |
| --- | --- |
| `POST /api/v1/sessions` | Create a session (requires `workspace_id` or `metadata.cwd`) |
| `GET /api/v1/sessions` | List sessions; cursor pagination with filters such as `busy` and `archived_only` |
| `GET /api/v1/sessions/{session_id}` | Read one session |
| `GET /api/v1/sessions/{session_id}/profile` | Read the session profile |
| `POST /api/v1/sessions/{session_id}/profile` | Update title, metadata, agent config |
| `POST /api/v1/sessions/{session_id}/title/generate` | Generate a title via the managed `chat_title` tool |
| `POST /api/v1/sessions/{session_id}:{action}` | Session actions: `fork` / `compact` / `undo` / `abort` / `btw` / `archive` / `restore` |
| `GET /api/v1/sessions/{session_id}/children` | List child sessions |
| `POST /api/v1/sessions/{session_id}/children` | Create a child session (fork with a tag) |
| `GET /api/v1/sessions/{session_id}/status` | Realtime status rollup |
| `GET /api/v1/sessions/{session_id}/goal` | Current goal snapshot (`null` when none) |
| `GET /api/v1/sessions/{session_id}/warnings` | Session-level warnings |
| `GET /api/v1/sessions/{session_id}/runtime` | Read the main agent's runtime binding |
| `POST /api/v1/sessions/{session_id}/runtime` | Switch the main agent's runtime binding |
| `POST /api/v1/sessions/{session_id}/export` | Export the session with diagnostics (zip stream, not enveloped) |
| `GET /api/v1/sessions/{session_id}/snapshot` | Full snapshot for client rebuilds (with `as_of_seq` and `epoch`) |
| `GET /api/v1/sessions/{session_id}/media/{file_id}` | Download prompt media by file id (binary) |
#### The session object
Every endpoint that returns a session uses this wire shape. The live facts (`busy`, `main_turn_active`, `pending_interaction`, `last_turn_reason`) are resolved from the session's activity aggregate: a session that is not loaded in this server process (a cold session) always reports not-busy with no pending interaction. A few fields are placeholders in the current projection β this is noted per field.
| Field | Type | Description |
| --- | --- | --- |
| `id` | string | Session id (`session_...`) |
| `workspace_id` | string | Owning workspace id |
| `title` | string | Session title; `""` when untitled |
| `created_at` / `updated_at` | string | Creation and last-update times, ISO 8601 |
| `archived` | boolean | Whether the session is archived (hidden from the default session list) |
| `archived_at` | string | Archive time, ISO 8601; present only when archived |
| `busy` | boolean | Any agent has an active turn or background task |
| `main_turn_active` | boolean | The main agent has an active turn |
| `pending_interaction` | string | `none` / `approval` / `question` β an unanswered interaction is waiting |
| `last_turn_reason` | string | Main agent's latest turn outcome: `completed` / `cancelled` / `failed` |
| `last_prompt` | string | Most recent user prompt text, when present |
| `metadata` | object | Custom metadata; always carries `cwd` (the session's working directory) |
| `agent_config` | object | Projected as `{ model }`; `model` is `""` in most responses and only filled with the live model by `GET /api/v1/sessions/{session_id}/snapshot` |
| `usage` | object | Token rollup `{ input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, context_tokens, context_limit?, total_cost_usd?, turn_count? }`; all zeros outside the snapshot endpoint |
| `permission_rules` | array | Session permission rules; currently always `[]` |
| `message_count` | integer | Message count; currently always `0` |
| `last_seq` | integer | Last event sequence number; currently always `0` |
#### `POST /api/v1/sessions`
Creates a session and returns it. The target directory comes from `workspace_id` (an already-registered workspace) or from `metadata.cwd` (the workspace is registered on first use); passing both requires them to agree. Creation broadcasts the global `event.session.created` event.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace_id` | body | string | **Required** when `metadata.cwd` is absent. Registered workspace id; the session is created at that workspace's root |
| `metadata` | body | object | Custom metadata. `metadata.cwd` is the working directory and is **required** when `workspace_id` is absent; with both given, it must equal the workspace root |
| `title` | body | string | Initial title (at least 1 character); the session is untitled otherwise |
| `agent_config` | body | object | Accepted by the schema but currently not applied β set the model and modes through `POST /api/v1/sessions/{session_id}/profile` |
On success, `data` is [the session object](#the-session-object) of the new session.
- `40001`: neither `workspace_id` nor `metadata.cwd` given, or `metadata.cwd` does not match the workspace root (`details` lists the field)
- `40409`: the working directory does not exist or is not a directory
- `40410`: no registered workspace with that `workspace_id`
#### `GET /api/v1/sessions`
Lists sessions across workspaces, newest `updated_at` first. Cursor pagination follows [Pagination](#pagination), with one twist: without `page_size` (and without `archived_only`) the response is a single unpaginated window whose `has_more` is always `false`, so pass `page_size` to actually page.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `before_id` | query | string | Only sessions older than this id; mutually exclusive with `after_id` |
| `after_id` | query | string | Only sessions newer than this id; mutually exclusive with `before_id` |
| `page_size` | query | integer | 1β100. When paging applies, the default is `20`; see the note above for the unpaginated default behavior |
| `busy` | query | boolean | Keep only busy (or only idle) sessions |
| `include_archive` | query | boolean | Include archived sessions alongside live ones. Default `false` |
| `archived_only` | query | boolean | Keep only archived sessions; mutually exclusive with `include_archive`; implies cursor paging even without `page_size` |
| `exclude_empty` | query | boolean | Drop sessions that carry no user prompt |
| `workspace_id` | query | string | Restrict to one workspace (aliases are resolved) |
On success, `data` is `{ items, has_more }` where each item is [the session object](#the-session-object).
- `40001`: validation failure β for example `before_id` combined with `after_id`, or `archived_only` combined with `include_archive`
- `40410`: unknown `workspace_id`
#### `GET /api/v1/sessions/{session_id}`
Reads one session from the index. Live facts are included when the session is loaded in this process; a cold session reports not-busy with its last persisted turn outcome.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is [the session object](#the-session-object).
- `40401`: session not found, or its workspace can no longer be resolved
#### `GET /api/v1/sessions/{session_id}/profile`
Reads the session profile β the same wire payload as `GET /api/v1/sessions/{session_id}`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is [the session object](#the-session-object).
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/profile`
Updates the session's profile: title, custom metadata, and the main agent's config. A title set here becomes a custom title, which wins over generated titles; setting one broadcasts the global `session.meta.updated` event.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `title` | body | string | New title (at least 1 character); becomes a custom title |
| `metadata` | body | object | Keys merged into the session's custom metadata |
| `agent_config` | body | object | Partial main-agent config; fields below, all optional |
Each `agent_config` field is applied immediately to the main agent:
| Field | Type | Description |
| --- | --- | --- |
| `model` | string | Model alias id; an empty string is ignored |
| `thinking` | string | Thinking-mode effort level |
| `permission_mode` | string | `manual` / `yolo` / `auto` |
| `plan_mode` | boolean | Enter or exit Plan mode |
| `swarm_mode` | boolean | Enter or exit swarm mode |
| `goal_objective` | string | Create a goal with this objective |
| `goal_control` | string | `pause` / `resume` / `cancel` the current goal |
The schema also accepts `system_prompt`, `tools`, `mcp_servers` inside `agent_config`, and a top-level `permission_rules` array, but the update route currently does not apply them.
On success, `data` is the updated [session object](#the-session-object).
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/title/generate`
Generates a title from the session's prompts through the managed provider's `chat_title` tool and applies it, broadcasting `session.meta.updated`. Generation requires the managed OAuth login; without `force`, a session that already has a custom or generated title is reported unavailable instead of being overwritten.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `force` | body | boolean | Regenerate even when a custom or generated title exists. Default `false` |
| `source` | body | string | Title input: `user_prompts` (default) / `first_turn` / `digest` |
On success, `data` is `{ title }` β the title now applied to the session.
- `40401`: session not found
- `40923`: generation unavailable β the flag is off, there is no managed OAuth login or no prompt content yet, an existing title without `force`, or the backend request failed
#### `POST /api/v1/sessions/{session_id}:{action}`
Session actions are dispatched through one route: the path tail is parsed as `{session_id}:{action}`, the body is validated against the action's schema, and a missing or unknown action fails `40001` (`unsupported action: ...`). Every action resolves the session first, so all of them can return `40401` for an unknown session. The supported actions are documented one by one below.
#### `POST /api/v1/sessions/{session_id}:fork`
Copies the session β its transcript, agent state, and files β into a new session in the same workspace, and broadcasts `event.session.created`. Forking is rejected while any of the session's agents has an active turn.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `title` | body | string | Title for the fork (at least 1 character). Default `Fork: <source title>` |
| `metadata` | body | object | Custom metadata for the fork |
On success, `data` is [the session object](#the-session-object) of the new session.
- `40901`: the session has an active turn and cannot be forked
#### `POST /api/v1/sessions/{session_id}:compact`
Starts a manual full compaction of the main agent's context. The call returns immediately; progress and completion are delivered as the `compaction.*` WebSocket events.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `instruction` | body | string | Extra guidance for the compaction summary; a blank value is ignored |
On success, `data` is an empty object.
- `40910`: a turn or another context change is active, or the history has nothing to compact
#### `POST /api/v1/sessions/{session_id}:undo`
Rewinds the main agent's conversation by `count` turns and reconciles the derived session state (including the session's `last_prompt`).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `count` | body | integer | Number of turns to undo; positive integer. Default `1` |
| `page_size` | body | integer | Size of the returned history window, 1β100. Default `50` |
On success, `data` is `{ messages, status }`: `messages` is a `{ items, has_more }` page of the remaining context messages, newest first, and `status` is the same rollup as `GET /api/v1/sessions/{session_id}/status`.
- `40901`: a turn is active or a compaction is running β wait for it to finish, then retry
- `40911`: that many turns cannot be undone (a compaction boundary or lost checkpoints); `data` carries `{ reason, requestedCount, undoableCount }`
#### `POST /api/v1/sessions/{session_id}:abort`
Cancels the main agent's running turn β the programmatic equivalent of the user aborting the turn in the TUI.
On success, `data` is `{ aborted: true }`.
#### `POST /api/v1/sessions/{session_id}:btw`
Starts a "by the way" side conversation: forks the main agent into a child agent whose tool calls are limited to the read-only tools `Read`, `Grep`, and `Glob`, so quick side questions run in isolation without touching the working context. Requires a usable model configuration.
On success, `data` is `{ agent_id }` β the id of the new child agent.
#### `POST /api/v1/sessions/{session_id}:archive`
Marks the session archived: it disappears from the default session list (it stays listed with `include_archive` or `archived_only`), and the server broadcasts the global `event.session.archived` event.
On success, `data` is `{ archived: true }`.
#### `POST /api/v1/sessions/{session_id}:restore`
Un-archives the session and resumes it.
On success, `data` is [the session object](#the-session-object) with `archived: false`.
#### `GET /api/v1/sessions/{session_id}/children`
Lists the session's children β the sessions created through `POST /api/v1/sessions/{session_id}/children`. Cursor pagination follows [Pagination](#pagination).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `before_id` | query | string | Only children older than this id; mutually exclusive with `after_id` |
| `after_id` | query | string | Only children newer than this id; mutually exclusive with `before_id` |
| `page_size` | query | integer | 1β100. Default `100` |
| `busy` | query | boolean | Keep only busy (or only idle) children |
On success, `data` is `{ items, has_more }` where each item is [the session object](#the-session-object).
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/children`
Creates a child session: a fork of this session recorded as its child, so it shows up under `GET /api/v1/sessions/{session_id}/children`. The same active-turn restriction as `:fork` applies.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `title` | body | string | Title for the child (at least 1 character). Default `Child: <source title>` |
| `metadata` | body | object | Custom metadata for the child |
On success, `data` is [the session object](#the-session-object) of the new session, and the server broadcasts `event.session.created`.
- `40901`: the session has an active turn and cannot be forked
#### `GET /api/v1/sessions/{session_id}/status`
Realtime status rollup of the main agent; reading it resumes the session if it is cold.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is `{ busy, model?, thinking_level, permission, plan_mode, swarm_mode, context_tokens, max_context_tokens?, context_usage? }`: `busy` reports an active turn, `model` / `thinking_level` / `permission` are the effective agent settings, `plan_mode` / `swarm_mode` are the mode flags, and `context_tokens` with `max_context_tokens` and `context_usage` (0β1) describe context-window consumption.
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/goal`
Reads the session's current goal snapshot, or `null` when no goal is active. Note that this payload uses camelCase keys, unlike most of this API.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is `null` or `{ goalId, objective, completionCriterion?, status, turnsUsed, tokensUsed, wallClockMs, budget, terminalReason? }`, where `status` is `active` / `paused` / `blocked` / `complete` and `budget` reports the token, turn, and wall-clock budgets together with the remaining amounts and per-budget reached flags (each nullable when no such budget is set).
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/warnings`
Reads session-level warnings. The current producer is the oversized `AGENTS.md` check (`agents-md-oversized`), so the list is empty for most sessions.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is `{ warnings }`, each entry `{ code, message, severity }` with `severity` one of `info` / `warning` / `error`.
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/runtime`
Reads the main agent's runtime binding β which runtime the session's agent loop runs on.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is `{ workspace_id, runtime_id }`.
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/runtime`
Switches the main agent's runtime binding.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `runtime_id` | body | string | **Required.** Target runtime id |
On success, `data` is the new binding `{ workspace_id, runtime_id }`.
- `40420`: no runtime with that `runtime_id`
- `40926`: the runtime exists but is unavailable
#### `POST /api/v1/sessions/{session_id}/export`
Exports the session together with diagnostic logs as a zip attachment (`kimi-session-<id>.zip`). The response is a binary stream, not a JSON envelope β capabilities and failure semantics are covered under [Binary and streaming endpoints](#binary-and-streaming-endpoints).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `web_log` | body | string | Client log text to include in the archive, at most 256 KB UTF-8 |
| `desktop` | body | boolean | Also include the desktop host's log. Default `false` |
#### `GET /api/v1/sessions/{session_id}/snapshot`
Assembles an atomic snapshot for rebuilding a client after a resync: the session, recent messages, the in-flight turn, live subagents, and pending interactions, all stamped with the `as_of_seq` watermark and `epoch` used to resubscribe β see [Reconnect and recovery](#reconnect-and-recovery). Unlike the plain session endpoints, the embedded session carries the live `agent_config.model` and real `usage` totals.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is `{ as_of_seq, epoch, session, messages, in_flight_turn, subagents?, pending_approvals, pending_questions }`: `session` is [the session object](#the-session-object), `messages` is the newest 100 messages as `{ items, has_more }`, `in_flight_turn` is the partially streamed turn (`null` when idle, with `current_prompt_id` when known), `subagents` lists live subagent tasks, and `pending_approvals` / `pending_questions` carry the unanswered interactions.
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/media/{file_id}`
Downloads a prompt media file (an image or other attachment referenced by the session's prompts) by file id; an id not yet committed to the session falls back to the staged uploads. The response is binary with `Range` support (206 on ranged requests) β see [Binary and streaming endpoints](#binary-and-streaming-endpoints) for the shared conventions; unlike the enveloped endpoints there, a missing session or file answers with a real 404 status carrying an envelope body.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `file_id` | path | string | **Required.** Media file id |
### Messages and transcript
The `messages` endpoints page the main agent's flattened message history, while the `transcript` endpoints serve the structured per-agent transcript β turns, tasks, interactions, attachments β that the WebSocket [Transcript protocol](#transcript-protocol) streams live. Use these endpoints for history paging and catch-up, and the WebSocket subscription for the live tail.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/sessions/{session_id}/messages` | Page messages (`before_id` / `after_id` / `role`) |
| `GET /api/v1/sessions/{session_id}/messages/{message_id}` | Read one message |
| `GET /api/v1/sessions/{session_id}/transcript` | Turn-paged transcript (requires `agent_id`); global state rides along unpaginated |
| `GET /api/v1/sessions/{session_id}/transcript/ops` | Op-batch catch-up (`since_seq`); `complete: false` means a full refresh is needed |
| `GET /api/v1/sessions/{session_id}/transcript/user-messages` | Turn-opening user inputs, unpaginated |
| `GET /api/v1/sessions/{session_id}/transcript/plan` | ExitPlanMode plan content, path, and review outcome |
#### `GET /api/v1/sessions/{session_id}/messages`
Pages the main agent's message history β the flattened context transcript shared with the session snapshot β newest first. Cursor pagination follows [Pagination](#pagination); reading the history resumes the session when it is cold.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `before_id` | query | string | Only messages older than this message id; mutually exclusive with `after_id` |
| `after_id` | query | string | Only messages newer than this message id; mutually exclusive with `before_id` |
| `page_size` | query | integer | 1β100. Default `50` |
| `role` | query | string | Keep only one role: `user` / `assistant` / `tool` / `system`. The filter applies after the page is sliced, so a filtered page can hold fewer than `page_size` items while `has_more` is still `true` β keep paging until `has_more` is `false` |
On success, `data` is `{ items, has_more }` where each item is a message object `{ id, session_id, role, content, created_at, prompt_id?, parent_message_id?, metadata? }`; `content` is an array of content parts in the wire format documented under [Prompts](#prompts) (`text`, `tool_use`, `tool_result`, `image`, `video`, `file`, `thinking`).
- `40001`: validation failure β for example `before_id` combined with `after_id`
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/messages/{message_id}`
Reads one message from the same history by id.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `message_id` | path | string | **Required.** Message id |
On success, `data` is the message object in the item shape documented under `GET /api/v1/sessions/{session_id}/messages` above.
- `40401`: session not found
- `40403`: no message with that id in this session
#### `GET /api/v1/sessions/{session_id}/transcript`
Returns one page of an agent's structured transcript: turns (with their steps and frames) plus the markers and task references between them. Live sessions answer from the in-memory store (the requested agent's persisted history is backfilled first); cold sessions rebuild the agent from the persisted wire records. This is the history half of the transcript surface β the live streaming half is the [Transcript protocol](#transcript-protocol) subscription.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `agent_id` | query | string | **Required.** Agent whose transcript to read; must be a plain agent id (letters, digits, `.`, `_`, `-` β no path separators) |
| `before_turn` | query | string | Only turns older than this turn id; mutually exclusive with `after_turn` |
| `after_turn` | query | string | Only turns newer than this turn id; mutually exclusive with `before_turn` |
| `page_size` | query | integer | 1β100 turns. Default `20` |
The page unit is the turn: without a cursor the newest page is returned, and `has_more` reports that older turns remain. On success, `data` is `{ agent_id, items, has_more, tasks, interactions, attachments, todos, meta, agents, pending_interactions, seq? }` β `items` is the paged turn slice, `tasks` / `interactions` / `attachments` / `todos` / `meta` / `agents` / `pending_interactions` are global agent state that ships unpaginated with every response, and `seq` is the agent's op-batch watermark for resuming the stream (live sessions only).
- `40001`: validation failure β `before_turn` combined with `after_turn`, or a non-plain `agent_id`
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/transcript/ops`
Serves point-to-point catch-up from the server's op journal: the journaled op batches with `seq > since_seq` for one agent, oldest first. It is the REST counterpart of the `transcript_since` resume cursor described in [Transcript protocol](#transcript-protocol) and shares the same bounded journal, so the same fallback rule applies.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `agent_id` | query | string | **Required.** Agent id (plain id, same constraint as the transcript endpoint) |
| `since_seq` | query | integer | **Required.** The caller's last applied op-batch seq, minimum `0`; batches above it are returned |
On success, `data` is `{ agent_id, batches, latest_seq, complete }`, each batch `{ seq, ops }`. `complete: true` means every batch up to `latest_seq` is present; `complete: false` means the journal no longer reaches back to `since_seq` (or the session is not live at all), and the caller must fall back to a full `GET .../transcript` refresh.
- `40001`: validation failure
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/transcript/user-messages`
Lists every turn-opening input of the session, grouped per agent and unpaginated: real user text, user-slash skill and plugin commands, and cron prompts β distinguishable via `origin` β plus attachment-only prompts projected with an empty `prompt`. Attachment entities referenced by the listed messages ride along (metadata only, never bytes).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `agent_id` | query | string | Read one agent only (plain id). Default reads every rostered agent |
On success, `data` is `{ agents }` where each entry is `{ agent_id, messages, attachments }`; a message is `{ turn_id, ordinal, state, origin, prompt, attachment_ids?, started_at? }` with `state` the turn state (`queued` / `running` / `completed` / `failed` / `cancelled`).
- `40001`: validation failure β a non-plain `agent_id`
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/transcript/plan`
Reads the plan information of an agent's `ExitPlanMode` tool calls β plan content, plan file path, offered options, and the review outcome β in timeline order. Content is projected from the first available fact: the linked approval interaction (interactive reviews), the live tool frame's display (auto mode), or the tool result output text; each entry records which one in `source`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `agent_id` | query | string | **Required.** Agent id (plain id) |
| `tool_call_id` | query | string | Narrow the read to one `ExitPlanMode` call; absent lists every call with recoverable plan content |
On success, `data` is `{ agent_id, plans }` where each plan is `{ tool_call_id, turn_id, source, plan, path?, options?, review? }`: `source` is `interaction` / `display` / `output`, `options` are the review choices as `{ label, description? }`, and `review` (present only for interactive reviews) is `{ state, selected_option?, feedback? }` with `state` one of `pending` / `approved` / `rejected` / `cancelled`.
- `40001`: validation failure
- `40401`: session not found
- `40416`: `tool_call_id` given, but no `ExitPlanMode` call with that id exists
### Prompts
A prompt is one unit of user input: submitting one enqueues it on the session's main agent (or a named agent), a queued prompt can be steered into the active turn, and a running prompt can be aborted. Turn progress itself streams over the WebSocket [events](#events), not these endpoints.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/sessions/{session_id}/prompts` | Active and queued prompts |
| `POST /api/v1/sessions/{session_id}/prompts` | Submit a prompt (content-part array, optional model / permission-mode overrides) |
| `POST /api/v1/sessions/{session_id}/prompts:steer` | Steer queued prompts into the active turn |
| `POST /api/v1/sessions/{session_id}/prompts/{prompt_id}:abort` | Abort a running prompt |
| `POST /api/v1/sessions/{session_id}/prompts/{prompt_id}:steer` | Steer one queued prompt |
#### `GET /api/v1/sessions/{session_id}/prompts`
Reads the main agent's prompt queue snapshot.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is `{ active, queued }`: `active` is the running prompt (`null` when idle) and `queued` lists the pending prompts in order. A prompt is `{ prompt_id, user_message_id, status, content, created_at }` with `status` one of `running` / `queued` / `blocked` and `content` in the content-part format accepted by `POST /api/v1/sessions/{session_id}/prompts`.
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/prompts`
Submits a user prompt to the session. Media references are validated first, then the optional overrides are applied to the target agent β `profile` (bound together with `model` / `thinking`), then `model`, `thinking`, `permission_mode`, and `disabled_tools` β and the prompt is enqueued; the response returns as soon as the prompt is accepted, without waiting for the turn. With `skills`, the prompt runs as a bundled skill activation instead of a plain user prompt.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `content` | body | array | **Required.** Non-empty array of content parts; variants below |
| `agent_id` | body | string | Target agent. Default the main agent |
| `prompt_id` | body | string | Client-chosen prompt id for idempotent submission; an id already reserved by an in-flight prompt fails `40927`, one that has already completed fails `40903`. Cannot be combined with `skills` |
| `skills` | body | array | Bundled skill activations, at least 1 entry of `{ name, args? }`; every skill must exist and be user-activatable |
| `profile` | body | string | Agent profile to bind before submitting |
| `model` | body | string | Model alias to switch the agent to |
| `thinking` | body | string | Thinking-mode effort level |
| `permission_mode` | body | string | `manual` / `yolo` / `auto` |
| `disabled_tools` | body | array | Tool names to disable for the session |
The schema also accepts `metadata`, `plan_mode`, `swarm_mode`, `goal_objective`, and `goal_control`, but the submit route currently does not apply them. Each `content` part is an object discriminated by `type`:
| Part | Fields | Description |
| --- | --- | --- |
| `text` | `text` | Plain text |
| `image` / `video` | `source` | Media input; `source` is one of `{ kind: "url", url, id? }`, `{ kind: "base64", media_type, data }`, `{ kind: "file", file_id }` (an upload from `POST /api/v1/files`), or `{ kind: "session_media", file_id }` (media already committed to this session) |
| `file` | `file_id`, `name`, `media_type`, `size` | A file attachment uploaded through `POST /api/v1/files` |
The schema also accepts the `tool_use`, `tool_result`, and `thinking` parts of the shared message format, but they are not meaningful in a user prompt. Unknown or mis-kinded `file_id` references are rejected before the prompt is created and before any override is applied.
On success, `data` is the accepted prompt `{ prompt_id, user_message_id, status, content, created_at }`.
- `40001`: validation failure β for example `prompt_id` combined with `skills`, or an unknown `profile`
- `40110`: no provider configured yet β finish login first
- `40111`: the resolved provider has no credential (`details.provider_id`)
- `40112`: the provider's credential was rejected (`details.provider_id`)
- `40113`: the model could not be resolved (`details.model_id` / `details.provider_id` when known)
- `40401`: session not found
- `40407`: a referenced `file_id` does not exist (or does not match the part's media kind)
- `40415`: a `skills` entry names an unknown skill
- `40903`: `prompt_id` belongs to an already-completed prompt; `data` carries `{ aborted: false }`
- `40912`: the skill exists but cannot be activated by the user
- `40927`: `prompt_id` is already reserved by an in-flight prompt
#### `POST /api/v1/sessions/{session_id}/prompts:steer`
Steers queued prompts into the active turn, so the running turn consumes them immediately instead of finishing first.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `prompt_ids` | body | array | **Required.** Non-empty array of queued prompt ids |
On success, `data` is `{ steered: true, prompt_ids }`.
- `40001`: validation failure
- `40401`: session not found
- `40402`: a listed prompt id is not in the queue
#### `POST /api/v1/sessions/{session_id}/prompts/{prompt_id}:abort`
Aborts a running prompt. This endpoint and `:steer` below dispatch through one route, `POST /api/v1/sessions/{session_id}/prompts/{tail}`: the tail is parsed as `{prompt_id}:{action}`, and a missing or unknown action fails `40001` (`unsupported action: ...`).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `prompt_id` | path | string | **Required.** Prompt id |
On success, `data` is `{ aborted: true }`.
- `40401`: session not found
- `40402`: no prompt with that id
- `40903`: the prompt already completed; `data` carries `{ aborted: false }`
#### `POST /api/v1/sessions/{session_id}/prompts/{prompt_id}:steer`
Steers one queued prompt into the active turn β the single-prompt form of `POST /api/v1/sessions/{session_id}/prompts:steer`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `prompt_id` | path | string | **Required.** Queued prompt id |
On success, `data` is `{ steered: true, prompt_ids: [prompt_id] }`.
- `40401`: session not found
- `40402`: no queued prompt with that id
### Approvals and questions
Approvals and questions are the session's two pending-interaction kinds: an approval asks permission for a tool call, a question asks for structured input with labeled options. These endpoints list and resolve them; new requests arrive over the WebSocket as `event.approval.requested` and `event.question.requested`.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/sessions/{session_id}/approvals` | List pending approval requests (`status=pending` is required) |
| `POST /api/v1/sessions/{session_id}/approvals/{approval_id}` | Resolve an approval |
| `GET /api/v1/sessions/{session_id}/questions` | List pending questions (`status=pending` is required) |
| `POST /api/v1/sessions/{session_id}/questions/{question_id}` | Answer a question |
| `POST /api/v1/sessions/{session_id}/questions/{question_id}:dismiss` | Dismiss a question |
#### `GET /api/v1/sessions/{session_id}/approvals`
Lists the session's pending approval requests β the permission prompts raised by tool calls. Reading the list resumes the session when it is cold.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `status` | query | string | **Required.** Must be `pending` |
On success, `data` is `{ items }` where each item is `{ approval_id, session_id, turn_id?, tool_call_id, tool_name, action, tool_input_display, created_at, expires_at }`: `tool_name` / `action` / `tool_input_display` describe the call waiting for permission, and `expires_at` is 24 hours after `created_at`.
- `40001`: `status` missing or not `pending`
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/approvals/{approval_id}`
Resolves a pending approval request, letting the waiting tool call proceed (or not).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `approval_id` | path | string | **Required.** Approval request id |
| `decision` | body | string | **Required.** `approved` / `rejected` / `cancelled` |
| `scope` | body | string | With `approved`, `session` (the only value) also remembers the approval rule for the rest of the session |
| `feedback` | body | string | Free-form feedback handed back to the agent |
| `selected_label` | body | string | The label of the chosen option, when the request offered labeled choices (for example a plan review) |
On success, `data` is `{ resolved: true, resolved_at }`.
- `40001`: validation failure
- `40401`: session not found
- `40404`: no pending approval with that id
- `40902`: the approval was already resolved; `data` carries `{ resolved: false }`
#### `GET /api/v1/sessions/{session_id}/questions`
Lists the session's pending questions.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `status` | query | string | **Required.** Must be `pending` |
On success, `data` is `{ items }` where each item is `{ question_id, session_id, turn_id?, tool_call_id?, questions, created_at }`. `questions` holds 1β4 items `{ id, question, header?, body?, options, multi_select?, allow_other?, other_label?, other_description? }`, each with 2β4 `options` of `{ id, label, description? }`; `multi_select` allows several options, `allow_other` a free-text answer.
- `40001`: `status` missing or not `pending`
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/questions/{question_id}`
Answers a pending question. Both question endpoints dispatch through one route, `POST /api/v1/sessions/{session_id}/questions/{tail}`: a bare question id answers the question, a `{question_id}:dismiss` tail dismisses it, and anything else fails `40001`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `question_id` | path | string | **Required.** Question id |
| `answers` | body | object | **Required.** Map of question item id (`q_0`, β¦) to an answer object; variants below |
| `method` | body | string | How the answer was produced: `enter` / `space` / `number_key` / `click` |
| `note` | body | string | Free-form note attached to the response |
Each answer is an object discriminated by `kind`:
| Kind | Fields | Description |
| --- | --- | --- |
| `single` | `option_id` | One chosen option |
| `multi` | `option_ids` | Several chosen options (at least 1) |
| `other` | `text` | A free-text answer |
| `multi_with_other` | `option_ids`, `other_text` | Options plus free text |
| `skipped` | β | The item was skipped |
On success, `data` is `{ resolved: true, resolved_at }`.
- `40001`: validation failure (`details` lists each field)
- `40401`: session not found
- `40405`: no pending question with that id
- `40902`: the question was already resolved; `data` carries `{ resolved: false }`
#### `POST /api/v1/sessions/{session_id}/questions/{question_id}:dismiss`
Dismisses a pending question without answering it.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `question_id` | path | string | **Required.** Question id |
On success the envelope `code` is `40909` (`question dismissed`) rather than `0`, with `data` `{ dismissed: true, dismissed_at }` β clients must special-case this endpoint's success code.
- `40401`: session not found
- `40405`: no pending question with that id
- `40902`: the question was already resolved; `data` carries `{ resolved: false }`
### Background tasks
Background tasks are the session's asynchronous units β background shells, subagents, and long-running tool tasks. The registry is live-only: a session not loaded in this server process reports an empty list.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/sessions/{session_id}/tasks` | List background tasks |
| `GET /api/v1/sessions/{session_id}/tasks/{task_id}` | Read a task (optional output preview) |
| `POST /api/v1/sessions/{session_id}/tasks/{task_id}:cancel` | Cancel a task |
| `POST /api/v1/sessions/{session_id}/tasks/{task_id}:detach` | Move a foreground task to the background |
#### `GET /api/v1/sessions/{session_id}/tasks`
Lists the session's background tasks.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `status` | query | string | Keep only one status: `running` / `completed` / `failed` / `cancelled` |
On success, `data` is `{ items }` where each item is a task object `{ id, session_id, kind, description, status, created_at, started_at?, completed_at?, command?, model?, thinking_effort?, agent_id?, subagent_type?, parent_tool_call_id?, output_preview?, output_bytes? }`. `kind` is `bash` / `subagent` / `tool`; `command` is set for `bash` tasks, the model and agent fields for `subagent` tasks, and the output fields only when a task is read with `with_output`. Timed-out and lost tasks report `failed`; killed tasks report `cancelled`.
- `40001`: validation failure β an unknown `status`
- `40401`: session not found
#### `GET /api/v1/sessions/{session_id}/tasks/{task_id}`
Reads one background task, optionally with a tail of its output.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `task_id` | path | string | **Required.** Task id |
| `with_output` | query | boolean | Include an output tail in the response. Default `false` |
| `output_bytes` | query | integer | Size of the requested output tail in bytes, minimum `0`. Default `32768` |
On success, `data` is the task object documented under `GET /api/v1/sessions/{session_id}/tasks` above; with `with_output=true` and non-empty output, `output_preview` carries the tail text and `output_bytes` its byte length.
- `40001`: validation failure
- `40401`: session not found
- `40406`: no task with that id (a cold session has no live tasks at all)
#### `POST /api/v1/sessions/{session_id}/tasks/{task_id}:cancel`
Cancels a running task. It dispatches through `POST /api/v1/sessions/{session_id}/tasks/{tail}` with `cancel` / `detach` as the supported actions β a bare task id or an unknown action fails `40001`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `task_id` | path | string | **Required.** Task id |
On success, `data` is `{ cancelled: true }`.
- `40001`: missing or unknown action suffix
- `40401`: session not found
- `40406`: no task with that id
- `40904`: the task already finished; `data` carries `{ cancelled: false }` and `details.current_status` the terminal status
#### `POST /api/v1/sessions/{session_id}/tasks/{task_id}:detach`
Moves a running foreground task to the background without stopping it: the tool call waiting on the task returns immediately with a background-task result, the turn continues, and the task keeps running under the background task registry (its output is persisted, and its completion arrives as a task notification). Already-background or finished tasks are an idempotent no-op. It dispatches through `POST /api/v1/sessions/{session_id}/tasks/{tail}` with `cancel` / `detach` as the supported actions β a bare task id or an unknown action fails `40001`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `task_id` | path | string | **Required.** Task id |
On success, `data` is `{ detached, status }`: `detached` is `true` when the call moved a running foreground task to the background and `false` for the idempotent no-op; `status` is the task's status after the call.
- `40001`: missing or unknown action suffix
- `40401`: session not found
- `40406`: no task with that id
### Skills, tools, and MCP
These endpoints expose the skill catalogs a session or workspace sees, the effective agent's tool list, and its MCP servers. Skill activation and MCP restart use the `:{action}` convention; activation is the REST analogue of the `/<skill>` slash command.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/sessions/{session_id}/skills` | Per-session skill catalog |
| `GET /api/v1/workspaces/{workspace_id}/skills` | Session-less skill catalog for a workspace |
| `POST /api/v1/sessions/{session_id}/skills/{skill_name}:activate` | Activate a skill (starts a turn) |
| `GET /api/v1/tools` | List tools of the effective agent |
| `GET /api/v1/mcp/servers` | List MCP servers |
| `POST /api/v1/mcp/servers/{mcp_server_id}:restart` | Restart an MCP server |
#### `GET /api/v1/sessions/{session_id}/skills`
Lists the skills available to one session, merged from every source (built-in, plugin, extra, user, project) with the session's precedence applied. Reading the catalog resumes the session when it is cold.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is `{ skills }` where each item is a skill descriptor `{ name, description, path, source, type?, disable_model_invocation? }`: `source` is `project` / `user` / `extra` / `builtin`, `type` classifies the skill (only user-activatable types can be activated), and `disable_model_invocation` hides the skill from the model.
- `40401`: session not found (or not activated)
#### `GET /api/v1/workspaces/{workspace_id}/skills`
Lists the skill catalog a session in this workspace would see, without creating or resuming a session β the same merge of built-in, plugin, extra, user, and project sources computed for the workspace root.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace_id` | path | string | **Required.** Registered workspace id |
On success, `data` is `{ skills }` with the skill descriptor documented under `GET /api/v1/sessions/{session_id}/skills` above.
- `40410`: workspace not found
#### `POST /api/v1/sessions/{session_id}/skills/{skill_name}:activate`
Activates a skill in the session β the REST analogue of the `/<skill>` slash command β starting a turn on the main agent with the skill's content plus `args` and attachments. The endpoint dispatches through one route, `POST /api/v1/sessions/{session_id}/skills/{tail}`: the tail is parsed as `{skill_name}:{action}`, `activate` is the only action, and a bare name or an unknown action fails `40001` (`unsupported action: ...`).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `skill_name` | path | string | **Required.** Name of the skill to activate |
| `args` | body | string | Free-form arguments handed to the skill, like the text after a slash command |
| `attachments` | body | array | Media parts attached to the activation. Image and video parts carry a `source` object whose `kind` is `url` / `base64` / `file` / `session_media` (same shapes as the prompt content parts); file parts carry the top-level `file_id`, `name`, `media_type`, and `size` |
On success, `data` is `{ activated: true, skill_name }`.
- `40001`: validation failure or unsupported action suffix
- `40401`: session not found (or not activated)
- `40407`: a referenced attachment file does not exist
- `40415`: no skill with that name
- `40912`: the skill exists but its type cannot be activated by the user
#### `GET /api/v1/tools`
Lists the tools of the effective agent β the main agent of the session given by `session_id`, or of the most recently created session when the parameter is omitted. When no such session is live in this server process, the list is empty.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | query | string | Session whose main agent to inspect. Default the most recently created session |
On success, `data` is `{ tools }` where each item is `{ name, description, input_schema, source, mcp_server_id?, active? }`: `source` is `builtin` / `skill` / `mcp`, `mcp_server_id` is set on MCP tools (parsed from the `mcp__<server>__<tool>` name), and `active` reports the tool policy's verdict. `input_schema` is currently always `null`.
#### `GET /api/v1/mcp/servers`
Lists the MCP servers configured for the effective agent (the most recently created live session's main agent, as in `GET /api/v1/tools`). With no live session, the list is empty.
On success, `data` is `{ servers }` where each item is `{ id, name, transport, status, last_error?, tool_count }`: `transport` is `stdio` / `http` / `sse`, `status` is `connected` / `connecting` / `disconnected` / `error`, and `last_error` carries the failure text when the server is in `error`.
#### `POST /api/v1/mcp/servers/{mcp_server_id}:restart`
Reconnects one MCP server of the effective agent. The endpoint dispatches through `POST /api/v1/mcp/servers/{tail}` with `restart` as the only action β a bare server id or an unknown action fails `40001`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `mcp_server_id` | path | string | **Required.** MCP server id (its configured name) |
On success, `data` is `{ restarting: true }`.
- `40001`: missing or unknown action suffix
- `40408`: no MCP server with that id (also reported when no session is live)
### Capabilities and plugins
Capabilities are built-in features with layered readiness β detection steps plus a background install; the current build registers `kimi-cu` (Kimi Computer Use) and `kimi-webbridge` (Kimi Browser Extension). Plugins are installed packages of skills, MCP servers, hooks, and commands. These endpoints report capability status and drive capability installs, and manage the plugin lifecycle from marketplace listing to removal.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/capabilities` | List built-in capabilities with readiness status |
| `GET /api/v1/capabilities/{capability_id}` | Read one capability's status |
| `POST /api/v1/capabilities/{capability_id}:install` | Start a capability install (background; poll GET for progress) |
| `GET /api/v1/plugins` | List installed plugins |
| `POST /api/v1/plugins` | Install a plugin from a local path, zip URL, or GitHub repo |
| `GET /api/v1/plugins/marketplace` | Marketplace catalog merged with live install state |
| `POST /api/v1/plugins/{plugin_id}:{action}` | Plugin actions: `enable` / `disable` / `remove` |
#### `GET /api/v1/capabilities`
Lists every registered capability with its readiness status.
On success, `data` is `{ capabilities }` where each item is a capability status object `{ id, pluginId?, displayName, description, supported, state, version?, steps, install }`. `state` is `ready` (every required detection step `ok`) / `partial` (some step `ok`) / `not_installed` / `unsupported` (not available on this platform/architecture); `steps` lists the detection steps as `{ id, state, detail?, optional? }` with `state` one of `ok` / `missing` / `failed`; `install` is the install progress `{ running, step?, percent?, error?, note? }` with `percent` between 0 and 100.
#### `GET /api/v1/capabilities/{capability_id}`
Reads one capability's readiness status β the polling counterpart of the `:install` action.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `capability_id` | path | string | **Required.** Capability id |
On success, `data` is the capability status object documented under `GET /api/v1/capabilities` above.
- `40418`: no capability with that id
#### `POST /api/v1/capabilities/{capability_id}:install`
Starts installing a capability in the background and returns immediately with the current status (`install.running` is `true`); poll `GET /api/v1/capabilities/{capability_id}` for progress. The endpoint dispatches through `POST /api/v1/capabilities/{tail}` with `install` as the only action β a bare id or an unknown action fails `40001`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `capability_id` | path | string | **Required.** Capability id |
On success, `data` is the capability status object documented under `GET /api/v1/capabilities` above.
- `40001`: missing or unknown action suffix
- `40418`: no capability with that id
- `40924`: an install of this capability is already running
- `40925`: the capability is not supported on this platform/architecture
#### `GET /api/v1/plugins`
Lists installed plugins.
On success, `data` is `{ plugins }` where each item is `{ id, displayName, version?, enabled, state, skillCount, mcpServerCount, enabledMcpServerCount, hookCount, commandCount, hasErrors, source, originalSource?, github? }`: `state` is `ok` / `error` (load failures also set `hasErrors`), `source` is `local-path` / `zip-url` / `github`, and `github` carries the provenance `{ owner, repo, ref, installedSha? }` with `ref` `{ kind: branch|tag|sha, value }` for GitHub-sourced plugins.
#### `POST /api/v1/plugins`
Installs a plugin and returns its summary.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `source` | body | string | **Required.** Where to install from: an absolute local path, an `http(s)` URL to a zip archive, or a GitHub URL β `https://github.com/<owner>/<repo>`, optionally pinned with `/tree/<branch-or-sha>`, `/releases/tag/<tag>`, or `/commit/<sha>` |
On success, `data` is the plugin summary documented under `GET /api/v1/plugins` above.
- `40001`: validation failure β for example `source` is neither a URL nor an absolute path, or the plugin failed to load
- `40409`: the local path does not exist
#### `GET /api/v1/plugins/marketplace`
Lists the plugin marketplace catalog merged with live install state. The catalog is fetched per request (10-second timeout) from the configured marketplace URL; with the default catalog, built-in capabilities missing from the catalog are merged in as rows (with `capabilityId` set) and rows whose capability is unsupported on this platform are dropped.
On success, `data` is `{ entries }` where each item is `{ id, tier, displayName, description?, homepage?, keywords?, version?, source, installed?, updateAvailable?, capabilityId? }`: `tier` is `official` / `curated` / `third-party`, `installed` is `{ version?, enabled }` when the plugin is installed, and `updateAvailable` marks rows whose catalog version is newer than the installed one. An entry's `source` feeds the `source` field of `POST /api/v1/plugins`.
- `50001`: the marketplace is unreachable or returned an invalid catalog
#### `POST /api/v1/plugins/{plugin_id}:enable`
Enables an installed plugin. Plugin actions dispatch through one route, `POST /api/v1/plugins/{tail}`: the tail is parsed as `{plugin_id}:{action}` with `enable` / `disable` / `remove` as the actions, and a bare id or an unknown action fails `40001` (`unsupported action: ...`).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `plugin_id` | path | string | **Required.** Installed plugin id |
On success, `data` is `{ ok: true }`.
- `40001`: missing or unknown action suffix
- `40419`: no installed plugin with that id
#### `POST /api/v1/plugins/{plugin_id}:disable`
Disables an installed plugin without removing it; the dispatch contract matches `:enable` above.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `plugin_id` | path | string | **Required.** Installed plugin id |
On success, `data` is `{ ok: true }`.
- `40001`: missing or unknown action suffix
- `40419`: no installed plugin with that id
#### `POST /api/v1/plugins/{plugin_id}:remove`
Removes an installed plugin; the dispatch contract matches `:enable` above.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `plugin_id` | path | string | **Required.** Installed plugin id |
On success, `data` is `{ ok: true }`.
- `40001`: missing or unknown action suffix
- `40419`: no installed plugin with that id
### Terminals
PTY terminal endpoints; mounted only on loopback binds (a non-loopback bind skips them unless `--allow-remote-terminals` is passed). Terminal input, output, and resize flow over WebSocket `terminal_*` frames β the REST surface manages the terminal lifecycle only.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/sessions/{session_id}/terminals` | List terminals |
| `POST /api/v1/sessions/{session_id}/terminals` | Create a terminal |
| `GET /api/v1/sessions/{session_id}/terminals/{terminal_id}` | Read a terminal |
| `POST /api/v1/sessions/{session_id}/terminals/{terminal_id}:close` | Close a terminal |
#### `GET /api/v1/sessions/{session_id}/terminals`
Lists the session's terminals. Reading the list resumes the session when it is cold.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
On success, `data` is `{ items }` where each item is a terminal object `{ id, session_id, cwd, shell, cols, rows, status, created_at, exited_at?, exit_code? }`: `status` is `running` / `exited`, and an exited terminal carries `exited_at` plus `exit_code` (`null` when the process reported none, for example after a signal). Scrollback is not part of the object β output replays and streams over the WebSocket.
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/terminals`
Creates a PTY terminal for the session.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `runtime_id` | body | string | Runtime to spawn in. Default `local` |
| `cwd` | body | string | Working directory, relative to the session workspace (an absolute path fails validation). Default the workspace root |
| `shell` | body | string | Shell executable. Default the runtime's shell |
| `cols` | body | integer | Terminal width, positive. Default `80` |
| `rows` | body | integer | Terminal height, positive. Default `24` |
On success, `data` is the terminal object documented under `GET /api/v1/sessions/{session_id}/terminals` above.
- `40001`: validation failure (`details` lists each field)
- `40401`: session not found
- `41304`: `cwd` resolves outside the session workspace
#### `GET /api/v1/sessions/{session_id}/terminals/{terminal_id}`
Reads one terminal.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `terminal_id` | path | string | **Required.** Terminal id |
On success, `data` is the terminal object documented under `GET /api/v1/sessions/{session_id}/terminals` above.
- `40401`: session not found
- `40414`: no terminal with that id
#### `POST /api/v1/sessions/{session_id}/terminals/{terminal_id}:close`
Closes a terminal, killing its process. The endpoint dispatches through `POST /api/v1/sessions/{session_id}/terminals/{tail}` with `close` as the only action β a bare id or an unknown action fails `40001`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `terminal_id` | path | string | **Required.** Terminal id |
On success, `data` is `{ closed: true }`.
- `40001`: missing or unknown action suffix
- `40401`: session not found
- `40414`: no terminal with that id
### Workspaces
Workspaces are the registered project directories sessions live in. These endpoints manage the registry β list, register, rename, unregister β plus the per-workspace trust state that gates project-level MCP config. Every endpoint that returns a workspace uses the wire shape documented once under [The workspace object](#the-workspace-object).
| Method and path | Description |
| --- | --- |
| `GET /api/v1/workspaces` | List registered workspaces |
| `POST /api/v1/workspaces` | Register a workspace (idempotent on the root path) |
| `PATCH /api/v1/workspaces/{workspace_id}` | Rename |
| `DELETE /api/v1/workspaces/{workspace_id}` | Unregister (keeps on-disk content) |
| `GET /api/v1/workspaces/{workspace_id}/trust` | Read the trust state |
| `POST /api/v1/workspaces/{workspace_id}/trust` | Grant trust |
| `POST /api/v1/workspaces/{workspace_id}/untrust` | Revoke trust |
| `POST /api/v1/workspaces/{workspace_id}/add-dir` | Add an additional directory |
#### The workspace object
Every endpoint that returns a workspace uses this wire shape. Registration and rename broadcast the global `event.workspace.created` / `event.workspace.updated` events.
| Field | Type | Description |
| --- | --- | --- |
| `id` | string | Workspace id, a `wd_<slug>_<hash12>` string derived from the root path |
| `root` | string | Absolute path of the project directory |
| `name` | string | Display name, 1β100 characters; defaults to the root's base name |
| `created_at` | string | Registration time, ISO 8601 |
| `last_opened_at` | string | Last time the workspace was opened or re-registered, ISO 8601 |
| `session_count` | integer | Number of sessions in the workspace |
#### `GET /api/v1/workspaces`
Lists every registered workspace.
On success, `data` is `{ items }` where each item is [the workspace object](#the-workspace-object).
#### `POST /api/v1/workspaces`
Registers a workspace and returns it. Registration is idempotent on the root path: registering an already-registered root returns the existing workspace with only `last_opened_at` refreshed (the stored name is kept), broadcasting `event.workspace.updated` instead of `event.workspace.created`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `root` | body | string | **Required.** Absolute path of an existing directory |
| `name` | body | string | Display name, 1β100 characters. Default the root's base name |
On success, `data` is [the workspace object](#the-workspace-object).
- `40001`: `root` is missing or not an absolute path (`details` lists the field)
- `40409`: `root` does not exist or is not a directory
#### `PATCH /api/v1/workspaces/{workspace_id}`
Renames a workspace β the display name only; the root path never changes.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace_id` | path | string | **Required.** Workspace id |
| `name` | body | string | **Required.** New display name, 1β100 characters |
On success, `data` is [the workspace object](#the-workspace-object).
- `40001`: validation failure (`details` lists each field)
- `40410`: workspace not found
#### `DELETE /api/v1/workspaces/{workspace_id}`
Unregisters a workspace. Only the registry entry is removed β the on-disk directory is untouched.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace_id` | path | string | **Required.** Workspace id |
On success, `data` is `{ deleted: true }`.
- `40410`: workspace not found
#### `GET /api/v1/workspaces/{workspace_id}/trust`
Reads the workspace trust state. Trust gates whether project-level MCP config loads for the workspace.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace_id` | path | string | **Required.** Workspace id |
On success, `data` is `{ trusted }`.
- `40410`: workspace not found
#### `POST /api/v1/workspaces/{workspace_id}/trust`
Marks the workspace trusted, loading its project-level MCP config.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace_id` | path | string | **Required.** Workspace id |
On success, `data` is `{ trusted: true }`.
- `40410`: workspace not found
#### `POST /api/v1/workspaces/{workspace_id}/untrust`
Revokes workspace trust, unloading its project-level MCP config.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace_id` | path | string | **Required.** Workspace id |
On success, `data` is `{ trusted: false }`.
- `40410`: workspace not found
#### `POST /api/v1/workspaces/{workspace_id}/add-dir`
Adds an additional directory to the workspace, with the same semantics as the CLI `--add-dir` flag and the TUI `/add-dir` command. The path accepts absolute paths, relative paths (resolved against the workspace root), and `~` expansion.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace_id` | path | string | **Required.** Workspace id |
| `path` | body | string | **Required.** Directory to add |
| `persist` | body | boolean | Defaults to `true`: appends to `workspace.additional_dir` in `<project root>/.kimi-code/local.toml`. With `false`, the directory only joins the in-memory ephemeral set shared by all sessions of the workspace |
On success, `data` is `{ project_root, config_path, additional_dirs, persisted }`, where `additional_dirs` lists every additional directory (existing ones included) and `persisted` reports whether this call wrote to disk.
- `40001`: validation failure (`details` lists each field), or an engine-side config validation error such as a corrupted project local config
- `40409`: `path` does not exist or is not a directory
- `40410`: workspace not found
### File system
In-session file operations go through `POST /api/v1/sessions/{session_id}/fs:{action}` with JSON bodies; actions are `list` / `read` / `list_many` / `stat` / `stat_many` / `mkdir` / `search` / `grep` / `git_status` / `diff` / `open` / `open-in` / `reveal`. Every action body also accepts an optional `runtime_id` (string, default `local`) selecting the runtime that executes the operation; `open`, `open-in`, and `reveal` only work on the `local` runtime. In addition:
| Method and path | Description |
| --- | --- |
| `POST /api/v1/workspace/fs:search` | Session-less workspace search (the body carries the workspace reference) |
| `POST /api/v1/workspace/fs:suggest` | Session-less file-completion candidates (for `@` file mentions) |
| `GET /api/v1/sessions/{session_id}/fs/{path}:download` | Download a session file (binary, see below) |
| `GET /api/v1/fs:browse` | List host directories (folder picker) |
| `GET /api/v1/fs:home` | The user's home directory and recent workspaces |
| `GET /api/v1/fs:content` | Raw bytes of any host file (gated only by the token β be careful when exposing the port) |
| `POST /api/v1/fs:mkdir` | Create a directory by absolute path |
#### `POST /api/v1/sessions/{session_id}/fs:list`
Lists the entries of a session workspace directory, optionally recursing into subdirectories.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `path` | body | string | Directory to list, relative to the session work directory. Default `.` |
| `depth` | body | integer | Recursion depth, 1β10. Default `1` |
| `limit` | body | integer | Maximum entries, 1β1000. Default `200` |
| `show_hidden` | body | boolean | Include dotfiles. Default `false` |
| `follow_gitignore` | body | boolean | Skip gitignored paths. Default `true` |
| `exclude_globs` | body | string[] | Additional globs to skip |
| `sort` | body | string | `type_first` (default) / `name_asc` / `name_desc` / `mtime_desc` / `size_desc` |
| `include_git_status` | body | boolean | Attach each entry's git status. Default `false` |
On success, `data` is `{ items, truncated }` β plus `children_by_path` (a path β entries map) when `depth` is greater than 1. Each item is an entry object `{ path, name, kind, size?, modified_at, etag?, mime?, language_id?, is_binary?, is_symlink_to?, git_status?, child_count? }`, where `kind` is `file` / `directory` / `symlink` and `git_status` (present only with `include_git_status: true`) is one of `clean` / `modified` / `added` / `deleted` / `renamed` / `untracked` / `ignored` / `conflicted`; `truncated` reports that `limit` cut the listing short.
- `40001`: body validation failure
- `40401`: session not found
- `40409`: path not found (including a `path` that is not a directory)
- `41304`: path escapes the session workspace
#### `POST /api/v1/sessions/{session_id}/fs:read`
Reads a slice of a session file as text or base64.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `path` | body | string | **Required.** File path, relative to the session work directory |
| `offset` | body | integer | Byte offset to start at. Default `0` |
| `length` | body | integer | Bytes to read, 1β10485760 (10 MiB). Default `1048576` (1 MiB) |
| `encoding` | body | string | `auto` (default) / `utf-8` / `base64` |
On success, `data` is `{ path, content, encoding, size, truncated, etag, mime, language_id?, line_count?, is_binary }`, where `encoding` reports the encoding actually used (`utf-8` or `base64`) and `size` is the full file size. With `encoding: "auto"`, text comes back as `utf-8` (non-UTF-8 text is transcoded) and binary content as `base64`; `encoding: "utf-8"` forces text and rejects binary files.
- `40001`: body validation failure
- `40401`: session not found
- `40409`: path not found
- `40906`: path is a directory
- `40907`: binary file requested with `encoding: "utf-8"`
- `41302`: file exceeds the 10 MiB read ceiling
- `41304`: path escapes the session workspace
#### `POST /api/v1/sessions/{session_id}/fs:list_many`
Lists several session directories in one call; a failing path folds into the response instead of failing the whole request.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `paths` | body | string[] | **Required.** Directories to list, 1β100 entries |
The remaining body fields (`depth`, `limit`, `show_hidden`, `follow_gitignore`, `exclude_globs`, `sort`, `include_git_status`) have the same types, ranges, and defaults as `fs:list`. On success, `data` is `{ results }`, a map from each requested path to its entry array (entry objects as described under `fs:list`), plus `truncated_paths` (paths whose listing hit `limit`) and `partial_errors`, a map from a failed path to its `{ code, msg }` error.
- `40001`: body validation failure
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/fs:stat`
Stats one path in the session workspace.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `path` | body | string | **Required.** Path to stat, relative to the session work directory |
On success, `data` is the entry object described under `fs:list`.
- `40001`: body validation failure
- `40401`: session not found
- `40409`: path not found
- `41304`: path escapes the session workspace
#### `POST /api/v1/sessions/{session_id}/fs:stat_many`
Stats many session paths in one call; missing paths report `null` instead of failing the request.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `paths` | body | string[] | **Required.** Paths to stat, 1β1000 entries |
On success, `data` is `{ entries }`, a map from each requested path to its entry object (as described under `fs:list`) or `null` when the path does not exist.
- `40001`: body validation failure
- `40401`: session not found
#### `POST /api/v1/sessions/{session_id}/fs:mkdir`
Creates a directory inside the session workspace.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `path` | body | string | **Required.** Directory to create, relative to the session work directory |
| `recursive` | body | boolean | Create missing parent directories. Default `false` |
On success, `data` is the created directory's entry object (as described under `fs:list`).
- `40001`: body validation failure
- `40401`: session not found
- `40409`: parent directory not found (non-recursive create)
- `40919`: path already exists (non-recursive create)
- `41304`: path escapes the session workspace
#### `POST /api/v1/sessions/{session_id}/fs:search`
Fuzzy-searches file and directory names across the session workspace. An empty `query` lists the top-level entries instead. When the `{session_id}` slot carries a workspace reference (a registered workspace id or an absolute root) rather than a session id, the search runs against that workspace β the session-less form for a not-yet-created draft session; the first-class session-less endpoint is `POST /api/v1/workspace/fs:search`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id, or a workspace reference |
| `query` | body | string | **Required.** Search text; `""` lists the top level |
| `limit` | body | integer | Maximum hits, 1β200. Default `50` |
| `include_globs` | body | string[] | Only paths matching one of these globs |
| `exclude_globs` | body | string[] | Skip paths matching these globs |
| `follow_gitignore` | body | boolean | Skip gitignored paths. Default `true` |
On success, `data` is `{ items, truncated }` where each item is `{ path, name, kind, score, match_positions }` β `kind` is `file` / `directory` / `symlink`, `score` is the fuzzy-match score between 0 and 1, and `match_positions` lists the matched character offsets. Hits sort by score (ties by path), and `truncated` reports that hits beyond `limit` were dropped.
- `40001`: body validation failure
- `40401`: neither a session nor a resolvable workspace with that reference
#### `POST /api/v1/sessions/{session_id}/fs:grep`
Searches file contents across the session workspace β a literal string by default, a regular expression with `regex: true`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `pattern` | body | string | **Required.** Text or regex to search for |
| `regex` | body | boolean | Treat `pattern` as a regular expression. Default `false` |
| `case_sensitive` | body | boolean | Default `true` |
| `include_globs` | body | string[] | Only files matching one of these globs |
| `exclude_globs` | body | string[] | Skip files matching these globs |
| `follow_gitignore` | body | boolean | Skip gitignored paths. Default `true` |
| `max_files` | body | integer | Files to scan at most, 1β10000. Default `200` |
| `max_matches_per_file` | body | integer | Matches kept per file, 1β10000. Default `50` |
| `max_total_matches` | body | integer | Matches kept overall, 1β100000. Default `5000` |
| `context_lines` | body | integer | Context lines around each match, 0β10. Default `2` |
On success, `data` is `{ files, files_scanned, truncated, elapsed_ms }` where each entry of `files` is `{ path, matches }` and each match is `{ line, col, text, before, after }` (`before` / `after` carry up to `context_lines` surrounding lines); `truncated` reports that one of the match budgets cut the results short.
- `40001`: body validation failure
- `40401`: session not found
- `41305`: the search timed out
#### `POST /api/v1/sessions/{session_id}/fs:git_status`
Reads the git status of the session workspace, optionally restricted to a set of paths.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `paths` | body | string[] | Restrict the status to these paths; omitted means the whole workspace |
On success, `data` is `{ branch, ahead, behind, entries, additions, deletions, pullRequest }` where `entries` maps each changed path to its status (`clean` / `modified` / `added` / `deleted` / `renamed` / `untracked` / `ignored` / `conflicted`) and `pullRequest` is `{ number, state, url }` (`state` is `open` / `merged` / `closed` / `draft`) or `null`.
- `40001`: body validation failure
- `40401`: session not found
- `40908`: git is unavailable (not a repository, or no git binary)
#### `POST /api/v1/sessions/{session_id}/fs:diff`
Returns the unified git diff of one file in the session workspace.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `path` | body | string | **Required.** File to diff, relative to the session work directory |
On success, `data` is `{ path, diff, truncated }` where `diff` is the unified diff text and `truncated` reports an over-long diff cut short.
- `40001`: body validation failure
- `40401`: session not found
- `40908`: git is unavailable (not a repository, or no git binary)
- `41304`: path escapes the session workspace
#### `POST /api/v1/sessions/{session_id}/fs:open`
Opens a session file with the host operating system's default handler. Local runtime only.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `path` | body | string | **Required.** File to open, relative to the session work directory |
| `line` | body | integer | Line number to jump to where the handler supports it (positive integer) |
On success, `data` is `{ opened: true }`.
- `40001`: body validation failure
- `40401`: session not found
- `40409`: path not found
- `41304`: path escapes the session workspace
#### `POST /api/v1/sessions/{session_id}/fs:open-in`
Opens a session file or directory in a specific host application. Local runtime only.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `app_id` | body | string | **Required.** Target application: `finder` / `cursor` / `vscode` / `iterm` / `terminal` |
| `path` | body | string | **Required.** File or directory to open, relative to the session work directory |
| `line` | body | integer | Line number to jump to where the application supports it (positive integer) |
On success, `data` is `{ opened: true }`.
- `40001`: body validation failure
- `40401`: session not found
- `40409`: path not found
- `41304`: path escapes the session workspace
- `50001`: the application failed to launch
#### `POST /api/v1/sessions/{session_id}/fs:reveal`
Reveals a session file in the host operating system's file manager. Local runtime only.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `path` | body | string | **Required.** File to reveal, relative to the session work directory |
On success, `data` is `{ revealed: true }`.
- `40001`: body validation failure
- `40401`: session not found
- `40409`: path not found
- `41304`: path escapes the session workspace
#### `GET /api/v1/sessions/{session_id}/fs/{path}:download`
Downloads a file from the session workspace; `{path}` is the workspace-relative file path with the literal `:download` suffix. The response is a binary stream with range and ETag support β see [Binary and streaming endpoints](#binary-and-streaming-endpoints).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `session_id` | path | string | **Required.** Session id |
| `path` | path | string | **Required.** Workspace-relative file path plus the `:download` suffix |
| `runtime_id` | query | string | Runtime to read from. Default `local` |
- `40001`: missing or empty path
- `40401`: session not found
- `40409`: path not found
- `41304`: path escapes the session workspace
#### `POST /api/v1/workspace/fs:search`
The session-less form of `fs:search`: the workspace travels in the body instead of the URL.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace` | body | string | **Required.** Registered workspace id or absolute root (registered on the spot) |
| `query` | body | string | **Required.** Search text; `""` lists the top level |
| `limit` | body | integer | Maximum hits, 1β200. Default `50` |
| `include_globs` | body | string[] | Only paths matching one of these globs |
| `exclude_globs` | body | string[] | Skip paths matching these globs |
| `follow_gitignore` | body | boolean | Skip gitignored paths. Default `true` |
| `runtime_id` | body | string | Runtime to search on. Default `local` |
On success, `data` is `{ items, truncated }` with the same hit shape and ordering as `fs:search`.
- `40001`: body validation failure
- `40410`: workspace not found and not a usable absolute path
#### `POST /api/v1/workspace/fs:suggest`
Suggests file and directory completion candidates in a workspace without a session β the backend for `@` file mentions in the composer.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `workspace` | body | string | **Required.** Registered workspace id or absolute root (registered on the spot) |
| `query` | body | string | **Required.** Partial path text to complete |
| `limit` | body | integer | Maximum candidates, 1β200. Default `50` |
| `follow_gitignore` | body | boolean | Skip gitignored paths. Default `true` |
| `show_hidden` | body | boolean | Include dotfiles. Default `false` |
| `include_globs` | body | string[] | Only paths matching one of these globs |
| `exclude_globs` | body | string[] | Skip paths matching these globs |
| `runtime_id` | body | string | Runtime to complete on. Default `local` |
On success, `data` is `{ items, truncated }` where each item is `{ path, name, kind, score, match_positions }`, the same hit shape as `fs:search`.
- `40001`: body validation failure
- `40410`: workspace not found and not a usable absolute path
#### `GET /api/v1/fs:browse`
Lists the subdirectories of one host directory β the backend of the folder picker.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `path` | query | string | Absolute directory path. Default the user's home directory |
On success, `data` is `{ path, parent, entries }` where `path` is the resolved directory, `parent` its parent (`null` at the filesystem root), and each entry is `{ name, path, is_dir: true }`.
- `40001`: `path` is not absolute
- `40409`: path not found
- `40411`: permission denied
#### `GET /api/v1/fs:home`
Returns the folder picker's landing payload. No parameters.
On success, `data` is `{ home, recent_roots }` where `home` is the user's home directory and `recent_roots` lists the roots of the registered workspaces.
#### `GET /api/v1/fs:content`
Streams the raw bytes of any file on the host filesystem β gated only by the API token, so be careful when exposing the port. Range requests and ETag caching are supported; see [Binary and streaming endpoints](#binary-and-streaming-endpoints).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `path` | query | string | **Required.** Absolute file path |
- `40001`: `path` is not absolute, or not a regular file
- `40409`: path not found
- `40411`: permission denied
- `40906`: path is a directory
#### `POST /api/v1/fs:mkdir`
Creates one directory on the host filesystem by absolute path β the folder picker's "new folder" backend. Non-recursive: the parent directory must already exist.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `path` | body | string | **Required.** Absolute directory path |
On success, `data` is `{ path }`.
- `40001`: `path` is not absolute
- `40409`: parent path not found
- `40411`: permission denied
- `40919`: path already exists
### File uploads
| Method and path | Description |
| --- | --- |
| `POST /api/v1/files` | Multipart upload (`file` field, optional `name` and `expires_in_sec`); returns file metadata |
| `GET /api/v1/files/{file_id}` | Download (binary; errors use real HTTP statuses) |
| `DELETE /api/v1/files/{file_id}` | Delete |
#### `POST /api/v1/files`
Uploads a file as `multipart/form-data` for later reference (for example as a prompt attachment).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `file` | body | binary | **Required.** The multipart file part |
| `name` | body | string | Stored display name. Default the uploaded filename |
| `expires_in_sec` | body | number | Seconds until the file expires (non-negative). Default never expires |
On success, `data` is the file metadata `{ id, name, media_type, size, created_at, expires_at? }` with `media_type` taken from the upload's content type.
- `40001`: the multipart body has no `file` field
#### `GET /api/v1/files/{file_id}`
Downloads an uploaded file. The response is a binary stream that honors range requests but ignores `If-None-Match`; failures use real HTTP statuses β see [Binary and streaming endpoints](#binary-and-streaming-endpoints).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `file_id` | path | string | **Required.** File id from the upload response |
- `40407` (HTTP 404): no file with that id (including an expired file)
#### `DELETE /api/v1/files/{file_id}`
Deletes an uploaded file.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `file_id` | path | string | **Required.** File id from the upload response |
On success, `data` is `{ deleted: true }`.
- `40407` (HTTP 404): no file with that id
### GUI store
A server-backed key/value store that mirrors the browser `localStorage` interface, persisted under the server's home directory; the web UI keeps cross-client UI state here. Values are opaque strings β serialization is the caller's job.
| Method and path | Description |
| --- | --- |
| `GET /api/v1/gui/store/length` | Number of stored keys |
| `GET /api/v1/gui/store/getItem` | Read a value by key |
| `POST /api/v1/gui/store/setItem` | Write a value by key |
| `POST /api/v1/gui/store/removeItem` | Delete a value by key |
| `POST /api/v1/gui/store/clear` | Delete all values |
#### `GET /api/v1/gui/store/length`
Returns the number of stored keys (mirrors `localStorage.length`). No parameters.
On success, `data` is `{ length }`.
#### `GET /api/v1/gui/store/getItem`
Reads one value (mirrors `localStorage.getItem`).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `key` | query | string | **Required.** Key to read, 1β256 characters |
On success, `data` is `{ value }`, the stored string or `null` when the key does not exist.
#### `POST /api/v1/gui/store/setItem`
Writes one value (mirrors `localStorage.setItem`).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `key` | body | string | **Required.** Key to write, 1β256 characters |
| `value` | body | string | **Required.** Value to store |
On success, `data` is `null`.
#### `POST /api/v1/gui/store/removeItem`
Deletes one value (mirrors `localStorage.removeItem`).
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `key` | body | string | **Required.** Key to delete, 1β256 characters |
On success, `data` is `null`.
#### `POST /api/v1/gui/store/clear`
Deletes every stored value (mirrors `localStorage.clear`). No parameters.
On success, `data` is `null`.
### Global search and misc
| Method and path | Description |
| --- | --- |
| `POST /api/v1/search` | Cross-session full-text search; `mode` is `terms` (default) or `literal` (exact substring); `page_token` pagination |
| `GET /api/v1/connections` | List live WebSocket connections |
| `GET /api/v2/sessions` | Next-generation session list, see below |
| `POST /api/v2/sessions:archive` | Batch-archive sessions, see below |
| `POST /api/v2/sessions:restore` | Batch-restore archived sessions, see below |
| `/api/v2/mcp/*` | Unified MCP management plane, see below |
| `/api/v1/debug/*` | Reflection debug RPC; mounted only with `--debug-endpoints` on loopback, not a stable protocol |
#### `POST /api/v1/search`
Cross-session full-text search over user messages, assistant replies, and session titles, backed by the server's persistent search index. When `container.session_id` names a session live in this server process, the search instead scans that session's in-memory transcript directly, and the response's `source` field (`index` or `live`) reports which path served the page.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `query` | body | string | **Required.** Search text |
| `mode` | body | string | `terms` (default) / `literal` |
| `op` | body | string | Term combiner in `terms` mode: `AND` (default) / `OR` |
| `container` | body | object | Restrict the search to `{ session_id?, agent_id? }` |
| `role` | body | string | Restrict to `user` / `assistant` / `title` hits |
| `start_time` | body | integer | Only hits at or after this time (epoch milliseconds) |
| `end_time` | body | integer | Only hits at or before this time (epoch milliseconds) |
| `sort` | body | string | `score` (default) / `time_desc` / `time_asc`; ignored by `literal` mode, which always returns newest-first |
| `page_size` | body | integer | Hits per page, 1β50. Default `20` |
| `page_token` | body | string | Token from the previous page's response |
In `terms` mode the query is tokenized (ASCII words plus CJK n-grams), deduplicated, and matched against the inverted index with at most 32 terms; `literal` mode is an exact substring search with zero false positives. On success, `data` is `{ items, has_more, page_token?, index_state, source }` where each item is `{ session_id, workspace_id, session_title, agent_id, role, snippet, time, turn?, step_id?, score }`. `index_state` is `{ state, indexed_sessions, total_sessions, documents, stale?, degraded? }` with `state` one of `building` / `ready` / `readonly`; `stale` marks a behind view still catching up, and `degraded` carries the last refresh failure. An over-budget page additionally carries `incomplete`, one of `candidate_cap` / `postings_budget` / `deadline`. Page tokens pin the index generation and the query conditions β a rebuild or a changed query invalidates them.
- `40001`: body validation failure, an unusable query (empty, or more than 32 terms), or an invalid page token
#### `GET /api/v1/connections`
Lists the WebSocket clients currently connected to this server, oldest connection first. No parameters.
On success, `data` is `{ connections }` where each item is `{ id, connected_at, remote_address, user_agent, has_client_hello, subscriptions }`: `connected_at` is an ISO 8601 timestamp, `remote_address` and `user_agent` are `null` when unknown, `has_client_hello` reports whether the client sent its handshake frame, and `subscriptions` lists the session ids the connection is subscribed to.
### `GET /api/v2/sessions`
A next-generation session query for list views β filtering, sorting, and field groups all travel in query parameters:
| Parameter | Description |
| --- | --- |
| `workspace.id` | Filter by workspace; repeatable |
| `activity.status` | Filter by activity status: `running` / `approval` / `question` / `failed` / `idle`; repeatable |
| `meta.updated_after` | Only sessions updated after this time (epoch milliseconds) |
| `meta.updated_before` | Only sessions updated before this time (epoch milliseconds) |
| `meta.archived` | `true` / `false` (default) / `all` |
| `meta.has_prompt` | `true` keeps only sessions that carry a user prompt, `false` keeps only empty ones (the `exclude_empty` equivalent of `GET /api/v1/sessions`) |
| `view` | `flat` (default) / `by_workspace`, see below |
| `group.page_size` | Sessions returned per workspace under `view=by_workspace`: 1β100, default 5 (up to 10000 with the `id,archived` projection); rejected without the grouped view (`40001`) |
| `sort` | `meta.updated_at_desc` (default) / `meta.updated_at_asc` / `meta.created_at_desc` |
| `include` | Comma-separated extra field groups; currently only `git` (branch and PR info, deduplicated per directory and cached for 60 seconds) |
| `fields` | Comma-separated item projection; currently only `id,archived`, trimming each item to `{ id, archived }` (select-all-matching flows). Not combinable with `include=git` (`40001`) |
| `page_size` | 1β100, default 50; up to 10000 with the `id,archived` projection. Under `view=by_workspace` it counts groups per page |
| `page_token` | Pagination token from the previous page |
| `page` | Stateless 1-based page number; mutually exclusive with `page_token` (`40001` when combined) |
Every response item carries the `workspace`, `meta`, and `activity` groups, plus `git` when `include=git` β or just `{ id, archived }` under `fields=id,archived`. The `activity` group also reports `model`: the session's bound model alias while it is live in this process, `null` for cold (not currently loaded) sessions. Every page additionally carries `total`, the size of the filtered set. The page token binds the first page's query conditions (including the projection); changing them mid-pagination returns `40922`. `page` mode is a stateless alternative for jumping to arbitrary pages: every request is an independent snapshot, no token is minted, and `next_page_token` is always `null`.
With `view=by_workspace` the same filtered, sorted set is re-projected into per-workspace groups, so an overview client replaces one polling loop per workspace with a single request:
```json
{
"code": 0,
"msg": "success",
"data": {
"groups": [
{
"workspace": { "id": "wd_my-app_a1b2c3d4e5f6", "cwd": "/Users/dev/my-app" },
"sessions": [ { "id": "session_...", "workspace": { "id": "wd_my-app_a1b2c3d4e5f6", "cwd": "/Users/dev/my-app" }, "meta": { "title": "Fix the login page", "last_prompt": "adjust the button spacing", "created_at": 1787000000000, "updated_at": 1787000100000, "archived": false, "archived_at": null }, "activity": { "status": "idle", "model": "kimi-for-coding" } } ],
"total": 42
}
],
"total": 7,
"has_more": true,
"next_page_token": "eyJ2IjoxLCJmIjoi..."
},
"request_id": "req_..."
}
```
Each group carries the workspace's first `group.page_size` sessions under the requested `sort` plus `total`, the workspace's full matching-session count (for a "view all" entry). Only workspaces with at least one matching session appear; groups order by their first session's sort key, ties broken by workspace id. `page` and `page_token` paginate over groups (the outer `total` is the group count), with the same fingerprint binding: the token also covers `view` and the grouping parameters, so flipping them mid-pagination returns `40922`.
### `POST /api/v2/sessions:archive` and `POST /api/v2/sessions:restore`
Batch archive/restore for session-management views. The body is `{ "ids": ["session_..."] }` β non-empty, at most 5000 unique ids (duplicates collapse). Live sessions go through the full lifecycle; cold sessions are patched on disk without being loaded.
Only a body validation failure fails the whole request (`40001`). Otherwise the response is per-item: `data.results` keeps the input order with `{ id, ok }` or `{ id, ok: false, error }` (an unknown id reports `40401` in its own item), plus `succeeded` / `failed` counts.
```json
{
"code": 0,
"msg": "success",
"data": {
"results": [
{ "id": "session_a", "ok": true },
{ "id": "session_b", "ok": false, "error": { "code": 40401, "message": "session session_b does not exist" } }
],
"succeeded": 1,
"failed": 1
},
"request_id": "req_..."
}
```
### MCP management (`/api/v2/mcp`)
The `/api/v2/mcp/*` routes are the server's unified MCP management plane: they manage the MCP server registry itself, independent of any session β global (user-level) CRUD with per-entry validation, connection-test probes, a locator-addressed inspection catalog, per-server auth-status listing, and the full OAuth flow lifecycle.
| Method and path | Description |
| --- | --- |
| `GET /api/v2/mcp/servers` | List every known MCP server |
| `GET /api/v2/mcp/servers/{name}` | Get one server by runtime name |
| `POST /api/v2/mcp/servers` | Add a server to the user-level `mcp.json` |
| `PUT /api/v2/mcp/servers/{name}` | Replace a user-level entry |
| `DELETE /api/v2/mcp/servers/{name}` | Remove a user-level entry |
| `POST /api/v2/mcp/servers:test` | Probe a real connection to one server |
| `POST /api/v2/mcp/servers:inspect` | Locator-addressed catalog with a batched connection probe |
| `GET /api/v2/mcp/auth-statuses` | Per-server OAuth state over the catalog |
| `POST /api/v2/mcp/auth:begin` | Begin an interactive OAuth flow |
| `POST /api/v2/mcp/auth:complete` | Await the browser callback and finish the code exchange |
| `POST /api/v2/mcp/auth:cancel` | Tear down a begun OAuth flow |
| `POST /api/v2/mcp/auth:reset` | Clear a server's stored credentials |
Two addressing schemes appear on this plane. The CRUD routes and `servers:test` take a plain runtime `name`; the inspection and OAuth routes take a **locator** β `{ "source": "global", "name" }` for a file-layer entry or `{ "source": "plugin", "pluginId", "serverName" }` for a plugin-manifest entry β because a plugin entry and a file entry can share one runtime name. Inspection items additionally carry a stable `serverId` wire id: `global:<name>` or `plugin:<pluginId>:<serverName>` (URL-encoded).
Most routes accept an optional `cwd` (a query parameter, or a body field on the `:`-action routes). Without it the catalog covers the user-level file and plugin manifests only; with it, the project-root and project-local layers of that directory join in β but only when the workspace is trusted, otherwise the project layers are skipped. For `servers:test` on a stdio server, `cwd` is also the child process's working directory. Connection probes and OAuth calls wait for the server's configuration to finish loading before acting.
#### `GET /api/v2/mcp/servers` and `GET /api/v2/mcp/servers/{name}`
Lists every MCP server the management plane knows about; the second route returns the single entry with that runtime name.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `name` | path | string | **Required (get only).** Runtime name of the server |
| `cwd` | query | string | Include the project layers of this (trusted) directory |
On success, `data` is an array of managed servers (a single object for the get route), each `{ name, config, source, origin, mutable, plugin? }`:
- `source`: `global` (a config-file layer) or `plugin` (a plugin manifest)
- `origin`: where the entry is defined β a file path or a plugin id
- `mutable`: only user-level entries are mutable; plugin and project-layer entries are read-only
- `config`: mutable entries carry the full config so edit UIs can prefill it; read-only entries are redacted to sorted key lists (`envKeys` / `headerKeys`) and never disclose secret values
- `plugin`: `{ id, name }`, present on plugin entries
- `40001`: validation failure
- `40408`: no server with that name
#### `POST` / `PUT` / `DELETE /api/v2/mcp/servers`
Global CRUD against the user-level `mcp.json`. The add body is a full server config including `name` β `transport` (`stdio` / `http` / `sse`) discriminates the shape, and each entry is validated before it is written. The update body carries the same config without `name` (the path names the entry); delete takes no body. All three return the refreshed server list in `data`. A write whose name collides with a project-layer entry is rejected as read-only β edit the defining file instead; a same-named plugin entry does not block the write, and the new file entry shadows it.
- `40001`: validation failure, or the target entry is read-only
- `40408`: (update/delete) no server with that name
#### `POST /api/v2/mcp/servers:test`
Probes a real connection to one server and never persists anything. Pass either `name` to test a registry entry (plugin and trusted project layers included) or `server` (a full inline config, `name` included) to probe it as-is; passing both or neither fails `40001`.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `name` | body | string | Runtime name of a registry entry |
| `server` | body | object | Inline server config to probe as-is |
| `cwd` | body | string | Project layers join the resolution; also the stdio working directory |
On success, `data` is `{ success, output }`: when the connection succeeds, `output` lists the server's available tools; otherwise it carries the failure text.
- `40001`: both or neither target form passed, an invalid inline config, or a runtime name shared by multiple enabled servers
- `40408`: no server with that name
#### `POST /api/v2/mcp/servers:inspect`
The locator-addressed catalog (redacted configs) plus a batched real-connection probe of every OAuth candidate.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `targets` | body | array | Locators narrowing the catalog; omitted inspects all servers |
| `cwd` | body | string | Include the project layers of this (trusted) directory |
On success, `data` is an array of inspections, each `{ serverId, locator, runtimeName, canonicalUrl?, origin, config, enabled, editable, authStatus, checkedAt?, error? }`: `canonicalUrl` is the credential URL of a remote server, `config` is the redacted view, and `authStatus` is one of `not-applicable` / `bearer-token` / `oauth-required` / `oauth-authorized` / `oauth-expired` / `unavailable`. A runtime name shared by multiple enabled servers cannot be probed unambiguously and reports `unavailable` with an explanatory `error`. A probe that hits an expired grant may refresh or invalidate the stored credentials.
- `40001`: validation failure
- `40408`: a `targets` locator matches nothing
#### `GET /api/v2/mcp/auth-statuses`
Per-server OAuth state over the registry catalog β the lightweight alternative to `servers:inspect` when only the auth dimension is needed.
| Parameter | In | Type | Description |
| --- | --- | --- | --- |
| `cwd` | query | string | Include the project layers of this (trusted) directory |
| `verify` | query | string | `true` probes every OAuth candidate through a real connection; `false` is fully offline (config and stored tokens only); omitted preserves implicit OAuth detection, probing only unpinned remote servers without stored credentials |
On success, `data` is an array of `{ name, authStatus }` with the same `authStatus` enum as `servers:inspect`. Verification probes may refresh or invalidate stored credentials.
#### `POST /api/v2/mcp/auth:begin` / `:complete` / `:cancel` / `:reset`
The OAuth flow lifecycle for remote servers. `auth:begin` takes a locator body (plus the optional `cwd` query) and answers `data` `{ status: "authorization-required", flowId, authorizationUrl }` β open the URL in a browser to grant access β or `{ status: "already-authorized" }` when a grant already exists. The target server must use a remote transport (`http` / `sse`) and must not carry a static bearer token; static headers are allowed only when the config explicitly sets `auth: "oauth"`.
`auth:complete` waits for the browser callback of a begun flow and finishes the code exchange. Its body is `{ flowId, timeoutMs? }`: the wait defaults to 15 minutes (`timeoutMs` overrides it), an idle flow expires after 15 minutes regardless, and closing the HTTP connection aborts the wait. `data` is `null` on success.
`auth:cancel` tears down a begun flow (`{ flowId }`) without finishing it; unknown flows are ignored. `auth:reset` takes a locator body and clears the server's stored credentials β the invalidation event reaches live sessions.
- `40001`: validation failure β including an unknown `flowId` on `:complete`, or a server that cannot do OAuth (stdio transport, a static bearer token, or static headers without `auth: "oauth"`) on `:begin`
- `40408`: (`:begin` / `:reset`) the locator matches nothing
- `40929`: the OAuth flow itself failed
## WebSocket protocol
### Connect
The only endpoint is `ws://<host>:<port>/api/v1/ws`; authentication happens at the upgrade request (see [Authentication](#authentication) above). Once connected, the server immediately sends `server_hello`:
```json
{
"type": "server_hello",
"timestamp": "2026-01-01T00:00:00.000Z",
"payload": {
"ws_connection_id": "conn_01JZX4...",
"protocol_version": 2,
"max_event_buffer_size": 1000,
"capabilities": { "event_batching": false, "compression": false }
}
}
```
Note that the server never sends heartbeats and never disconnects an idle connection β keepalive and reconnection are the client's job.
### Control frames
Clients send JSON frames `{ "type", "id"?, "payload" }`; every request frame gets an acknowledgement `{ "type": "ack", "id", "code", "msg", "payload" }`, where `code` 0 means success.
| Frame | payload | Description |
| --- | --- | --- |
| `subscribe` | `{ session_ids, cursors?, agent_filter? }` | Subscribe to session events; with `cursors` (per-session `{seq, epoch}`) the server replays missed durable events |
| `unsubscribe` | `{ session_ids }` | Drop session subscriptions |
| `subscribe_v2` | `{ session_id, transcript, transcript_since? }` | Subscribe to transcript streams (the only transcript channel); `transcript` sets per-agent grades |
| `unsubscribe_v2` | `{ session_id, agent_ids? }` | Detach transcript streams; omitting `agent_ids` means the whole session |
| `client_hello` | `{ client_id }` | Handshake frame; the remaining fields are legacy compatibility |
### Events
Event frames look like `{ "type", "seq", "epoch"?, "volatile"?, "offset"?, "session_id"?, "timestamp", "payload" }`, where `type` is the event type itself. Two delivery scopes:
- **Global events**: sent to every established connection, no subscription needed β `session.meta.updated`, `event.session.created`, `event.session.archived`, `event.session.work_changed`, `event.session.status_changed`, `event.workspace.*`, `event.config.*`, `event.model_catalog.*`.
- **Session events**: sent only to connections subscribed to that session, subject to `agent_filter`. Main families:
| Family | Main events |
| --- | --- |
| Turns | `turn.started`, `turn.ended`, `turn.step.started` / `completed` / `interrupted` / `retrying` |
| Streaming text | `assistant.delta`, `thinking.delta` (carry `offset` for alignment) |
| Tool calls | `tool.call.started`, `tool.call.delta`, `tool.progress`, `tool.result` |
| Interactions | `event.approval.requested` / `resolved`, `event.question.requested` / `answered` / `dismissed` |
| Subagents | `subagent.spawned` / `started` / `suspended` / `completed` / `failed` |
| Background | `task.started` / `terminated`, `shell.started` / `output` / `completed` |
| Misc | `compaction.*`, `skill.activated`, `goal.updated`, `prompt.*`, `error`, `warning` |
Three global lifecycle events keep a cross-workspace overview fresh without polling per workspace. `event.session.archived` fires on both the live and the cold archive path; its envelope `session_id` is the global watermark `__global__` and the real session id rides in the payload: `{ "type": "event.session.archived", "workspace_id": "wd_...", "sessionId": "session_..." }` (payload keys `workspace_id` / `sessionId`). `event.workspace.created` / `updated` carry the full workspace object (`{ id, root, name, created_at, last_opened_at, session_count }` β an `updated` also fires when a session creation touches the workspace), and `event.workspace.deleted` carries `{ "workspace_id", "root" }`. These events only cover changes made inside this server process; changes from other processes (for example a CLI writing to the same home) surface through the index reconciliation (about a minute), so overview clients should keep a low-frequency fallback poll. There is no session-deleted event.
Events also split into durable and volatile: durable events carry a strictly increasing `seq`, are journaled, and can be replayed; volatile events (the `*.delta` family, `tool.progress`, `shell.*`, and similar) are marked `volatile: true` and never replayed. When consuming a volatile text stream, compare `offset` (the cumulative character offset within the turn) against your locally accumulated text: below the local length means a duplicate frame; above means a gap that needs snapshot recovery.
### Reconnect and recovery
After reconnecting, pass each session's last applied `{seq, epoch}` in `subscribe`'s `cursors`; the server replays the gap. If you fall more than the buffer (1000 events) behind, or the cursor is no longer valid, you get `resync_required` instead. In that case, call `GET /api/v1/sessions/{session_id}/snapshot` for a full snapshot (with `as_of_seq` and `epoch`), then subscribe again with the fresh cursor.
### Transcript protocol
`subscribe_v2`'s `transcript` field sets a per-agent grade: `off` / `turn` / `block` / `delta` (the `"*"` key sets the default grade), with higher grades pushing finer detail. An agent with a non-`off` grade receives two frame types: `transcript.reset` (a baseline snapshot; history pages in over REST) and `transcript.ops` (incremental op batches with a per-agent strictly increasing `seq`). The agent's legacy events are suppressed on that connection and carried by transcript frames instead. After a disconnect, resume with `transcript_since`; when the server's op journal cannot cover the gap (REST catch-up returns `complete: false`), do a full refresh. The REST counterparts are `GET .../transcript` (turn-paged) and `GET .../transcript/ops?since_seq=` (op-batch catch-up).
## Binary and streaming endpoints
The following endpoints stream binary bodies instead of a JSON payload. Their HTTP capabilities differ per endpoint:
| Method and path | Description | Range (206) | ETag / 304 |
| --- | --- | --- | --- |
| `GET /api/v1/files/{file_id}` | Download an uploaded file | Yes | No (sends an `etag` header but ignores `If-None-Match`) |
| `GET /api/v1/sessions/{session_id}/fs/{path}:download` | Download a session workspace file | Yes | Yes |
| `GET /api/v1/fs:content` | Raw bytes of any host file (gated only by the token β be careful when exposing the port) | Yes | Yes |
| `POST /api/v1/sessions/{session_id}/export` | Export the session with diagnostics (zip stream) | No | No |
Error semantics differ as well: `GET /api/v1/files/{file_id}` answers lookup and storage failures with real 404 / 500 statuses (parameter validation still uses the HTTP 200 envelope), while the other three report every failure through the standard [response envelope](#response-envelope) β clients must keep checking the envelope `code` on those endpoints.
## Next steps
- [Using Kimi Code in the browser](../guides/web.md) β start the server and use Kimi Code in a browser
- [kimi command](./kimi-command.md#kimi-web) β all `kimi web` command-line options
|