kiki-agent 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +3 -3
  2. package/dist/cpu-worker.mjs +52744 -0
  3. package/dist/docs/en/configuration/config-files.md +121 -46
  4. package/dist/docs/en/configuration/data-locations.md +34 -7
  5. package/dist/docs/en/configuration/env-vars.md +37 -9
  6. package/dist/docs/en/configuration/overrides.md +20 -9
  7. package/dist/docs/en/configuration/providers.md +114 -9
  8. package/dist/docs/en/customization/agent-profiles.md +1 -1
  9. package/dist/docs/en/customization/agents-and-subagents.md +55 -12
  10. package/dist/docs/en/customization/hooks.md +3 -3
  11. package/dist/docs/en/customization/personas.md +36 -2
  12. package/dist/docs/en/customization/plugins.md +56 -3
  13. package/dist/docs/en/customization/prompt-fields.md +65 -5
  14. package/dist/docs/en/customization/recipes.md +77 -0
  15. package/dist/docs/en/customization/skins.md +2 -2
  16. package/dist/docs/en/customization/themes.md +1 -1
  17. package/dist/docs/en/features/agent-workflows.md +8 -8
  18. package/dist/docs/en/features/browser-and-computer.md +40 -0
  19. package/dist/docs/en/features/daily.md +13 -13
  20. package/dist/docs/en/features/ecosystem.md +6 -6
  21. package/dist/docs/en/features/extend.md +11 -10
  22. package/dist/docs/en/features/freedom.md +9 -9
  23. package/dist/docs/en/features/index.md +58 -28
  24. package/dist/docs/en/features/long-work.md +18 -14
  25. package/dist/docs/en/features/look.md +6 -6
  26. package/dist/docs/en/features/people.md +6 -6
  27. package/dist/docs/en/features/phone.md +13 -3
  28. package/dist/docs/en/features/spaces.md +12 -12
  29. package/dist/docs/en/features/workbench.md +8 -8
  30. package/dist/docs/en/getting-started/desktop-app.md +4 -8
  31. package/dist/docs/en/getting-started/first-launch.md +1 -1
  32. package/dist/docs/en/guides/goals.md +4 -2
  33. package/dist/docs/en/guides/interface.md +32 -10
  34. package/dist/docs/en/guides/memory.md +64 -10
  35. package/dist/docs/en/guides/sessions.md +21 -9
  36. package/dist/docs/en/guides/settings.md +64 -40
  37. package/dist/docs/en/index.md +3 -1
  38. package/dist/docs/en/reference/command.md +90 -31
  39. package/dist/docs/en/reference/model-vocabulary.md +2 -2
  40. package/dist/docs/en/reference/slash-commands.md +1 -1
  41. package/dist/docs/en/reference/tools.md +65 -20
  42. package/dist/docs/en/server/acp.md +9 -3
  43. package/dist/docs/en/server/local-server.md +19 -27
  44. package/dist/docs/en/server/mcp.md +9 -5
  45. package/dist/docs/en/server/rest-api.md +350 -22
  46. package/dist/docs/en/server/script-tools.md +268 -0
  47. package/dist/docs/zh/configuration/config-files.md +121 -46
  48. package/dist/docs/zh/configuration/data-locations.md +34 -7
  49. package/dist/docs/zh/configuration/env-vars.md +37 -9
  50. package/dist/docs/zh/configuration/overrides.md +20 -9
  51. package/dist/docs/zh/configuration/providers.md +114 -9
  52. package/dist/docs/zh/customization/agent-profiles.md +1 -1
  53. package/dist/docs/zh/customization/agents-and-subagents.md +55 -12
  54. package/dist/docs/zh/customization/hooks.md +3 -3
  55. package/dist/docs/zh/customization/personas.md +36 -2
  56. package/dist/docs/zh/customization/plugins.md +56 -3
  57. package/dist/docs/zh/customization/prompt-fields.md +65 -5
  58. package/dist/docs/zh/customization/recipes.md +77 -0
  59. package/dist/docs/zh/customization/skins.md +2 -2
  60. package/dist/docs/zh/customization/themes.md +1 -1
  61. package/dist/docs/zh/features/agent-workflows.md +10 -10
  62. package/dist/docs/zh/features/browser-and-computer.md +40 -0
  63. package/dist/docs/zh/features/daily.md +13 -13
  64. package/dist/docs/zh/features/ecosystem.md +6 -6
  65. package/dist/docs/zh/features/extend.md +10 -9
  66. package/dist/docs/zh/features/freedom.md +9 -9
  67. package/dist/docs/zh/features/index.md +58 -28
  68. package/dist/docs/zh/features/long-work.md +17 -13
  69. package/dist/docs/zh/features/look.md +6 -6
  70. package/dist/docs/zh/features/people.md +5 -5
  71. package/dist/docs/zh/features/phone.md +13 -3
  72. package/dist/docs/zh/features/spaces.md +12 -12
  73. package/dist/docs/zh/features/workbench.md +8 -8
  74. package/dist/docs/zh/getting-started/desktop-app.md +4 -8
  75. package/dist/docs/zh/getting-started/first-launch.md +1 -1
  76. package/dist/docs/zh/guides/goals.md +4 -2
  77. package/dist/docs/zh/guides/interface.md +32 -10
  78. package/dist/docs/zh/guides/memory.md +64 -10
  79. package/dist/docs/zh/guides/sessions.md +21 -9
  80. package/dist/docs/zh/guides/settings.md +64 -40
  81. package/dist/docs/zh/index.md +4 -2
  82. package/dist/docs/zh/reference/command.md +90 -31
  83. package/dist/docs/zh/reference/model-vocabulary.md +2 -2
  84. package/dist/docs/zh/reference/slash-commands.md +1 -1
  85. package/dist/docs/zh/reference/tools.md +65 -20
  86. package/dist/docs/zh/server/acp.md +9 -3
  87. package/dist/docs/zh/server/local-server.md +19 -27
  88. package/dist/docs/zh/server/mcp.md +9 -5
  89. package/dist/docs/zh/server/rest-api.md +338 -21
  90. package/dist/docs/zh/server/script-tools.md +268 -0
  91. package/dist/external-harness/agy-cli-acp.mjs +168 -162
  92. package/dist/external-harness/agy-hook-registration.mjs +69 -30
  93. package/dist/external-harness/agy-mcp-plugin.mjs +19 -0
  94. package/dist/external-harness/agy-permission-hook.mjs +29 -2
  95. package/dist/hostRunner.mjs +112 -3
  96. package/dist/mailbox-worker.mjs +403 -0
  97. package/dist/main.mjs +2 -2
  98. package/dist/memory-worker.mjs +1008 -0
  99. package/dist/native/windows-process-helper.exe +0 -0
  100. package/dist/query-store-worker.mjs +487 -0
  101. package/dist/sqlite-indexer.mjs +255 -403
  102. package/dist/sqlite-query-worker.mjs +261 -249
  103. package/dist/usage-parser-worker.mjs +3977 -9
  104. package/dist/usage-read-model-worker.mjs +761 -0
  105. package/dist/web/assets/AppErrorBoundary-B5Fc4f6-.js +1 -0
  106. package/dist/web/assets/NavScopeBoundary-C7MnGQio.js +1 -0
  107. package/dist/web/assets/{arc-DYDCMlOS.js → arc-DGB9OVgQ.js} +1 -1
  108. package/dist/web/assets/{architectureDiagram-3BPJPVTR-C9Y7T0O2.js → architectureDiagram-3BPJPVTR-glnQCMub.js} +1 -1
  109. package/dist/web/assets/{blockDiagram-GPEHLZMM-CdUrp-tD.js → blockDiagram-GPEHLZMM-bM0tnGby.js} +1 -1
  110. package/dist/web/assets/{c4Diagram-AAUBKEIU-PrwvB9IJ.js → c4Diagram-AAUBKEIU-DMf_rTtt.js} +1 -1
  111. package/dist/web/assets/channel-Cj8SKJ38.js +1 -0
  112. package/dist/web/assets/{chunk-2J33WTMH-BL56g_Es.js → chunk-2J33WTMH-mTccJ3tW.js} +1 -1
  113. package/dist/web/assets/{chunk-4BX2VUAB-DvJD5M9M.js → chunk-4BX2VUAB-DhqPYMjY.js} +1 -1
  114. package/dist/web/assets/{chunk-55IACEB6-C8f-nzvx.js → chunk-55IACEB6-BujrYRoO.js} +1 -1
  115. package/dist/web/assets/{chunk-727SXJPM-DOGkWKkV.js → chunk-727SXJPM-ciMmSI4G.js} +1 -1
  116. package/dist/web/assets/{chunk-AQP2D5EJ-fFOuz7g6.js → chunk-AQP2D5EJ-CZW9pKTc.js} +1 -1
  117. package/dist/web/assets/{chunk-FMBD7UC4-BpeXZ9LM.js → chunk-FMBD7UC4-hdALNnnU.js} +1 -1
  118. package/dist/web/assets/{chunk-ND2GUHAM-CRUh76fb.js → chunk-ND2GUHAM-CgKyqUdb.js} +1 -1
  119. package/dist/web/assets/{chunk-QZHKN3VN-uNfxaPk0.js → chunk-QZHKN3VN-B2mmUz_E.js} +1 -1
  120. package/dist/web/assets/classDiagram-4FO5ZUOK-f8V9p-dD.js +1 -0
  121. package/dist/web/assets/classDiagram-v2-Q7XG4LA2-f8V9p-dD.js +1 -0
  122. package/dist/web/assets/client-ClWQBErG.js +3 -0
  123. package/dist/web/assets/connection-C0J3BPgk.js +1 -0
  124. package/dist/web/assets/{cose-bilkent-S5V4N54A-BNkxG-qX.js → cose-bilkent-S5V4N54A-UV3uPjkK.js} +1 -1
  125. package/dist/web/assets/{dagre-BM42HDAG-BerioUei.js → dagre-BM42HDAG-Zjy-gQ6C.js} +1 -1
  126. package/dist/web/assets/{diagram-2AECGRRQ-Czv2SR07.js → diagram-2AECGRRQ-DL-kilIf.js} +1 -1
  127. package/dist/web/assets/{diagram-5GNKFQAL-Uzi1weGK.js → diagram-5GNKFQAL-CjB_xR5B.js} +1 -1
  128. package/dist/web/assets/{diagram-KO2AKTUF-W36h_ff3.js → diagram-KO2AKTUF-CjN4i3b9.js} +1 -1
  129. package/dist/web/assets/{diagram-LMA3HP47-FG4dDk52.js → diagram-LMA3HP47-CPCAMndo.js} +1 -1
  130. package/dist/web/assets/{diagram-OG6HWLK6-CQoEjIAY.js → diagram-OG6HWLK6-DVeBWBKd.js} +1 -1
  131. package/dist/web/assets/{erDiagram-TEJ5UH35-Ck06KVyZ.js → erDiagram-TEJ5UH35-CHKzBHrr.js} +1 -1
  132. package/dist/web/assets/export-CXoWon32.js +2 -0
  133. package/dist/web/assets/{flowDiagram-I6XJVG4X-C5hgxdFZ.js → flowDiagram-I6XJVG4X-C5rQa2pq.js} +1 -1
  134. package/dist/web/assets/{ganttDiagram-6RSMTGT7-BS52Pw5_.js → ganttDiagram-6RSMTGT7-BrLjEsNJ.js} +1 -1
  135. package/dist/web/assets/{gitGraphDiagram-PVQCEYII-DLlQKZHs.js → gitGraphDiagram-PVQCEYII-3DRR5VZj.js} +1 -1
  136. package/dist/web/assets/highlighted-body-OFNGDK62-Bdj5SJfv.js +1 -0
  137. package/dist/web/assets/index-2Vx5mHRn.js +1 -0
  138. package/dist/web/assets/index-B1UXw2C9.js +1 -0
  139. package/dist/web/assets/{index-CM-nNfuV.js → index-BJxtlf4P.js} +4 -4
  140. package/dist/web/assets/{index-DKIysLbI.js → index-BY7jPurv.js} +1 -1
  141. package/dist/web/assets/index-Bq79v-Sa.js +1 -0
  142. package/dist/web/assets/index-BqD3iTIl.js +1 -0
  143. package/dist/web/assets/index-Br3AlBrQ.js +1 -0
  144. package/dist/web/assets/{index-Ca607_hK.js → index-BvRBCpc6.js} +2 -2
  145. package/dist/web/assets/index-BxYCSNg_.js +3 -0
  146. package/dist/web/assets/{index-B2Pu0Iuu.js → index-C62wjCF_.js} +1 -1
  147. package/dist/web/assets/index-CBvwNH_H.js +1 -0
  148. package/dist/web/assets/{index-BNch_a4L.js → index-CG9e6lgq.js} +1 -1
  149. package/dist/web/assets/{index-ByiwExpV.js → index-CPSWYh_R.js} +2 -2
  150. package/dist/web/assets/index-CS4xJLZV.js +1 -0
  151. package/dist/web/assets/index-CjvqtF2I.js +1 -0
  152. package/dist/web/assets/index-CprdjRRk.js +13 -0
  153. package/dist/web/assets/{index-Bg99yVX_.js → index-CypTtrCB.js} +1 -1
  154. package/dist/web/assets/{index-BwcG86o3.js → index-DDJQGcUL.js} +1 -1
  155. package/dist/web/assets/index-DLWzxUOO.js +1 -0
  156. package/dist/web/assets/index-DQxkxZmn.js +7 -0
  157. package/dist/web/assets/index-DRo5Y_9p.js +1 -0
  158. package/dist/web/assets/index-De_LkTZx.js +1 -0
  159. package/dist/web/assets/{index-CZX3qUe2.js → index-DfUpwUTM.js} +2 -2
  160. package/dist/web/assets/{index-BLU8_Um7.js → index-Dkbz748K.js} +2 -2
  161. package/dist/web/assets/index-DmwFFSkV.js +1 -0
  162. package/dist/web/assets/index-DpcWEDhW.js +1 -0
  163. package/dist/web/assets/index-Dqq1RDP4.js +1 -0
  164. package/dist/web/assets/index-H1uMvIoa.css +1 -0
  165. package/dist/web/assets/index-ICHWJ2SM.js +1 -0
  166. package/dist/web/assets/index-O5fSd569.js +229 -0
  167. package/dist/web/assets/index-odjtqLLS.js +1 -0
  168. package/dist/web/assets/index-v_yAQ0Am.js +1 -0
  169. package/dist/web/assets/{infoDiagram-5YYISTIA-CD4XJGFm.js → infoDiagram-5YYISTIA-CCwV4Z0v.js} +1 -1
  170. package/dist/web/assets/{ishikawaDiagram-YF4QCWOH-fu5E3_CT.js → ishikawaDiagram-YF4QCWOH-BwwZcGyZ.js} +1 -1
  171. package/dist/web/assets/{journeyDiagram-JHISSGLW-CXcnKBfJ.js → journeyDiagram-JHISSGLW-Dc6WqniQ.js} +1 -1
  172. package/dist/web/assets/{kanban-definition-UN3LZRKU-BawKH6Pl.js → kanban-definition-UN3LZRKU-DVUqULOS.js} +1 -1
  173. package/dist/web/assets/{linear-BplJuXph.js → linear-d6rWsNOU.js} +1 -1
  174. package/dist/web/assets/memoryAdvisor-DBQXJB1o.js +1 -0
  175. package/dist/web/assets/mermaid-GHXKKRXX-Ik6SkVDT.js +642 -0
  176. package/dist/web/assets/{mindmap-definition-RKZ34NQL-DA1SE2uy.js → mindmap-definition-RKZ34NQL-_JHAkhHL.js} +1 -1
  177. package/dist/web/assets/navViewState-DaCMIYWA.js +1 -0
  178. package/dist/web/assets/{pieDiagram-4H26LBE5-6i021QeX.js → pieDiagram-4H26LBE5-BlhlygGy.js} +1 -1
  179. package/dist/web/assets/{quadrantDiagram-W4KKPZXB-CcKSZDMT.js → quadrantDiagram-W4KKPZXB-jn6R_C0S.js} +1 -1
  180. package/dist/web/assets/{requirementDiagram-4Y6WPE33-lYVuWRuD.js → requirementDiagram-4Y6WPE33-B9fXCHBr.js} +1 -1
  181. package/dist/web/assets/{sankeyDiagram-5OEKKPKP-4Zfb4_h4.js → sankeyDiagram-5OEKKPKP-fPJwIxkl.js} +1 -1
  182. package/dist/web/assets/{sequenceDiagram-3UESZ5HK-DqltKmlY.js → sequenceDiagram-3UESZ5HK-1v1DTNGt.js} +1 -1
  183. package/dist/web/assets/{spaces-CjuXbmxF.js → spaces-CvL2DRZM.js} +1 -1
  184. package/dist/web/assets/{stateDiagram-AJRCARHV-HFdhqxzx.js → stateDiagram-AJRCARHV-CEc_PLov.js} +1 -1
  185. package/dist/web/assets/stateDiagram-v2-BHNVJYJU-iAMctzaT.js +1 -0
  186. package/dist/web/assets/theme-LRSmy8mD.js +1 -0
  187. package/dist/web/assets/{timeline-definition-PNZ67QCA-HNRxaB3t.js → timeline-definition-PNZ67QCA-CEjhuitj.js} +1 -1
  188. package/dist/web/assets/{vennDiagram-CIIHVFJN-DwsCTyaD.js → vennDiagram-CIIHVFJN-CActt9h9.js} +1 -1
  189. package/dist/web/assets/{wardley-L42UT6IY-BWW2wtVO.js → wardley-L42UT6IY-Bp3q2izt.js} +1 -1
  190. package/dist/web/assets/{wardleyDiagram-YWT4CUSO-C-ktKm7v.js → wardleyDiagram-YWT4CUSO-C_zutiQ2.js} +1 -1
  191. package/dist/web/assets/{xychartDiagram-2RQKCTM6-48AxNW9k.js → xychartDiagram-2RQKCTM6-CRafvv33.js} +1 -1
  192. package/dist/web/icons/apple-touch-icon.png +0 -0
  193. package/dist/web/icons/icon-192.png +0 -0
  194. package/dist/web/icons/icon-512.png +0 -0
  195. package/dist/web/icons/maskable-512.png +0 -0
  196. package/dist/web/index.html +12 -2
  197. package/dist/web/manifest.webmanifest +16 -0
  198. package/native/auth-native/prebuilds/linux-arm64/auth-native.node +0 -0
  199. package/native/auth-native/prebuilds/linux-x64/auth-native.node +0 -0
  200. package/native/auth-native/prebuilds/win32-arm64/auth-native.node +0 -0
  201. package/native/auth-native/prebuilds/win32-x64/auth-native.node +0 -0
  202. package/package.json +23 -4
  203. package/dist/search-worker.mjs +0 -14177
  204. package/dist/web/assets/AppErrorBoundary-DiGMUg4r.js +0 -1
  205. package/dist/web/assets/LifeMark-CL6-HWDu.js +0 -1
  206. package/dist/web/assets/NavScopeBoundary-CFCnvZR0.js +0 -1
  207. package/dist/web/assets/channel-Bj_gZ_Lv.js +0 -1
  208. package/dist/web/assets/classDiagram-4FO5ZUOK-ssCwe2R4.js +0 -1
  209. package/dist/web/assets/classDiagram-v2-Q7XG4LA2-ssCwe2R4.js +0 -1
  210. package/dist/web/assets/client-DGj93bGT.js +0 -3
  211. package/dist/web/assets/connection-Bpf-EjrL.js +0 -1
  212. package/dist/web/assets/export-T_izwEkQ.js +0 -2
  213. package/dist/web/assets/highlighted-body-OFNGDK62-Btm6MuZ4.js +0 -1
  214. package/dist/web/assets/index-5_yzg61S.js +0 -1
  215. package/dist/web/assets/index-B-6LiYTY.js +0 -1
  216. package/dist/web/assets/index-B4iu4SJW.js +0 -1
  217. package/dist/web/assets/index-B9MlqF7J.js +0 -1
  218. package/dist/web/assets/index-BECSk4If.js +0 -1
  219. package/dist/web/assets/index-BFcyN2Zw.js +0 -1
  220. package/dist/web/assets/index-BIebkSEI.css +0 -1
  221. package/dist/web/assets/index-BMWid2q9.js +0 -1
  222. package/dist/web/assets/index-BeMvPEXs.js +0 -1
  223. package/dist/web/assets/index-Bezli3SF.js +0 -1
  224. package/dist/web/assets/index-BkPV0psm.js +0 -1
  225. package/dist/web/assets/index-CG8uIlD7.js +0 -1
  226. package/dist/web/assets/index-CJ92kLtO.js +0 -1
  227. package/dist/web/assets/index-CRDDqofN.js +0 -1
  228. package/dist/web/assets/index-Cd62y0wD.js +0 -1
  229. package/dist/web/assets/index-CgcJPsK6.js +0 -3
  230. package/dist/web/assets/index-Cy8C_eFR.js +0 -7
  231. package/dist/web/assets/index-D8z7lcQn.js +0 -166
  232. package/dist/web/assets/index-D_oPSlBL.js +0 -1
  233. package/dist/web/assets/index-Dceu0bqY.js +0 -1
  234. package/dist/web/assets/index-eUyF-8Sq.js +0 -1
  235. package/dist/web/assets/index-hG2s2Spn.js +0 -13
  236. package/dist/web/assets/mermaid-GHXKKRXX-BO9hkP3Z.js +0 -621
  237. package/dist/web/assets/stateDiagram-v2-BHNVJYJU-Dx28QuZF.js +0 -1
  238. package/dist/web/assets/theme-beWE_6f8.js +0 -1
@@ -12,7 +12,7 @@ The REST and WebSocket APIs described on this page are experimental: interface s
12
12
 
13
13
  ### Address
14
14
 
15
- 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 `~/.kiki/server/instances/`.
15
+ 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 `<home>/server/instances/` (default `~/.kiki/server/instances/`).
16
16
 
17
17
  ### Authentication
18
18
 
@@ -91,6 +91,23 @@ Endpoints are grouped by resource below. A `:{action}` suffix in a path is the a
91
91
  | `GET /api/meta` | Server version, capability map, `server_id`, experimental flags |
92
92
  | `POST /api/shutdown` | Graceful shutdown (replies 200 first); mounted only on loopback binds |
93
93
 
94
+ ### Mailbox storage upgrade
95
+
96
+ A home with legacy or interrupted mailbox storage starts in maintenance mode before the ordinary engine, plugins, or sessions are bootstrapped. Authenticated `GET /api/meta` returns `storage_mode: "maintenance"`, `storage_status_path: "/api/storage"`, and the usual `server_id` and `server_home_id`; unavailable capabilities are `false`. It uses the existing server address, authentication, host checks, and origin policy. Session endpoints return HTTP `503` until normal startup.
97
+
98
+ | Method and path | Request | Response data |
99
+ | --- | --- | --- |
100
+ | `GET /api/storage` | No body | `StorageMigrationView`; reads status without starting migration or changing authority |
101
+ | `POST /api/storage` | `{ "action": "migrate" }`, `cancel`, `rollback`, `start`, or `retry_cleanup` | Updated `StorageMigrationView`; launches the requested operation |
102
+
103
+ The schemas are exported by `@kiki/protocol`: `storageMigrationViewSchema` and `storageMigrationActionSchema`. A view contains `schemaVersion: 1`, `mode`, `status`, `actions`, `transition`, and optional `operationFailure`. Status supplies `authority`, `phase`, `state`, `progress`, source and backup paths, optional `writer`, `failure`, and `warning`, and `canCancel` / `canRollback`. These status fields also appear in [`kiki storage --json`](../reference/command.md#kiki-storage). A `mailbox.checkpoint_warning` means the SQLite mailbox is usable but historical upgrade progress needs repair before rollback; it does not mark migration as failed or offer another `migrate`.
104
+
105
+ Drive controls from `actions`, not from a guessed combination of phase and state: a durable phase may finish while its worker and locks are still closing. `migrate` resumes preserved progress; `waiting` leaves the old writer in control, so stop that writer and retry when `migrate` is offered. `cancel` stops a cancellable import or normal-start attempt. `rollback` is offered only while the original can be restored without losing new SQLite writes. A malformed action returns envelope code `40001`; an unavailable action returns `40901`. Missing credentials return HTTP `401`.
106
+
107
+ After migration, `start` explicitly requests normal startup. Continue polling the same address: preparation longer than 30 seconds remains `starting`, with `cancel` available rather than an automatic timeout. A failed or cancelled start leaves the upgrade intact and reports `transition.state: "failed"` with the original startup `failure`. While the attempt is closing, `cleanupPending` is `true` and `actions` is empty; another start waits for its cleanup. If cleanup fails, `transition.cleanupFailure` explains it and the only action is `retry_cleanup`; this retries unfinished cleanup without starting the engine again. Once cleanup succeeds, `cleanupPending` becomes `false` and `actions` offers `start` and any available `rollback`.
108
+
109
+ Switch to normal session loading only when `GET /api/meta` reports `storage_mode: "normal"` with the same `server_id` and `server_home_id`. The home, identity, and port stay unchanged; clients do not need to launch another daemon. An interrupted rollback also returns to maintenance and offers `rollback` so it can finish before another migration or normal startup. In normal mode, `GET /api/storage` remains readable and `actions` is empty.
110
+
94
111
  ### Space presets
95
112
 
96
113
  `GET /api/homes/presets` returns `{ items: [{ id, name, color?, description }] }`. Only the `kiki` baseline preset is currently bundled. Create a space from the main space's server with `POST /api/homes`:
@@ -146,11 +163,15 @@ The response uses schema version `1` with independent sources and meters. Each m
146
163
  | `GET /api/config` | Read the global config (secret fields redacted) |
147
164
  | `POST /api/config` | Merge-patch the config; broadcasts `event.config.changed` |
148
165
 
166
+ `request_compression` and `responses_web_socket` are system sections on both calls. Omit a section to leave it unchanged. JSON `null` removes it. A compression object needs `encoding` and `targets`, with optional `min_bytes` and `dictionary`, or `encoding` set to `"off"` and no other fields. `dictionary` applies only to `zstd`. A WebSocket object needs `targets`, or `off: true` and no targets. An incomplete object is rejected and the saved file stays unchanged.
167
+
149
168
  Session-title prompt reads, read-only defaults and field-level save/delete patches are documented under [`session_title`](../configuration/config-files.md#session-title).
150
169
 
151
170
  The `hooks` value accepts a legacy command-rule array or a declarative object with `schemaVersion: 2`. Both reads and saves retain the complete value, including `rules`, `legacy`, `enabled`, `disabled`, and `files`. Nested JSON keys use camelCase (`textFile`, `agentRoles`, `everyCompletedSteps`, `counterScope`, `partitionBy`); TOML uses snake_case. Send the complete hooks array or object when editing it; omit `hooks` to leave it unchanged, or send `[]` to clear it. `null` and unsupported rule shapes return validation code `40001` without changing the saved file. Reading or saving configuration does not execute hook commands. See [Hooks](../customization/hooks.md) for supported events and actions.
152
171
 
153
- `GET /api/sessions/{session_id}/agents/{agent_id}/hooks` is a separate read-only inspection view. Active agents return their effective rules, source statuses, diagnostics, and cadence counts. Closed sessions use the saved agent binding and cadence records with the current rule sources, without resuming the agent or executing hooks. Invalid workspace sources remain visible in diagnostics while valid global rules are retained. This endpoint does not save configuration.
172
+ `GET /api/sessions/{session_id}/agents/{agent_id}/hooks` is a separate read-only inspection view. Active agents return their effective rules, source statuses, diagnostics, and cadence counts. An unstarted `main` in an existing session returns native root defaults and zero cadence counts, retaining any configured rules. Closed sessions use the saved agent binding and cadence records with the current rule sources, without resuming the agent or executing hooks. Add `?observe=true` to avoid scanning a cold agent's log when it exceeds 8 MiB; this returns `40901` (`SESSION_BUSY`) instead. An explicit inspection without `observe=true` retains the full saved-cadence read. Invalid workspace sources remain visible in diagnostics while valid global rules are retained. This endpoint does not save configuration.
173
+
174
+ `GET /api/sessions/{session_id}/agents/{agent_id}/auto-compact` and `GET /api/sessions/{session_id}/agents/{agent_id}/context-strategy` also accept `?observe=true` for reads that never restore a cold agent. A saved, model-bound agent that is not active returns `40901` rather than an estimated setting. An unbound `main` returns `Model not set` for automatic compaction and the global or default context strategy. Omit `observe` or set it to `false` for the ordinary read.
154
175
 
155
176
  ### Models and providers
156
177
 
@@ -163,7 +184,7 @@ The `hooks` value accepts a legacy command-rule array or a declarative object wi
163
184
  | `POST /api/models/{model_id}:set_default` | Set the global default model |
164
185
  | `GET /api/providers` | List providers |
165
186
  | `POST /api/providers` | Create a provider (201) |
166
- | `GET /api/providers/{provider_id}` | Read a provider (reveals the stored key) |
187
+ | `GET /api/providers/{provider_id}` | Read a provider with credential-source metadata; values require `POST /api/secrets:reveal` |
167
188
  | `PATCH /api/providers/{provider_id}` | Change only the supplied provider fields |
168
189
  | `DELETE /api/providers/{provider_id}` | Delete a provider (204) |
169
190
  | `POST /api/providers/{provider_id}:refresh` | Refresh one provider's model metadata |
@@ -171,23 +192,93 @@ The `hooks` value accepts a legacy command-rule array or a declarative object wi
171
192
  | `GET /api/catalog/providers` | Browse the models.dev directory (server-proxied) |
172
193
  | `GET /api/catalog/providers/{catalog_id}` | Read one directory entry |
173
194
 
195
+ Provider listings distinguish `service: "chat" | "decision"`; decision rows report `decision_protocol`, optional `decision_endpoint`, `effective_base_url` and an empty `models` array. Create a decision provider with `type: "system_one" | "pair_score"`, its address and a remote `default_model`; `models: []` is accepted. Protocol and endpoint belong to the connection. An endpoint override may be a path or same-origin HTTP(S) URL without embedded credentials. These connections use existing provider credentials, environment variables and custom headers and stay out of chat discovery and model pickers. See [decision connections](../configuration/providers.md#decision-connections).
196
+
197
+ `GET /api/providers` and `GET /api/providers/{provider_id}` include `request_compression` and `responses_web_socket` when that provider saved them. A partial compression object, `encoding: "off"`, `off: true`, and the saved `targets` order come back as stored. The read does not fill those fields from the system section. `POST /api/providers` and `PATCH /api/providers/{provider_id}` accept the same objects. JSON `null` on PATCH clears that provider field. Omitted fields stay unchanged.
198
+
199
+ Directory reads return the last fetched catalog or bundled snapshot immediately while one background update runs. Successful fetches are fresh for ten minutes; a failed background update leaves the local directory readable and postpones another automatic attempt for ten minutes. Without a local catalog, the read waits for the upstream fetch and reports an error if it fails. Explicit `import_catalog` waits for any required catalog update before validating and saving the selected entry; if upstream is unavailable, it can use the same cached or bundled entry. Directory browsing never fetches model lists from your configured providers; those requests require an explicit `refresh` action.
200
+
174
201
  Model creation accepts an optional `protocol`: `openai`, `openai_responses`, `anthropic`, or `google-genai`. PATCH accepts the same values; omitted `protocol` leaves the model unchanged, and `"protocol": null` clears the local override. Include `base_revision` from the model read to reject concurrent changes without writing. Invalid protocol values return `config.invalid` (business code `40001`) without changing configuration.
175
202
 
176
203
  Model reads expose the saved `protocol` and resolved `effective_protocol` separately. An absent saved value inherits the provider's default format; an absent effective value in the list means no usable requester was materialized. Changing a model's protocol does not write the provider connection, credentials, request identity, or default pointers. See [model request format overrides](../configuration/providers.md#model-request-format-overrides) for configuration examples and endpoint compatibility.
177
204
 
205
+ The single-model response also separates the stored `base_url` override from read-only `effective_base_url`. The latter resolves the model override, provider URL, provider environment and vendor default in that order, and is omitted if none resolves. Create and PATCH accept only stored fields; do not copy `effective_base_url` into a write.
206
+
207
+ ### Recipes and markets
208
+
209
+ [Recipes](../customization/recipes.md) use a preview/install flow. Package reads and option previews do not change model bindings; apply a package with `PATCH /api/models/{model_id}`, passing `recipe`, optional `recipe_options` and that model's current `base_revision`.
210
+
211
+ | Method and path | Description |
212
+ | --- | --- |
213
+ | `GET /api/recipes` | Installed package summaries, accepted option definitions and current model usage |
214
+ | `GET /api/recipes/{id}` | Accepted package, source files, history, editability and `used_by`; optional `recipe_options` query is a JSON boolean map |
215
+ | `GET /api/recipes/{id}/export` | Portable `{ name, revision, files }`; the client creates the ZIP |
216
+ | `POST /api/recipes:preview` | Inspect `{ source: { locator, sha256? } }`; returns `preview_id`, resolved content and script-consent requirements |
217
+ | `POST /api/recipes:install` | Accept `{ preview_id, update_mode?, consent? }` from that preview |
218
+ | `POST /api/recipes:check-updates` | Check following installations without replacing accepted revisions |
219
+ | `POST /api/recipes:update` | Update or pin an installation; accepts `installation_id`, `expected_revision?`, `update_mode?`, `revision?` |
220
+ | `POST /api/recipes:fork` | Create a local `copy` or `extend` using `{ installation_id, mode, id, name }` |
221
+ | `POST /api/recipes:save-local` | Save `{ installation_id, expected_revision, files }` on an editable local package |
222
+ | `DELETE /api/recipes/{id}` | Remove an installation; optional `expected_revision` and explicit `disable_models=true` query guard affected models |
223
+ | `GET /api/recipe-markets` | Configured markets, cached catalogs and offline diagnostics |
224
+ | `POST /api/recipe-markets` | Add `{ id, name, url, enabled }`; URL must use HTTPS |
225
+ | `PUT /api/recipe-markets/{id}` | Replace `{ name, url, enabled }` for that market |
226
+ | `DELETE /api/recipe-markets/{id}` | Remove the market configuration |
227
+
228
+ A directory summary's optional `used_by` lists effective model aliases, including inherited references; it is omitted when unused. `options` contains definitions and defaults from the accepted revision. Per-model choices are returned by `GET /api/models` as `recipe_options`, alongside `recipe`; both are omitted when the model has no active Recipe reference. Strip an `installation:` prefix before joining a reference to a directory id. A missing or corrupt accepted revision remains in the directory with `health: "unavailable"`, no `options`, and `last_error.code: "recipe-revision-unavailable"`.
229
+
230
+ Preview ids expire after 15 minutes. On expiry, preview again. Installation uses the inspected snapshot; new scripts require `consent: true`. Local-file edits can also be previewed with `installation_id`, `expected_revision` and `files`. A stale `expected_revision` rejects the write; reload the package before retrying.
231
+
232
+ Removal with affected models returns code `40001` and `details.used_by` unless explicitly authorized to disable them. With `disable_models=true`, their Recipe fields become `off` while other model settings remain. This usage check covers model references; profile references must be handled separately. Existing bound sessions retain their frozen snapshot. The equivalent typed facade is `klient.global.recipes`, with market operations under `.markets`.
233
+
234
+ ### Decision connections
235
+
236
+ Permission review and Memory Advisor each store a `source`: `{ kind: "connection", connection, model? }` for a decision connection, or `{ kind: "model", model }` for a configured chat alias. Save it under `permission.reviewer` with `POST /api/config`, or under `advisor` with `PATCH /api/memory/settings`. An omitted source is preserved; an object replaces the whole source. `source: null` clears it and the advisor's legacy selector, or resets the Reviewer to an unconfigured model backend. Without a source, legacy configurations continue working. Permission review rejects `pair_score`; Memory Advisor uses those scores for `rank` only.
237
+
238
+ Configuration reads expose `reviewer.source_status` and `advisor_status.source_status`. They report `state` (`ready`, `unconfigured`, `auth`, `protocol` or `capability_mismatch`) plus available connection, model, protocol, origin, destination and credential source metadata. No credential value is included. A ready configuration still needs a successful request to establish that the service answers the chosen protocol.
239
+
240
+ | Method and path | Description |
241
+ | --- | --- |
242
+ | `POST /api/decision/probe` | Test `{ source, confirm_destination }` with synthetic content; returns `{ ok, status, duration_ms, reason? }` |
243
+ | `POST /api/decision/move-reviewer-key` | Move a saved legacy Reviewer key on the server; body `{ connection }`, response `{ connection, state, retryable }` |
244
+
245
+ Pass the exact destination reported for the source as `confirm_destination` to bind the test to that service. The decision probe reads no user memory and does not save a source. Its `status` uses the source-status shape above. The [saved-advisor probe](#memory) instead uses the saved advisor configuration and returns advisor status and optional token usage.
246
+
247
+ Key movement creates a connection without exposing the key to the caller, switches the Reviewer source, then removes the old key. `complete` confirms all stages; `connection_saved` and `source_switched` identify the completed stage when a later write fails or concurrent settings change. Refresh the connection and Reviewer before retrying. Reuse the name only when it still represents the same key and settings; if the Reviewer key changed while the connection holds the old key, choose a new name. Conflicting connections and newer settings are preserved. Environment-variable Jev connections need no key movement.
248
+
178
249
  ### Executor catalog and checks
179
250
 
180
- The executor catalog lists registered engines without waiting for executable discovery or authentication checks. Reading it does not launch an engine or sign in.
251
+ The executor catalog and the two discovery views below answer different questions and are read-only. Catalog reads do not wait for executable discovery or authentication checks. The candidate view evaluates dispatchable profile and native-engine references, while the executor discovery view reads local installation metadata; none of these GET requests launches an engine or signs in.
181
252
 
182
253
  | Method and path | Description |
183
254
  | --- | --- |
255
+ | `GET /api/agents/references` | Caller-permitted profile and native-engine message-reference candidates; accepts one of the query forms below and does not launch a child |
184
256
  | `GET /api/executors` | Registered engines and the latest check for each. This request does not probe. A result older than 60 seconds has `check_stale: true` |
185
257
  | `GET /api/executors/{id}` | One engine's capabilities, connection settings, and latest check. This request does not probe |
186
- | `POST /api/executors/{id}/check` | Check only that engine's executable sources and its declared authentication hints |
258
+ | `GET /api/executors/discovery` | Read-only discovery of installed external-engine files and metadata; takes no query or body and does not spawn a process |
259
+ | `POST /api/executors/{id}/check` | Explicitly check that engine's executable sources and its declared authentication hints |
187
260
  | `GET /api/executors/installations` | Pinned adapter releases and any selected source-owned adapter. This request does not install. An item with no installation omits `active` |
188
261
  | `POST /api/executors/{id}/install` | Explicitly update one selected adapter. The request has no body fields |
189
262
  | `POST /api/executors/{id}/rollback` | Restore that adapter's previous installation. The request has no body fields |
190
263
 
264
+ `GET /api/agents/references` accepts exactly one of these strict query forms; unknown fields are rejected:
265
+
266
+ | Query form | Use |
267
+ | --- | --- |
268
+ | `session_id=<id>&agent_id=<id>` | Read the live caller's candidates, or the saved caller binding when the session or agent is cold |
269
+ | `workspace_id=<id>&profile=<name>` | Preview candidates for a named profile in a registered workspace |
270
+ | `cwd=<absolute-path>&profile=<name>` | Preview candidates for a named profile from an absolute working directory |
271
+
272
+ A cold session is read from the session index and persisted agent metadata; this endpoint does not resume the session or agent. Workspace and `cwd` forms use a draft profile catalog. The endpoint only inventories candidates: it does not call `AgentRun`, start an external engine, or change `show_in_profile_list`.
273
+
274
+ The response data is `{ items, delegation_available, unavailable_reason? }`; `delegation_available` reports whether the caller can use `AgentRun`, and the top-level `unavailable_reason` explains a false value. Each item contains `profile`, `label`, `executor`, `engine_label`, a `reference` in the form `kiki://agents/<percent-encoded-profile>`, `configuration` (`native` for an engine target or `profile` for a named role), `group` (`native`, `profile`, or `main`), `defaults_available`, `available`, and optional `unavailable_reason`, `unavailable_reason_code`, and `description`. Hard-policy-blocked targets are omitted; a missing engine or missing defaults remains as an item with `available: false` so a client can render it disabled.
275
+
276
+ Use `group: "main"` to place main-profile candidates in an advanced group, and preserve `reference` unchanged when embedding the target in a message. A later `AgentRun.source_ref` is a server-generated ID associated with that visible message, not the URI itself. Stored `AgentReference` and `AgentRunSource` objects also carry an optional `engine_label` for display without a catalog lookup; `executor` remains the engine ID. The typed Klient method is `klient.rest.agents.referenceCandidates(query, options?)`.
277
+
278
+ `GET /api/executors/discovery` takes no query or body and returns `{ items }` for registered non-native executors only. Each item contains `id`, `label`, `protocol`, `installed`, `status` (`installed`, `missing`, or `error`), `checked_at`, and `components`, plus optional `version`, `path`, `source`, `source_kind` (`explicit-path`, `env`, `glob`, `path-lookup`, or `node-script`), `reason`, and `reason_code`. A component contains `id`, `label`, `role` (`program` or `dependency`), `installed`, and optional `path`, `version`, `reason`, and `reason_code`. Unknown versions are omitted. Top-level `installed` reports whether the selected program files were found; a source-owned AGY adapter also requires its AGY CLI dependency. Other declared dependency results are reported independently in `components`. Discovery does not establish authentication or launch readiness.
279
+
280
+ This discovery reads local files, PATH/environment values, glob matches, and package metadata only. It does not spawn a process, run a CLI or version probe, inspect credentials, contact a network service, or change `show_in_profile_list`. `reason` remains the English diagnostic text without a `code:` prefix; common stable `reason_code` values include `not_on_path`, `path_not_found`, `env_unset`, `no_glob_match`, and `metadata_unreadable`. Clients should preserve unknown codes. Results are cached for 30 seconds from completion while the descriptor and source configuration remain unchanged. Use `POST /api/executors/{id}/check` when an explicit executable or authentication check is intended; that probe is separate from this safe discovery. The typed Klient method is `klient.rest.executors.discover(options?)`.
281
+
191
282
  Catalog `status` is `ready`, `unavailable`, or `unknown`. Native is always `ready`. An external engine with no check yet is `unknown`. `check_status` keeps the latest explicit check as `ready`, `warning`, or `unavailable`, and `checked_at` is that time. While the launch configuration is unchanged, `check_stale` is false for 60 seconds and true after that. The list still returns the previous `check_status` instead of falling back to `unknown`. After the engine revision changes, both fields disappear and that engine is unchecked again. `POST` updates only the named engine. The others keep the results they already have. One engine timing out or failing does not mark the rest ready. `GET` does not start a probe.
192
283
 
193
284
  Binary readiness and authentication are stored separately. `connection.login_status: "unknown"` means the login state has not been read. Catalog `status: "ready"` means the program requirement passed. When preflight is `warning` and the program requirement passed, catalog `status` is `ready` and `check_status` stays `warning`. New profile choices and bare execution entries include an external engine only when `show_in_profile_list` is `true`. A missing field leaves it on the settings page. `false` stays off after refresh, another check, and another import. `externals_visible = false` blocks every external engine from new choices. A bare execution entry also needs a ready program and either a confirmed login or the engine's declared API-key environment. A profile or session already bound to a hidden or unavailable engine keeps that identity. Settings still lists every engine. Sending a prompt still runs the real program, source, and authentication checks. The previous check in the display catalog does not replace the launch check.
@@ -225,6 +316,7 @@ Attachment does not copy the vendor transcript or send a prompt. The first promp
225
316
  | Method and path | Description |
226
317
  | --- | --- |
227
318
  | `POST /api/sessions` | Create a session; omit both `workspace_id` and `metadata.cwd` to allocate a new workspace |
319
+ | `GET /api/sessions/creation/{creation_id}` | Check a creation receipt without creating or resuming a session |
228
320
  | `GET /api/sessions` | List sessions; cursor pagination with `busy`, `archived_only` and title/workspace search `q` |
229
321
  | `GET /api/sessions/{session_id}` | Read one session |
230
322
  | `GET /api/sessions/{session_id}/profile` | Read the session profile |
@@ -242,6 +334,10 @@ Attachment does not copy the vendor transcript or send a prompt. The first promp
242
334
 
243
335
  When the session is not live in this process, the snapshot is read from the saved main-agent wire and session metadata. The request does not resume the session or its workspace. `messages` is the newest 100 entries of the current logical context after compaction, undo, and edit, oldest first. `has_more` is true when older logical entries exist, and `message_count` is that logical length. `as_of_seq` and `epoch` are the session journal watermark. Permission mode and plan mode come from the saved runtime records; model and effort come from the saved agent binding. Context-token totals and breakdowns are omitted when this process has not measured them. `in_flight_turn`, `pending_approvals`, and `pending_questions` describe only activity in this process, so a session that is active in another process is not reported as active here.
244
336
 
337
+ Session reads and `event.session.work_changed` expose `executing` separately from `busy`. `busy` includes unfinished work, queued prompts and terminal task results awaiting delivery. `executing` reports current local execution or finite process/media work; it excludes those queues, undelivered terminal results, resident services and agent task rows without an active executor. A cold session reports `executing: false` for this process. Older servers omit the field; omission means unknown. A historical subagent row with `status: "running"` is not current execution evidence.
338
+
339
+ `cleanup_pending: true` on a session, task or `event.session.work_changed` means process cleanup is unconfirmed. The session remains `busy`; that task does not count toward `executing`, though another active turn or task can still make it true. Thread summaries use `state: "cleanup_pending"`, and the GUI shows “Process cleanup unconfirmed” ahead of ordinary running or idle status. Pending approval or question still takes precedence. Retry `TaskStop` for the same task to confirm cleanup before replacing its work; root exit code 0 alone does not make the task terminal. Confirmed cleanup clears the flag and lets the normal terminal result and controls apply. Older servers omit the flag.
340
+
245
341
  Snapshot `subagents` roster rows carry an optional `created_at` UTC ISO timestamp for the agent's immutable creation time. A newly created agent has it before its first run starts, including while queued; resuming the same agent, restoring its scope, restarting the server, or switching its model does not change it. A fork that creates a new agent records a new creation time. The separate optional `started_at` identifies the run described by the row and may change on a later run.
246
342
 
247
343
  Model, effort and executor fields prefer the current committed agent metadata over its spawn snapshot, with spawn values used only when current values are unavailable. Effort provenance and executor protocol stay with their selected source; a current binding alone does not prove which model served a request.
@@ -250,6 +346,17 @@ An agent whose saved metadata has no creation time omits `created_at`; treat it
250
346
 
251
347
  For automatic allocation, send `{}` to `POST /api/sessions`. The server creates a distinct directory under `$KIKI_HOME/workspaces/`, registers it, and returns its `workspace_id` and `metadata.cwd` in the session response. Supplying an existing `workspace_id` or `metadata.cwd` keeps the existing targeting behavior; an unknown `workspace_id` is still rejected.
252
348
 
349
+ For retry-safe creation, generate a UUID once and send it as the optional top-level `creation_id`. Keep that ID and the same request body when retrying after a timeout or disconnect. Concurrent matching requests share the creation; completed requests replay the saved result, including after a server restart. Saved failures are also replayed without repeating creation side effects. The resulting session ID is `session_<creation_id>`, with the UUID normalized to lowercase.
350
+
351
+ Creation identities belong to the connected home: clients must keep separate pending requests for each home and connection. Omitting `creation_id` retains ordinary creation without retry deduplication. Cancelling a client wait does not delete a session the server has created.
352
+
353
+ After an unconfirmed result, call `GET /api/sessions/creation/{creation_id}`. It returns `{ creation_id, session_id, status, session?, failure? }`; `status` is `missing`, `pending`, `completed`, `failed`, or `unknown`. This read neither joins a pending creation nor starts one. Only `completed` supplies the saved session response; `missing` permits retrying the original ID and body. Keep an unknown outcome when the read fails.
354
+
355
+ | Creation error code | Recovery |
356
+ | --- | --- |
357
+ | `40948` | The creation identity conflicts. `details.reason` is `body_mismatch` when the same `creation_id` carries a different body, or `session_id_exists` when its mapped session ID is already occupied outside this creation. Keep the pending identity and draft. A collision is not a successful replay; use a new ID only for a deliberately separate creation. |
358
+ | `50006` | The creation outcome is unconfirmed. `details` contains `{ creation_id, session_id, evidence }`. Diagnostic values include `session_present_without_completion`, `session_absent`, `completion_receipt_write_failed`, `session_read_error`, and `receipt_read_error`; clients must also preserve unknown diagnostic values. Keep the draft and creation identity, and inspect the exact session ID. This code never confirms that starting a replacement is safe; the server does not rerun creation or its hooks. |
359
+
253
360
  Set `agent_config.execution` at creation to select a harness independently of a profile:
254
361
 
255
362
  ```json
@@ -264,6 +371,66 @@ Session reads return the committed `agent_config.execution` binding as `{ versio
264
371
 
265
372
  On an idle agent, `thinking: null` in `agent_config` clears only the session thinking override, so the lower-priority effort applies again: the profile, then the harness setting, then the engine default when Kiki has not pinned an effort. Leaving `model` out keeps the saved model. An empty thinking string is rejected; omitting `thinking` keeps the current effort. While the agent is running, that profile update is refused. A prompt can carry the same `thinking: null`; Kiki applies it when that prompt launches, and an omitted model stays in place.
266
373
 
374
+ Session creation and profile updates accept `agent_config.plan_gate: "free" | "gated"`. A profile update applies it to the live main agent without sending a prompt; live snapshots echo the effective `plan_gate`. This override lasts for the live agent's lifetime; after restoration it uses the configured gate again. Cold snapshots omit the gate. To leave Plan mode on a specific agent through klient, call `klient.session(sessionId).agent(agentId).exitPlan()`; its parent and siblings stay in their current modes.
375
+
376
+ #### Pause and resume execution through Klient
377
+
378
+ Pause and resume are session-scoped Klient procedures, not additional REST
379
+ session actions. Use the existing `POST /api/klient/call` contract, or the
380
+ typed `klient.session(sessionId).execution` facade. For example, pause a
381
+ session with:
382
+
383
+ ```json
384
+ {
385
+ "procedure": {
386
+ "scope": "session",
387
+ "sessionId": "session_example",
388
+ "service": "sessionExecutionControl",
389
+ "method": "pause"
390
+ },
391
+ "params": [{ "operationId": "pause-1" }]
392
+ }
393
+ ```
394
+
395
+ The `read` call uses `method: "read"` and `params: []`. Resume uses
396
+ `method: "resume"` and `params: [{ "operationId": "resume-1", "pauseOperationId": "pause-1" }]`.
397
+ The execution state is returned in the usual response envelope's `data`.
398
+ Subscribe to `execution.changed` through `session.events` over the authenticated
399
+ `/api/klient/events` socket, and use `read` to reconcile after reconnecting;
400
+ this is not a new `/api/sessions/{session_id}:pause` route or a legacy
401
+ `/api/ws` event.
402
+
403
+ The returned `phase` is `running`, `pausing`, `paused`, `resuming`, or `failed`.
404
+ `pause` atomically persists the hold intent before settling the session's
405
+ `main` and native child agents. A native model or tool step that has already
406
+ started finishes with its real result, then the hold takes effect before the
407
+ next step. External execution, process, and media work is not forcibly
408
+ cancelled, so the session can remain `pausing` until that work settles. Each
409
+ `agents` entry reports `settling`, `paused`, `idle`, or `unknown`, plus whether
410
+ it is `resumable`. A `failed` state may include an `error` string. If `phase` is
411
+ `failed`, read `error` and `agents` to inspect the failure; the hold remains in
412
+ place, and an `unknown` result from a cold session does not authorize automatic
413
+ resume.
414
+
415
+ After the state becomes `paused`, normal close preserves the turn, tasks, queue,
416
+ and binding. A restart keeps the hold; call `resume` explicitly with the
417
+ current `pauseOperationId`, and do not automatically replay work whose
418
+ external result is unknown. `operationId` and `pauseOperationId` must be
419
+ non-empty strings of at most 256 characters. Start each new `pause` or `resume`
420
+ cycle with a new `operationId`; reuse the stable ID only when retrying that same
421
+ action. Retrying the same action with the same ID returns the operation's saved
422
+ receipt or latest saved state, while reusing an ID for a different action is
423
+ rejected. Ordinary sends remain accepted and queued while a hold is active. A
424
+ user-requested pause is independent of Goal handling; Goal work does not resume
425
+ it implicitly. `execution.resume` also does not reopen a Goal that the user
426
+ paused.
427
+
428
+ Session list and cold reads do not activate a cold session. `GET /api/sessions`
429
+ and `GET /api/sessions/{session_id}` may include the optional read-only
430
+ `execution_phase` fact; `GET /api/sessions/query` exposes the same projection as
431
+ `meta.execution_phase`. This field is not an input to session profile updates or
432
+ Klient `session.update`.
433
+
267
434
  #### `POST /api/sessions/{session_id}:archive`
268
435
 
269
436
  An empty body keeps the single-session behavior. Send `{ "include_attached": true, "exclude_session_ids": ["independent-thread-id"] }` to archive the attached family. The server reads persisted metadata across all workspaces, not the client's loaded page. `created_by_session_id` records a created thread; `parent_session_id` counts only with `child_session_kind: "child"`, so ordinary forks are not included. Each excluded thread cuts its whole subtree; excluding the requested root does not exclude that root.
@@ -315,7 +482,7 @@ When an older-page request is still locating its anchor in saved history, it can
315
482
 
316
483
  `GET /api/sessions/{session_id}/transcript/detail` reads one entity. Query `agent_id` is a plain agent id, `kind` is `task`, `attachment`, `prompt`, or `tool`, and `id` is that entity's id. For `kind=tool`, `lookup.status` is `found`, `preparing`, or `not_found`. `found` includes `turnId`, `stepId`, and `frame`. That `frame`, and a returned task, attachment, or prompt body, can carry `contentRefs`; continue those with the POST below. `preparing` means the call is not yet located in the session's source history: retry the same request. `read.source` is then `derived` and `read.readiness` is `preparing`. `not_found` means the located history has no such call.
317
484
 
318
- A session already covered in memory returns the live tool call directly, with `read.source` `live` and `readiness` `ready`. A located cold session reports `cold` and `ready`, and replays the body from that source history.
485
+ A session already covered in memory returns the live tool call directly, with `read.source` `live` and `readiness` `ready`. A located cold session reports `cold` and `ready`, and replays the body from that source history. Legacy message and part `provenance` carries an absolute `recordOrdinal` when known. A bounded cold window without a verified prefix instead carries `recordSpan: { startByteOffset, endByteOffset }`, measured in logical-wire bytes, and omits `recordOrdinal`. Do not interpret a missing ordinal as zero or infer it from the page position. Entity IDs remain opaque; send returned references unchanged when navigation becomes ready.
319
486
 
320
487
  A transcript page keeps large fields as `contentRefs`. Each reference carries `source`, `revision`, `path`, `kind` (`text`, `array`, or `object`), `offset`, and `total`. Continue it with `POST /api/klient/session-view/{session_id}/transcript/content` and JSON `{ "agentId", "ref" }`. Send the reference unchanged. The HTTP status stays 200 and the envelope carries the result. `code: 0` returns `value` and, when more of the field remains, `next`. Submit that `next` unchanged as the next `ref`, until `next` is absent. The same `ref` again returns the same part; `"range": true` does not advance `offset`. On a text ref it only limits the slice that already starts at `offset` (about 4096 characters, inside the field budget), and a snapshot ref ignores `range`. A page is budgeted at 64 KiB, and each field slice aims at half of that, 32 KiB.
321
488
 
@@ -330,7 +497,7 @@ The transcript response's `agents` descriptors use camelCase: `{ agentId, type?,
330
497
  | `GET /api/sessions/{session_id}/prompts` | Active and queued prompts |
331
498
  | `POST /api/sessions/{session_id}/prompts` | Submit a prompt (content-part array, optional model / permission-mode overrides) |
332
499
  | `POST /api/sessions/{session_id}/prompts:steer` | Send selected queued prompts now |
333
- | `POST /api/sessions/{session_id}/prompts/{prompt_id}:abort` | Abort one queued, launching, running, or steered prompt |
500
+ | `POST /api/sessions/{session_id}/prompts/{prompt_id}:abort` | Abort one queued, launching, running, or steered prompt; `?queued_only=true` removes only a not-yet-started queue item |
334
501
  | `POST /api/sessions/{session_id}/prompts/{prompt_id}:steer` | Send one queued prompt now |
335
502
  | `GET /api/sessions/{session_id}/prompts/{prompt_id}?admission=durable` | Read a saved request, including its complete content, without restoring the agent |
336
503
  | `POST /api/sessions/{session_id}/prompts/{prompt_id}:resume?admission=durable` | Retry a held or failed saved request |
@@ -343,7 +510,23 @@ Invalid request shapes, empty messages, missing targets and unavailable uploads
343
510
 
344
511
  Read `GET /api/sessions/{session_id}/prompts?admission=durable` to receive `ingress` items. Follow `ingress_next_cursor` as `cursor` until absent, even if a page has no items for the selected agent. Pages scan at most 64 saved requests and return a text preview of at most 1024 characters with `admission_content_truncated: true`. A saved request with no text previews as `[Attachment]`. Use the point-read route for the original. Both reads leave cold agents unloaded. For a child agent, include the same `agent_id` in the submission body and every query or action.
345
512
 
346
- `admission: "admitted"` means the agent accepted the request; `status` reports its saved receipt state, not its current queue position or model consumption. For immediate delivery, optional `delivery_state: "steered"` means the core assigned the message to the target turn; `"queued"` means it is still awaiting delivery, including a pending model-switch boundary. Neither assignment nor admission confirms insertion into a model request; use the delivered transcript frame and subsequent request for that.
513
+ `admission: "admitted"` means the agent accepted the request; `status` reports its saved receipt state, not its current queue position or model consumption. For immediate delivery, optional `delivery_state: "steered"` means the core assigned the message to the target turn; `"queued"` means it was awaiting delivery when that receipt was recorded, including a pending model-switch boundary. Neither assignment nor admission confirms insertion into a model request; use the delivered transcript frame and subsequent request for that. A newer canonical started, steered or terminal prompt takes precedence over an older queued receipt.
514
+
515
+ Optional `delivery_reason` explains the immediate-delivery decision on submit receipts and durable reads. A single-ID `:steer` response also carries `delivery_state` and `delivery_reason`; `steered: true` means the prompt joined the turn, while `steered: false` means it stayed queued or had already left the queue. A known prompt that is no longer selectable returns `prompt_no_longer_pending` rather than a 404; an unknown ID still returns `40402`. Multi-ID steer acknowledgements omit the single-prompt fields. With `:abort?queued_only=true`, `aborted: true` confirms an unstarted prompt was removed and hidden from the queue and timeline; `aborted: false` means it was not removed, so refresh its current state. A started turn and its history remain intact. Ordinary `:abort` still stops a running prompt.
516
+
517
+ | `delivery_reason` | Meaning |
518
+ | --- | --- |
519
+ | `target_changed` | The active turn or prompt changed before delivery; the message was left queued. |
520
+ | `steer_rejected` | The core refused insertion into the active turn, such as for incompatible execution controls. |
521
+ | `executor_deferred` | The external executor did not deliver this message into its active run; it remains queued for a later turn. This does not distinguish an unsupported operation from a declined one. |
522
+ | `model_switch_boundary` | Delivery is waiting for the selected model-switch boundary. |
523
+ | `no_active_turn` | No active turn was available; the selected message follows the new-turn path. |
524
+ | `external_retry` | A known external submission was replayed without repeating its immediate-delivery action. |
525
+ | `prompt_no_longer_pending` | The prompt was no longer selectable in the pending queue. This alone proves neither delivery nor that it is still queued; read its canonical state. |
526
+
527
+ While a saved message waits for restoration, optional `restore_progress` reports `phase`, `started_at`, `elapsed_ms` and, in the process-wide restore queue, one-based `queue_position`. A restore attempt has a 60-second deadline including its queue wait; expiration releases its restore slot and preserves the message as `failed` with `admission_error`. Durable message preparation also has a 120-second deadline before core submission begins. The GUI shows the phase and elapsed time, with **Retry saved message** and **Cancel message** actions.
528
+
529
+ Submitting identical content under another ID while its first copy is restoring holds the new copy with `admission_duplicate_of`; it does not run automatically. Cancel the copy, or explicitly resume it to send it separately. Matching retries under the original ID keep the original request.
347
530
 
348
531
  `failed` includes `admission_error` and keeps the original content and attachments. Restarted or uncertain submissions become `held` until an explicit `:resume`; the server checks the original receipt before retrying, and a failed receipt lookup does not authorize another launch. Use `:abort` to cancel. `aborted: false` with admission `held` means cancellation still needs reconciliation; `cancelled` confirms it. To edit a saved request, cancel it and submit a new ID.
349
532
 
@@ -361,7 +544,9 @@ Sending now adds ordinary selected prompts to the active turn at a safe step bou
361
544
 
362
545
  Use `after_model_switch` only for a message intentionally dependent on an existing explicit switch operation. Do not combine it with a new model, effort, profile, execution or context choice: the server rejects mixed selections instead of silently replacing them with the old dependency's binding. Standalone manual compaction reports its own `compaction.started`, `compaction.completed` or `compaction.cancelled` progress; it neither accepts nor executes a pending message's model choice.
363
546
 
364
- For an explicit switch operation, an accepted send is not a completed switch. If switching fails or its durable completion is uncertain, the original message remains queued and the switch exposes its recoverable state. Retry the same operation to finish the accepted delivery; a cancelled switch is not revived. Prompts with an unrelated execution selection still require their own turn. After a restart, sending now bypasses the recovery hold only for the selected prompts; other restored prompts still wait for confirmation. Aborting a steered prompt cancels the turn it joined, not a later turn. Aborting an unknown or already settled prompt returns `40402`.
547
+ Standalone native model switches apply before the next model request without submitting a prompt or interrupting the current request. Their `thinking` input accepts a string for an explicit effort or `null` to clear that selection and resolve the persona pin, target model-profile default, then model default, in that order. Omitting `thinking` keeps the current effort on the same model (including its aliases), but resolves those defaults when changing models. To keep a hand-picked effort across models, send it explicitly.
548
+
549
+ For an explicit switch operation, an accepted send is not a completed switch. If switching fails or its durable completion is uncertain, the original message remains queued and the switch exposes its recoverable state. Retry the same operation to finish the accepted delivery; a cancelled switch is not revived. Prompts with an unrelated execution selection still require their own turn. After a restart, sending now bypasses the recovery hold only for the selected prompts; other restored prompts still wait for confirmation. Aborting a steered prompt cancels the turn it joined, not a later turn. Ordinary `:abort` returns `40402` for an unknown or already settled prompt; use `?queued_only=true` when removing a queue row.
365
550
 
366
551
  ### Approvals and questions
367
552
 
@@ -451,11 +636,21 @@ These endpoints manage saved browser connections, not the sessions that use them
451
636
 
452
637
  `PUT` takes the same discriminated body as the GUI. A body whose `type` is `agent-browser-profile` needs `name` and accepts `profilePath`, `executablePath`, `headed` and `driverPath`; one whose `type` is `agent-browser-cdp` needs `name` and `endpoint` — either `{ "action": "set", "value": "<CDP http/ws URL>" }` or `{ "action": "keep" }` to leave the stored address unchanged. Both accept `enabled`, which defaults to `true`. A new CDP connection without `set` is rejected. A stored CDP address reads back masked; revealing it is an explicit `POST /api/secrets:reveal` whose `ref` has `kind: "browser_endpoint"`. A body whose `type` is `ego-lite` needs `name` and accepts optional `cliPath`, `profileId`, and `serverName`. It has no endpoint.
453
638
 
639
+ A `kimi-webbridge` body needs `name`, accepts `enabled` and optional `driverPath`, and rejects `endpoint`. It uses the Kimi HTTP daemon at `http://127.0.0.1:10086` on the server; it does not start the CDP driver. A running extension does not register a Kiki connection: if `BrowserConnections` or the REST API reports `browser.not_found` for this id, save a `kimi-webbridge` connection in Browser control or `config.toml`, then check it again. Legacy saved CDP entries whose id is exactly `kimi-webbridge` use this HTTP route by default without rewriting the saved type; see [`webbridge_preset_route`](../configuration/config-files.md#browser-control). Other CDP ids keep their CDP route.
640
+
641
+ A `webbridge-command` body needs `name`, accepts `enabled` (default `true`), and rejects both `endpoint` and `driverPath`. It sends extension commands to the fixed local `/command` endpoint without starting agent-browser. Its catalog reports `contextIsolation: "extension-command-session"`. Each caller has a separate command session; tab identities are `wb:<decimal id>`, not DevTools target IDs. Page actions, tab selection and close apply only to the tab that caller's last navigate opened. Kiki does not find a different tab by URL, including when two tabs share a URL. Window and frame methods are unavailable. Disconnect releases Kiki's binding without closing tabs; the explicit `agent_browser_end_session` page operation closes that caller's command session.
642
+
643
+ The existing `kimi-webbridge` HTTP bridge's catalog reports `contextIsolation: "main-frame-only"`: window creation and non-main frames are unsupported. Tab selection uses the exact id returned by the tab list and verifies the selected id; switching to another tab is rejected when duplicate URLs prevent an unambiguous selection. A saved connection whose local HTTP status is unavailable, whose daemon reports stopped, or whose extension reports disconnected returns `state: "disconnected"` with `failure.code: "browser.disconnected"` and a cause-specific message. A later healthy `:check` clears this failure; if the connection is no longer attached, it returns `idle`, so connect before listing tabs. When a command was sent but its response is lost or unreadable, status is `unconfirmed` with `failure.reason: "outcome_unknown"`. The command is not replayed. `:check` only checks bridge health; if it returns `idle` after an unconfirmed command, reconnect, select the tab, and observe it before deciding the next action. An explicit negative acknowledgement is a finished `failed` result instead.
644
+
454
645
  Execution actions fail closed: without the `native_browser` experimental flag `:connect` returns envelope code `40001` with `details.code: "browser.disabled"` and `details.reason: "feature_disabled"`, while a switched-off connection returns `details.reason: "connection_disabled"`. Klient exposes the same surface as `rest.browser.list()`, `upsert(id, input)`, `remove(id)`, `setDefault(browser?)`, `status(id)`, `tabs(id)`, `catalog(id, { includeSchema })`, `check(id)`, `connect(id)`, and `disconnect(id)`.
455
646
 
456
647
  ### Browser setup presets
457
648
 
458
- Presets are `kimi-webbridge`, `independent-browser`, `codex-browser`, and `ego-lite`. `kimi-webbridge` and `independent-browser` manage local components, while `codex-browser` lists matching endpoint names as unverified candidates (`candidates`, up to 20 entries) and saves an explicitly selected pipe. The name prefix is shared with desktop app tools, so discovery does not verify an extension connection. An empty list alone does not establish that the extension is disabled. Kiki does not install the external app. `kimi-webbridge` connects and opens one fixed local bridge and does not take a candidate list. Codex pipes and independent-browser profiles are separate connection styles; they do not create extra Kimi WebBridge instances. `ego-lite` uses `controlSurface: "external-app"` and `sourceUrl` `https://lite.ego.app/download?auto=1`. Its status does not launch `nodejs`. `ready` is reported only after a check prints `kiki-ego-ready`. Other reasons are `ego_installed`, `ego_onboarding`, and `ego_choose_cli`. `:prepare` rejects this preset. `:connect` runs the check and, when it succeeds and the id is absent, saves connection id `ego-lite` without changing the allowed set or the default browser.
649
+ Presets are `kimi-webbridge`, `independent-browser`, `codex-browser`, and `ego-lite`. `kimi-webbridge` and `independent-browser` manage local components, while `codex-browser` lists matching endpoint names as unverified candidates (`candidates`, up to 20 entries) and saves an explicitly selected pipe. The name prefix is shared with desktop app tools, so discovery does not verify an extension connection. An empty list alone does not establish that the extension is disabled. Kiki does not install the external app. `kimi-webbridge` connects and opens one fixed local bridge and does not take a candidate list. After the extension probe succeeds, it creates an endpoint-free `webbridge-command` connection if that id is free and returns `connectionId: "webbridge-command"` plus `connection` runtime state. If another type already occupies the id, it returns `reason: "connection_conflict"` without replacing that row or any existing `kimi-webbridge` connection. Codex pipes and independent-browser profiles are separate connection styles; they do not create extra Kimi WebBridge instances.
650
+
651
+ `ego-lite` uses `controlSurface: "external-app"` and `sourceUrl` `https://lite.ego.app/download?auto=1`. Status reads share one background detection. While it runs, GET returns `state: "preparing"`, `reason: "ego_detecting"`, and a `detect` step in `running`; the other presets remain available. Poll again to read the outcome. Discovery and any automatic CLI check share a five-second deadline; a timeout returns `failed` with `reason: "ego_detection_failed"` and its error. Completed results stay fresh for 30 seconds from completion. `:cancel` stops the active detection, and disabling the source stops it without changing browser permissions.
652
+
653
+ An existing saved Ego connection or a recognized Citro installation can be checked automatically with `nodejs`; an unrelated executable found only on PATH requires an explicit check. `ready` is reported only after a check prints `kiki-ego-ready`. Other reasons are `ego_installed`, `ego_onboarding`, and `ego_choose_cli`. `:prepare` rejects this preset. `:connect` runs the check and, when it succeeds and the id is absent, saves connection id `ego-lite` without changing the allowed set or the default browser.
459
654
 
460
655
  | Method and path | Description |
461
656
  | --- | --- |
@@ -512,8 +707,10 @@ Both `PATCH` variants accept `{ name?, pinned? }`, with at least one field requi
512
707
 
513
708
  | Method and path | Description |
514
709
  | --- | --- |
515
- | `GET /api/memory/settings` | Read the memory section, with `effective_enabled` |
516
- | `PATCH /api/memory/settings` | Change `enabled`, `approval` or `budget` |
710
+ | `GET /api/memory/settings` | Read the memory section, with `effective_enabled`, optional `advisor` and `advisor_status`; optional `workspace_id` resolves effective memory access for that workspace |
711
+ | `PATCH /api/memory/settings` | Change `enabled`, `approval`, `budget` or sparse `advisor` fields; accepts the same optional `workspace_id` |
712
+ | `POST /api/memory/advisor/probe` | Test the saved advisor source using synthetic content; body: `{ confirm_destination }` |
713
+ | `GET /api/memory/advisor/status` | Read a live agent's status with `session_id` and optional `agent_id` (default `main`); returns `null` for a cold or absent agent |
517
714
  | `GET /api/memory/workspaces/{workspace_id}/settings` | Read one workspace's switch |
518
715
  | `PATCH /api/memory/workspaces/{workspace_id}/settings` | Set it to `true` / `false`, or `null` to follow the global setting |
519
716
  | `GET /api/memory/{scope}` | Search or list entries; see below for filters and pagination |
@@ -523,12 +720,35 @@ Both `PATCH` variants accept `{ name?, pinned? }`, with at least one field requi
523
720
  | `GET /api/memory/{scope}/inbox` | List proposals awaiting review |
524
721
  | `GET /api/memory/{scope}/journal` | Change history, optionally narrowed to one `id` |
525
722
  | `POST /api/memory/{scope}/undo` | Undo one operation by `operation_id` |
723
+ | `GET /api/memory/authority` | Read the persisted backend, mode, epoch and migration progress |
724
+ | `POST /api/memory/authority/retry` | Retry the persisted startup migration using its operation ID |
725
+ | `POST /api/memory/authority/migrate` | Compatibility endpoint for one bounded migration batch |
726
+ | `POST /api/memory/authority/cancel` | Cancel the matching paused maintenance batch |
727
+ | `POST /api/memory/authority/recover-readonly` | Save a governed recovery package and enter read-only mode |
728
+ | `POST /api/memory/authority/resume-editing` | Resume SQLite editing with the current recovery ID and epoch |
729
+ | `POST /api/memory/{scope}/forget-preview` | Expand exact IDs into the complete source-lineage target set |
730
+ | `POST /api/memory/{scope}/forget` | Irreversibly forget the confirmed target set |
731
+ | `GET /api/memory/{scope}/{id}/provenance` | Read original sources, human adjudications and related IDs |
732
+ | `GET /api/memory/{scope}/{id}/revisions/{revision}` | Read an exact historical revision; URL-encode the revision |
733
+ | `GET /api/memory/{scope}/{id}/export` | Export one complete revision-bound Markdown document and its entry |
734
+ | `POST /api/memory/{scope}/import-preview` | Compare a Markdown document with the current governed entry |
735
+ | `POST /api/memory/{scope}/import` | Apply an explicitly confirmed preview token |
736
+
737
+ Set `advisor.source` to a [decision source](#decision-connections). It takes precedence over an existing `selector`. Sparse `{ "advisor": { "mode": "off" } }` preserves the source and other preferences. `mode` is `off`, `rank` or `select`; `pair_score` supports `rank` only. `advisor: null` removes the whole block; `source: null` clears both the source and legacy selector, while `selector: null` clears only the selector. Updates apply without restarting.
738
+
739
+ The legacy selector remains `{ protocol: "chat_json" | "system_one" | "pair_score", model, endpoint? }`, where `model` is a configured alias and a non-chat `endpoint` must share the origin of that model's `effective_base_url`. New connection sources keep the protocol and endpoint on the connection instead.
740
+
741
+ Configuring a source and enabling the advisor starts recommendations using that service. Existing `advisor.egress_ack` values remain readable and are preserved, but do not gate requests; `advisor_status.consent_required` is `false`. Changing the destination cancels unfinished recommendations and recomputes against the new service. See [Memory Advisor](../guides/memory.md#memory-advisor) for setup.
742
+
743
+ The probe requires `confirm_destination` to match the current `advisor_status.destination`, binding this test request to the service. It reads no saved entries and works while automatic advice is off. It returns `{ ok, status, duration_ms, input_tokens?, output_tokens?, usage_known }`.
744
+
745
+ Status carries `state`, optional `reason`, destination and model, plus `logical_calls`, real `requests`, `retries`, `recommended_count`, directory `enumeration`, `unjudged_count` and `displaced_ids`. Settings status describes configuration readiness; `/advisor/status` reads runtime outcomes without starting or resuming an agent.
526
746
 
527
747
  `GET /api/memory/{scope}` returns bounded pages as `{ items, mode, next_cursor, coverage }`, including when no pagination parameters are supplied. `mode` defaults to `list` with no `query` and to `search` with one; `page_size` is 1–20. Without explicit `statuses`, list reads `active` and `pending`, search reads `active`, and `include_inactive=true` widens either to all four. `statuses` is a comma-separated list of `active`, `pending`, `superseded` and `archived`. Existing clients must consume `next_cursor` rather than treating the first page as the whole namespace.
528
748
 
529
- Continue until `next_cursor` is null and `coverage.exhausted` is true. An empty preparation page with a cursor is not an empty namespace. `coverage.complete` and `warnings` report unreadable, invalid or oversized records; those records do not hide the other readable entries. Scan budgets are per call, not a permanent inventory limit; search ranking and list title ordering apply within each bounded source chunk.
749
+ Continue until `next_cursor` is null and `coverage.exhausted` is true. An empty preparation page with a cursor is not an empty namespace. `coverage.complete` and `warnings` report unreadable, invalid or oversized records; those records do not hide the other readable entries. Scan budgets are per call, not a permanent inventory limit. The file backend ranks and orders each bounded source chunk; SQLite pages share one committed generation.
530
750
 
531
- Keep the same `{scope}` path and owning `workspace_id` / `persona_id`, and send `cursor` alone, without the original filters or page size. Mixing them returns `40944`. A cursor is invalidated by source changes or a store restart; restart and reconcile by scope plus ID. `GET /api/memory/{scope}/inbox` returns the same page shape for `pending` only and accepts `page_size` or a pending-list `cursor`; cursors for other statuses or search mode are rejected.
751
+ Keep the same `{scope}` path and owning `workspace_id` / `persona_id`, and send `cursor` alone, without the original filters or page size. Mixing them returns `40944`. File-backend source changes or a store restart invalidate a cursor; restart and reconcile by scope plus ID. SQLite continuation retains its committed view across later writes, while rechecking scope access and forget barriers. `GET /api/memory/{scope}/inbox` returns the same page shape for `pending` only and accepts `page_size` or a pending-list `cursor`; cursors for other statuses or search mode are rejected.
532
752
 
533
753
  `PUT /api/memory/{scope}/{id}` takes the same action vocabulary as [`MemoryWrite`](../reference/tools.md#writing-an-entry): `action` (`create`, `update`, `supersede`, `archive`), `type`, `title`, `body`, `reason`, `expected_revision` and `pinned`. Writes through REST are recorded as coming from you, whatever `source` the agent would have used. The response is `{ entry, operationId, outcome, warnings? }`, where `outcome` is `applied`, `pending` or `unchanged`; `operationId` is `null` for `unchanged` and for a proposal identical to one already waiting, and those two cases have nothing to undo. For `update`, `supersede` and `archive`, `expected_revision` is required — a `PUT` built on a stale revision is refused instead of overwriting a newer one.
534
754
 
@@ -541,6 +761,41 @@ Two metadata fields are optional and behave differently on omission:
541
761
 
542
762
  `GET /api/memory/{scope}/{id}` returns the full entry plus `scope`, a `target` of `{ scope, id, expected_revision }`, an `applicability` of `expired`, `recheck` or `unrecorded`, and `complete: true`. The `target` is an addressing object, not a request body: `scope` and `id` belong in the path, the owning workspace or persona in the query string, and `expected_revision` is the one field the `PUT` body takes from it — alongside the `action`, `type`, `title`, `body` and `reason` for the change you are making. Read an entry before writing to it. A `PUT` whose `expected_revision` no longer matches returns the `40944` code, and the response's `details` carries the domain's own `code` and `recovery` while the numeric envelope code stays the one existing clients already handle.
543
763
 
764
+ #### Markdown export and import
765
+
766
+ These three routes require a completed SQLite migration and the same scope ownership query parameters as ordinary entry reads. They remain available for explicit management while agent memory access is off. Read-only recovery permits export but refuses preview and import.
767
+
768
+ `GET /api/memory/{scope}/{id}/export` returns `{ markdown, entry }` in the normal envelope. `markdown` is a complete `kiki-memory-v1` document: JSON or YAML frontmatter followed by the full body. Preserve `format`, `scope`, `id`, `revision`, `origin: { id, revision }` and source coordinates when editing an existing entry. A genuinely new document uses `id: "new"`, `revision: null`, `origin: null` and `status: "active"`. The file also carries `type`, `title`, `status`, `pinned`, optional `basis` and `validity`. In this complete-document format, `validity: null` or omitting `validity` clears the check, unlike a partial `PUT`. The body limit remains 1,500 characters.
769
+
770
+ Send `{ markdown, source_locator, reason }` to `POST /api/memory/{scope}/import-preview`. Use a stable source-file locator; it is recorded as provenance, not fetched by the server. The entire document is limited to 65,536 UTF-16 units, the locator to 2,000 characters and the reason to 500. Unknown request fields are rejected. The response uses camelCase fields:
771
+
772
+ - **`incoming`, `current`**: the complete parsed document and current governed entry, or `current: null` for a new target. Review both before confirming.
773
+ - **`action`**: `create`, `update`, `unchanged` or `retained`. `unchanged` needs no write; `retained` resolves a previously admitted source to its current entry rather than replaying old content.
774
+ - **`canApply`, `issue`**: only `canApply: true` permits confirmation. A blocked preview can include `issue: { code, recovery }`, for example for a stale revision, duplicate title or inactive target.
775
+ - **`previewToken`, `expiresAt`**: present for a confirmable preview. The token binds the complete reviewed input to this server process and authority epoch for ten minutes.
776
+
777
+ To confirm, send `{ preview_token: previewToken, operation_id: UUID, confirm_import: true }` to `POST /api/memory/{scope}/import` with the same scope owner. Do not resend or reconstruct the edited document. Success returns the normal `{ entry, operationId, outcome, warnings? }` write result. The confirmed import is recorded as your write while preserving the original Markdown source.
778
+
779
+ The server rechecks the target revision and source barriers when applying. A concurrent edit or forget cannot be overwritten; revision conflicts return `40944` with domain details. An expired, altered or pre-restart token returns `40001`; preview the original file again after a token failure or authority change. After a revision conflict, re-export the entry if it still exists, reconcile the document and preview again. If it was forgotten, stop importing that old source. Changing an old file's ID, title or locator does not revive its corrected or forgotten source. Import cannot approve pending proposals, restore retired entries or move entries between scopes; use the ordinary review or restoration operation first.
780
+
781
+ #### Backend migration and recovery
782
+
783
+ App startup automatically runs the existing SQLite migration pipeline, including for new homes and when `memory.enabled=false`. Normal Memory store preparation, reads and writes share that startup operation. Completed homes reuse SQLite without importing again; read-only recovery stays read-only. Storage upgrade does not enable agent memory access or authorize advisor egress.
784
+
785
+ `GET authority` reports `backend`, `mode`, `epoch` and the persisted `migration`. During migration, `migration.id` is the operation ID, `namespaces` names the discovered scopes, `index` counts completed namespaces, and optional `after` is the last committed source key in the current namespace. Optional `phase` is `importing`, `validating` or `failed`; `issues` contains `{ scope, key, issue }`, and `failure` supplies `{ code, message }`.
786
+
787
+ Malformed or unreadable sources preserve the original files and block ordinary memory access instead of falling back to an older copy. Repair the reported sources, then send `{ operation_id: migration.id }` to `authority/retry`, or restart to resume the same operation and saved progress. Scopes with earlier issues are imported again before continuation. After an uncertain response, read status before retrying. Completion returns `backend: "sqlite", mode: "active", migrationId`; the same-ID retry also reconciles an already completed operation. Optional top-level `migrationIssues` retains non-blocking `{ scope, key, issue }` notes: `current_revision_preserved` keeps the stored revision, and `forgotten_source_rejected` skips a forgotten source. These notes remain available in active and read-only mode.
788
+
789
+ The compatibility `authority/migrate` endpoint still accepts `{ operation_id: UUID, max_pages?: 1..64 }` for a bounded maintenance batch; the default is eight pages. The old `older_writers_stopped: true` field is optional and is not sent by startup. `authority/cancel` accepts `{ operation_id }` for a paused batch, not a running automatic operation; subsequent normal preparation starts the automatic upgrade again. Upgrade other installations sharing the home: the marker and write barrier govern compatible writers, not pre-protocol binaries.
790
+
791
+ Send `{ confirm_readonly: true }` to `authority/recover-readonly` to save the current governed SQLite database, its legacy-shaped current-view export and a manifest under `store/memory-recovery-v1/<recoveryId>`. The response includes `recoveryId`, `scope`, `generation`, `namespaces` and `mode: "readonly"`. Reads continue from SQLite and mutations are refused. To resume normal editing, read `authority` and send `{ recovery_id: recoveryId, expected_epoch: epoch }` to `authority/resume-editing`. A changed recovery ID or epoch is rejected. The full database preserves post-cutover operations, corrections, proposals and forget barriers; the Markdown export is only the compatible current-view representation.
792
+
793
+ #### Irreversible forget and historical reads
794
+
795
+ After SQLite migration, send `{ ids: ["m_example"] }` to `{scope}/forget-preview`. Its `{ generation, targets }` response expands the complete source lineage; each target contains `id`, `expectedRevision` and its current `entry`, or `entry: null` for a recoverably deleted object. Show this exact set before confirmation. Submit `{ operation_id: UUID, confirm_irreversible: true, targets: [{ id, expected_revision }] }` to `{scope}/forget`, copying each preview revision into `expected_revision`. A changed revision or incomplete lineage is refused. This operation cannot be undone and does not delete conversation history, external source files or independently held backups.
796
+
797
+ Exact historical reads return the entry with `historical: true`, not current guidance. Forgotten revisions return the same not-found outcome as forgotten current entries. Before restoring an older backup, retain the latest applicable adjudications and forget barriers rather than reintroducing its retired content.
798
+
544
799
  ### Session leases and peer threads
545
800
 
546
801
  A session lease is a periodically renewed "online token" a client holds: `POST /api/leases` creates or renews one (default validity 60 seconds) and responds with `lease_id` and `expires_at`. A live lease can hold resources that need cleanup (such as PTY terminals and file watches) and keeps the shared daemon from exiting as idle — see `--idle-exit` under [`kiki serve`](../reference/command.md#kiki-serve).
@@ -554,13 +809,21 @@ The peer-thread endpoints support cross-session collaboration: a thread is addre
554
809
  | Method and path | Description |
555
810
  | --- | --- |
556
811
  | `GET /api/threads` | List addressable threads, filterable by `workspace_id`; cursor pagination |
557
- | `POST /api/threads:read` | Read a thread's completed turns with their recorded origin, optionally continuing from a `cursor` |
812
+ | `POST /api/threads:read` | Read a thread's completed turns with their recorded origin, optionally continuing from a `cursor`; preparation can return an incomplete page with an opaque continuation |
558
813
  | `POST /api/threads:send` | Durably accept a message for another thread (requires a non-empty `idempotency_key`; a key maps to a single message) |
559
814
  | `POST /api/threads:wait` | Long-poll for activity on up to 8 threads, `timeout_ms` capped at 60 seconds |
560
815
  | `GET /api/workspaces/{workspace_id}/thread-communication` | Read the persisted override and effective thread-communication state for the workspace |
561
816
  | `PUT /api/workspaces/{workspace_id}/thread-communication` | Persist the workspace's enable/disable override |
562
817
  | `DELETE /api/workspaces/{workspace_id}/thread-communication` | Clear the override |
563
818
 
819
+ #### ThreadRead continuation
820
+
821
+ A `POST /api/threads:read` response can contain `turns: []`, `incomplete: "history_preparing"`, and an opaque `next_cursor` while the local history projection is preparing. This is an incomplete preparation page, not proof that the thread has no conversation. Repeat the request with `next_cursor`, keeping the same thread and bridge scope. The preparation cursor binds its projection generation and fixed source watermark while retaining the original older-turn boundary; once preparation completes, ended-turn pages keep the existing default `limit` of 20, 1–100 range, and chronological order.
822
+
823
+ Local turn `input` and `output` fields of at most 4,096 UTF-16 units remain inline. Longer fields return a preview and a field-specific entry in `content_refs`. Send that entry as `content_ref` with the same thread to receive `view.segment`; keep the preview and append each segment's `value`, following `next` until it is absent. Each segment contains at most 16,384 UTF-16 units, and its reference starts after the text already returned. Reading segments does not resume the thread.
824
+
825
+ Existing read cursors remain accepted for compatibility. A history rewrite explicitly invalidates affected cursors, as does a generation change; when the server reports an invalid cursor, restart from the first page rather than treating the thread as empty.
826
+
564
827
  #### Communication history
565
828
 
566
829
  `GET /api/threads/messages` reads accepted cross-thread messages without resuming sessions. It excludes ordinary user input, external REST/Klient sends, and parent–subagent exchanges. Reads remain available for archived sessions and when new peer sends are disabled.
@@ -600,7 +863,7 @@ For `undeliverable` records, `reason_code` is a stable localization key and `rea
600
863
 
601
864
  Klient provides `klient.rest.threads.messages(query, options)` with these snake_case wire shapes. `klient.global.threads.messages({ workspaceId, sessionId, peerSessionId, cursor, limit })` provides the same read using camelCase shapes over HTTP, IPC, and memory transports.
602
865
 
603
- Peer messages are no longer evicted by the mailbox's former 512-message limit. The first upgraded mailbox owner resumes a checkpointed backfill of records still present in the mailbox; messages already evicted by older versions are not reconstructed from session wires. Restart older processes sharing the same Kiki home before relying on the new retention behavior.
866
+ Peer messages are no longer evicted by the mailbox's former 512-message limit. The [mailbox storage upgrade](#mailbox-storage-upgrade) backfills records still present in the old mailbox before switching authority; messages already evicted by older versions are not reconstructed from session wires. Close older writers and complete that upgrade before using the home with Kiki 0.5.x.
604
867
 
605
868
  ### Room conversation entries
606
869
 
@@ -646,6 +909,55 @@ Pages are sorted by score descending, then path; an empty query lists the root d
646
909
  | `GET /api/files/{file_id}` | Download (binary; errors use real HTTP statuses) |
647
910
  | `DELETE /api/files/{file_id}` | Delete |
648
911
 
912
+ ### IM account and channel bindings
913
+
914
+ [Two-way messaging](../features/phone.md) binds each input or output channel to a session. A Persona is optional; changing or clearing it does not move the session's bindings.
915
+
916
+ | Method and path | Description |
917
+ | --- | --- |
918
+ | `GET /api/im/sessions` | Snapshot of policy, instances, discoveries, bindings, strangers and voice fallbacks |
919
+ | `GET /api/im/sessions/catalog` | Personas and sessions available as binding targets |
920
+ | `PUT /api/im/sessions/policy` | Set `allowed`, `default_enabled`, and optional `allow_channel_borrowing` (default `false`) |
921
+ | `POST /api/im/sessions/instances/{id}/listen` | Set `{ listening: true \| false }`; retry a stopped listener with `true` |
922
+ | `POST /api/im/sessions/discoveries/{id}/confirm` | Bind to `target`; optional `rebind`, `input_enabled`, `output_enabled`, `busy`, `reply`, `mobile_interactions`, `also_home` |
923
+ | `PATCH /api/im/sessions/bindings/{id}` | Update this binding's target, direction switches or options |
924
+ | `DELETE /api/im/sessions/bindings/{id}` | Remove this IM binding |
925
+ | `GET /api/im/sessions/targets/{session_id}/channels` | Read output channels and candidates with their actual media capabilities |
926
+ | `PUT /api/im/sessions/targets/{session_id}/notify/{channel_id}` | Bind a notification output or change its session switch with `{ enabled: boolean }` |
927
+ | `DELETE /api/im/sessions/targets/{session_id}/notify/{channel_id}` | Remove only this session's notification binding |
928
+ | `GET /api/sessions/{session_id}/optional-capabilities` | Read authoritative capability rows, including `send_message` |
929
+ | `POST /api/sessions/{session_id}/optional-capabilities` | Set `{ id: "send_message", choice: "on" \| "off" \| "inherit" }`; applies at the next step without restarting |
930
+
931
+ A `target` is `{ kind: "session", session_id }`, or the compatible `{ kind: "persona", persona_id }` shortcut to that Persona's home session. PATCH also accepts legacy `session_id`, but not together with `target`; `also_home` belongs only to confirmation. Reconfirming preserves existing `enabled`, `session_enabled`, `input_enabled` and `output_enabled` unless explicitly changed. `session_enabled: null` follows `policy.default_enabled`; a direction set to `null` removes that direction override. Both directions still require the binding and session allowance to be enabled.
932
+
933
+ For groups, confirmation and PATCH accept `binding_scope: "sender" | "topic" | "chat"`; omission matches only the original sender. `topic_id: "0"` means there is no topic: choose `"chat"` for the whole group or `"sender"` for the original sender; `"topic"` returns business code `40001` / `topic_scope_unavailable`. Choosing `"topic"` or `"chat"` outside a group returns `40001` / `group_binding_scope_required`. A stored no-topic `"topic"` binding still matches only its original sender; it does not widen to the group.
934
+
935
+ PATCH changes a binding in place. If broadening its scope overlaps another enabled input binding, send `rebind: true`; a rejected or failed save keeps the previous binding and pending replies. Explicitly enabling a direction the connection does not support returns `40001` / `input_unsupported` or `output_unsupported`. These errors are business codes in an HTTP 200 envelope; identity conflicts use business code `40949`. Topic/chat scopes share a session across members while preserving real sender IDs and isolating their pending interactions.
936
+
937
+ New topic/chat group bindings default to `group_policy: { wake: "mention_or_reply" }`. Confirmation and PATCH accept `group_policy: { wake: "always" | "mention_or_reply" | "manual", prefixes?: string[] }`: `always` wakes on every message, `mention_or_reply` wakes on a real mention, a reply to a known self message, or a literal configured prefix, and `manual` records without waking. Existing sender-scoped bindings with no policy keep every-message wake.
938
+
939
+ Mention/reply detection requires adapter metadata. Built-in Telegram provides real message IDs, timestamps, sender/chat names, entity-based mentions and reply IDs; update IDs remain separate event deduplication keys. Other transports without those fields can use prefixes or `always` instead.
940
+
941
+ Choose a group binding's scope and wake rule in Notifications & messages. To change them through REST, use confirmation or `PATCH /api/im/sessions/bindings/{id}`. For a transport without mention/reply metadata, set `{ "group_policy": { "wake": "mention_or_reply", "prefixes": ["Kiki:"] } }` to use a prefix, or `{ "group_policy": { "wake": "always" } }` to wake on every message.
942
+
943
+ An enabled inbound group binding keeps a bounded, persistent received timeline per account, chat and topic. Quiet messages do not start a model turn. A triggered prompt includes recent unconsumed background and up to four quoted ancestors as untrusted external data; accepted submission advances only its captured background watermark, without deleting the timeline or losing newer arrivals. The main agent can use [ReadMessageHistory](../reference/tools.md#im-chat-history) for explicit local searches or optional platform backfill. Disabling input stops both collection and reads for that binding.
944
+
945
+ An input identity belongs to one session at a time. Moving a binding to another session without `rebind: true` returns business code `40949`, `msg: "im_identity_already_bound"`, and `details` containing `existing_binding_id`, `previous_session_id`, `target_session_id` and `variant_key`. Show these identities for confirmation, then repeat the request with `rebind: true`; cancelling sends no mutation. Old interaction tickets cannot act on the new session, and old reply watchers expire on transfer. The mobile `:target` command lists targets but requires confirmation in Kiki to transfer them. A legacy binding with a missing session stays visible as `pending_reanchor: true`, retaining its old identity and Persona provenance without routing until explicitly reanchored.
946
+
947
+ The output response contains `internal_enabled: true` and `channels`. Each channel has `id`, `kind` (`internal`, `im`, `notify`), `enabled`, `capabilities`, and optional `bound`; `bound: false` is a candidate, not a session binding. `internal` stays enabled; the legacy internal-switch endpoint rejects `{ enabled: false }`. Klient exposes `rest.imSessions.channelViews`, `setNotificationChannel` and `removeNotificationChannel`.
948
+
949
+ Binding channels does not grant `SendMessage`. Ordinary reply threads default to off; `[optionalCapabilities.defaults] send_message = true` changes the global default, while a session choice of `on` works even when the default is off. Persona message mode retains its implicit-on behavior; explicit session `off` and hard tool-policy denies take precedence. Turning the tool off neither unbinds channels nor hides ordinary final replies.
950
+
951
+ With the tool admitted, omit `channel`/`channels` to send only to enabled bound outputs, including `internal`; explicit IDs select one or more outputs. Borrowing an unbound channel requires `allow_channel_borrowing: true` and an enabled, authorized target. `to: "user"`, `to: "@Bot"` and Room routing retain their recipient meaning; channel IDs cannot be combined with Room or `@Bot` routing. Per-channel receipts distinguish `delivered`, `partial`, `unsupported`, `failed` and `unknown`, and mark borrowed targets. Notification outputs currently carry text only. Inspect partial or unknown receipts instead of resending automatically; an accepted provider response does not prove a person received the message.
952
+
953
+ An instance's `listening` records the requested state. Its `adapter` is `missing`, `running`, `shared` or `stopped`; optional `connection` is `starting`, `reconnecting`, `auth_expired` or `stopped`. Normal running omits `connection`. For `auth_expired`, renew authorization through setup; for a stopped connection, retry listening explicitly. Optional `connection_detail` contains a finite `code` (`transport_error`, `http_error`, `api_error`, `invalid_response`, `auth_expired`, `loop_failed`) and optional numeric `http_status`, `ret`, `errcode`, `failure_count`, `retry_in_ms`. A successful reconnect clears that detail; an absent detail does not identify a failure cause.
954
+
955
+ Channel identity uses `chat_id`, `sender_id`, and `topic_id` (`"0"` for no topic). Optional `chat_kind` is `private` or `group`; do not infer it from a title when absent. The current WeChat connection supports private contacts only. Confirming a group returns business `code: 40001`, `msg: "unsupported_wechat_group"`, preserving the discovery without creating a persona home or changing a binding.
956
+
957
+ If an older Feishu thread binding has no reply context, send a new message from the same sender in that thread to restore delivery of still-pending approvals and questions. Unsupported WeChat group bindings remain unsent; disable or remove them rather than retrying them as private chats. A blocked binding does not prevent delivery to other channels.
958
+
959
+ IM sends wait at most 60 seconds, including time queued for that destination. If an approval or question send times out or is interrupted after dispatch, Kiki does not resend it automatically, including after restart. Open the session in Kiki to handle the pending interaction.
960
+
649
961
  ### Global search and misc
650
962
 
651
963
  | Method and path | Description |
@@ -666,6 +978,8 @@ Pages are sorted by score descending, then path; an empty query lists the root d
666
978
 
667
979
  `POST /api/search` accepts `query` and defaults to user/assistant text plus session titles. Set `include_tool_output: true` to include tool results and Shell output; thinking, tool names and tool inputs remain excluded. `role` can select `user`, `assistant`, `tool` or `title`, with `role: "tool"` explicitly selecting tool results. The same content scope applies to live sessions and existing indexes. Changing it invalidates the old `page_token`; start again without a token.
668
980
 
981
+ For a live `container.session_id`, search uses bounded resident text and the shared history-navigation projection. The request deadline and client cancellation cover preparation as well as matching. A live response includes `coverage: { domain: "full_text", complete, gaps, scanned: { bytes, records } }`. `incomplete: "scan_budget"` marks unfinished scanning or skipped history; `incomplete: "deadline"` marks an exhausted time or text budget. An empty partial page is not a no-match result: follow `page_token` when `has_more` is true. Continuations reuse completed preparation and expire after 60 seconds; restart without a token if it becomes invalid. `gaps` also identifies page-local ordering and records that exceeded the scan allowance. Display partial counts as lower bounds, even when no continuation remains.
982
+
669
983
  `POST /api/search/retry` takes no body. When the indexer has stopped after repeated memory pressure, call it to clear the backoff and restart the stopped writer. This applies to the default SQLite backend and to MiniDB. Documents already in the published index stay searchable; the call does not delete or rebuild that index. Success uses the normal envelope with `data.retried` set to `true`. Klient exposes `rest.search.retry()`.
670
984
 
671
985
  ### Usage source grouping
@@ -676,15 +990,27 @@ Repeat `model`, `provider`, `profile`, `agent.id`, or `workspace.id` to select m
676
990
 
677
991
  Source groups use opaque keys such as `provider:"example-provider"` or `profile:"explore"`; missing sources have distinct `provider:null` or `profile:null` keys and a `null` attribution field. They retain their recorded usage and are never inferred from a model or agent ID. Use `group.provider` or `group.profile_name`, not the group key, as a filter value. There is no filter sentinel for missing sources; the literal value `unknown` selects only records that actually carry that name.
678
992
 
679
- For a selected period or comparison, send `range=custom&start_at=A&end_at=B` with epoch-millisecond bounds `[A,B)`. Summary, trend groups, and each session's `usage` apply the same record filters and exact window; session totals do not include unrelated profiles or the rest of a time bucket. Cost and token unknown flags remain separate from their recorded numeric subtotals. Keep the existing archive, timezone, and pagination parameters; discard `page_token` when changing filters or the window.
993
+ For a selected period or comparison, send `range=custom&start_at=A&end_at=B` with epoch-millisecond bounds `[A,B)`. Summary, trend groups, and each session's `usage` apply the same record filters and exact window; session totals do not include unrelated profiles or the rest of a time bucket. Cost and token unknown flags remain separate from their recorded numeric subtotals. Page tokens bind the filters, data revision and current prices; changing any of them returns business code `40922`. Discard the token and restart from the first page. The GUI does this automatically.
994
+
995
+ ### Session cumulative usage
996
+
997
+ Ordinary `GET /api/sessions/{sessionId}` returns the last published `usage.accounting` summary, or saved metadata when no summary is available; it does not scan the session's agents. To refresh cumulative usage, call `GET /api/usage/sessions/{sessionId}/accounting` or `klient.rest.sessionUsageAccounting(sessionId, { signal })`. This route reads the session index without reopening the session and returns the accounting snapshot directly in the normal success envelope. A missing session returns business code `40401`.
998
+
999
+ The snapshot includes `tokens`, `tokens_unknown`, `cost_usd_estimated`, `cost_unknown`, `covered_at` (epoch milliseconds), `source_revision`, `complete` and `freshness`. `complete` describes source coverage; unknown usage or prices can remain after coverage completes. `freshness` is `current` for the latest verification slice, `stale` after an observed change or ten minutes without verification, and `unverified` when no published summary exists. Older servers may omit it. Keep the known subtotal visible when stale, and do not treat freshness as completeness.
1000
+
1001
+ Each refresh advances at most ten seconds, 100,000 wire records and 128 MiB of conversation data. When `complete` is false, repeat the same GET to continue from committed progress; concurrent calls for one session share the work. A client disconnect cancels its wait, not publication of that slice. The GUI refreshes incomplete or stale accounting after 250 ms and complete accounting every 15 seconds while the detail panel is open and the page is visible. It shows "May be out of date" or "Not yet checked" when needed and hides that status for current accounting.
680
1002
 
681
1003
  ### Full usage rescan
682
1004
 
683
1005
  On the usage page's History tab, **Rescan all usage** scans every indexed session, including archived sessions. It runs only when requested and can take a while. `POST /api/usage/rescan` starts the task without a body; another POST while it is running returns the same task's current progress. Poll `GET /api/usage/rescan` about once per second. Both use the normal success envelope with `data` containing `state` (`idle`, `running`, `completed`, or `failed`), `scanned_sessions`, `total_sessions`, `scanned_records`, `started_at`, `finished_at`, and `error`. Times are epoch milliseconds or `null`; `error` is `null` unless the task failed. `scanned_records` counts newly read wire records, including non-usage records; unchanged checkpoints need no wire reads.
684
1006
 
685
- The rescan bypasses session, record, and time scan budgets and saves incremental checkpoints; regular queries keep serving committed checkpoints while it runs. A regular query has a 10-second deadline, a 500-session cold-scan limit, and a budget of 200,000 newly scanned usage facts, including unknown and invalid facts. Non-usage wire records no longer consume that cumulative record budget. Sessions it rescans successfully stop consuming the cold-session limit: their keys are saved in `cache/usage-aggregation-v1/full-scan.json`. Deleted-session and ephemeral ledgers remain subject to regular query budgets. A completed rescan does not supply missing provider usage or model prices. Task progress is process-local and resets to `idle` on restart, while checkpoints and the completed inventory survive; cancellation of the rescan is not supported.
1007
+ The rescan bypasses ordinary session, record, and time scan budgets and saves incremental source checkpoints; regular queries keep reading committed data while it runs. A regular query has a 10-second deadline, an inventory allowance of 500 sessions, a synchronization allowance of 2048 agent sources, and a budget of 200,000 facts to import or recover, including unknown and invalid facts. Sources whose checkpoint matches the current generation, size and modification time, or whose modification time predates the requested range, do not consume the synchronization allowance. Inventory enumeration and source verification continue on the next query without repeating the completed prefix; an observed session change verifies only that session, with a full inventory repair every ten minutes or when watching is unavailable. Non-usage wire records do not consume that fact budget, and querying already indexed facts does not consume it again. Deleted-session and ephemeral ledgers also resume under regular query budgets. A completed rescan does not supply missing provider usage or model prices. Task progress is process-local and resets to `idle` on restart; committed facts, source coverage and import progress survive. Cancellation of the rescan is not supported.
686
1008
 
687
- History and agent totals share lightweight usage facts saved as conversation records are committed. Valid existing usage checkpoints migrate automatically. Without a usable checkpoint, the first query recovers only the uncovered source prefix; `reliability.complete=false` means the displayed subtotal is not yet complete. A later query continues from committed progress, and cancelling a history request stops recovery when no other caller still needs it. Restarting with valid facts or rebuilding their query index does not require reading conversation bodies again.
1009
+ History and agent totals share lightweight usage facts saved as conversation records are committed. Valid existing usage checkpoints migrate automatically. History allows up to two seconds for metadata-only verification of existing checkpoints. Once import or recovery is needed, it uses the 250 ms foreground preparation allowance, then reads the committed subtotal while the bounded background slice continues. `reliability.complete=false` keeps that subtotal visible; repeat the query to continue after a slice reaches its budget. The Usage page and today's strip refresh automatically and show **Counting N/M** instead of an empty zero. Restarting with valid facts or rebuilding their query index does not require reading conversation bodies again.
1010
+
1011
+ After the source inventory is counted, partial responses include `reliability.import_progress`: `verified_sources`, `total_sources`, `read_bytes`, and `total_bytes`. A source is an agent wire or a nonempty retained ledger. `verified_sources` counts sources whose current coverage has been verified after journal import or canonical recovery and publication; `total_sources` counts sources that need inspection for the query's workspace, archive and time bounds. Record-level model, provider, profile and agent filters still require inspecting those sources. The byte pair measures canonical recovery and retained-ledger reads for this verification pass; importing an existing facts journal does not consume canonical bytes. Newly discovered uncovered tails can increase the byte total. These fields are omitted before the inventory is available and after coverage completes; `scanned_sessions` keeps its session-count meaning.
1012
+
1013
+ Agent-panel settle calls wait up to 650 ms for the shared five-second preparation slice, then return committed per-agent subtotals with `usageComplete=false` while preparation continues. Header reads consume published subtotals without importing sources. Background canonical recovery uses one parser worker, one transferred chunk at a time, and a cooperative 64 MiB/s read ceiling.
688
1014
 
689
1015
  ### Usage pricing
690
1016
 
@@ -698,16 +1024,18 @@ History and agent totals share lightweight usage facts saved as conversation rec
698
1024
 
699
1025
  These example rates are illustrative, not a published price for `proxy/model`. Rates must be finite and nonnegative, and `currency` is a three-letter uppercase code. Non-USD overrides are stored and returned without currency conversion; they do not contribute to `cost_usd_estimated`. Unknown models are never assigned an invented price. Overrides are atomically stored in `<home>/model-pricing/overrides.toml` and survive restart. Validation errors return envelope code `40001`; storage failures return `50001`. The HTTP client methods are `klient.rest.usagePricing.get(models?)` and `.set({ overrides })`.
700
1026
 
701
- Usage checkpoints are persisted per session. Unchanged agent inventories and wire size/mtime reuse their recorded usage without reading wire boundaries; appends or changed fingerprints trigger incremental reads or rebuilds. Sessions with no agents contribute complete zero usage and do not occupy a usage detail row.
1027
+ Source facts and coverage are persisted in the dedicated Usage SQLite read model. Unchanged agent inventories, generations and wire size/mtime reuse recorded usage without reading wire boundaries; appends or changed fingerprints trigger incremental recovery or a replacement generation. Sessions with no agents contribute complete zero usage and do not occupy a usage detail row. Estimated cost preserves the subtotal of fully priced records when another record lacks a required price; it does not price only the known token categories of an otherwise unpriced record.
702
1028
 
703
1029
  ### `GET /api/sessions/query`
704
1030
 
705
- A next-generation session query for list views — filtering, sorting, and field groups all travel in query parameters:
1031
+ A next-generation session query for list views — filtering, sorting, and field groups all travel in query parameters.
1032
+
1033
+ `activity.status` prioritizes pending approval or question, then `cleanup_pending`, then current execution. `running` follows `executing`, falling back to main-turn activity on older hosts; unfinished queued work alone does not make it running.
706
1034
 
707
1035
  | Parameter | Description |
708
1036
  | --- | --- |
709
1037
  | `workspace.id` | Filter by workspace; repeatable |
710
- | `activity.status` | Filter by activity status: `running` / `approval` / `question` / `failed` / `idle`; repeatable |
1038
+ | `activity.status` | Filter by activity status: `running` / `approval` / `question` / `cleanup_pending` / `failed` / `idle`; repeatable |
711
1039
  | `meta.updated_after` | Only sessions updated after this time (epoch milliseconds) |
712
1040
  | `meta.updated_before` | Only sessions updated before this time (epoch milliseconds) |
713
1041
  | `meta.archived` | `true` / `false` (default) / `all` |