@makaio/framework 1.0.0-dev-1779046984397

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 (410) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/account-identity-Ce1Bwrqi.mjs +1 -0
  4. package/dist/adapter-CbyjCE2d.mjs +1 -0
  5. package/dist/adapters/acp-client/index.d.mts +209 -0
  6. package/dist/adapters/acp-client/index.mjs +1 -0
  7. package/dist/adapters/config/index.d.mts +429 -0
  8. package/dist/adapters/config/index.mjs +1 -0
  9. package/dist/adapters/index.d.mts +4175 -0
  10. package/dist/adapters/index.mjs +11 -0
  11. package/dist/adapters/node.d.mts +263 -0
  12. package/dist/adapters/node.mjs +4 -0
  13. package/dist/adapters/stream-session/index.d.mts +1384 -0
  14. package/dist/adapters/stream-session/index.mjs +1 -0
  15. package/dist/adapters/stream-session/testing/index.d.mts +29 -0
  16. package/dist/adapters/stream-session/testing/index.mjs +1 -0
  17. package/dist/base-orchestrator-9z8TuA5a.d.mts +772 -0
  18. package/dist/bus/index.d.mts +3331 -0
  19. package/dist/bus/index.mjs +1 -0
  20. package/dist/bus-B1seC4M_.mjs +2 -0
  21. package/dist/capability-service-tnpR_TaB.mjs +1 -0
  22. package/dist/chunk-Dc06z0qk.mjs +1 -0
  23. package/dist/chunk-cpUYaJdV.mjs +1 -0
  24. package/dist/cleanEnvForAdapter-DvcIGXTG.mjs +1 -0
  25. package/dist/client-Dh4x4GQN.mjs +1 -0
  26. package/dist/clients/index.d.mts +2786 -0
  27. package/dist/clients/index.mjs +1 -0
  28. package/dist/clients-namespace-B0xAPZ6J.d.mts +332 -0
  29. package/dist/config-namespace-DLSs83zr.d.mts +638 -0
  30. package/dist/config-namespace-MJT8P0Ud.mjs +1 -0
  31. package/dist/contracts/adapter/index.d.mts +3 -0
  32. package/dist/contracts/adapter/index.mjs +1 -0
  33. package/dist/contracts/adapter/schemas/session-lineage.d.mts +2 -0
  34. package/dist/contracts/adapter/schemas/session-lineage.mjs +1 -0
  35. package/dist/contracts/client/index.d.mts +3 -0
  36. package/dist/contracts/client/index.mjs +1 -0
  37. package/dist/contracts/common/index.d.mts +2 -0
  38. package/dist/contracts/common/index.mjs +1 -0
  39. package/dist/contracts/config/index.d.mts +455 -0
  40. package/dist/contracts/config/index.mjs +1 -0
  41. package/dist/contracts/extension/index.d.mts +3 -0
  42. package/dist/contracts/extension/index.mjs +1 -0
  43. package/dist/contracts/harness/index.d.mts +2 -0
  44. package/dist/contracts/harness/index.mjs +1 -0
  45. package/dist/contracts/host/index.d.mts +2 -0
  46. package/dist/contracts/host/index.mjs +1 -0
  47. package/dist/contracts/index.d.mts +12665 -0
  48. package/dist/contracts/index.mjs +1 -0
  49. package/dist/contracts/model-registry/index.d.mts +2 -0
  50. package/dist/contracts/model-registry/index.mjs +1 -0
  51. package/dist/contracts/native-session-supervisor/index.d.mts +2 -0
  52. package/dist/contracts/native-session-supervisor/index.mjs +1 -0
  53. package/dist/contracts/platform/index.d.mts +2 -0
  54. package/dist/contracts/platform/index.mjs +1 -0
  55. package/dist/contracts/provider/index.d.mts +3 -0
  56. package/dist/contracts/provider/index.mjs +1 -0
  57. package/dist/contracts/session/index.d.mts +3 -0
  58. package/dist/contracts/session/index.mjs +1 -0
  59. package/dist/contracts/shared/index.d.mts +2 -0
  60. package/dist/contracts/shared/index.mjs +1 -0
  61. package/dist/contracts/skill/index.d.mts +2 -0
  62. package/dist/contracts/skill/index.mjs +1 -0
  63. package/dist/contracts/toast/index.d.mts +198 -0
  64. package/dist/contracts/toast/index.mjs +1 -0
  65. package/dist/contracts/variant/index.d.mts +2 -0
  66. package/dist/contracts/variant/index.mjs +1 -0
  67. package/dist/core/index.d.mts +1001 -0
  68. package/dist/core/index.mjs +1 -0
  69. package/dist/credential-ref-DLCsoKVZ.mjs +1 -0
  70. package/dist/cursor-storage-DOQdvo9j.mjs +1 -0
  71. package/dist/definition-DkYy1PZz.mjs +1 -0
  72. package/dist/definition-DtUNiGom.d.mts +158 -0
  73. package/dist/definition-DxvZ9e22.d.mts +376 -0
  74. package/dist/drizzle-CWVVw7Er.mjs +1 -0
  75. package/dist/execution-target-BW_uiBVe.mjs +1 -0
  76. package/dist/extension-COqwS-2Q.mjs +1 -0
  77. package/dist/extension-Cbrl4YGX.mjs +1 -0
  78. package/dist/extension-namespace-zaGKi6Qj.mjs +1 -0
  79. package/dist/handlers-iGKUJ380.mjs +41 -0
  80. package/dist/harness-CEq1Zkf9.mjs +1 -0
  81. package/dist/hooks/index.d.mts +423 -0
  82. package/dist/hooks/index.mjs +1 -0
  83. package/dist/host-CXAUGGN0.mjs +1 -0
  84. package/dist/identity-B_A0mE63.mjs +1 -0
  85. package/dist/index-6lyShOoU.d.mts +225 -0
  86. package/dist/index-7sXlairn2.d.mts +43 -0
  87. package/dist/index-BAKM2GMH2.d.mts +535 -0
  88. package/dist/index-BB419vv-.d.mts +3897 -0
  89. package/dist/index-BJOfdtbw.d.mts +729 -0
  90. package/dist/index-BXP9GK5q.d.mts +1075 -0
  91. package/dist/index-BdPwu6c0.d.mts +1730 -0
  92. package/dist/index-BePI0ckL.d.mts +40 -0
  93. package/dist/index-Bigx81Kr.d.mts +37 -0
  94. package/dist/index-BnNqbx2I.d.mts +134 -0
  95. package/dist/index-Bv15sNLn.d.mts +389 -0
  96. package/dist/index-C-myW_aK.d.mts +412 -0
  97. package/dist/index-C9F3Fc1A.d.mts +2938 -0
  98. package/dist/index-CNxS4Tlu.d.mts +1 -0
  99. package/dist/index-CVA0m1g9.d.mts +995 -0
  100. package/dist/index-C_kS2aqV2.d.mts +438 -0
  101. package/dist/index-Ch3ph52M2.d.mts +40 -0
  102. package/dist/index-CnZOKNjU.d.mts +89 -0
  103. package/dist/index-D1T-PPqF.d.mts +67 -0
  104. package/dist/index-D7T8XCku.d.mts +341 -0
  105. package/dist/index-DBQtpFLE.d.mts +4843 -0
  106. package/dist/index-DEw90pa2.d.mts +183 -0
  107. package/dist/index-DQRsGXb5.d.mts +109 -0
  108. package/dist/index-Dd5s4MSm.d.mts +72 -0
  109. package/dist/index-DubqLGH8.d.mts +1002 -0
  110. package/dist/index-ESSDWIB7.d.mts +11 -0
  111. package/dist/index-N5K1NOYs.d.mts +184 -0
  112. package/dist/index-PdUSmPT2.d.mts +180 -0
  113. package/dist/index-SzSiyG61.d.mts +117 -0
  114. package/dist/index-T0471kWA.d.mts +6760 -0
  115. package/dist/index-WKjrpcA_.d.mts +218 -0
  116. package/dist/index-hapw9_En.d.mts +13592 -0
  117. package/dist/index-iID2R9G1.d.mts +1490 -0
  118. package/dist/kernel/cli/index.d.mts +141 -0
  119. package/dist/kernel/cli/index.mjs +1 -0
  120. package/dist/kernel/cli/schemas.d.mts +63 -0
  121. package/dist/kernel/cli/schemas.mjs +1 -0
  122. package/dist/kernel/extension/index.d.mts +2 -0
  123. package/dist/kernel/extension/index.mjs +1 -0
  124. package/dist/kernel/index.d.mts +296 -0
  125. package/dist/kernel/index.mjs +1 -0
  126. package/dist/kernel/namespace/index.d.mts +2 -0
  127. package/dist/kernel/namespace/index.mjs +1 -0
  128. package/dist/kernel/observability/index.d.mts +2 -0
  129. package/dist/kernel/observability/index.mjs +1 -0
  130. package/dist/kernel/providers/index.d.mts +2 -0
  131. package/dist/kernel/providers/index.mjs +1 -0
  132. package/dist/kernel/window/index.d.mts +2 -0
  133. package/dist/kernel/window/index.mjs +1 -0
  134. package/dist/model-registry-BNzpR6TU.mjs +1 -0
  135. package/dist/model-registry-CIscwC52.mjs +1 -0
  136. package/dist/namespace-0yuzAKlr.mjs +1 -0
  137. package/dist/namespace-8cNguvIp.mjs +1 -0
  138. package/dist/namespace-BK2erxpV.d.mts +921 -0
  139. package/dist/namespace-Bmc7AW4J2.mjs +1 -0
  140. package/dist/namespace-C2ufjgaQ.d.mts +767 -0
  141. package/dist/namespace-C54Oj025.d.mts +159 -0
  142. package/dist/namespace-CCDEOwmW.d.mts +1313 -0
  143. package/dist/namespace-CfEWMXBx.mjs +1 -0
  144. package/dist/namespace-CkLUtc0g.d.mts +580 -0
  145. package/dist/namespace-D5Wrt7YU.mjs +1 -0
  146. package/dist/namespace-DZcuLwEA.d.mts +51 -0
  147. package/dist/namespace-Db-p67Rg.mjs +1 -0
  148. package/dist/namespace-FWx6HxaW.d.mts +611 -0
  149. package/dist/namespace-GLGGcWPH.d.mts +43 -0
  150. package/dist/namespace-N0dfwSg6.mjs +1 -0
  151. package/dist/namespace-O5SNY-LV.d.mts +2226 -0
  152. package/dist/namespace-ZbthBQVt.d.mts +142 -0
  153. package/dist/namespace-bq4Prtzn.d.mts +2046 -0
  154. package/dist/namespace-pNcSglBS.mjs +1 -0
  155. package/dist/namespace-ptv-pw_g.d.mts +3019 -0
  156. package/dist/namespace-xkvVw3hf2.d.mts +189 -0
  157. package/dist/native-session-supervisor-L-UIaEfd.mjs +1 -0
  158. package/dist/node/bus-server/index.d.mts +178 -0
  159. package/dist/node/bus-server/index.mjs +1 -0
  160. package/dist/node/bus-server/server-lifecycle.d.mts +2 -0
  161. package/dist/node/bus-server/server-lifecycle.mjs +1 -0
  162. package/dist/node/machine-identity/index.d.mts +85 -0
  163. package/dist/node/machine-identity/index.mjs +3 -0
  164. package/dist/node/transports/index.d.mts +1752 -0
  165. package/dist/node/transports/index.mjs +2 -0
  166. package/dist/orchestrator-shared-DrjtTXYh.d.mts +249 -0
  167. package/dist/orchestrator-shared-Wv1GI2mW.mjs +1 -0
  168. package/dist/platform-BbSLVg5b.mjs +1 -0
  169. package/dist/profile-4StaDQW0.mjs +1 -0
  170. package/dist/provider-context-CNRQ4d5m.mjs +1 -0
  171. package/dist/providers/index.d.mts +135 -0
  172. package/dist/providers/index.mjs +1 -0
  173. package/dist/providers-Cr4Za8a1.mjs +1 -0
  174. package/dist/providers-namespace-CDwxY_DV.d.mts +583 -0
  175. package/dist/schema-BwzXEtT2.d.mts +837 -0
  176. package/dist/schema-CAw_BqaG.mjs +1 -0
  177. package/dist/schema-introspection-D61TT_7b.mjs +1 -0
  178. package/dist/schema-uSGW-6oM.mjs +1 -0
  179. package/dist/schemas-BXstpWVp.mjs +1 -0
  180. package/dist/schemas-BdMU-gew.d.mts +160 -0
  181. package/dist/schemas-C40ZAJ33.mjs +1 -0
  182. package/dist/schemas-C5xtVqdb.d.mts +46 -0
  183. package/dist/schemas-CGZy_rU6.d.mts +13 -0
  184. package/dist/schemas-CLxtoKFy.mjs +1 -0
  185. package/dist/schemas-Co_sVhzz.mjs +1 -0
  186. package/dist/schemas-D9108Iv1.d.mts +182 -0
  187. package/dist/schemas-DENVYyds.d.mts +463 -0
  188. package/dist/schemas-DbWs_hj8.d.mts +174 -0
  189. package/dist/schemas-Di0XnnMX.d.mts +73 -0
  190. package/dist/schemas-KMA1efQg.d.mts +944 -0
  191. package/dist/schemas-qmn5SWPU.d.mts +312 -0
  192. package/dist/schemas-sshQEF3l.d.mts +237 -0
  193. package/dist/server-lifecycle-Cf_SZ27k.d.mts +160 -0
  194. package/dist/server-lifecycle-DbFwlrTW.mjs +1 -0
  195. package/dist/service-base/index.d.mts +98 -0
  196. package/dist/service-base/index.mjs +1 -0
  197. package/dist/services/adapter-runtime/index.d.mts +4 -0
  198. package/dist/services/adapter-runtime/index.mjs +1 -0
  199. package/dist/services/adapter-runtime/namespace.d.mts +2 -0
  200. package/dist/services/adapter-runtime/namespace.mjs +1 -0
  201. package/dist/services/adapter-runtime/schemas.d.mts +2 -0
  202. package/dist/services/adapter-runtime/schemas.mjs +1 -0
  203. package/dist/services/adapter-subsystem/index.d.mts +3 -0
  204. package/dist/services/adapter-subsystem/index.mjs +1 -0
  205. package/dist/services/adapter-subsystem/namespace.d.mts +2 -0
  206. package/dist/services/adapter-subsystem/namespace.mjs +1 -0
  207. package/dist/services/agent-runtime/index.d.mts +3 -0
  208. package/dist/services/agent-runtime/index.mjs +1 -0
  209. package/dist/services/agent-runtime/namespace.d.mts +2 -0
  210. package/dist/services/agent-runtime/namespace.mjs +1 -0
  211. package/dist/services/agent-runtime/schemas.d.mts +2 -0
  212. package/dist/services/agent-runtime/schemas.mjs +1 -0
  213. package/dist/services/capability/index.d.mts +2 -0
  214. package/dist/services/capability/index.mjs +1 -0
  215. package/dist/services/cli-detection/namespace.d.mts +56 -0
  216. package/dist/services/cli-detection/namespace.mjs +1 -0
  217. package/dist/services/codebase/index.d.mts +3 -0
  218. package/dist/services/codebase/index.mjs +1 -0
  219. package/dist/services/codebase/namespace.d.mts +2 -0
  220. package/dist/services/codebase/namespace.mjs +1 -0
  221. package/dist/services/codebase/schemas.d.mts +2 -0
  222. package/dist/services/codebase/schemas.mjs +1 -0
  223. package/dist/services/compression/index.d.mts +3 -0
  224. package/dist/services/compression/index.mjs +1 -0
  225. package/dist/services/compression/namespace.d.mts +2 -0
  226. package/dist/services/compression/namespace.mjs +1 -0
  227. package/dist/services/compression/schemas.d.mts +2 -0
  228. package/dist/services/compression/schemas.mjs +1 -0
  229. package/dist/services/context-rules/index.d.mts +412 -0
  230. package/dist/services/context-rules/index.mjs +1 -0
  231. package/dist/services/credential-change/index.d.mts +17 -0
  232. package/dist/services/credential-change/index.mjs +1 -0
  233. package/dist/services/definition/index.d.mts +2 -0
  234. package/dist/services/definition/index.mjs +1 -0
  235. package/dist/services/definition/namespace.d.mts +71 -0
  236. package/dist/services/definition/namespace.mjs +1 -0
  237. package/dist/services/definition/schemas.d.mts +38 -0
  238. package/dist/services/definition/schemas.mjs +1 -0
  239. package/dist/services/dialog/namespace.d.mts +105 -0
  240. package/dist/services/dialog/namespace.mjs +1 -0
  241. package/dist/services/dialog/schemas.d.mts +109 -0
  242. package/dist/services/dialog/schemas.mjs +1 -0
  243. package/dist/services/execution-target/index.d.mts +4 -0
  244. package/dist/services/execution-target/index.mjs +1 -0
  245. package/dist/services/execution-target/namespace.d.mts +2 -0
  246. package/dist/services/execution-target/namespace.mjs +1 -0
  247. package/dist/services/execution-target/schemas.d.mts +2 -0
  248. package/dist/services/execution-target/schemas.mjs +1 -0
  249. package/dist/services/filesystem/namespace.d.mts +432 -0
  250. package/dist/services/filesystem/namespace.mjs +1 -0
  251. package/dist/services/filesystem/schemas.d.mts +240 -0
  252. package/dist/services/filesystem/schemas.mjs +1 -0
  253. package/dist/services/harness/index.d.mts +861 -0
  254. package/dist/services/harness/index.mjs +1 -0
  255. package/dist/services/harness/storage/schema.d.mts +424 -0
  256. package/dist/services/harness/storage/schema.mjs +1 -0
  257. package/dist/services/index.d.mts +5703 -0
  258. package/dist/services/index.mjs +1 -0
  259. package/dist/services/local-notification/index.d.mts +25 -0
  260. package/dist/services/local-notification/index.mjs +1 -0
  261. package/dist/services/local-notification/namespace.d.mts +73 -0
  262. package/dist/services/local-notification/namespace.mjs +1 -0
  263. package/dist/services/local-notification/schemas.d.mts +88 -0
  264. package/dist/services/local-notification/schemas.mjs +1 -0
  265. package/dist/services/log-import/browser.d.mts +3 -0
  266. package/dist/services/log-import/browser.mjs +1 -0
  267. package/dist/services/log-import/index.d.mts +275 -0
  268. package/dist/services/log-import/index.mjs +2 -0
  269. package/dist/services/log-import/log-import.d.mts +3 -0
  270. package/dist/services/log-import/log-import.mjs +1 -0
  271. package/dist/services/log-import/namespace.d.mts +327 -0
  272. package/dist/services/log-import/namespace.mjs +1 -0
  273. package/dist/services/log-import/schemas.d.mts +217 -0
  274. package/dist/services/log-import/schemas.mjs +1 -0
  275. package/dist/services/model-registry/index.d.mts +2 -0
  276. package/dist/services/model-registry/index.mjs +1 -0
  277. package/dist/services/preferences/index.d.mts +3 -0
  278. package/dist/services/preferences/index.mjs +1 -0
  279. package/dist/services/preferences/schemas.d.mts +2 -0
  280. package/dist/services/preferences/schemas.mjs +1 -0
  281. package/dist/services/preferences/storage-namespace.d.mts +3 -0
  282. package/dist/services/preferences/storage-namespace.mjs +1 -0
  283. package/dist/services/provider-context/index.d.mts +2 -0
  284. package/dist/services/provider-context/index.mjs +1 -0
  285. package/dist/services/provider-runtime/index.d.mts +136 -0
  286. package/dist/services/provider-runtime/index.mjs +1 -0
  287. package/dist/services/session/handlers/index.d.mts +2 -0
  288. package/dist/services/session/handlers/index.mjs +1 -0
  289. package/dist/services/session/index.d.mts +10 -0
  290. package/dist/services/session/index.mjs +1 -0
  291. package/dist/services/session/messages/namespace.d.mts +2 -0
  292. package/dist/services/session/messages/namespace.mjs +1 -0
  293. package/dist/services/session/orchestrator-testing/index.d.mts +2 -0
  294. package/dist/services/session/orchestrator-testing/index.mjs +1 -0
  295. package/dist/services/session/session-events/namespace.d.mts +2 -0
  296. package/dist/services/session/session-events/namespace.mjs +1 -0
  297. package/dist/services/session/storage/namespace.d.mts +2 -0
  298. package/dist/services/session/storage/namespace.mjs +1 -0
  299. package/dist/services/session/storage/schema.d.mts +2 -0
  300. package/dist/services/session/storage/schema.mjs +1 -0
  301. package/dist/services/session/testing/index.d.mts +35 -0
  302. package/dist/services/session/testing/index.mjs +52 -0
  303. package/dist/services/session/testing/orchestrator-shared.d.mts +2 -0
  304. package/dist/services/session/testing/orchestrator-shared.mjs +1 -0
  305. package/dist/services/session/turns/namespace.d.mts +2 -0
  306. package/dist/services/session/turns/namespace.mjs +1 -0
  307. package/dist/services/session-editor/index.d.mts +119 -0
  308. package/dist/services/session-editor/index.mjs +1 -0
  309. package/dist/services/settings/index.d.mts +47 -0
  310. package/dist/services/settings/index.mjs +1 -0
  311. package/dist/services/settings/namespace.d.mts +662 -0
  312. package/dist/services/settings/namespace.mjs +1 -0
  313. package/dist/services/settings/storage/clients-namespace.d.mts +2 -0
  314. package/dist/services/settings/storage/clients-namespace.mjs +1 -0
  315. package/dist/services/settings/storage/extension-configs/namespace.d.mts +184 -0
  316. package/dist/services/settings/storage/extension-configs/namespace.mjs +1 -0
  317. package/dist/services/settings/storage/index.d.mts +4 -0
  318. package/dist/services/settings/storage/index.mjs +1 -0
  319. package/dist/services/settings/storage/providers-namespace.d.mts +2 -0
  320. package/dist/services/settings/storage/providers-namespace.mjs +1 -0
  321. package/dist/services/tool-approval/index.d.mts +2 -0
  322. package/dist/services/tool-approval/index.mjs +1 -0
  323. package/dist/services/tools/index.d.mts +2 -0
  324. package/dist/services/tools/index.mjs +1 -0
  325. package/dist/services/tray-menu/index.d.mts +4 -0
  326. package/dist/services/tray-menu/index.mjs +1 -0
  327. package/dist/services/tray-menu/namespace.d.mts +2 -0
  328. package/dist/services/tray-menu/namespace.mjs +1 -0
  329. package/dist/services/tray-menu/schemas.d.mts +2 -0
  330. package/dist/services/tray-menu/schemas.mjs +1 -0
  331. package/dist/services/turn/index.d.mts +2 -0
  332. package/dist/services/turn/index.mjs +1 -0
  333. package/dist/services/turn/namespace.d.mts +2 -0
  334. package/dist/services/turn/namespace.mjs +1 -0
  335. package/dist/services/turn/schemas.d.mts +335 -0
  336. package/dist/services/turn/schemas.mjs +1 -0
  337. package/dist/services/worker/index.d.mts +3 -0
  338. package/dist/services/worker/index.mjs +1 -0
  339. package/dist/services/worker/namespace.d.mts +2 -0
  340. package/dist/services/worker/namespace.mjs +1 -0
  341. package/dist/services/worker/schemas.d.mts +2 -0
  342. package/dist/services/worker/schemas.mjs +1 -0
  343. package/dist/session-Do6lDZM4.mjs +123 -0
  344. package/dist/session-lineage-Eev4uo4I.d.mts +65 -0
  345. package/dist/session-piI1R5rP.mjs +1 -0
  346. package/dist/shared-DxHLl9UP.mjs +1 -0
  347. package/dist/shared-schemas-BgQv_tnu.mjs +1 -0
  348. package/dist/skill-CB5h-ZFQ.mjs +1 -0
  349. package/dist/storage/drizzle/client.d.mts +78 -0
  350. package/dist/storage/drizzle/client.mjs +1 -0
  351. package/dist/storage/drizzle/index.d.mts +98 -0
  352. package/dist/storage/drizzle/index.mjs +1 -0
  353. package/dist/storage/handlers/drizzle/index.d.mts +2 -0
  354. package/dist/storage/handlers/drizzle/index.mjs +1 -0
  355. package/dist/storage/handlers/index.d.mts +33 -0
  356. package/dist/storage/handlers/index.mjs +1 -0
  357. package/dist/storage/index.d.mts +192 -0
  358. package/dist/storage/index.mjs +1 -0
  359. package/dist/storage-namespace-ADwyijoe.mjs +1 -0
  360. package/dist/storage-namespace-DAm8iWEj.d.mts +221 -0
  361. package/dist/storage-namespace-definition-CHu2k14q.mjs +1 -0
  362. package/dist/storage-namespace-definition-CJgqyXH1.d.mts +17 -0
  363. package/dist/style.css +3782 -0
  364. package/dist/testing/drizzle-harness.d.mts +130 -0
  365. package/dist/testing/drizzle-harness.mjs +1 -0
  366. package/dist/testing/index.d.mts +106 -0
  367. package/dist/testing/index.mjs +1 -0
  368. package/dist/tool-approval-service-BcBSUZCO.mjs +1 -0
  369. package/dist/tools/index.d.mts +825 -0
  370. package/dist/tools/index.mjs +1 -0
  371. package/dist/tools/testing/index.d.mts +53 -0
  372. package/dist/tools/testing/index.mjs +1 -0
  373. package/dist/tools-CDSgj0ee.mjs +1 -0
  374. package/dist/tray-menu-service-CTXC1Elg.mjs +1 -0
  375. package/dist/types-6WxLfoM3.d.mts +31 -0
  376. package/dist/types-BjToUrHp.d.mts +6619 -0
  377. package/dist/types-CD1LJwPc.d.mts +1009 -0
  378. package/dist/types-Cvrj2ogm.d.mts +305 -0
  379. package/dist/types-DYF5LxZY.d.mts +233 -0
  380. package/dist/types-t295YC6T.d.mts +262 -0
  381. package/dist/types-vNpkAe4Y.d.mts +128 -0
  382. package/dist/ui-components/index.d.mts +2342 -0
  383. package/dist/ui-components/index.mjs +8 -0
  384. package/dist/ui-config-CXmbsqZV.mjs +1 -0
  385. package/dist/ui-hooks/index.d.mts +1805 -0
  386. package/dist/ui-hooks/index.mjs +1 -0
  387. package/dist/ui-kernel/index.d.mts +2793 -0
  388. package/dist/ui-kernel/index.mjs +1 -0
  389. package/dist/ui-kernel/pages/namespace.d.mts +88 -0
  390. package/dist/ui-kernel/pages/namespace.mjs +1 -0
  391. package/dist/ui-kernel/pages/schemas.d.mts +2 -0
  392. package/dist/ui-kernel/pages/schemas.mjs +1 -0
  393. package/dist/ui-views/index.d.mts +487 -0
  394. package/dist/ui-views/index.mjs +30 -0
  395. package/dist/utils/health-probe.d.mts +26 -0
  396. package/dist/utils/health-probe.mjs +1 -0
  397. package/dist/utils/index.d.mts +227 -0
  398. package/dist/utils/index.mjs +2 -0
  399. package/dist/utils/keychain.d.mts +31 -0
  400. package/dist/utils/keychain.mjs +1 -0
  401. package/dist/utils/resolve-package-root.d.mts +12 -0
  402. package/dist/utils/resolve-package-root.mjs +1 -0
  403. package/dist/utils/workspace-root.d.mts +27 -0
  404. package/dist/utils/workspace-root.mjs +2 -0
  405. package/dist/variant-D5kSrL3m.mjs +1 -0
  406. package/dist/version-CjS20oXi.mjs +1 -0
  407. package/dist/visibility-CZu8ooOA.mjs +1 -0
  408. package/dist/window-registry-CUftmDr3.mjs +1 -0
  409. package/dist/window-registry-C_IJmY8_.d.mts +130 -0
  410. package/package.json +346 -0
@@ -0,0 +1,4175 @@
1
+ import { A as MessageHandle, B as ISessionToolLedger, C as SendMessageRequestPayload, D as IAdapterConfigFactory, E as ConfigFactoryInput, F as ProcessingState, H as SessionToolLedger, I as SendMessageOptions, L as AIModel, M as normalizeMessageInput, N as MessageResult, O as AIAgentConnector, P as MessageState, R as AIReasoningLevel, S as NormalizedCallUsage, T as StartAgentOptions, U as ToolLedgerEntry, V as LedgerSessionContext, _ as ConnectorSendMessageOptions, a as AgentCwdChangeRequestPayload, b as ExecutionContext, c as AgentInterruptRequestPayload, d as AgentMcpServersSetResponsePayload, f as AgentModelChangeRequestPayload, g as BaseAgentConnectorConfig, h as AgentStartResult, i as AgentCredentialChangeResponsePayload, j as NormalizedMessageInput, k as MessageDeliveryMode, l as AgentInterruptResponsePayload, m as AgentSendMessageOptions, n as AgentContext, o as AgentCwdChangeResponsePayload, p as AgentModelChangeResponsePayload, r as AgentCredentialChangeRequestPayload, s as AgentIdentity, t as AIAgentConfig, u as AgentMcpServersSetRequestPayload, v as ConnectorStartOptions, w as SendMessageResponsePayload, x as GetCapabilitiesResponsePayload, y as ContextWindowInput, z as ReasoningLevelMap } from "../types-CD1LJwPc.mjs";
2
+ import { _ as LogImporterConfig, a as CompactionMetadata, b as StorageMessagePayload, c as ExternalToolIdentifiers, d as ImportMetadata, f as ImportSegment, g as LogImporter, h as LogImportTestConfig, l as ExternalToolMeta, m as LogImportSessionContext, n as LogOrchestratorConfig, o as DiscoveryMetadata, p as ImportSegmentLineage, r as ParseFileResult, s as ExternalToolIdentifier, u as ImportCursorPosition, v as NormalizedEvent, x as toImportSegment, y as ProcessLogFileResult } from "../base-orchestrator-9z8TuA5a.mjs";
3
+ import { z } from "zod";
4
+ import * as _$_makaio_core0 from "@makaio/framework/core";
5
+ import { ExtractSubjectPayload, FilterablePayloadIntersection, HandlerForSubjectDefinition, RequestContext, SchemaRecord, ScopedSubjectDefinition, SubjectDefinition, SubjectRecordFromSchemaRecord } from "@makaio/framework/core";
6
+ import { BusNamespace, IMakaioBus, NamespaceRegistrationOptions, OnOptions, ScopedBus, ScopedBusFor } from "@makaio/framework/bus";
7
+ import { AIReasoningLevel as AIReasoningLevel$1, AdapterClientRef, AdapterDefinitionContract, AdapterProviderDefinitionContract, AdapterSubjects, AgentSchemas, AgentStarted, AgentSubjects, AgentToolApproveRequest, AgentToolApproveResponse, BlockData, HarnessDefinition, HarnessSubjects, JsonValue, McpResolvedServer, McpRuntimeSessionContext, McpSessionContext, McpToolState, Message, MessageInput, ProviderContext, ProviderDefinitionInput, ReasoningLevelMap as ReasoningLevelMap$1, SendMessageRequest, SendMessageResponse, SessionContext, SessionMessageBlock, StartAgentRequest, StartAgentResponse, StepType, SystemPrompt, ToolListItem } from "@makaio/framework/contracts";
8
+ import * as _$_makaio_storage_core0 from "@makaio/framework/storage";
9
+ import * as _$type_fest0 from "type-fest";
10
+ import { JsonObject, SetRequired } from "type-fest";
11
+ import { MessageBlock as MessageBlock$1 } from "@makaio/framework/contracts/shared";
12
+
13
+ //#region adapters/core/src/log-importer/registry-types.d.ts
14
+ /**
15
+ * Configuration for log import behavior.
16
+ *
17
+ * Shared between runtime config and orchestrator setup.
18
+ */
19
+ interface LogImportConfig {
20
+ /** Whether log import is enabled. */
21
+ enabled: boolean;
22
+ /** Polling interval for the file watcher in milliseconds. */
23
+ pollIntervalMs?: number;
24
+ /** Maximum events to emit per second (rate limiting). */
25
+ eventsPerSecond?: number;
26
+ /** Function to check if a session is managed by Makaio (to skip already tracked sessions). */
27
+ checkMakaioManaged?: (sessionId: string) => Promise<boolean>;
28
+ }
29
+ /**
30
+ * Minimal interface for log import orchestrators.
31
+ *
32
+ * Allows LogImportRegistry to manage lifecycle without coupling
33
+ * to a specific orchestrator implementation.
34
+ */
35
+ interface LogImportOrchestrator {
36
+ /** Whether the orchestrator is running. */
37
+ isRunning(): boolean;
38
+ /** Start the orchestrator. */
39
+ start(): Promise<void>;
40
+ /** Stop the orchestrator. */
41
+ stop(): void | Promise<void>;
42
+ /** Dispose of any resources. */
43
+ dispose(): void | Promise<void>;
44
+ }
45
+ /** Shared constructor signature for log import orchestrator classes. */
46
+ type LogOrchestratorConstructor = new (config: LogOrchestratorConfig) => LogImportOrchestrator;
47
+ /** Shared constructor signature for log importer classes. */
48
+ type LogImporterConstructor = new (config: LogImporterConfig) => LogImporter<unknown, unknown>;
49
+ /**
50
+ * Registration metadata for log importers.
51
+ *
52
+ * Used by runtimes to wire importers into the LogImportRegistry.
53
+ * The adapter name is provided by the runtime at registration time via `adapter.name`.
54
+ */
55
+ interface LogImportRegistration {
56
+ /** Human-readable name. */
57
+ displayName: string;
58
+ /** Log importer class constructor. */
59
+ LogImporterClass: LogImporterConstructor;
60
+ /** Optional orchestrator class for full session import mode. */
61
+ LogOrchestratorClass?: LogOrchestratorConstructor;
62
+ /**
63
+ * Optional orchestrator class for shallow discovery mode.
64
+ *
65
+ * When present, the runtime uses this class instead of {@link LogOrchestratorClass}
66
+ * when the adapter's import mode is set to `'discover'`.
67
+ */
68
+ LogDiscoveryOrchestratorClass?: LogOrchestratorConstructor;
69
+ /** Glob pattern for log files. */
70
+ logFilePattern: string;
71
+ }
72
+ //#endregion
73
+ //#region adapters/core/src/types/provider-definition.d.ts
74
+ /**
75
+ * Runtime adapter provider definition pairing a serializable provider definition
76
+ * with optional runtime-only schemas.
77
+ *
78
+ * Extends {@link AdapterProviderDefinitionContract} from `@makaio/contracts` which
79
+ * is the single source of truth for the `definition`, `configSchema`, and
80
+ * `credentialSchema` fields. All fields are inherited from the contract — this
81
+ * type exists to give the shape a domain-specific name used throughout
82
+ * adapter implementation packages and to allow future additions specific to
83
+ * `ai-adapters-core`.
84
+ *
85
+ * Each adapter exports an array of these from its `definition.ts` (via `providers`).
86
+ * The `definition` field contains serializable data (models, endpoints, etc.).
87
+ * The schema fields are runtime-only — used for UI form generation, never serialized.
88
+ * @example
89
+ * ```typescript
90
+ * const anthropicProvider: AdapterProviderDefinition = {
91
+ * definition: {
92
+ * id: 'anthropic',
93
+ * name: 'Anthropic',
94
+ * endpoints: { anthropic: 'https://api.anthropic.com' },
95
+ * defaultModel: 'sonnet',
96
+ * availableModels: [...]
97
+ * },
98
+ * credentialSchema: z.object({
99
+ * apiKey: z.string().describe('Anthropic API Key')
100
+ * })
101
+ * };
102
+ * ```
103
+ */
104
+ interface AdapterProviderDefinition extends AdapterProviderDefinitionContract {
105
+ /**
106
+ * Provider-specific config schema for UI form generation (runtime-only).
107
+ *
108
+ * Defines provider-specific configuration fields like debugging flags,
109
+ * rate limiting options, or provider-specific features.
110
+ * Not serialized — used for dynamic form generation in the settings UI.
111
+ */
112
+ readonly configSchema?: z.ZodObject<z.ZodRawShape>;
113
+ /**
114
+ * Provider-specific credential schema for secure credential capture (runtime-only).
115
+ *
116
+ * Defines credential fields (apiKey, apiSecret, etc.) for secure input.
117
+ * Credentials are stored separately via the credential service, never in plain config.
118
+ * Not serialized — used for dynamic form generation in the settings UI.
119
+ */
120
+ readonly credentialSchema?: z.ZodObject<z.ZodRawShape>;
121
+ }
122
+ //#endregion
123
+ //#region adapters/core/src/types/ai-adapter-init-options.d.ts
124
+ /**
125
+ * Platform-provided defaults injected by the runtime.
126
+ * These are the lowest priority and will be overridden by request-level values.
127
+ */
128
+ interface PlatformDefaults {
129
+ /** Default working directory for agent execution (e.g., os.tmpdir() on Node.js) */
130
+ cwd?: string;
131
+ /** Default environment variables */
132
+ env?: Record<string, string>;
133
+ }
134
+ /**
135
+ * Initialization options for `AIAdapter.init()`.
136
+ * @example
137
+ * ```typescript
138
+ * await adapter.init({
139
+ * defaultModel: "claude-3.5-sonnet",
140
+ * providerOptions: { apiKey: process.env.API_KEY }
141
+ * });
142
+ * ```
143
+ * @see {@link AIAdapterPromptOptions} for per-message config
144
+ * @see [Creating Adapters Guide](../../docs/creating-adapters.md)
145
+ */
146
+ interface AIAdapterInitOptions {
147
+ /** Default model when not specified per-message. Provider-specific identifier. */
148
+ defaultModel?: string;
149
+ /** Provider-specific config (API keys, base URLs, defaults, etc.). Type explicitly in adapter implementations. */
150
+ providerOptions?: unknown;
151
+ adapterId?: string;
152
+ /**
153
+ * Platform-provided defaults (cwd, env, etc.).
154
+ * Lowest priority - overridden by request values.
155
+ * Injected by runtime during adapter initialization.
156
+ */
157
+ platformDefaults?: PlatformDefaults;
158
+ /**
159
+ * Log import configuration for external session imports.
160
+ */
161
+ logImport?: LogImportConfig;
162
+ /**
163
+ * Provider definitions from the adapter definition.
164
+ * Contains provider definitions with available models for context window lookup.
165
+ * Injected by runtime during adapter initialization.
166
+ */
167
+ definitionProviders?: AdapterProviderDefinition[];
168
+ /** Client identifier for the application this adapter belongs to (e.g., 'claude-code', 'codex'). Omit for API-only adapters. */
169
+ clientId?: string;
170
+ }
171
+ //#endregion
172
+ //#region adapters/core/src/utils/safeJsonStringify.d.ts
173
+ /**
174
+ * Safely serialize a value to JSON string.
175
+ *
176
+ * Handles BigInt values, circular references, and non-serializable types
177
+ * without throwing. Circular nodes are replaced with `'[Circular]'` rather
178
+ * than aborting the entire serialization. Falls back to `String(value)` when
179
+ * JSON serialization is not possible at all.
180
+ * @param value - The value to serialize
181
+ * @returns JSON string representation or a fallback string on failure
182
+ */
183
+ declare function safeJsonStringify(value: unknown): string;
184
+ //#endregion
185
+ //#region adapters/core/src/utils/serializeTurnContext.d.ts
186
+ /**
187
+ * A single serialized context entry ready for adapter-specific formatting.
188
+ */
189
+ interface SerializedContextBlock {
190
+ /** XML tag name, e.g. 'skills', 'cwdChange' */
191
+ readonly tag: string;
192
+ /** Pre-formatted content (Markdown for skills/catalog, JSON for others) */
193
+ readonly content: string;
194
+ }
195
+ /**
196
+ * Format one context block as an XML-tagged text block.
197
+ * @param tag - Block tag name (sanitized before rendering)
198
+ * @param content - Block content (XML-escaped before rendering)
199
+ * @returns XML-tagged text block safe for prompt injection
200
+ */
201
+ declare function formatContextBlockAsText(tag: string, content: string): string;
202
+ /**
203
+ * Serialize a MessageHandle's turnContext into ordered text blocks.
204
+ *
205
+ * All non-null, non-undefined keys are serialized. The `skillCatalog`,
206
+ * `skills`, and `contextRules` keys get dedicated markdown formatting;
207
+ * all other keys are JSON-serialized.
208
+ *
209
+ * Each adapter converts these blocks to its wire format:
210
+ * - Claude SDK: each block → prependContextBlock(msg, tag, content)
211
+ * - Anthropic/OpenAI: join and prepend to user message
212
+ * - Gemini: push as requestPart
213
+ * - CLI/Copilot: prepend to prompt string
214
+ * - Codex: push as userInput
215
+ * @param turnContext - The context record from MessageHandle.turnContext
216
+ * @returns Ordered blocks: skillCatalog, skills, contextRules, then remaining keys alphabetical.
217
+ * Empty when turnContext is nullish or empty.
218
+ */
219
+ declare function serializeTurnContext(turnContext: Record<string, JsonValue | undefined> | undefined): SerializedContextBlock[];
220
+ /**
221
+ * Format serialized context blocks as XML-tagged text.
222
+ * Convenience for adapters that prepend context as plain text to the user message.
223
+ * @param blocks - Blocks from serializeTurnContext()
224
+ * @returns Single string with each block wrapped in XML tags, separated by newlines.
225
+ * Empty string when no blocks.
226
+ */
227
+ declare function formatContextBlocksAsText(blocks: SerializedContextBlock[]): string;
228
+ //#endregion
229
+ //#region adapters/core/src/types/capabilities.d.ts
230
+ /**
231
+ * Extensible registry of all known AI adapter capabilities.
232
+ *
233
+ * This interface can be extended by external packages (extensions) via declaration merging:
234
+ * @example
235
+ * ```typescript
236
+ * // In a plugin package
237
+ * declare module '@makaio/framework/adapters' {
238
+ * interface AIAdapterCapabilityRegistry {
239
+ * customAuth: {
240
+ * oauth: boolean;
241
+ * saml: boolean;
242
+ * };
243
+ * }
244
+ * }
245
+ *
246
+ * // Now these work automatically:
247
+ * caps.hasAll(['customAuth:oauth']) // ✅ Type-safe
248
+ * caps.customAuthOauth // ✅ Auto-generated property
249
+ * ```
250
+ */
251
+ interface AIAdapterCapabilityRegistry {
252
+ systemPrompt: {
253
+ override: boolean;
254
+ append: boolean;
255
+ };
256
+ session: {
257
+ resume: boolean;
258
+ fork: boolean;
259
+ };
260
+ chat: {
261
+ inTurnMessages: boolean;
262
+ };
263
+ modelSwitchInSession: boolean;
264
+ streaming: boolean;
265
+ tools: boolean;
266
+ vision: boolean;
267
+ /**
268
+ * Adapter supports native structured output (JSON schema enforcement
269
+ * at the model level via response_format or equivalent).
270
+ */
271
+ structuredOutput: boolean;
272
+ }
273
+ /**
274
+ * Recursively builds capability path strings from registry.
275
+ * Example: `'systemPrompt'` | `'systemPrompt:override'` | `'systemPrompt:append'`
276
+ * @internal
277
+ */
278
+ type CapabilityPath<T> = T extends object ? { [K in keyof T]: K extends string ? T[K] extends boolean ? K : T[K] extends object ? `${K}:${CapabilityPath<T[K]>}` | K : K : never }[keyof T] : never;
279
+ /** Union of all valid capability strings from the registry. */
280
+ type ValidCapability = CapabilityPath<AIAdapterCapabilityRegistry>;
281
+ /**
282
+ * Converts capability path to camelCase property name.
283
+ * Example: `'session:fork'` → `'sessionFork'`
284
+ * @internal
285
+ */
286
+ type PathToPropertyName<S extends string> = S extends `${infer First}:${infer Rest}` ? `${First}${PathToPropertyName<Capitalize<Rest>>}` : S;
287
+ /** Flattens registry into camelCase boolean properties. @internal */
288
+ type GeneratedCapabilityProperties = { [P in ValidCapability as PathToPropertyName<P>]?: boolean };
289
+ /**
290
+ * Runtime-queryable capabilities object returned by AI adapters.
291
+ *
292
+ * Auto-generates boolean properties from {@link AIAdapterCapabilityRegistry}:
293
+ * - `'systemPrompt'` → `caps.systemPrompt`
294
+ * - `'systemPrompt:override'` → `caps.systemPromptOverride`
295
+ * - `'session:fork'` → `caps.sessionFork`
296
+ * @remarks
297
+ * Capabilities are **optional and declarative**:
298
+ * - Adapters declare only what their underlying service supports
299
+ * - Platform checks capabilities before using optional features
300
+ * - No "not implemented" exceptions
301
+ * - Plugin-extendable via declaration merging
302
+ * @example
303
+ * ```typescript
304
+ * const caps = adapter.getCapabilities();
305
+ *
306
+ * // Single checks (most common)
307
+ * if (caps.vision) { ... }
308
+ * if (caps.tools && caps.vision) { ... }
309
+ *
310
+ * // Batch checks (explicit AND/OR)
311
+ * if (caps.hasAll(['vision', 'tools'])) { ... }
312
+ * if (caps.hasAny(['session:resume', 'session:fork'])) { ... }
313
+ * ```
314
+ * @see {@link AIAdapterCapabilityRegistry} - Schema and plugin extensibility
315
+ * @see {@link parseAIAdapterCapabilities} - Create instances from strings
316
+ */
317
+ type AIAdapterCapabilities = GeneratedCapabilityProperties & {
318
+ /** Check if ALL specified capabilities are present (AND logic) */hasAll(capabilities: ValidCapability[]): boolean; /** Check if ANY of the specified capabilities are present (OR logic) */
319
+ hasAny(capabilities: ValidCapability[]): boolean;
320
+ };
321
+ type AIAdapterCapability = keyof GeneratedCapabilityProperties;
322
+ //#endregion
323
+ //#region adapters/core/src/utils/capabilities.d.ts
324
+ /**
325
+ * Parses capability strings into a typed AIAdapterCapabilities object.
326
+ *
327
+ * Transforms strings (e.g., from adapter.json) into runtime-queryable object with:
328
+ * - Auto-generated camelCase boolean properties (`'session:fork'` → `caps.sessionFork`)
329
+ * - `hasAll()` and `hasAny()` methods for batch checks
330
+ * @example
331
+ * ```typescript
332
+ * const caps = parseAIAdapterCapabilities(['systemPrompt', 'vision', 'session:resume']);
333
+ *
334
+ * caps.systemPrompt // true
335
+ * caps.sessionResume // true
336
+ * caps.hasAll(['vision', 'systemPrompt']) // true
337
+ * ```
338
+ * @param caps - Capability strings declared by the adapter
339
+ * @returns Capabilities object with auto-generated properties and batch methods
340
+ * @see {@link AIAdapterCapabilities} - Runtime API
341
+ * @see {@link AIAdapterCapabilityRegistry} - Schema for custom capabilities
342
+ */
343
+ declare function parseAIAdapterCapabilities(caps: string[]): AIAdapterCapabilities;
344
+ //#endregion
345
+ //#region adapters/core/src/utils/cleanEnvForAdapter.d.ts
346
+ type AdapterEnv = Record<string, string | undefined>;
347
+ /**
348
+ * Options for adapter environment cleanup.
349
+ */
350
+ interface CleanEnvForAdapterOptions {
351
+ /**
352
+ * Additional environment variables to remove from the inherited environment.
353
+ */
354
+ omitEnvVars?: readonly string[];
355
+ }
356
+ /**
357
+ * Clean environment variables for adapter child processes.
358
+ *
359
+ * Removes variables that should not be inherited by spawned adapter
360
+ * processes (for example Claude Code SDK and CLI wrappers).
361
+ *
362
+ * SEAM: Extend this list as additional problematic environment variables
363
+ * are discovered across adapter implementations.
364
+ * @param env - Optional base environment to clean (defaults to `undefined`)
365
+ * @param options - Additional cleanup options
366
+ * @returns Cleaned environment object with problematic variables removed.
367
+ * @example
368
+ * ```typescript
369
+ * const session = query({
370
+ * options: {
371
+ * env: cleanEnvForAdapter(customEnv),
372
+ * },
373
+ * });
374
+ * ```
375
+ */
376
+ declare function cleanEnvForAdapter(env?: AdapterEnv, options?: CleanEnvForAdapterOptions): Record<string, string>;
377
+ //#endregion
378
+ //#region adapters/core/src/utils/discriminated-handlers.d.ts
379
+ /**
380
+ * Type-safe emit function for discriminated handlers.
381
+ * Each call is validated at compile time to ensure payload matches subject.
382
+ *
383
+ * The emit function signature matches AIAgent.emitGlobal, allowing handlers
384
+ * to emit events without knowing whether they're running in live agent context
385
+ * or log import context.
386
+ */
387
+ type TypedEmitFn = <S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext>) => void | Promise<void>;
388
+ /**
389
+ * Synchronous variant of TypedEmitFn.
390
+ * Use with processDiscriminatedItemsSync to enforce sync handlers at compile time.
391
+ */
392
+ type SyncTypedEmitFn = <S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext>) => void;
393
+ /**
394
+ * Handler function that receives narrowed payload and typed emit.
395
+ * @typeParam TPayload - The narrowed payload type (discriminated union member)
396
+ * @typeParam TEmit - The emit function type (defaults to TypedEmitFn)
397
+ */
398
+ type DiscriminatedHandler<TPayload, TEmit extends TypedEmitFn = TypedEmitFn> = (payload: TPayload, emit: TEmit) => void | Promise<void>;
399
+ /**
400
+ * Synchronous handler that cannot return a Promise.
401
+ * Use with processDiscriminatedItemsSync to catch async handlers at compile time.
402
+ */
403
+ type SyncDiscriminatedHandler<TPayload> = (payload: TPayload, emit: SyncTypedEmitFn) => void;
404
+ /**
405
+ * Handlers map with discriminator-narrowed payload types.
406
+ *
407
+ * Each key is a possible value of the discriminator property,
408
+ * and each handler receives the narrowed payload type for that discriminator value.
409
+ * @typeParam TPayload - The full discriminated union type
410
+ * @typeParam TDiscriminator - The property key used to discriminate union members
411
+ */
412
+ type DiscriminatedHandlersMap<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string> = { [K in TPayload[TDiscriminator] & string]?: DiscriminatedHandler<Extract<TPayload, { [P in TDiscriminator]: K }>> };
413
+ /**
414
+ * Synchronous handlers map for compile-time async prevention.
415
+ * Use with defineDiscriminatedHandlersSync and processDiscriminatedItemsSync.
416
+ */
417
+ type SyncDiscriminatedHandlersMap<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string> = { [K in TPayload[TDiscriminator] & string]?: SyncDiscriminatedHandler<Extract<TPayload, { [P in TDiscriminator]: K }>> };
418
+ /**
419
+ * Configuration returned by defineDiscriminatedHandlers.
420
+ *
421
+ * Encapsulates the discriminator key and handler map for use with
422
+ * processDiscriminatedItems.
423
+ * @typeParam TPayload - The full discriminated union type
424
+ * @typeParam TDiscriminator - The property key used to discriminate union members
425
+ */
426
+ interface DiscriminatedHandlersConfig<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string> {
427
+ discriminator: TDiscriminator;
428
+ handlers: DiscriminatedHandlersMap<TPayload, TDiscriminator>;
429
+ }
430
+ /**
431
+ * Synchronous configuration for compile-time async prevention.
432
+ * Use with defineDiscriminatedHandlersSync and processDiscriminatedItemsSync.
433
+ */
434
+ interface SyncDiscriminatedHandlersConfig<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string> {
435
+ discriminator: TDiscriminator;
436
+ handlers: SyncDiscriminatedHandlersMap<TPayload, TDiscriminator>;
437
+ }
438
+ /**
439
+ * Factory to create typed discriminated handlers.
440
+ *
441
+ * This function provides compile-time validation that handlers receive
442
+ * correctly narrowed payload types based on the discriminator value.
443
+ * @param discriminator - The property key used to discriminate union members
444
+ * @param handlers - Map of discriminator values to handler functions
445
+ * @returns Configuration object for use with processDiscriminatedItems
446
+ * @example
447
+ * ```typescript
448
+ * // Define handlers with full type safety
449
+ * const handlers = defineDiscriminatedHandlers<BetaContentBlock, 'type'>('type', {
450
+ * text: (block, emit) => {
451
+ * // block is narrowed to BetaTextBlock
452
+ * emit(AgentSubjects.message, { content: block.text });
453
+ * },
454
+ * thinking: (block, emit) => {
455
+ * // block is narrowed to BetaThinkingBlock
456
+ * emit(AgentSubjects.reasoning, { content: block.thinking });
457
+ * },
458
+ * tool_use: (block, emit) => {
459
+ * // block is narrowed to BetaToolUseBlock
460
+ * emit(AgentSubjects.tool.use, {
461
+ * toolName: block.name,
462
+ * args: block.input,
463
+ * toolCallId: block.id,
464
+ * });
465
+ * },
466
+ * });
467
+ * ```
468
+ */
469
+ declare function defineDiscriminatedHandlers<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string = keyof TPayload & string>(discriminator: TDiscriminator, handlers: DiscriminatedHandlersMap<TPayload, TDiscriminator>): DiscriminatedHandlersConfig<TPayload, TDiscriminator>;
470
+ /**
471
+ * Factory for sync-only handlers with compile-time async prevention.
472
+ *
473
+ * Use this instead of defineDiscriminatedHandlers when handlers will be
474
+ * used with processDiscriminatedItemsSync. Async handlers will cause
475
+ * compile-time errors rather than runtime errors.
476
+ * @param discriminator - Property key used to discriminate payload types
477
+ * @param handlers - Map of discriminator values to sync handler functions
478
+ * @returns Config object for processDiscriminatedItemsSync
479
+ */
480
+ declare function defineDiscriminatedHandlersSync<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string = keyof TPayload & string>(discriminator: TDiscriminator, handlers: SyncDiscriminatedHandlersMap<TPayload, TDiscriminator>): SyncDiscriminatedHandlersConfig<TPayload, TDiscriminator>;
481
+ /**
482
+ * Process items through discriminated handlers.
483
+ *
484
+ * Iterates over items (or processes single item), reads discriminator,
485
+ * and calls appropriate handler with typed emit. Items without a matching
486
+ * handler are silently skipped.
487
+ * @param items - Single item or array of items to process
488
+ * @param config - Handler configuration from defineDiscriminatedHandlers
489
+ * @param emit - Typed emit function (can be emitGlobal, collection push, etc.)
490
+ * @example
491
+ * ```typescript
492
+ * // Agent usage - emit directly
493
+ * await processDiscriminatedItems(
494
+ * content,
495
+ * CONTENT_BLOCK_HANDLERS,
496
+ * (subject, payload) => this.emitGlobal(subject, payload),
497
+ * );
498
+ *
499
+ * // Importer usage - collect events with enrichment
500
+ * const events: NormalizedEvent[] = [];
501
+ * await processDiscriminatedItems(
502
+ * content,
503
+ * CONTENT_BLOCK_HANDLERS,
504
+ * (subject, payload) => {
505
+ * events.push({ subject, payload: { ...basePayload, ...payload } });
506
+ * },
507
+ * );
508
+ * ```
509
+ */
510
+ declare function processDiscriminatedItems<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string>(items: TPayload | TPayload[], config: DiscriminatedHandlersConfig<TPayload, TDiscriminator>, emit: TypedEmitFn): Promise<void>;
511
+ /**
512
+ * Synchronous variant of processDiscriminatedItems.
513
+ *
514
+ * Two usage modes:
515
+ * 1. With SyncDiscriminatedHandlersConfig: Full compile-time async prevention
516
+ * 2. With DiscriminatedHandlersConfig: Runtime-only async detection (for shared handlers)
517
+ * @param items - Single item or array of items to process
518
+ * @param config - Handler configuration (sync or async)
519
+ * @param emit - Synchronous emit function
520
+ * @throws Error if a handler returns a Promise
521
+ */
522
+ declare function processDiscriminatedItemsSync<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string>(items: TPayload | TPayload[], config: SyncDiscriminatedHandlersConfig<TPayload, TDiscriminator>, emit: SyncTypedEmitFn): void;
523
+ /**
524
+ * Overload for shared handlers defined with defineDiscriminatedHandlers.
525
+ * Provides runtime-only async detection (no compile-time safety).
526
+ * @param items - Single item or array of items to process
527
+ * @param config - Discriminated handlers config from defineDiscriminatedHandlers
528
+ * @param emit - Typed emit function for publishing events
529
+ */
530
+ declare function processDiscriminatedItemsSync<TPayload extends Record<string, unknown>, TDiscriminator extends keyof TPayload & string>(items: TPayload | TPayload[], config: DiscriminatedHandlersConfig<TPayload, TDiscriminator>, emit: SyncTypedEmitFn): void;
531
+ //#endregion
532
+ //#region adapters/core/src/utils/normalizeEnvValue.d.ts
533
+ /**
534
+ * Normalize blank environment values to `undefined`.
535
+ * @param value - Raw environment value
536
+ * @returns Trimmed value when non-empty
537
+ */
538
+ declare function normalizeEnvValue(value: string | undefined): string | undefined;
539
+ //#endregion
540
+ //#region adapters/core/src/utils/resolveTestConfig.d.ts
541
+ /** Fields injected by resolveTestConfig */
542
+ type InjectedTestFields<TBus extends ScopedBus<string>> = {
543
+ agentId: string;
544
+ adapterId: string;
545
+ adapterName: string;
546
+ bus: TBus;
547
+ /**
548
+ * Unresolved provider context for conformance tests.
549
+ *
550
+ * When a `testProviderDefinition` is supplied, credential refs are built
551
+ * from the definition's `credentialEnvVars` mapping using `env:VAR_NAME`
552
+ * format. Connectors resolve these refs locally via `resolveConnectorCredentials()`
553
+ * — which reads from `process.env` for `env:` refs — mirroring the full
554
+ * credential-resolution chain without requiring a database or bus handlers.
555
+ *
556
+ * Falls back to a minimal sentinel (empty `credentialRefs`) when no definition
557
+ * is provided.
558
+ */
559
+ providerContext: ProviderContext;
560
+ };
561
+ /** Result type: options merged with injected fields (handles undefined options) */
562
+ type ResolvedTestConfig<TOptions, TBus extends ScopedBus<string>> = (TOptions extends undefined ? object : TOptions) & InjectedTestFields<TBus>;
563
+ /**
564
+ * Build an unresolved provider context for conformance tests.
565
+ *
566
+ * When a provider definition is supplied, builds credential refs in `env:VAR_NAME`
567
+ * format from `credentialEnvVars`. Connectors resolve these refs locally via
568
+ * `resolveConnectorCredentials()`. Otherwise returns a minimal sentinel.
569
+ * @param definition - Optional provider definition to build credential refs from
570
+ * @param ambientCredentialDefinitions - Provider definitions whose credential
571
+ * env vars should be stripped from ambient subprocess environments
572
+ * @returns Fresh unresolved provider context per call to prevent cross-test mutation leaks
573
+ */
574
+ declare function createTestProviderContext(definition?: ProviderDefinitionInput, ambientCredentialDefinitions?: readonly ProviderDefinitionInput[]): ProviderContext;
575
+ /**
576
+ * Resolves test configuration by adding required fields (bus, agentId, adapterId, adapterName, providerContext).
577
+ *
578
+ * When `testProviderDefinition` is supplied, credential refs and endpoint overrides
579
+ * are built from the definition's `credentialEnvVars` and `endpoints` — so
580
+ * conformance tests can run against real providers without the full orchestrator.
581
+ * @param options - Partial test agent options (undefined = empty config)
582
+ * @param bus - Scoped bus instance for the adapter
583
+ * @param testProviderDefinition - Optional provider definition for credential ref building
584
+ * @param ambientCredentialDefinitions - Provider definitions whose credential
585
+ * env vars should be stripped from ambient subprocess environments
586
+ * @returns Complete test config with required fields injected
587
+ */
588
+ declare function resolveTestConfig<TOptions extends CreateTestAgentOptions | undefined, TBus extends ScopedBus<string>>(options: TOptions, bus: TBus, testProviderDefinition?: ProviderDefinitionInput, ambientCredentialDefinitions?: readonly ProviderDefinitionInput[]): ResolvedTestConfig<TOptions, TBus>;
589
+ //#endregion
590
+ //#region adapters/core/src/utils/resolveConformanceTestPreset.d.ts
591
+ /** Default environment variable for selecting a conformance provider preset. */
592
+ declare const MAKAIO_CONFORMANCE_PROVIDER_ENV = "MAKAIO_CONFORMANCE_PROVIDER";
593
+ /** Default environment variable for overriding the primary conformance model. */
594
+ declare const MAKAIO_CONFORMANCE_PRIMARY_MODEL_ENV = "MAKAIO_CONFORMANCE_PRIMARY_MODEL";
595
+ /** Default environment variable for overriding the secondary conformance model. */
596
+ declare const MAKAIO_CONFORMANCE_SECONDARY_MODEL_ENV = "MAKAIO_CONFORMANCE_SECONDARY_MODEL";
597
+ /** Environment variable used by the conformance runner to pass provider definitions into worker forks. */
598
+ declare const MAKAIO_CONFORMANCE_PROVIDER_DEFINITIONS_ENV = "MAKAIO_CONFORMANCE_PROVIDER_DEFINITIONS";
599
+ /** Reads an environment variable value by name. */
600
+ type ConformanceEnvReader = (name: string) => string | undefined;
601
+ /**
602
+ * Options for resolving the provider/model preset used by conformance tests.
603
+ */
604
+ interface ResolveConformanceTestPresetOptions {
605
+ /** Adapter name used in configuration error messages. */
606
+ adapterName: string;
607
+ /** Provider ID used when no env override is supplied. */
608
+ defaultProviderId: string;
609
+ /** Provider IDs accepted by this adapter's conformance config. */
610
+ providerIds: readonly string[];
611
+ /** Full provider definitions supplied by the conformance harness. */
612
+ providerDefinitions?: readonly ProviderDefinitionInput[];
613
+ /** Default reasoning effort to attach to resolved model refs. */
614
+ reasoningEffort?: TestModelRef['reasoningEffort'];
615
+ /** Environment reader, injectable for tests. */
616
+ readEnv?: ConformanceEnvReader;
617
+ /** Provider override env var name. */
618
+ providerEnvVar?: string;
619
+ /** Primary model override env var name. */
620
+ primaryModelEnvVar?: string;
621
+ /** Secondary model override env var name. */
622
+ secondaryModelEnvVar?: string;
623
+ }
624
+ /**
625
+ * Resolved conformance provider/model preset.
626
+ */
627
+ interface ResolvedConformanceTestPreset {
628
+ /** Provider selected for this test run. */
629
+ provider: ProviderDefinitionInput;
630
+ /** All accepted provider definitions, including the selected provider. */
631
+ providers: readonly ProviderDefinitionInput[];
632
+ /** Provider context derived from the selected provider. */
633
+ providerContext: ProviderContext;
634
+ /** Fast/cheap model used by most conformance tests. */
635
+ primaryModel: TestModelRef;
636
+ /** Second model used by lifecycle mutation tests. */
637
+ secondaryModel: TestModelRef;
638
+ }
639
+ /**
640
+ * Resolve a conformance test provider preset from defaults plus MAKAIO_CONFORMANCE_* overrides.
641
+ *
642
+ * Provider, primary model, secondary model, credentials, and endpoint overrides
643
+ * are resolved together so CI can swap test economics without changing local
644
+ * OAuth/default behavior.
645
+ * @param options - Resolver inputs and optional env variable names
646
+ * @returns Provider/model/context preset for adapter `createTestConfig()`
647
+ */
648
+ declare function resolveConformanceTestPreset(options: ResolveConformanceTestPresetOptions): ResolvedConformanceTestPreset;
649
+ //#endregion
650
+ //#region adapters/core/src/utils/resolveDisabledNativeTools.d.ts
651
+ /** Result of an optional harness lookup — either unhandled or resolved. */
652
+ type OptionalHarnessResult = Promise<{
653
+ handled: false;
654
+ } | {
655
+ handled: true;
656
+ data: HarnessDefinition;
657
+ }>;
658
+ /**
659
+ * Minimal requester contract for harness lookups.
660
+ *
661
+ * Supports both ID-based lookup (`HarnessSubjects.get`) and adapter-scoped
662
+ * default lookup (`HarnessSubjects.getDefault`).
663
+ */
664
+ interface HarnessRequester {
665
+ requestOptional(subject: typeof HarnessSubjects.get, payload: {
666
+ id: string;
667
+ }): OptionalHarnessResult;
668
+ requestOptional(subject: typeof HarnessSubjects.getDefault, payload: {
669
+ adapterName?: string;
670
+ clientId?: string;
671
+ }): OptionalHarnessResult;
672
+ }
673
+ /**
674
+ * Resolve SDK-native tool names disabled by the active harness for an adapter.
675
+ *
676
+ * When `harnessId` is provided, fetches that specific harness by ID.
677
+ * Otherwise falls back to the adapter's default harness via `adapterName` and
678
+ * optional `clientId` so that client-scoped harnesses are considered.
679
+ *
680
+ * Uses optional request semantics so callers can run without harness registration
681
+ * (for example, in lightweight test runtimes).
682
+ * @param requester - Bus-like requester supporting requestOptional for harness subjects
683
+ * @param adapterName - Adapter name used to look up the default harness (fallback path)
684
+ * @param harnessId - Optional explicit harness ID; takes precedence over the default lookup
685
+ * @param clientId - Optional client identifier for client-scoped default harness lookup
686
+ * @returns Disabled native tool names, or an empty array when unavailable
687
+ */
688
+ declare function resolveDisabledNativeTools(requester: HarnessRequester, adapterName: string, harnessId?: string, clientId?: string): Promise<readonly string[]>;
689
+ //#endregion
690
+ //#region adapters/core/src/utils/formatMessageHistoryAsTranscript.d.ts
691
+ /**
692
+ * Formats message history as a human-readable conversation transcript.
693
+ *
694
+ * Converts structured Message[] into plain text format:
695
+ * ```
696
+ * User: Hello, my name is Alice
697
+ * Assistant: Nice to meet you, Alice!
698
+ * ```
699
+ *
700
+ * This avoids exposing JSON structure to the LLM, which can trigger
701
+ * meta-analysis of the format rather than natural conversation continuation.
702
+ * @param history - Array of Message objects with role and blocks
703
+ * @returns Human-readable transcript string
704
+ */
705
+ declare function formatMessageHistoryAsTranscript(history: Message[]): string;
706
+ //#endregion
707
+ //#region adapters/core/src/utils/serialize-block-to-text.d.ts
708
+ /**
709
+ * Serialize a {@link MessageBlock} to plain text for contexts where native
710
+ * block rendering is unavailable — for example, media blocks in text positions,
711
+ * or history serialization for providers that only accept string content.
712
+ *
713
+ * - `text` and `reasoning` blocks return their content verbatim.
714
+ * - `tool_call` blocks emit a bracketed label followed by JSON-serialized args.
715
+ * - `tool_output` blocks emit a bracketed label with the call ID and output body.
716
+ * - `image` and `document` blocks emit a static placeholder.
717
+ * - `attachment` blocks emit the display name when present, otherwise the file name.
718
+ * @param block - The message block to serialize.
719
+ * @returns Plain-text representation of the block.
720
+ */
721
+ declare function serializeBlockToText(block: MessageBlock$1): string;
722
+ //#endregion
723
+ //#region adapters/core/src/connector/base-connector-session.d.ts
724
+ /**
725
+ * Configuration for a connector session.
726
+ * @typeParam TBus - Scoped bus type for adapter namespace
727
+ */
728
+ interface ConnectorSessionConfig<TBus extends ScopedBus<string> = ScopedBus<string>> {
729
+ bus: TBus;
730
+ adapterId: string;
731
+ adapterName: string;
732
+ cwd: string;
733
+ model: string;
734
+ env: Record<string, string>;
735
+ }
736
+ /**
737
+ * Interface for turn-like objects that support pause/abort operations.
738
+ * Allows base session class to work with different turn implementations.
739
+ */
740
+ interface PausableTurn {
741
+ pause(): Promise<unknown>;
742
+ }
743
+ /**
744
+ * Base abstract class for connector session implementations.
745
+ *
746
+ * Sessions manage SDK query lifecycle across multiple turns:
747
+ * - SDK connection management
748
+ * - Turn creation and coordination
749
+ * - Session ID management
750
+ *
751
+ * Each adapter implements its own session subclass.
752
+ * @typeParam TConfig - Configuration type extending ConnectorSessionConfig
753
+ */
754
+ declare abstract class BaseConnectorSession<TConfig extends ConnectorSessionConfig = ConnectorSessionConfig> {
755
+ protected readonly config: TConfig;
756
+ protected readonly bus: TConfig['bus'];
757
+ protected sessionId?: string;
758
+ protected currentTurn?: PausableTurn;
759
+ constructor(config: TConfig);
760
+ /**
761
+ * Abort the session and cleanup resources.
762
+ * Pauses the current turn if one is active.
763
+ */
764
+ abort(): Promise<void>;
765
+ /**
766
+ * Send a message to the provider.
767
+ * Not used - subclasses should implement processQueue instead.
768
+ * @param _message - Unused message parameter
769
+ * @param _options - Unused options parameter
770
+ */
771
+ sendMessage(_message: unknown, _options?: unknown): Promise<void>;
772
+ /**
773
+ * Get the adapter session ID.
774
+ * @returns The session ID from the provider
775
+ */
776
+ getAdapterSessionId(): Promise<string>;
777
+ }
778
+ //#endregion
779
+ //#region adapters/core/src/connector/base-connector-turn.d.ts
780
+ /**
781
+ * Result of pausing a turn.
782
+ * @typeParam TState - Turn state type
783
+ */
784
+ interface PauseResult<TState = string> {
785
+ /** The state the turn was in before pausing */
786
+ stateBeforePause: TState;
787
+ /** Whether the turn had already ended when pause was requested */
788
+ turnEnded: boolean;
789
+ }
790
+ /**
791
+ * Base abstract class for connector turn implementations.
792
+ *
793
+ * Turns manage the state machine for a single user message:
794
+ * - State transitions (idle to turn_started to step_started to ...)
795
+ * - Pause/resume mechanics
796
+ * - Safe boundary detection for immediate messages
797
+ * - Message handle delegation (acknowledgment, completion)
798
+ *
799
+ * Each adapter implements its own turn subclass with adapter-specific
800
+ * state handling and SDK integration.
801
+ * @typeParam TState - Turn state enum type (string union)
802
+ */
803
+ declare abstract class BaseConnectorTurn<TState extends string = string> {
804
+ protected state: TState;
805
+ protected readonly bus: ScopedBus<string>;
806
+ protected readonly adapterId: string;
807
+ protected readonly adapterName: string;
808
+ protected stateChangedCallback?: (oldState: TState, newState: TState) => Promise<void> | void;
809
+ /**
810
+ * Active message handle for this turn.
811
+ * Subclasses must provide this handle for message lifecycle management.
812
+ */
813
+ protected abstract activeMessageHandle: MessageHandle;
814
+ constructor(bus: ScopedBus<string>, adapterId: string, adapterName: string, initialState: TState);
815
+ /**
816
+ * Pause the turn at next safe boundary.
817
+ * @returns Pause result indicating whether turn already ended
818
+ */
819
+ abstract pause(): Promise<PauseResult<TState>>;
820
+ /**
821
+ * Resume the paused turn with optional additional message.
822
+ * @param message - Optional message to inject when resuming
823
+ */
824
+ abstract resume(message?: unknown): Promise<void>;
825
+ /**
826
+ * Check if turn is currently paused.
827
+ */
828
+ abstract isPaused(): boolean;
829
+ /**
830
+ * Register callback for state changes.
831
+ * @param cb - Callback to invoke on state transitions
832
+ */
833
+ onStateChanged(cb: (oldState: TState, newState: TState) => Promise<void> | void): void;
834
+ /**
835
+ * Transition to new state and notify listeners.
836
+ * Template method for shared state transition pattern.
837
+ *
838
+ * NOTE: Subclasses should use their typed namespace subjects for emission.
839
+ * This is a template - concrete implementation in adapter-specific Turn classes.
840
+ * @param newState - New state to transition to
841
+ */
842
+ protected transitionTo(newState: TState): Promise<void>;
843
+ /**
844
+ * Emit state change event - implemented by subclass with typed subjects.
845
+ * @param oldState - Previous state
846
+ * @param newState - New state
847
+ */
848
+ protected abstract emitStateChange(oldState: TState, newState: TState): Promise<void>;
849
+ /**
850
+ * Get current turn state.
851
+ * @returns Current turn state
852
+ */
853
+ getState(): TState;
854
+ /**
855
+ * Get the message handle for this turn.
856
+ * @returns The message handle for this turn
857
+ */
858
+ getMessageHandle(): MessageHandle;
859
+ /**
860
+ * Mark message handle as acknowledged.
861
+ */
862
+ markAcknowledged(): void;
863
+ /**
864
+ * Mark message handle as completed.
865
+ * @param result - The completion result with outcome and optional result/error
866
+ */
867
+ markCompleted(result: {
868
+ outcome: string;
869
+ result?: unknown;
870
+ error?: unknown;
871
+ }): void;
872
+ }
873
+ //#endregion
874
+ //#region adapters/core/src/connector/procedural-connector-turn.d.ts
875
+ /**
876
+ * Typed subject references for turn lifecycle events.
877
+ *
878
+ * Each adapter provides its namespace-specific subjects when constructing
879
+ * a ProceduralConnectorTurn. The subjects must all accept the same
880
+ * TurnStateChangedPayload shape.
881
+ * @typeParam TSubject - The subject definition type for the adapter's bus
882
+ */
883
+ interface TurnSubjects<TSubject = ScopedSubjectDefinition> {
884
+ state_changed: TSubject;
885
+ turn_started: TSubject;
886
+ step_started: TSubject;
887
+ step_finished: TSubject;
888
+ turn_finished: TSubject;
889
+ }
890
+ /**
891
+ * Standard turn state type for procedural adapters.
892
+ *
893
+ * Procedural adapters (Gemini, OpenAI, Copilot) use abort+restart
894
+ * rather than true pause/resume. Their state machine is:
895
+ * idle to turn_started to step_started to step_finished to turn_finished
896
+ */
897
+ type ProceduralTurnState = 'idle' | 'turn_started' | 'step_started' | 'step_finished' | 'turn_finished';
898
+ /**
899
+ * Configuration for ProceduralConnectorTurn.
900
+ * @typeParam TBus - Scoped bus type for the adapter
901
+ * @typeParam TSubject - Subject definition type
902
+ */
903
+ interface ProceduralTurnConfig<TBus extends ScopedBus<string>, TSubject> {
904
+ bus: TBus;
905
+ adapterId: string;
906
+ adapterName: string;
907
+ agentId: string;
908
+ messageHandle: MessageHandle;
909
+ turnSubjects: TurnSubjects<TSubject>;
910
+ }
911
+ /**
912
+ * Base turn implementation for procedural adapters (Gemini, OpenAI, Copilot).
913
+ *
914
+ * These adapters share an abort+restart pattern rather than true pause/resume.
915
+ * This class extracts the common state machine, lifecycle methods, and
916
+ * message handle delegation that was duplicated across all three.
917
+ *
918
+ * Subclasses only need to add adapter-specific behavior:
919
+ * - Gemini: AbortController for SDK cancellation
920
+ * - OpenAI: AbortController for SDK cancellation
921
+ * - Copilot: SDK event handling (handleSdkEvent)
922
+ * @typeParam TState - Turn state type (defaults to ProceduralTurnState)
923
+ * @typeParam TBus - Scoped bus type for the adapter
924
+ * @typeParam TSubject - Subject definition type for emit calls
925
+ */
926
+ declare class ProceduralConnectorTurn<TState extends string = ProceduralTurnState, TBus extends ScopedBus<string> = ScopedBus<string>, TSubject extends ScopedSubjectDefinition = ScopedSubjectDefinition> extends BaseConnectorTurn<TState> {
927
+ protected activeMessageHandle: MessageHandle;
928
+ protected readonly connectorBus: TBus;
929
+ protected readonly agentId: string;
930
+ protected readonly turnSubjects: TurnSubjects<TSubject>;
931
+ protected aborted: boolean;
932
+ constructor(config: ProceduralTurnConfig<TBus, TSubject>, initialState: TState);
933
+ /**
934
+ * Emit state change using adapter-provided turn subjects.
935
+ * @param oldState - Previous state before transition
936
+ * @param newState - New state after transition
937
+ */
938
+ protected emitStateChange(oldState: TState, newState: TState): Promise<void>;
939
+ /**
940
+ * Start the turn.
941
+ */
942
+ start(): Promise<void>;
943
+ /**
944
+ * Transition to step_started (called when first content arrives).
945
+ * Allows turn_started to step_started AND step_finished to step_started
946
+ * (for tool recursion).
947
+ */
948
+ markStepStarted(): Promise<void>;
949
+ /**
950
+ * Transition to step_finished (called after content block completes).
951
+ */
952
+ markStepFinished(): Promise<void>;
953
+ /**
954
+ * Mark turn as finished.
955
+ */
956
+ markTurnFinished(): Promise<void>;
957
+ /**
958
+ * Pause (abort) at next opportunity.
959
+ * Procedural adapters don't support true pause - caller creates a new turn
960
+ * with merged content instead.
961
+ * @returns Pause result indicating turn state
962
+ */
963
+ pause(): Promise<PauseResult<TState>>;
964
+ /**
965
+ * Resume is not supported for procedural adapters - caller creates new turn.
966
+ * @param _message - Unused
967
+ * @throws Error always
968
+ */
969
+ resume(_message?: unknown): Promise<void>;
970
+ /**
971
+ * Check if turn was aborted.
972
+ * @returns True if turn was aborted
973
+ */
974
+ isPaused(): boolean;
975
+ /**
976
+ * Check if turn is completed.
977
+ * @returns True if turn has finished
978
+ */
979
+ isCompleted(): boolean;
980
+ /**
981
+ * Check if turn can accept immediate message.
982
+ * True if turn is active (not finished, not aborted).
983
+ * @returns True if turn can accept an immediate message
984
+ */
985
+ canAcceptImmediate(): boolean;
986
+ }
987
+ //#endregion
988
+ //#region adapters/core/src/session/user-message-queue.d.ts
989
+ /**
990
+ * Simple FIFO queue for user messages with delivery mode support.
991
+ *
992
+ * This queue is owned by adapter Connectors and passed to Sessions for processing.
993
+ *
994
+ * Delivery modes:
995
+ * - 'enqueue': Add to end of queue (default)
996
+ * - 'replace': Supersede all unacknowledged messages, add to queue
997
+ * - 'immediate': Handled by Session (abort/restart), not queue
998
+ *
999
+ * Design:
1000
+ * - Connector enqueues messages as they arrive
1001
+ * - Session dequeues messages when ready to process
1002
+ * - Peek allows Session to inspect next message without removing
1003
+ */
1004
+ declare class UserMessageQueue {
1005
+ private readonly queue;
1006
+ /**
1007
+ * Add message to queue based on delivery mode.
1008
+ * @param handle - Message handle to enqueue
1009
+ */
1010
+ enqueue(handle: MessageHandle): void;
1011
+ /**
1012
+ * Remove all superseded messages from queue.
1013
+ */
1014
+ private removeSuperseded;
1015
+ /**
1016
+ * Remove and return first message from queue.
1017
+ * @returns First message or undefined if queue empty
1018
+ */
1019
+ dequeue(): MessageHandle | undefined;
1020
+ /**
1021
+ * Look at first message without removing.
1022
+ * @returns First message or undefined if queue empty
1023
+ */
1024
+ peek(): MessageHandle | undefined;
1025
+ /**
1026
+ * Check if queue is empty.
1027
+ * @returns True if queue has no messages
1028
+ */
1029
+ isEmpty(): boolean;
1030
+ /**
1031
+ * Get current queue size.
1032
+ * @returns Number of messages in queue
1033
+ */
1034
+ size(): number;
1035
+ /**
1036
+ * Clear all messages from queue.
1037
+ */
1038
+ clear(): void;
1039
+ /**
1040
+ * Find the first immediate message in the queue.
1041
+ * @returns First immediate message or undefined
1042
+ */
1043
+ findImmediate(): MessageHandle | undefined;
1044
+ /**
1045
+ * Remove a specific immediate message from the queue.
1046
+ * @param handle - Handle to remove
1047
+ */
1048
+ removeImmediate(handle: MessageHandle): void;
1049
+ /**
1050
+ * Remove and return all enqueued (non-immediate) messages.
1051
+ * Used when immediate arrives to merge their content.
1052
+ * @returns Array of enqueued message handles in FIFO order
1053
+ */
1054
+ drainEnqueued(): MessageHandle[];
1055
+ }
1056
+ //#endregion
1057
+ //#region adapters/core/src/session/process-queue.d.ts
1058
+ /**
1059
+ * Minimal turn interface required by processQueue orchestration.
1060
+ *
1061
+ * Any turn implementation (Claude, Gemini, OpenAI, Copilot) that exposes
1062
+ * these methods can participate in the shared processQueue flow.
1063
+ */
1064
+ interface QueueableTurn {
1065
+ canAcceptImmediate(): boolean;
1066
+ isCompleted(): boolean;
1067
+ getMessageHandle(): MessageHandle;
1068
+ pause(): Promise<PauseResult>;
1069
+ }
1070
+ /**
1071
+ * Result of processing an immediate message merge.
1072
+ *
1073
+ * Returned by the `extractMergeContent` callback so that adapters
1074
+ * can collect adapter-specific content (e.g., Gemini collects non-text parts).
1075
+ * The `mergedContent` array is always present; `extra` is an opaque bag
1076
+ * for adapter-specific data that flows through to `startNewTurn`.
1077
+ */
1078
+ interface MergeResult {
1079
+ /** Text content collected from superseded/merged messages */
1080
+ mergedContent: string[];
1081
+ /** Adapter-specific merge data (e.g., non-text parts for Gemini) */
1082
+ extra?: unknown;
1083
+ }
1084
+ /**
1085
+ * Callbacks for adapter-specific behavior during queue processing.
1086
+ * @typeParam TExtra - Type of adapter-specific extra merge data
1087
+ */
1088
+ interface ProcessQueueCallbacks<TExtra = unknown> {
1089
+ /**
1090
+ * Get the current turn, if any.
1091
+ * @returns The current turn or undefined
1092
+ */
1093
+ getCurrentTurn: () => QueueableTurn | undefined;
1094
+ /**
1095
+ * Extract text content from a message handle for merge.
1096
+ * Default: `handle.message.message as string`
1097
+ * @param handle - The message handle to extract content from
1098
+ * @returns The text content
1099
+ */
1100
+ extractContent?: (handle: MessageHandle) => string;
1101
+ /**
1102
+ * Called after merge content is collected from superseded/enqueued messages.
1103
+ * Allows adapters to collect additional content (e.g., Gemini's non-text parts).
1104
+ *
1105
+ * If not provided, only text content is collected using `extractContent`.
1106
+ * @param currentHandle - The in-flight message handle being superseded (or undefined)
1107
+ * @param enqueuedHandles - The enqueued handles being merged
1108
+ * @returns Extra merge data to pass through to startNewTurn
1109
+ */
1110
+ collectMergeExtra?: (currentHandle: MessageHandle | undefined, enqueuedHandles: MessageHandle[]) => TExtra;
1111
+ /**
1112
+ * Hook called after merge is collected but before starting the new turn.
1113
+ * Used by Claude to create a fresh query instance.
1114
+ */
1115
+ onBeforeImmediateTurn?: () => Promise<void>;
1116
+ /**
1117
+ * Start a new turn with the given message and optional merge data.
1118
+ * @param handle - The message handle to process
1119
+ * @param mergedContent - Text content from superseded/merged messages
1120
+ * @param extra - Adapter-specific extra merge data
1121
+ */
1122
+ startNewTurn: (handle: MessageHandle, mergedContent?: string[], extra?: TExtra) => Promise<void>;
1123
+ }
1124
+ /**
1125
+ * Shared processQueue orchestration for all session implementations.
1126
+ *
1127
+ * Handles the complete immediate-mode flow:
1128
+ * 1. Detect immediate message while a turn is active
1129
+ * 2. Pause the active turn
1130
+ * 3. Supersede the in-flight message and drain enqueued messages
1131
+ * 4. Collect merged content from all superseded/merged messages
1132
+ * 5. Start a new turn with the immediate message and merged context
1133
+ *
1134
+ * Also handles the normal queue flow:
1135
+ * - Late immediate rejection (immediate arrives after turn finishes)
1136
+ * - Normal enqueue/replace message processing
1137
+ *
1138
+ * Returns `true` when a new turn was started, `false` otherwise.
1139
+ * Callers can use this to decide whether to transition to idle when
1140
+ * the queue drains without starting a new turn (e.g., all-rejection case).
1141
+ * @param queue - The user message queue to process
1142
+ * @param callbacks - Adapter-specific callbacks
1143
+ * @returns True if a new turn was started, false otherwise
1144
+ * @typeParam TExtra - Type of adapter-specific extra merge data
1145
+ */
1146
+ declare function processQueueMessages<TExtra = unknown>(queue: UserMessageQueue, callbacks: ProcessQueueCallbacks<TExtra>): Promise<boolean>;
1147
+ //#endregion
1148
+ //#region adapters/core/src/connector/procedural-agent-connector.d.ts
1149
+ /**
1150
+ * Minimal session interface required by ProceduralAgentConnector.
1151
+ *
1152
+ * Any session implementation (OpenAI, Copilot, Gemini) that exposes
1153
+ * these methods can be used with ProceduralAgentConnector's default
1154
+ * wireSessionEvents / processUserMessages / acceptsImmediate.
1155
+ */
1156
+ interface ProceduralConnectorSession {
1157
+ /** Process messages from the queue. */
1158
+ processQueue(queue: UserMessageQueue): Promise<void>;
1159
+ /** Get the current turn for state inspection. */
1160
+ getCurrentTurn(): QueueableTurn | undefined;
1161
+ }
1162
+ /**
1163
+ * Turn subject references for wireSessionEvents.
1164
+ *
1165
+ * Each adapter provides its namespace-specific subjects. The subjects
1166
+ * must accept TurnStateChangedPayload (or compatible shape).
1167
+ * @typeParam TNamespace - The bus namespace string for subject typing
1168
+ */
1169
+ interface WireSessionSubjects<TNamespace extends string = string> {
1170
+ turn_started: ScopedSubjectDefinition<TNamespace>;
1171
+ step_started: ScopedSubjectDefinition<TNamespace>;
1172
+ step_finished: ScopedSubjectDefinition<TNamespace>;
1173
+ turn_finished: ScopedSubjectDefinition<TNamespace>;
1174
+ }
1175
+ /**
1176
+ * Configuration for ProceduralAgentConnector's wireSessionEvents behavior.
1177
+ *
1178
+ * The `onTurnStarted` and `onTurnFinished` hooks allow adapters to inject
1179
+ * logic at turn boundaries. By default both are no-ops.
1180
+ */
1181
+ interface WireSessionConfig {
1182
+ /**
1183
+ * Called when a new turn starts (turn_started bus event).
1184
+ *
1185
+ * Executes before the default `updateProcessingState('turn_started')` so
1186
+ * the connector state machine is always updated regardless of this hook.
1187
+ *
1188
+ * Supports async so that turn-start operations with I/O — such as a pending
1189
+ * MCP tool refresh via the bus — can complete before the API call is made.
1190
+ * In-memory operations (recordInjection, consumeTurnNumber) are not affected
1191
+ * by the async signature.
1192
+ */
1193
+ onTurnStarted?: () => Promise<void> | void;
1194
+ /**
1195
+ * Custom handler for turn_finished events.
1196
+ *
1197
+ * When provided, replaces the default turn_finished behavior entirely.
1198
+ * The handler receives a callback to process the queue, which it should
1199
+ * call when the message is considered complete and the queue should drain.
1200
+ * @param drainQueue - Callback that processes the queue or goes idle
1201
+ */
1202
+ onTurnFinished?: (drainQueue: () => Promise<void>) => Promise<void>;
1203
+ }
1204
+ /**
1205
+ * Abstract base class for procedural (non-event-driven) agent connectors.
1206
+ *
1207
+ * Procedural adapters (OpenAI, Copilot, Gemini) share common patterns:
1208
+ * - wireSessionEvents: subscribe to turn lifecycle events and update processing state
1209
+ * - processUserMessages: initialize session, enqueue, transition to active, process queue
1210
+ * - complete: poll processing state until idle/paused
1211
+ * - start: delegate to sendMessage and return AgentStartResult
1212
+ * - acceptsImmediate: delegate to session's current turn
1213
+ *
1214
+ * Subclasses must implement:
1215
+ * - `getSession()` / `ensureSession()` for session access and lazy initialization
1216
+ * - `getSessionQueue()` for the adapter's UserMessageQueue instance
1217
+ * - `getTurnSubjects()` for namespace-specific turn subjects
1218
+ * - `sendMessage()`, `abort()`, `close()`, `interrupt()`, `getAdapterSessionId()`
1219
+ *
1220
+ * Subclasses may override:
1221
+ * - `getWireSessionConfig()` for custom turn_finished behavior (e.g., Copilot multi-turn)
1222
+ * @typeParam TBus - Scoped bus type for adapter namespace
1223
+ * @typeParam TConfig - Configuration type extending BaseAgentConnectorConfig
1224
+ */
1225
+ declare abstract class ProceduralAgentConnector<TBus extends ScopedBus<string> = ScopedBus<string>, TConfig extends BaseAgentConnectorConfig<TBus> = BaseAgentConnectorConfig<TBus>> extends AIAgentConnector<TBus, TConfig> {
1226
+ /** Whether turn event wiring has been setup. */
1227
+ private turnEventsWired;
1228
+ /**
1229
+ * Get the adapter's session instance (may be undefined if not yet initialized).
1230
+ * @returns The session or undefined
1231
+ */
1232
+ protected abstract getSession(): ProceduralConnectorSession | undefined;
1233
+ /**
1234
+ * Initialize and return the adapter's session.
1235
+ * Must be idempotent (no-op if already initialized).
1236
+ * @returns The initialized session
1237
+ */
1238
+ protected abstract ensureSession(): Promise<ProceduralConnectorSession>;
1239
+ /**
1240
+ * Get the adapter's UserMessageQueue instance.
1241
+ * @returns The message queue
1242
+ */
1243
+ protected abstract getSessionQueue(): UserMessageQueue;
1244
+ /**
1245
+ * Get the adapter's namespace-specific turn subjects for wireSessionEvents.
1246
+ * @returns Turn subject definitions
1247
+ */
1248
+ protected abstract getTurnSubjects(): WireSessionSubjects<TBus['namespace']>;
1249
+ /**
1250
+ * Get optional wire session configuration for custom turn_finished behavior.
1251
+ * Override in subclasses that need non-standard turn_finished handling
1252
+ * (e.g., Copilot multi-turn message completion).
1253
+ * @returns Wire session configuration, or undefined for default behavior
1254
+ */
1255
+ protected getWireSessionConfig(): WireSessionConfig | undefined;
1256
+ /**
1257
+ * Wire Session turn events to Connector state updates.
1258
+ *
1259
+ * Session emits typed events, Connector subscribes and updates processing state.
1260
+ * This maintains separation of concerns - Session does not know about Connector state.
1261
+ *
1262
+ * Default turn_finished behavior: transition through processing_finished to idle,
1263
+ * or drain the queue if messages are pending. Override via `getWireSessionConfig()`.
1264
+ */
1265
+ protected wireSessionEvents(): void;
1266
+ /**
1267
+ * Process queued user messages by delegating to Session.
1268
+ *
1269
+ * Shared flow:
1270
+ * 1. Initialize session if not yet created
1271
+ * 2. Enqueue the message
1272
+ * 3. Set adapterSessionId on handle
1273
+ * 4. Transition to active if currently idle/paused
1274
+ * 5. Process queue via session
1275
+ * @param messageHandles - Array of message handles to process
1276
+ * @returns Set of message handles that were processed
1277
+ */
1278
+ protected processUserMessages(messageHandles: MessageHandle[]): Promise<Set<MessageHandle>>;
1279
+ /**
1280
+ * Initialize the connector's SDK session without sending a message.
1281
+ * Must set adapterSessionId before returning.
1282
+ * Called by createAgent for idle agent setup.
1283
+ * Implementations MUST be idempotent (no-op if already initialized).
1284
+ * @param options - Optional start options (e.g., systemPrompt)
1285
+ */
1286
+ initialize(options?: ConnectorStartOptions): Promise<void>;
1287
+ /**
1288
+ * Start session with initial message.
1289
+ * @param message - The initial message to send
1290
+ * @param options - Optional send message options
1291
+ * @returns The agent start result with session ID and message handle
1292
+ */
1293
+ start(message: NormalizedMessageInput, options?: ConnectorSendMessageOptions): Promise<AgentStartResult>;
1294
+ /**
1295
+ * Complete the agent session by waiting for all messages to finish.
1296
+ * @returns Last message result or null if no messages processed
1297
+ */
1298
+ complete(): Promise<MessageResult | null>;
1299
+ /**
1300
+ * Returns true if current turn can accept immediate messages.
1301
+ * @returns True if turn can accept immediate, false otherwise
1302
+ */
1303
+ protected acceptsImmediate(): boolean;
1304
+ }
1305
+ //#endregion
1306
+ //#region adapters/core/src/utils/tool-approval.d.ts
1307
+ /**
1308
+ * Context required to complete a global tool approval request.
1309
+ *
1310
+ * Provides adapter identity so the approval handler knows which
1311
+ * adapter/agent/session is requesting permission.
1312
+ */
1313
+ interface ToolApprovalContext {
1314
+ /** Adapter instance ID */
1315
+ adapterId: string;
1316
+ /** Adapter type name (e.g., 'gemini-sdk', 'openai-node') */
1317
+ adapterName: string;
1318
+ /** Agent ID within the adapter */
1319
+ agentId: string;
1320
+ /** Adapter-side session ID */
1321
+ adapterSessionId: string;
1322
+ /** Makaio session ID — required for approval routing to the owning tab */
1323
+ sessionId: string;
1324
+ }
1325
+ /**
1326
+ * Options controlling how scoped approval payloads are promoted to the global schema.
1327
+ */
1328
+ interface MergeScopedToolApprovalOptions {
1329
+ /**
1330
+ * Allow `payload.sessionId` to satisfy the global request when context lacks one.
1331
+ *
1332
+ * This should stay `false` for connector-scoped RPC handlers, which must rely on
1333
+ * agent context rather than connector-provided session identity. Enable only for
1334
+ * trusted call sites that already hold a canonical global approval payload.
1335
+ */
1336
+ allowPayloadSessionFallback?: boolean;
1337
+ /**
1338
+ * Allow payload identity fields (`agentId`, `adapterId`, `adapterName`,
1339
+ * `adapterSessionId`) to satisfy the global request when context lacks them.
1340
+ *
1341
+ * This should stay `false` for connector-scoped RPC handlers, which must rely on
1342
+ * agent context rather than connector-provided identity. Enable only for trusted
1343
+ * call sites that already hold a canonical global approval payload (e.g., direct
1344
+ * bus invocations that supply the full payload without a live agent context).
1345
+ */
1346
+ allowPayloadIdentityFallback?: boolean;
1347
+ }
1348
+ /**
1349
+ * Resolve the Makaio session ID required for global tool approval routing.
1350
+ *
1351
+ * Scoped connector payloads may omit `sessionId`; agent context should normally
1352
+ * provide it. Callers may optionally allow a payload fallback when their scoped
1353
+ * payload is already trusted to carry the same value.
1354
+ * @param contextSessionId - Session ID from agent context
1355
+ * @param payloadSessionId - Optional session ID from scoped payload
1356
+ * @param sourceLabel - Short source label used in error messages
1357
+ * @param allowPayloadSessionFallback - Whether trusted callers may reuse the payload session ID
1358
+ * @returns Resolved session ID
1359
+ * @throws Error if session ID is absent from all allowed sources
1360
+ */
1361
+ declare function resolveRequiredSessionId(contextSessionId: string | undefined, payloadSessionId: string | undefined, sourceLabel: string, allowPayloadSessionFallback?: boolean): string;
1362
+ /**
1363
+ * Merge a scoped tool approval payload with agent context into the global request shape.
1364
+ *
1365
+ * All five identity fields (`sessionId`, `agentId`, `adapterId`, `adapterName`,
1366
+ * `adapterSessionId`) must come from trusted agent context by default. Payload
1367
+ * fallback for each group is enabled via the corresponding option flag.
1368
+ * @param payload - Scoped approval payload emitted by the connector
1369
+ * @param context - Agent context used to enrich the scoped payload
1370
+ * @param sourceLabel - Short source label used in error messages
1371
+ * @param options - Controls whether trusted call sites may reuse payload identity
1372
+ * @returns Global tool approval request with all required identity fields resolved
1373
+ */
1374
+ declare function mergeScopedToolApproval(payload: ScopedToolApprovalRequest, context: Partial<ToolApprovalContext>, sourceLabel: string, options?: MergeScopedToolApprovalOptions): AgentToolApproveRequest;
1375
+ /**
1376
+ * Scoped tool approval schema for adapter connector buses.
1377
+ *
1378
+ * `sessionId` is optional here because the connector emits the approval request
1379
+ * before the agent layer has enriched it. The agent's `wireToolApprovalRpc`
1380
+ * (or equivalent) injects `sessionId` from its own context before forwarding
1381
+ * to the global `AgentSubjects.toolApprove` subject, where `sessionId` is required.
1382
+ *
1383
+ * Adapters with a genuinely different wire format (e.g., gemini-sdk's callId/name)
1384
+ * should define their own schema rather than extending this one.
1385
+ */
1386
+ declare const ScopedToolApprovalSchema: {
1387
+ request: z.ZodObject<{
1388
+ agentId: z.ZodString;
1389
+ adapterId: z.ZodString;
1390
+ adapterName: z.ZodString;
1391
+ adapterSessionId: z.ZodString;
1392
+ messageId: z.ZodOptional<z.ZodString>;
1393
+ turnId: z.ZodOptional<z.ZodString>;
1394
+ clientId: z.ZodOptional<z.ZodString>;
1395
+ providerConfigId: z.ZodOptional<z.ZodString>;
1396
+ occurredAt: z.ZodOptional<z.ZodNumber>;
1397
+ toolName: z.ZodOptional<z.ZodString>;
1398
+ args: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1399
+ toolCallId: z.ZodString;
1400
+ reasoning: z.ZodOptional<z.ZodString>;
1401
+ sessionId: z.ZodOptional<z.ZodString>;
1402
+ }, z.core.$strip>;
1403
+ response: z.ZodDiscriminatedUnion<[z.ZodObject<{
1404
+ action: z.ZodLiteral<"allow">;
1405
+ updatedInput: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1406
+ updatedPermissions: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
1407
+ }, z.core.$strip>, z.ZodObject<{
1408
+ action: z.ZodLiteral<"deny">;
1409
+ message: z.ZodString;
1410
+ shouldAbort: z.ZodOptional<z.ZodBoolean>;
1411
+ }, z.core.$strip>], "action">;
1412
+ };
1413
+ /** Scoped tool approval request payload type — `sessionId` is optional at the connector layer. */
1414
+ type ScopedToolApprovalRequest = z.infer<typeof ScopedToolApprovalSchema.request>;
1415
+ /** Scoped tool approval response payload type — identical to the global response. */
1416
+ type ScopedToolApprovalResponse = z.infer<typeof ScopedToolApprovalSchema.response>;
1417
+ /**
1418
+ * Transform function signature: SDK payload → AgentToolApproveRequest.
1419
+ * @param payload - SDK-specific tool approval payload
1420
+ * @param context - Resolved tool approval context with adapter identity
1421
+ * @returns Global tool approval request for AgentSubjects.toolApprove
1422
+ */
1423
+ type ToGlobalToolApprovalFn<TPayload, TContext = ToolApprovalContext> = (payload: TPayload, context: TContext) => AgentToolApproveRequest;
1424
+ /**
1425
+ * Transform function signature: AgentToolApproveResponse → SDK response format.
1426
+ * @param response - Global tool approval response from AgentSubjects.toolApprove
1427
+ * @returns SDK-compatible response format
1428
+ */
1429
+ type FromGlobalToolApprovalFn<TResponse> = (response: AgentToolApproveResponse) => TResponse;
1430
+ /**
1431
+ * Factory: Create tool approval handler for adapter connector.
1432
+ *
1433
+ * Wires adapter-scoped tool approval subject → AgentSubjects.toolApprove.
1434
+ * Handles lazy context resolution to avoid race conditions with adapterSessionId.
1435
+ *
1436
+ * Used by both test harnesses (createTestConfig) and production (agent.ts).
1437
+ * @param subject - Adapter-scoped subject for tool approval requests
1438
+ * @param toGlobal - Transform SDK payload to global request
1439
+ * @param fromGlobal - Transform global response to SDK format
1440
+ * @returns Handler registration function
1441
+ * @example
1442
+ * ```typescript
1443
+ * // In gemini-sdk/src/tool-handling.ts
1444
+ * export const registerToolApprovalHandler = createToolApprovalHandler(
1445
+ * GeminiConnectorSubjects.acp.tool_approval,
1446
+ * toGlobalToolApproval,
1447
+ * fromGlobalToolApproval,
1448
+ * );
1449
+ * ```
1450
+ */
1451
+ declare function createToolApprovalHandler<TPayload, TContext = ToolApprovalContext, TResponse = AgentToolApproveResponse>(subject: ScopedSubjectDefinition<string>, toGlobal: ToGlobalToolApprovalFn<TPayload, TContext>, fromGlobal: FromGlobalToolApprovalFn<TResponse>): (connector: Pick<AIAgentConnector, "on">, context: TContext | (() => Promise<TContext>)) => () => void;
1452
+ //#endregion
1453
+ //#region adapters/core/src/utils/normalizeMimeType.d.ts
1454
+ /**
1455
+ * Normalize a MIME type string for comparison.
1456
+ *
1457
+ * Strips parameters (e.g., "; charset=utf-8") and converts to lowercase.
1458
+ * This ensures that values like "text/plain; charset=utf-8" or
1459
+ * "TEXT/PLAIN" are handled correctly.
1460
+ * Falls back to 'application/octet-stream' if mimeType is null/undefined.
1461
+ * @param mimeType - MIME type string to normalize.
1462
+ * @returns Normalized MIME type string (lowercase, no parameters).
1463
+ */
1464
+ declare function normalizeMimeType(mimeType: string | undefined | null): string;
1465
+ /**
1466
+ * Check if a MIME type represents text content that can be sent as a document.
1467
+ *
1468
+ * Covers `text/*` and common text-based `application/*` subtypes (JSON, XML,
1469
+ * SQL, GraphQL, JavaScript, TypeScript, YAML, TOML).
1470
+ * @param mimeType - MIME type string (parameters are allowed, e.g., "text/plain; charset=utf-8")
1471
+ * @returns True if the content is text-based.
1472
+ */
1473
+ declare function isTextLikeMimeType(mimeType: string | undefined | null): boolean;
1474
+ //#endregion
1475
+ //#region adapters/core/src/utils/resolvePresetCredentials.d.ts
1476
+ /**
1477
+ * Resolve credentials from environment variables using a provider definition's credential mapping.
1478
+ *
1479
+ * Reads `definition.credentialEnvVars` and checks `process.env` for each declared variable.
1480
+ * Only includes fields where the env var is actually set.
1481
+ * @param definition - Provider definition with optional credentialEnvVars mapping
1482
+ * @returns Object mapping credential field names to resolved values, or undefined if none resolved
1483
+ */
1484
+ declare function resolvePresetCredentials(definition: ProviderDefinitionInput): Record<string, string> | undefined;
1485
+ //#endregion
1486
+ //#region adapters/core/src/utils/createConnectorEventMapping.d.ts
1487
+ /**
1488
+ * Emit helper passed to handler functions for emitting to global subjects.
1489
+ * Automatically enriches payloads with AgentContext.
1490
+ */
1491
+ type ConnectorEmitFn = <S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext>) => Promise<void>;
1492
+ /**
1493
+ * Handler function signature for connector event mapping.
1494
+ * Receives the narrowed payload and an emit helper for further emissions.
1495
+ * Can be sync or async — async handlers are awaited.
1496
+ */
1497
+ type ConnectorEventHandlerFn<TPayload> = (payload: TPayload, emit: ConnectorEmitFn) => void | Promise<void>;
1498
+ /**
1499
+ * Handler value: either a subject definition for passthrough or a handler function.
1500
+ */
1501
+ type ConnectorEventHandlerValue<TPayload> = (SubjectDefinition & {
1502
+ $meta: {
1503
+ payload: TPayload;
1504
+ };
1505
+ }) | ConnectorEventHandlerFn<TPayload>;
1506
+ /**
1507
+ * Discriminator keys type - extracts string keys from the message type.
1508
+ */
1509
+ type DiscriminatorKeys<TMessage> = (TMessage extends object ? keyof TMessage : never) & string;
1510
+ /**
1511
+ * Discriminator values type - extracts possible values at the discriminator key.
1512
+ */
1513
+ type DiscriminatorValues<TMessage, TDiscriminator extends string> = (TMessage extends object ? TMessage[TDiscriminator & keyof TMessage] : never) & string;
1514
+ /**
1515
+ * Narrowed message type - extracts the union member matching a discriminator value.
1516
+ */
1517
+ type NarrowedMessage<TMessage, TDiscriminator extends string, K extends string> = Extract<TMessage, { [P in TDiscriminator]: K }>;
1518
+ /**
1519
+ * Complete handlers record type for connector event mapping.
1520
+ */
1521
+ type ConnectorEventHandlers<TMessage, TDiscriminator extends string> = { [K in DiscriminatorValues<TMessage, TDiscriminator>]?: ConnectorEventHandlerValue<NarrowedMessage<TMessage, TDiscriminator, K>> };
1522
+ //#endregion
1523
+ //#region adapters/core/src/agent/message-lifecycle-tracker.d.ts
1524
+ /**
1525
+ * Emit function type for global bus emissions.
1526
+ * Matches the signature of AIAgent.emitGlobal.
1527
+ */
1528
+ type EmitGlobalFn = <S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext>) => Promise<void>;
1529
+ /**
1530
+ * Configuration for MessageLifecycleTracker.
1531
+ */
1532
+ interface MessageLifecycleTrackerConfig {
1533
+ /** Function to emit events to global bus with auto-enrichment */
1534
+ emitGlobal: EmitGlobalFn;
1535
+ }
1536
+ /**
1537
+ * Tracks message lifecycle and emits corresponding events.
1538
+ *
1539
+ * Responsibilities:
1540
+ * - Track current messageId being processed
1541
+ * - Emit user_message.acknowledged / user_message.completed events
1542
+ * - Emit agent.turn.started / agent.turn.completed events
1543
+ *
1544
+ * This provides a clean separation between message lifecycle tracking
1545
+ * and the core AIAgent functionality.
1546
+ */
1547
+ declare class MessageLifecycleTracker {
1548
+ /** Current messageId being processed (set on acknowledgment, cleared on completion) */
1549
+ private currentMessageId?;
1550
+ /** Current turnId from the session orchestrator (set at sendMessage entry, cleared on completion) */
1551
+ private currentTurnId?;
1552
+ /** Emit function injected from AIAgent */
1553
+ private readonly emitGlobal;
1554
+ constructor(config: MessageLifecycleTrackerConfig);
1555
+ /**
1556
+ * Get the current messageId being processed.
1557
+ * Used by enrichPayload() to add messageId to intermediate events.
1558
+ * @returns The current messageId or undefined if no message is being processed
1559
+ */
1560
+ getCurrentMessageId(): string | undefined;
1561
+ /**
1562
+ * Set the current turnId from the session orchestrator.
1563
+ * Called at the start of sendMessage processing.
1564
+ * @param turnId - Turn ID to track, or undefined to clear
1565
+ */
1566
+ setCurrentTurnId(turnId: string | undefined): void;
1567
+ /**
1568
+ * Clear the currently tracked turn ID.
1569
+ */
1570
+ clearCurrentTurnId(): void;
1571
+ /**
1572
+ * Get the current turnId being processed.
1573
+ * Used by enrichPayload() to add turnId to intermediate events.
1574
+ * @returns The current turnId or undefined if not set
1575
+ */
1576
+ getCurrentTurnId(): string | undefined;
1577
+ /**
1578
+ * Acknowledge a message - marks turn start.
1579
+ *
1580
+ * Emits:
1581
+ * - user_message.acknowledged
1582
+ * - agent.turn.started
1583
+ * @param handle - The message handle being acknowledged
1584
+ */
1585
+ acknowledge(handle: MessageHandle): void;
1586
+ /**
1587
+ * Complete a message - marks turn end.
1588
+ *
1589
+ * Emits:
1590
+ * - agent.turn.completed (always, with outcome — paired with agent.turn.started)
1591
+ * - user_message.completed (always, with outcome)
1592
+ * @param handle - The message handle being completed
1593
+ * @param result - The completion result with outcome
1594
+ */
1595
+ complete(handle: MessageHandle, result: MessageResult): void;
1596
+ /**
1597
+ * Wire up a message handle for lifecycle tracking.
1598
+ *
1599
+ * Subscribes to the handle's acknowledgment and completion promises
1600
+ * and emits the appropriate events.
1601
+ * @param handle - The message handle to track
1602
+ * @param onTerminal - Optional callback for any terminal outcome (emits agent.complete)
1603
+ */
1604
+ track(handle: MessageHandle, onTerminal?: (messageId: string, result: MessageResult) => void): void;
1605
+ }
1606
+ //#endregion
1607
+ //#region adapters/core/src/agent/tool-call-tracker.d.ts
1608
+ /**
1609
+ * Hints for resolving tool output to its originating tool.use event.
1610
+ * Adapters provide what they can - strategies try each hint in order.
1611
+ */
1612
+ interface ResolveHints {
1613
+ /** Native provider ID (e.g., toolu_* for Claude, call_* for Codex/OpenAI) */
1614
+ nativeId?: string;
1615
+ /** Tool name for FIFO matching when no native ID available */
1616
+ toolName?: string;
1617
+ }
1618
+ type ResolveStrategy = 'nativeId' | 'toolName' | 'oldest' | 'none';
1619
+ interface ResolveResult {
1620
+ correlationId: string | null;
1621
+ strategy: ResolveStrategy;
1622
+ /** Tool name from the matched tool.use call. Undefined when no match was found. */
1623
+ toolName?: string;
1624
+ /** Arguments from the matched tool.use call. Undefined when no match was found. */
1625
+ args?: Record<string, unknown>;
1626
+ }
1627
+ /**
1628
+ * Tracks tool.use → tool.output correlation across adapters.
1629
+ *
1630
+ * Different adapters have different correlation capabilities:
1631
+ * - Claude Code: toolu_* IDs
1632
+ * - Codex/OpenAI: call_* IDs
1633
+ * - Others: may have nothing
1634
+ *
1635
+ * ToolCallTracker provides a unified interface that:
1636
+ * 1. Uses native IDs when available
1637
+ * 2. Falls back to FIFO by tool name otherwise
1638
+ * 3. Generates UUIDs for adapters without native IDs
1639
+ */
1640
+ declare class ToolCallTracker {
1641
+ private pending;
1642
+ /**
1643
+ * Register a tool.use event. Returns correlation ID to use.
1644
+ * If nativeId provided, uses that. Otherwise generates UUID.
1645
+ * @param toolName - Name of the tool being invoked
1646
+ * @param args - Tool arguments (optional, for future correlation strategies)
1647
+ * @param nativeId - Native provider ID if available
1648
+ * @returns Correlation ID to use for this tool call
1649
+ */
1650
+ register(toolName: string, args?: Record<string, unknown>, nativeId?: string): string;
1651
+ /**
1652
+ * Find correlation ID for a tool output.
1653
+ * Tries native ID first, then falls back to FIFO by tool name,
1654
+ * and finally to the oldest pending tool call.
1655
+ * @param hints - Available hints for correlation
1656
+ * @returns Correlation result with strategy metadata
1657
+ */
1658
+ resolve(hints: ResolveHints): ResolveResult;
1659
+ /**
1660
+ * Clear all pending entries.
1661
+ * Call on turn end to prevent stale entries from leaking across turns.
1662
+ */
1663
+ clear(): void;
1664
+ }
1665
+ //#endregion
1666
+ //#region adapters/core/src/agent/ai-agent.d.ts
1667
+ interface ToolOutputResolution {
1668
+ toolCallId: string;
1669
+ toolName: string;
1670
+ args?: Record<string, unknown>;
1671
+ }
1672
+ /**
1673
+ * Abstract base class for AI agents.
1674
+ *
1675
+ * Bridges adapter/agent bus subjects to connector sessions.
1676
+ * @typeParam TBus - The scoped bus type for this adapter
1677
+ * @typeParam TConnector - The connector type this agent wraps
1678
+ */
1679
+ declare abstract class AIAgent<TBus extends ScopedBus<string> = ScopedBus<string>, TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>> {
1680
+ /** The underlying connector instance (created in init) */
1681
+ protected connector: TConnector;
1682
+ protected confirmedModel?: string;
1683
+ protected initialModel?: string;
1684
+ /** Cached adapterSessionId from the last connector that had a session — survives connector swaps. */
1685
+ private lastKnownAdapterSessionId?;
1686
+ /** Cleanup functions for bus subscriptions (stable, survive connector swap) */
1687
+ private busHandlerCleanups;
1688
+ /** Whether init() has been called */
1689
+ private initialized;
1690
+ /** Runtime system prompt captured from start/initialize, preserved across connector swaps. */
1691
+ private runtimeSystemPrompt?;
1692
+ /** Runtime response schema captured from start/initialize, preserved across connector swaps. */
1693
+ private runtimeResponseSchema?;
1694
+ /** Tracks message lifecycle and emits turn events. */
1695
+ protected readonly lifecycleTracker: MessageLifecycleTracker;
1696
+ /** Tracks tool.use → tool.output correlation across adapters. */
1697
+ protected readonly toolCallTracker: ToolCallTracker;
1698
+ /** Event-focused helper for usage/tool/step emissions. */
1699
+ private readonly eventBridge;
1700
+ /** Shared turn pipeline for start/sendMessage paths. */
1701
+ private readonly turnExecutor;
1702
+ /** Runtime mutation helper for cwd/model change handlers. */
1703
+ private readonly runtimeMutationManager;
1704
+ /** Connector lifecycle helper for swap/wiring ownership. */
1705
+ private readonly connectorLifecycleManager;
1706
+ /** Payload enrichment and global emission helper. */
1707
+ private readonly payloadEmitter;
1708
+ /** Stateful lifecycle emitter for start/complete/error/session.closed. */
1709
+ private readonly lifecycleEmitter;
1710
+ /** Current content block index within the turn, reset on each turn start */
1711
+ private currentBlockIndex;
1712
+ /** Normalized config with defaults applied */
1713
+ protected readonly config: SetRequired<AIAgentConfig<TBus, TConnector>, 'globalBus'>;
1714
+ /** Available models for context window lookup */
1715
+ protected readonly availableModels?: AIModel[];
1716
+ /**
1717
+ * Create an AIAgent instance.
1718
+ *
1719
+ * Note: Does NOT create the connector yet - call init() after construction.
1720
+ * @param config - Agent configuration
1721
+ */
1722
+ constructor(config: AIAgentConfig<TBus, TConnector>);
1723
+ private getEventMetadataDefaults;
1724
+ private createLifecycleEmitter;
1725
+ /** @returns Unique agent identifier */
1726
+ get agentId(): string;
1727
+ /** @returns Adapter instance identifier */
1728
+ get adapterId(): string;
1729
+ /** @returns Adapter type name (e.g., 'claude-code', 'gemini-sdk') */
1730
+ get adapterName(): string;
1731
+ /** @returns Adapter capabilities for runtime feature detection */
1732
+ get capabilities(): string[];
1733
+ /** @returns Native tools built into the adapter */
1734
+ get nativeTools(): string[];
1735
+ /** @returns Shared Makaio sessionId */
1736
+ get sessionId(): string | undefined;
1737
+ /** @returns Initial adapter session ID from config (may differ from connector's resolved session ID) */
1738
+ protected get adapterSessionId(): string | undefined;
1739
+ /** @returns Global bus for cross-namespace communication (defaulted in constructor) */
1740
+ protected get globalBus(): IMakaioBus;
1741
+ /**
1742
+ * Initialize the agent.
1743
+ *
1744
+ * Creates the connector via the abstract createConnector() method
1745
+ * and sets up handlers for agent.* subjects with agentId filtering.
1746
+ * @throws Error if already initialized
1747
+ */
1748
+ init(): Promise<void>;
1749
+ protected emitStart(event?: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId' | 'model' | 'cwd'>): Promise<void>;
1750
+ protected emitCompletion(result: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>): Promise<void>;
1751
+ /**
1752
+ * Stash error metadata for the next emitCompletion call.
1753
+ *
1754
+ * The lifecycle tracker emits `agent.complete` with `outcome: 'error'` when the
1755
+ * message handle completes. This method runs first (from the connector's errorHandler)
1756
+ * and stashes `errorCategory` so emitCompletion can include it in the complete payload.
1757
+ *
1758
+ * No longer emits `agent.error` — all terminal events flow through `agent.complete`.
1759
+ * @param result - Error payload from the connector
1760
+ */
1761
+ protected emitError(result: Pick<z.infer<typeof AgentSchemas.complete>, 'error' | 'errorCategory'>): void;
1762
+ /**
1763
+ * Emit agent session closed event. Emits only once per session.
1764
+ * AIAdapter listens to cleanup agent and re-emit as AdapterSubjects.session.closed.
1765
+ * @param reason - Reason for session closure (e.g., 'aborted', 'closed')
1766
+ */
1767
+ protected emitSessionClosed(reason?: string): void;
1768
+ /**
1769
+ * Enrich a payload with agent context fields.
1770
+ * @param payload - The base payload to enrich
1771
+ * @returns Payload with AgentContext fields and optional messageId added
1772
+ */
1773
+ protected enrichPayload<T extends object>(payload: T): Promise<T & AgentContext & {
1774
+ messageId?: string;
1775
+ }>;
1776
+ /**
1777
+ * Emit to a global subject with automatic payload enrichment.
1778
+ * @param subject - The subject to emit to
1779
+ * @param payload - The payload (without AgentContext fields - they're added automatically)
1780
+ */
1781
+ protected emitGlobal<S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext> & {
1782
+ messageId?: string;
1783
+ }): Promise<void>;
1784
+ /**
1785
+ * Track usage and emit to global bus.
1786
+ * AIAdapter aggregates session totals from per-call usage events.
1787
+ * @param normalized - Normalized usage metrics from adapter-specific normalizer
1788
+ */
1789
+ protected trackUsage(normalized: NormalizedCallUsage): Promise<void>;
1790
+ /**
1791
+ * Get context window size for a model.
1792
+ *
1793
+ * Looks up the context window size from availableModels based on model name.
1794
+ * @param modelName - Model name to look up (defaults to confirmedModel or initialModel)
1795
+ * @returns Context window size in tokens, or undefined if not found
1796
+ */
1797
+ protected getContextWindowSize(modelName?: string): number | undefined;
1798
+ /**
1799
+ * Emit context window status for compression trigger decisions.
1800
+ *
1801
+ * Calculates fill percentage and warning level from raw metrics.
1802
+ * Called by subclasses after usage tracking with provider-specific metrics.
1803
+ * @param input - Raw metrics: currentTokens, maxTokens, optional cachedTokens
1804
+ */
1805
+ protected emitContextWindowUpdate(input: ContextWindowInput): Promise<void>;
1806
+ /**
1807
+ * Emit tool.use event with automatic correlation tracking.
1808
+ * Registers the tool call with ToolCallTracker and emits to global bus.
1809
+ * Use this instead of directly emitting to AgentSubjects.tool.use.
1810
+ * @param toolName - Name of the tool being invoked
1811
+ * @param args - Tool arguments
1812
+ * @param nativeId - Native provider ID if available (e.g., toolu_*, call_*)
1813
+ * @returns The correlation ID used (nativeId if provided, else generated UUID)
1814
+ */
1815
+ protected emitToolUse(toolName: string, args?: Record<string, unknown>, nativeId?: string): Promise<string>;
1816
+ /**
1817
+ * Emit tool.output event with automatic correlation resolution.
1818
+ * Resolves the correlation ID from ToolCallTracker using provided hints.
1819
+ * Use this instead of directly emitting to AgentSubjects.tool.output.
1820
+ * @param output - Tool output content
1821
+ * @param hints - Hints for correlation (nativeId and/or toolName)
1822
+ * @returns Resolved toolCallId, toolName (falls back to 'unknown'), and args from the matched tool.use call
1823
+ */
1824
+ protected emitToolOutput(output: string, hints: ResolveHints): Promise<ToolOutputResolution>;
1825
+ /**
1826
+ * Emit step.started event with automatic block index management.
1827
+ * Call this when a content block begins processing.
1828
+ * @param stepType - The type of step (text, reasoning, tool_use)
1829
+ * @param blockData - Optional metadata for the block (e.g., toolName for tool_use)
1830
+ * @param content - Optional content for the step (e.g., tool_call block for tool_use)
1831
+ */
1832
+ protected emitStepStarted(stepType: StepType, blockData?: BlockData, content?: SessionMessageBlock): Promise<void>;
1833
+ /**
1834
+ * Emit step.finished event with content and increment block index.
1835
+ * Call this when a content block completes processing.
1836
+ * @param stepType - The type of step that finished
1837
+ * @param content - The complete content of the step (text, reasoning, tool_call, or tool_output)
1838
+ */
1839
+ protected emitStepFinished(stepType: StepType, content: SessionMessageBlock): Promise<void>;
1840
+ /**
1841
+ * Get the current block index (for adapters that need to track it externally).
1842
+ * @returns Current block index within the turn
1843
+ */
1844
+ protected getBlockIndex(): number;
1845
+ /**
1846
+ * Increment block index (for adapters using SDK-provided indices).
1847
+ * Call after emitting step.finished if managing index externally.
1848
+ */
1849
+ protected incrementBlockIndex(): void;
1850
+ /**
1851
+ * Handle agent.sendMessage request.
1852
+ * The filter has already been applied at subscription time - this method
1853
+ * only receives messages intended for this agent.
1854
+ * Runs PreUserMessage hooks before delegating to the connector's sendMessage method.
1855
+ * Uses sessionContext signals to decide between native resume and fresh with history.
1856
+ * HookAbortError propagates to caller (session layer handles lifecycle).
1857
+ * Subclasses can override for custom handling.
1858
+ * @param ctx - Request context with payload and response methods
1859
+ */
1860
+ protected sendMessage(ctx: RequestContext<SendMessageRequestPayload, SendMessageResponsePayload>): Promise<void>;
1861
+ /**
1862
+ * Handle agent.interrupt request.
1863
+ * Delegates to the connector's native interrupt behavior.
1864
+ * @param ctx - Request context with interrupt payload
1865
+ */
1866
+ private handleInterrupt;
1867
+ /**
1868
+ * Register a cleanup function for connector wiring.
1869
+ * These cleanups are cleared on connector swap but preserved across bus handler changes.
1870
+ * @param cleanup - Cleanup function to register
1871
+ */
1872
+ protected addConnectorWiringCleanup(cleanup: () => void): void;
1873
+ /**
1874
+ * Registers a cleanup function for a global bus subscription.
1875
+ * These survive connector swaps and are cleaned up in close().
1876
+ * @param cleanup - Function to unsubscribe from the bus
1877
+ */
1878
+ protected addBusHandlerCleanup(cleanup: () => void): void;
1879
+ /**
1880
+ * Replace the current connector with a fresh one.
1881
+ *
1882
+ * Uses create-before-close pattern with rollback for safety:
1883
+ * 1. Create new connector first (old connector still alive)
1884
+ * 2. Wire events to new connector (accumulate cleanups separately)
1885
+ * 3. If successful: close old connector, assign new one
1886
+ * 4. If failed: close new connector, restore old wiring, throw
1887
+ *
1888
+ * This ensures the agent always has a working connector, even if factory or wiring fails.
1889
+ *
1890
+ * Preserves runtime overrides across sequential swaps by using current connector values
1891
+ * as baseline for non-overridden fields.
1892
+ * @param configOverrides - Optional config overrides (e.g., new cwd, model)
1893
+ * @throws Error if connector is currently processing a turn
1894
+ */
1895
+ swapConnector(configOverrides?: Partial<{
1896
+ cwd: string;
1897
+ model: string;
1898
+ providerContext: ProviderContext;
1899
+ mcpSessionContext: McpRuntimeSessionContext | McpSessionContext | LedgerSessionContext;
1900
+ }>): Promise<void>;
1901
+ /**
1902
+ * Resolve the supported reasoning levels for a given model name.
1903
+ *
1904
+ * Centralised lookup into `availableModels` so callers do not repeat the
1905
+ * find/optional-chain pattern inline.
1906
+ * @param model - Model name to look up, or `undefined` to return `undefined`
1907
+ * @returns The `supportedReasoningLevels` map for the model, or `undefined`
1908
+ */
1909
+ private getSupportedReasoningLevels;
1910
+ /**
1911
+ * Build config factory input from agent config with optional overrides.
1912
+ *
1913
+ * Explicitly maps AIAgentConfig fields to ConfigFactoryInput — avoids
1914
+ * accidentally forwarding adapter-only fields (capabilities, nativeTools, etc.)
1915
+ * into the factory.
1916
+ * @param overrides - Optional field overrides (e.g., cwd, model, adapterSessionId)
1917
+ * @returns ConfigFactoryInput ready for config factory
1918
+ */
1919
+ private buildConfigInput;
1920
+ /**
1921
+ * Create the onMessageSent callback for connector factories.
1922
+ *
1923
+ * Returns a callback that emits user_message.sent events to the global bus.
1924
+ * @returns Callback function for connector config
1925
+ */
1926
+ private createOnMessageSent;
1927
+ /**
1928
+ * Handle agent.cwd.change request — prefers native in-place change, falls back to connector swap.
1929
+ * @param ctx - Request context with newCwd payload
1930
+ */
1931
+ private handleCwdChange;
1932
+ /**
1933
+ * Handle agent.model.change request — prefers native in-place change, falls back to connector swap.
1934
+ * @param ctx - Request context with newModel payload
1935
+ */
1936
+ private handleModelChange;
1937
+ /**
1938
+ * Handle agent.mcp.servers.set request — rebuilds immediately when idle or stages for the next turn.
1939
+ * @param ctx - Request context with replacement MCP session context
1940
+ */
1941
+ private handleMcpServersSet;
1942
+ /**
1943
+ * Handle agent.credential.change request — defers when a turn is active, otherwise swaps connector.
1944
+ * @param ctx - Request context with credential change payload
1945
+ */
1946
+ private handleCredentialChanged;
1947
+ /**
1948
+ * Wire adapter-specific connector events.
1949
+ * Called automatically during init() and connector swap.
1950
+ * Subclasses implement this to set up their event mappings.
1951
+ * @param connector - Connector instance to wire
1952
+ */
1953
+ protected abstract wireEvents(connector: TConnector): void | Promise<void>;
1954
+ /**
1955
+ * Subscribe to a connector subject and register its cleanup as connector wiring.
1956
+ *
1957
+ * Use this in adapter `wireEvents()` implementations so connector swaps can
1958
+ * remove old listeners before rewiring the new connector.
1959
+ * @param connector - Connector instance to subscribe on
1960
+ * @param subject - Subject definition to subscribe to
1961
+ * @param handler - Subject handler
1962
+ * @param options - Optional bus subscription options
1963
+ */
1964
+ protected subscribeConnector<Subject extends ScopedSubjectDefinition<TConnector extends AIAgentConnector<infer TBus> ? TBus['namespace'] : never>>(connector: TConnector, subject: Subject, handler: HandlerForSubjectDefinition<Subject>, options?: OnOptions): void;
1965
+ /**
1966
+ * Clean up resources and emit session closed event.
1967
+ *
1968
+ * Emits session.closed event (once per session) unless explicitly suppressed,
1969
+ * then unsubscribes from all bus handlers and aborts the connector if available.
1970
+ * @param options - Cleanup options; ephemeral agents suppress session-close lifecycle events because they never join a session.
1971
+ */
1972
+ close(options?: {
1973
+ emitSessionClosed?: boolean;
1974
+ }): Promise<void>;
1975
+ /**
1976
+ * Ensure the connector is initialized, throwing if not.
1977
+ * @returns The initialized connector instance
1978
+ * @throws Error if connector is not initialized
1979
+ */
1980
+ private ensureConnector;
1981
+ /**
1982
+ * Determine whether to use native session resume or fresh with history.
1983
+ *
1984
+ * Native resume: SDK manages history, don't inject messageHistory, preserve cache.
1985
+ * Fresh with history: Create new session, inject messageHistory.
1986
+ *
1987
+ * Override in adapter-specific agents if needed.
1988
+ * @param sessionContext - Context signals from SessionOrchestrator
1989
+ * @returns true if native resume should be used
1990
+ */
1991
+ protected shouldUseNativeResume(sessionContext?: SessionContext): boolean;
1992
+ /**
1993
+ * Whether this adapter supports native session resume.
1994
+ * Override in adapter-specific agents that can resume SDK sessions.
1995
+ * @returns true if native resume is supported
1996
+ */
1997
+ protected supportsNativeResume(): boolean;
1998
+ /**
1999
+ * Start the agent with an initial message.
2000
+ *
2001
+ * Ensures the agent is initialized (idempotent) before delegating to the connector.
2002
+ * Runs PreUserMessage hooks before sending the message.
2003
+ * Uses sessionContext signals to decide between native resume and fresh with history.
2004
+ * HookAbortError propagates to caller.
2005
+ * @param message - User message (normalized or unnormalized)
2006
+ * @param options - Optional start options (e.g., delivery mode, sessionContext)
2007
+ * @returns Session ID, agent ID, and message handle for tracking
2008
+ */
2009
+ start(message: NormalizedMessageInput | MessageInput, options?: StartAgentOptions): Promise<AgentStartResult>;
2010
+ /**
2011
+ * Initialize the agent without sending a message (idle creation).
2012
+ * Ensures init() is called, then delegates to connector.initialize().
2013
+ * @param options - Optional initialization options (system prompt, sessionContext)
2014
+ */
2015
+ initialize(options?: StartAgentOptions): Promise<void>;
2016
+ protected onBeforeEmitCompletion(): Promise<void>;
2017
+ protected onMessageHandle(messageHandle: MessageHandle): Promise<void>;
2018
+ /**
2019
+ * Abort the agent immediately (panic mode).
2020
+ * Triggers AbortController which may cause provider errors.
2021
+ * Use close() for graceful shutdown instead.
2022
+ *
2023
+ * Emits session.closed event (once per session) then delegates
2024
+ * to the underlying connector's abort method.
2025
+ * @throws Error if connector is not initialized
2026
+ */
2027
+ abort(): void;
2028
+ /**
2029
+ * Get session ID, waiting for provider to generate it if not yet available.
2030
+ *
2031
+ * Delegates to the underlying connector's getSessionId method.
2032
+ * @returns Session ID from provider
2033
+ * @throws Error if connector is not initialized
2034
+ */
2035
+ getAdapterSessionId(): Promise<string>;
2036
+ /**
2037
+ * Complete the agent session by waiting for all messages to finish.
2038
+ *
2039
+ * Delegates to the underlying connector's complete method.
2040
+ * @returns Last message result or null if no messages processed
2041
+ * @throws Error if connector is not initialized
2042
+ */
2043
+ complete(): Promise<MessageResult | null>;
2044
+ /**
2045
+ * Creates a type-safe event mapping from connector events to scoped subjects or handlers.
2046
+ * @param sourceSubject - The connector subject to subscribe to
2047
+ * @param discriminator - The discriminator key within the message (e.g., 'type')
2048
+ * @param handlers - Map of discriminator values to target subjects or handler functions
2049
+ * @param nestedMessageProp - Property containing the discriminated union (e.g., 'msg'), or undefined for top-level
2050
+ * @returns Unsubscribe function for the connector event mapping subscription
2051
+ */
2052
+ protected createConnectorEventMapping<TSourceSubject extends ScopedSubjectDefinition<TConnector extends AIAgentConnector<infer TBus> ? TBus['namespace'] : never>, TNestedMessageProp extends keyof TSourceSubject['$meta']['payload'] | undefined = undefined, TMessage = (TNestedMessageProp extends keyof TSourceSubject['$meta']['payload'] ? TSourceSubject['$meta']['payload'][TNestedMessageProp] : TSourceSubject['$meta']['payload']), TDiscriminator extends DiscriminatorKeys<TMessage> = DiscriminatorKeys<TMessage>>(sourceSubject: TSourceSubject, discriminator: TDiscriminator, handlers: ConnectorEventHandlers<TMessage, TDiscriminator>, nestedMessageProp?: TNestedMessageProp): () => void;
2053
+ }
2054
+ //#endregion
2055
+ //#region adapters/core/src/factory/create-adapter-namespace.d.ts
2056
+ /**
2057
+ * Adapter namespace extends BusNamespace with additional metadata for adapters.
2058
+ *
2059
+ * Provides:
2060
+ * - All BusNamespace features (subjects, scoped bus factory)
2061
+ * - Raw schema access for adapter factory internals
2062
+ * - Domain name for debugging/logging
2063
+ * @typeParam N - Namespace domain string
2064
+ * @typeParam Schemas - Schema record type
2065
+ */
2066
+ type AdapterNamespace<Domain extends string = string> = Omit<BusNamespace<Domain>, 'subjects'>;
2067
+ /**
2068
+ * Creates an adapter namespace with typed subject definitions.
2069
+ *
2070
+ * **Seam:** Thin wrapper around MakaioBus.registerNamespace that:
2071
+ * - Delegates to bus-core for namespace registration
2072
+ * - Preserves FilterPayload type for type-safe withFilter()
2073
+ * - Provides extension point for future adapter-specific features
2074
+ * @param domain - Namespace domain (e.g., 'adapter:claudeCode')
2075
+ * @param schemas - Record of subject schemas (events and requests)
2076
+ * @param options - Registration options (e.g., busValidationMode for Zod version conflicts)
2077
+ * @returns Adapter namespace with typed subjects and pre-computed FilterPayload
2078
+ * @example
2079
+ * ```typescript
2080
+ * const ClaudeCodeNamespace = createAdapterNamespace('adapter:claudeCode', {
2081
+ * thinking: z.object({ content: z.string() }),
2082
+ * getContext: {
2083
+ * request: z.object({ path: z.string() }),
2084
+ * response: z.object({ content: z.string() }),
2085
+ * },
2086
+ * });
2087
+ *
2088
+ * // Access typed subjects
2089
+ * ClaudeCodeNamespace.subjects.thinking;
2090
+ *
2091
+ * // Get scoped bus with type-safe filtering
2092
+ * const bus = await ClaudeCodeNamespace.scopedBus();
2093
+ * bus.withFilter({ content: 'test' }); // ✅ Type-checked
2094
+ *
2095
+ * // For adapters with bundled Zod v3 (e.g., @github/copilot-sdk):
2096
+ * const CopilotNamespace = createAdapterNamespace('adapter:copilot', schemas, {
2097
+ * busValidationMode: 'skip', // Skip validation due to Zod version conflict
2098
+ * });
2099
+ *
2100
+ * // For adapters with lenient validation (schema drift triggers warnings, not crashes):
2101
+ * const ClaudeNamespace = createAdapterNamespace('adapter:claude-code', schemas, {
2102
+ * busValidationMode: 'lenient',
2103
+ * onSchemaViolation: (report) => console.warn(report),
2104
+ * });
2105
+ * ```
2106
+ */
2107
+ declare function createAdapterNamespace<N extends string, Schemas extends SchemaRecord>(domain: N, schemas: Schemas, options?: NamespaceRegistrationOptions): BusNamespace<N, SubjectRecordFromSchemaRecord<Schemas>, FilterablePayloadIntersection<SubjectRecordFromSchemaRecord<Schemas>>, Schemas>;
2108
+ //#endregion
2109
+ //#region adapters/core/src/factory/adapter-context.d.ts
2110
+ /**
2111
+ * Context provided to adapter implementations.
2112
+ *
2113
+ * Contains shared infrastructure and configuration that all adapters need:
2114
+ * - Adapter name and capabilities from config
2115
+ * - Local event bus for emitting events
2116
+ */
2117
+ interface AIAdapterContext<Scope extends ScopedBus<string>> {
2118
+ /** Unique adapter instance identifier. */
2119
+ adapterId: string;
2120
+ /** Unique adapter name (kebab-case). */
2121
+ name: string;
2122
+ /** Adapter capabilities (unparsed). Use parseAIAdapterCapabilities() to parse. */
2123
+ capabilities: AIAdapterCapability[];
2124
+ /** Scoped bus for adapter-level events. */
2125
+ adapterBus: Scope;
2126
+ /** Global event bus. */
2127
+ globalBus: IMakaioBus;
2128
+ }
2129
+ //#endregion
2130
+ //#region adapters/core/src/agent/agent-event-bridge.d.ts
2131
+ /**
2132
+ * Dependencies for AgentEventBridge.
2133
+ */
2134
+ interface AgentEventBridgeConfig {
2135
+ /** Emit usage payload (agent context gets added by AIAgent). */
2136
+ emitUsage: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.usage>, keyof AgentContext>) => Promise<void>;
2137
+ /** Emit context window status payload. */
2138
+ emitContextWindowUpdated: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.contextWindow.updated>, keyof AgentContext>) => Promise<void>;
2139
+ /** Emit tool.use payload. */
2140
+ emitToolUse: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.tool.use>, keyof AgentContext>) => Promise<void>;
2141
+ /** Emit tool.output payload. */
2142
+ emitToolOutput: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.tool.output>, keyof AgentContext>) => Promise<void>;
2143
+ /** Emit adapter log payload. */
2144
+ emitAdapterLog: (payload: Omit<ExtractSubjectPayload<typeof AdapterSubjects.log>, 'adapterId' | 'adapterName'>) => Promise<void>;
2145
+ /** Emit step.started payload. */
2146
+ emitStepStarted: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.step.started>, keyof AgentContext>) => Promise<void>;
2147
+ /** Emit step.finished payload. */
2148
+ emitStepFinished: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.step.finished>, keyof AgentContext>) => Promise<void>;
2149
+ /** Correlation tracker for tool.use -\> tool.output. */
2150
+ toolCallTracker: ToolCallTracker;
2151
+ /** Current content block index getter. */
2152
+ getBlockIndex: () => number;
2153
+ /** Increment block index after step completion. */
2154
+ incrementBlockIndex: () => void;
2155
+ /** Resolve model name for usage events. */
2156
+ getUsageModel: () => string | undefined;
2157
+ }
2158
+ /**
2159
+ * Resolution metadata returned when emitting tool output.
2160
+ */
2161
+ interface ToolOutputResult {
2162
+ toolCallId: string;
2163
+ toolName: string;
2164
+ args?: Record<string, unknown>;
2165
+ }
2166
+ /**
2167
+ * Event-focused helper for AIAgent.
2168
+ *
2169
+ * Keeps event payload formatting, correlation warnings, and block-indexed
2170
+ * step emissions out of the base class while preserving existing behavior.
2171
+ */
2172
+ declare class AgentEventBridge {
2173
+ private readonly emitUsagePayload;
2174
+ private readonly emitContextWindowUpdatedPayload;
2175
+ private readonly emitToolUsePayload;
2176
+ private readonly emitToolOutputPayload;
2177
+ private readonly emitAdapterLogPayload;
2178
+ private readonly emitStepStartedPayload;
2179
+ private readonly emitStepFinishedPayload;
2180
+ private readonly toolCallTracker;
2181
+ private readonly getBlockIndex;
2182
+ private readonly incrementBlockIndex;
2183
+ private readonly getUsageModel;
2184
+ /**
2185
+ * Create an event bridge with emission and correlation dependencies.
2186
+ * @param config - Event bridge dependencies (emitters, tracker, and block-index accessors)
2187
+ */
2188
+ constructor(config: AgentEventBridgeConfig);
2189
+ /**
2190
+ * Emit usage event to global bus.
2191
+ * @param normalized - Provider-normalized usage metrics
2192
+ */
2193
+ trackUsage(normalized: NormalizedCallUsage): Promise<void>;
2194
+ /**
2195
+ * Emit context window health signal.
2196
+ * @param input - Raw usage and capacity metrics
2197
+ */
2198
+ emitContextWindowUpdate(input: ContextWindowInput): Promise<void>;
2199
+ /**
2200
+ * Emit tool.use event with correlation tracking.
2201
+ * @param toolName - Tool identifier
2202
+ * @param args - Tool arguments
2203
+ * @param nativeId - Provider-native call ID
2204
+ * @returns Correlation ID for the call
2205
+ */
2206
+ emitToolUse(toolName: string, args?: Record<string, unknown>, nativeId?: string): Promise<string>;
2207
+ /**
2208
+ * Emit tool.output event with best-effort correlation resolution.
2209
+ * @param output - Tool output text
2210
+ * @param hints - Correlation hints from adapter events
2211
+ * @returns Resolved toolCallId, toolName (falls back to 'unknown'), and args from the matched tool.use call
2212
+ */
2213
+ emitToolOutput(output: string, hints: ResolveHints): Promise<ToolOutputResult>;
2214
+ /**
2215
+ * Emit step.started for the current block index.
2216
+ * @param stepType - Block step type
2217
+ * @param blockData - Optional step metadata
2218
+ * @param content - Optional immediate block content
2219
+ */
2220
+ emitStepStarted(stepType: StepType, blockData?: BlockData, content?: SessionMessageBlock): Promise<void>;
2221
+ /**
2222
+ * Emit step.finished and advance block index.
2223
+ * @param stepType - Completed step type
2224
+ * @param content - Final block content
2225
+ */
2226
+ emitStepFinished(stepType: StepType, content: SessionMessageBlock): Promise<void>;
2227
+ }
2228
+ //#endregion
2229
+ //#region adapters/core/src/agent/agent-turn-executor.d.ts
2230
+ /**
2231
+ * Runtime dependencies for AgentTurnExecutor.
2232
+ */
2233
+ interface AgentTurnExecutorConfig {
2234
+ /** Stable agent identifier. */
2235
+ agentId: string;
2236
+ /** Stable adapter identifier. */
2237
+ adapterId: string;
2238
+ /** Optional Makaio session identifier. */
2239
+ sessionId?: string;
2240
+ /** Global bus instance for hooks. */
2241
+ globalBus: IMakaioBus;
2242
+ /** Current connector reference resolver. */
2243
+ getConnector: () => AIAgentConnector;
2244
+ /** Native resume decision function. */
2245
+ shouldUseNativeResume: ShouldUseNativeResumeFn;
2246
+ /** Completion/lifecycle tracker hook. */
2247
+ onMessageHandle: (messageHandle: MessageHandle) => Promise<void>;
2248
+ /** Side-effect callback to mark agent status active before dispatch. */
2249
+ onBeforeDispatch?: () => void | Promise<void>;
2250
+ /** When true, PreUserMessage hooks are skipped. */
2251
+ ephemeral?: boolean;
2252
+ }
2253
+ /**
2254
+ * Function type for native resume decision.
2255
+ */
2256
+ type ShouldUseNativeResumeFn = (sessionContext?: StartAgentOptions['sessionContext']) => boolean;
2257
+ /**
2258
+ * Shared start/send-message execution pipeline for AIAgent.
2259
+ */
2260
+ declare class AgentTurnExecutor {
2261
+ private readonly agentId;
2262
+ private readonly adapterId;
2263
+ private readonly sessionId?;
2264
+ private readonly globalBus;
2265
+ private readonly getConnector;
2266
+ private readonly shouldUseNativeResume;
2267
+ private readonly onMessageHandle;
2268
+ private readonly onBeforeDispatch?;
2269
+ private readonly ephemeral;
2270
+ constructor(config: AgentTurnExecutorConfig);
2271
+ /**
2272
+ * Execute the turn pipeline for agent.sendMessage.
2273
+ * @param payload - agent.sendMessage request payload
2274
+ * @returns Resolved messageId from connector handle
2275
+ */
2276
+ executeSendMessage(payload: SendMessageRequestPayload): Promise<{
2277
+ messageId: string;
2278
+ }>;
2279
+ /**
2280
+ * Execute the turn pipeline for agent.start.
2281
+ * @param message - Initial message payload
2282
+ * @param options - Start options from caller
2283
+ * @param systemPrompt - Runtime system prompt chosen by AIAgent
2284
+ * @param responseSchema - Runtime response schema chosen by AIAgent
2285
+ * @returns Agent start result from connector
2286
+ */
2287
+ executeStart(message: NormalizedMessageInput | MessageInput, options: StartAgentOptions | undefined, systemPrompt: StartAgentOptions['systemPrompt'], responseSchema?: Record<string, unknown>): Promise<AgentStartResult>;
2288
+ /**
2289
+ * Resolve the pre-user hook result or preserve the caller payload for ephemeral turns.
2290
+ * @param input - Message and context for the outgoing user turn
2291
+ * @returns Message and session context to dispatch to the connector
2292
+ */
2293
+ private resolvePreUserMessageTurn;
2294
+ /**
2295
+ * Fire PostUserMessage hooks without blocking the turn.
2296
+ * @param messageId - Message ID for correlation
2297
+ */
2298
+ private firePostUserMessageHooks;
2299
+ }
2300
+ //#endregion
2301
+ //#region adapters/core/src/adapter/types.d.ts
2302
+ /** Payload type for adapter.startAgent requests. */
2303
+ type StartAgentRequestPayload = ExtractSubjectPayload<typeof AdapterSubjects.startAgent>;
2304
+ /**
2305
+ * Options for creating an agent, derived from a subset of `StartAgentRequestPayload`.
2306
+ * Used by both `handleStartAgent` and the rehydration module.
2307
+ *
2308
+ * `providerContext` is typed directly as `ProviderContext` (not via `Pick` from the
2309
+ * inferred payload type) because Zod loses the `CredentialRef` brand when it infers
2310
+ * through complex union schemas. Using the canonical TypeScript type preserves
2311
+ * the brand and ensures `resolveConnectorCredentials()` receives the correct type.
2312
+ */
2313
+ type AgentCreationOptions = Omit<Partial<Pick<StartAgentRequestPayload, 'model' | 'cwd' | 'env' | 'allowedTools' | 'disallowedTools' | 'reasoningEffort' | 'mode' | 'mcpSessionContext' | 'harnessId' | 'clientId' | 'clientProfileName' | 'providerContext' | 'ephemeral'>>, 'providerContext'> & {
2314
+ adapterSessionId?: string; /** Unresolved provider context (credential refs, not plaintext). */
2315
+ providerContext?: ProviderContext;
2316
+ };
2317
+ /**
2318
+ * Cumulative usage totals tracked per agent.
2319
+ *
2320
+ * Token totals (`totalInputTokens`, `totalOutputTokens`) are fully restored on
2321
+ * rehydration by summing persisted turn history, so they reflect the lifetime
2322
+ * of the session across process restarts.
2323
+ *
2324
+ * `totalCalls` is intentionally **not** restored on rehydration: it is reset to
2325
+ * zero on each process start because the historical number of API calls is not
2326
+ * stored per-turn with sufficient fidelity to reconstruct accurately (one turn
2327
+ * may represent multiple API calls for streaming or multi-step adapters).
2328
+ * Treat `totalCalls` as "calls since last process start", not a lifetime count.
2329
+ */
2330
+ interface AgentUsageTotals {
2331
+ totalInputTokens: number;
2332
+ totalOutputTokens: number;
2333
+ totalCalls: number;
2334
+ }
2335
+ /** Result from creating an agent runtime. */
2336
+ interface AgentRuntimeCreationResult {
2337
+ cleanup: () => void;
2338
+ }
2339
+ /**
2340
+ * Configuration for AIAdapter constructor.
2341
+ * @typeParam TBus - Scoped bus type for adapter-specific events
2342
+ */
2343
+ interface AIAdapterConfig<TBus extends ScopedBus<string> = ScopedBus<string>> {
2344
+ /** Unique adapter name (e.g., 'openai-node', 'claude-code'). */
2345
+ name: string;
2346
+ /** Adapter capabilities (e.g., ['streaming', 'tools', 'vision']). */
2347
+ capabilities: string[];
2348
+ /** Native tools built into the adapter (e.g., ['shell_command', 'apply_patch']). */
2349
+ nativeTools?: string[];
2350
+ /** Adapter namespace for creating scoped bus. Bus created lazily in init(). */
2351
+ namespace: AdapterNamespace;
2352
+ /** Optional pre-generated adapter ID. Defaults to UUID. */
2353
+ adapterId?: string;
2354
+ /** Optional global bus override. Defaults to MakaioBus singleton. */
2355
+ globalBus?: IMakaioBus;
2356
+ scopedBus?: TBus;
2357
+ /**
2358
+ * Optional log import configuration.
2359
+ * When enabled, the adapter will watch for external session logs and import them as Makaio events.
2360
+ */
2361
+ logImport?: LogImportConfig;
2362
+ /** Provider definitions for model lookup. Injected by runtime. */
2363
+ definitionProviders?: readonly AdapterProviderDefinition[];
2364
+ /** Client identifier for the application this adapter belongs to (e.g., 'claude-code', 'codex'). Omit for API-only adapters. */
2365
+ clientId?: string;
2366
+ }
2367
+ /**
2368
+ * Full constructor config including factory injections.
2369
+ *
2370
+ * Replaces the inline intersection type previously used in `AIAdapter`'s
2371
+ * constructor signature.
2372
+ * @typeParam TBus - Scoped bus type for adapter-specific events
2373
+ * @typeParam TConnector - Connector type bridging to the AI SDK
2374
+ * @typeParam TAgent - Agent implementation type (must extend AIAgent)
2375
+ */
2376
+ interface AIAdapterConstructorConfig<TBus extends ScopedBus<string>, TConnector extends AIAgentConnector<TBus>, TAgent extends AIAgent<TBus, TConnector>> extends AIAdapterConfig {
2377
+ /** Factory to create agent instances from config. */
2378
+ agentFactory: (agentConfig: AIAgentConfig<TBus, TConnector>) => TAgent;
2379
+ /** Config factory — transforms partial input into full adapter-specific config (includes adapterId). */
2380
+ configFactory: (input: ConfigFactoryInput<TBus>) => Promise<BaseAgentConnectorConfig<TBus> & {
2381
+ adapterId: string;
2382
+ }>;
2383
+ /** Connector factory — creates connector from full config (includes adapterId). */
2384
+ connectorFactory: (config: BaseAgentConnectorConfig<TBus> & {
2385
+ adapterId: string;
2386
+ }) => TConnector | Promise<TConnector>;
2387
+ /** Platform-provided defaults (cwd, env). Injected by runtime. */
2388
+ platformDefaults?: PlatformDefaults;
2389
+ /** Provider definitions for model lookup. Injected by runtime. */
2390
+ definitionProviders?: readonly AdapterProviderDefinition[];
2391
+ }
2392
+ //#endregion
2393
+ //#region adapters/core/src/agent/agent-connector-lifecycle-manager.d.ts
2394
+ /**
2395
+ * Dependencies for connector lifecycle management.
2396
+ */
2397
+ interface AgentConnectorLifecycleManagerConfig<TBus extends ScopedBus<string>, TConnector extends AIAgentConnector<TBus>> {
2398
+ /** Stable agent identifier (used for diagnostics). */
2399
+ agentId: string;
2400
+ /** Create config input for connector/config factories. */
2401
+ buildConfigInput: (overrides?: Partial<{
2402
+ cwd: string;
2403
+ model: string;
2404
+ providerContext: ProviderContext;
2405
+ adapterSessionId: string;
2406
+ mcpSessionContext: McpRuntimeSessionContext | McpSessionContext | LedgerSessionContext;
2407
+ }>) => ConfigFactoryInput<TBus>;
2408
+ /** Adapter config factory from AIAgent config. */
2409
+ configFactory: (input: ConfigFactoryInput<TBus>) => Promise<BaseAgentConnectorConfig<TBus> & {
2410
+ adapterId: string;
2411
+ }>;
2412
+ /** Connector factory from AIAgent config. */
2413
+ connectorFactory: (config: BaseAgentConnectorConfig<TBus> & {
2414
+ adapterId: string;
2415
+ }) => Promise<TConnector> | TConnector;
2416
+ /** Build onMessageSent callback for connector creation. */
2417
+ createOnMessageSent: () => (handle: MessageHandle) => void;
2418
+ /** Wire adapter-specific events on a connector instance. */
2419
+ wireEvents: (connector: TConnector) => void | Promise<void>;
2420
+ /** Emit idle lifecycle event on processing-state idle transitions. */
2421
+ emitIdle: () => Promise<void>;
2422
+ /** Get current connector for swap guards/baseline values. */
2423
+ getConnector: () => TConnector;
2424
+ /** Replace active connector reference on successful swap. */
2425
+ setConnector: (connector: TConnector) => void;
2426
+ /** Get runtime system prompt to preserve across swaps. */
2427
+ getRuntimeSystemPrompt: () => SystemPrompt | undefined;
2428
+ /** Get runtime response schema to preserve across swaps. */
2429
+ getRuntimeResponseSchema: () => Record<string, unknown> | undefined;
2430
+ /** Store latest adapter session ID for enrichment after swaps. */
2431
+ setLastKnownAdapterSessionId: (adapterSessionId: string | undefined) => void;
2432
+ }
2433
+ /**
2434
+ * Manages connector lifecycle for AIAgent.
2435
+ *
2436
+ * Owns per-connector wiring cleanup registration and swap lifecycle choreography.
2437
+ */
2438
+ declare class AgentConnectorLifecycleManager<TBus extends ScopedBus<string>, TConnector extends AIAgentConnector<TBus>> {
2439
+ /** Cleanup functions for connector event wiring (cleared on each connector swap) */
2440
+ private connectorWiringCleanups;
2441
+ private readonly config;
2442
+ constructor(config: AgentConnectorLifecycleManagerConfig<TBus, TConnector>);
2443
+ /**
2444
+ * Register a cleanup function for connector wiring.
2445
+ * @param cleanup - Cleanup function to register
2446
+ */
2447
+ addConnectorWiringCleanup(cleanup: () => void): void;
2448
+ /**
2449
+ * Clear connector wiring cleanups.
2450
+ */
2451
+ clearConnectorWiring(): void;
2452
+ /**
2453
+ * Wire base and adapter-specific connector events.
2454
+ * @param connector - Connector instance to wire
2455
+ */
2456
+ wireAllConnectorEvents(connector: TConnector): Promise<void>;
2457
+ /**
2458
+ * Replace the active connector with a fresh instance.
2459
+ *
2460
+ * Uses create-before-close pattern with rollback to preserve availability.
2461
+ * @param configOverrides - Optional runtime override fields
2462
+ */
2463
+ swapConnector(configOverrides?: Partial<{
2464
+ cwd: string;
2465
+ model: string;
2466
+ providerContext: ProviderContext;
2467
+ mcpSessionContext: McpRuntimeSessionContext | McpSessionContext | LedgerSessionContext;
2468
+ }>): Promise<void>;
2469
+ }
2470
+ //#endregion
2471
+ //#region adapters/core/src/agent/agent-lifecycle-emitter.d.ts
2472
+ /**
2473
+ * Dependencies for AgentLifecycleEmitter.
2474
+ */
2475
+ interface AgentLifecycleEmitterConfig {
2476
+ /** Stable agent identifier for persistence updates. */
2477
+ agentId: string;
2478
+ /** Global bus for best-effort status updates. */
2479
+ globalBus: IMakaioBus;
2480
+ /** Emit callback for `agent.started`. */
2481
+ emitStarted: (payload: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2482
+ /** Emit callback for `agent.complete`. */
2483
+ emitComplete: (payload: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>) => Promise<void>;
2484
+ /** Emit callback for `agent.session.closed`. */
2485
+ emitSessionClosed: (payload: {
2486
+ reason?: string;
2487
+ }) => Promise<void>;
2488
+ /** Hook executed before terminal completion emission. */
2489
+ onBeforeEmitCompletion: () => Promise<void>;
2490
+ /** Clear tool-call tracker entries on terminal outcomes. */
2491
+ clearToolCallTracker: () => void;
2492
+ }
2493
+ /**
2494
+ * Stateful lifecycle emitter for AIAgent terminal/start/session events.
2495
+ */
2496
+ declare class AgentLifecycleEmitter {
2497
+ /** Tracks whether session.closed has been emitted (emit only once). */
2498
+ private sessionClosedEmitted;
2499
+ /** Tracks whether agent.started has been emitted (lifecycle invariant). */
2500
+ private agentStartedEmitted;
2501
+ /** Tracks whether agent.complete has been emitted for the current turn. */
2502
+ private agentCompleteEmitted;
2503
+ /** Stashed error category consumed by the next emitCompletion call. */
2504
+ private pendingErrorCategory?;
2505
+ private readonly config;
2506
+ constructor(config: AgentLifecycleEmitterConfig);
2507
+ /**
2508
+ * Emit `agent.started` and reset per-turn lifecycle state.
2509
+ * @param event - Start payload without auto-enriched AgentContext fields
2510
+ */
2511
+ emitStart(event: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>): Promise<void>;
2512
+ /**
2513
+ * Reset per-turn dedup state so the next completion can fire.
2514
+ *
2515
+ * Called when a new message handle is tracked — guarantees the guard
2516
+ * resets per-turn even for adapters that don't emit `agent.started`
2517
+ * on every turn (e.g., codex emits `thread_started` once per thread).
2518
+ */
2519
+ resetTurnState(): void;
2520
+ /**
2521
+ * Emit terminal completion event with deferred error-category propagation.
2522
+ * @param result - Completion payload without AgentContext fields
2523
+ */
2524
+ emitCompletion(result: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>): Promise<void>;
2525
+ /**
2526
+ * Stash error metadata for the next completion emission.
2527
+ * @param result - Error payload from connector/runtime error handler
2528
+ */
2529
+ emitError(result: Pick<z.infer<typeof AgentSchemas.complete>, 'error' | 'errorCategory'>): void;
2530
+ /**
2531
+ * Emit `agent.session.closed` once for this agent lifecycle.
2532
+ * @param reason - Optional closure reason
2533
+ */
2534
+ emitSessionClosed(reason?: string): void;
2535
+ }
2536
+ //#endregion
2537
+ //#region adapters/core/src/agent/agent-payload-emitter.d.ts
2538
+ interface AgentPayloadEventMetadata {
2539
+ clientId?: string;
2540
+ providerConfigId?: string;
2541
+ occurredAt?: number;
2542
+ }
2543
+ interface AgentPayloadEventFields extends AgentPayloadEventMetadata {
2544
+ messageId?: string;
2545
+ turnId?: string;
2546
+ sessionId?: string;
2547
+ }
2548
+ interface EmitGlobalOptions {
2549
+ includeEventMetadata?: boolean;
2550
+ }
2551
+ /**
2552
+ * Dependencies for AgentPayloadEmitter.
2553
+ */
2554
+ interface AgentPayloadEmitterConfig {
2555
+ /** Global bus for outbound emissions. */
2556
+ globalBus: IMakaioBus;
2557
+ /** Stable agent identity fields. */
2558
+ getAgentContextBase: () => Pick<AgentContext, 'agentId' | 'adapterId' | 'adapterName'> & {
2559
+ sessionId?: string;
2560
+ };
2561
+ /** Current messageId from lifecycle tracker, if any. */
2562
+ getCurrentMessageId: () => string | undefined;
2563
+ /** Current turnId from lifecycle tracker, if any. */
2564
+ getCurrentTurnId: () => string | undefined;
2565
+ /** Connector adapterSessionId, if currently available. */
2566
+ getConnectorAdapterSessionId: () => string | undefined;
2567
+ /** Last known adapterSessionId cached across connector swaps. */
2568
+ getLastKnownAdapterSessionId: () => string | undefined;
2569
+ /** Persist latest adapterSessionId after resolution. */
2570
+ setLastKnownAdapterSessionId: (adapterSessionId: string | undefined) => void;
2571
+ /** Async fallback to wait for adapter session ID. */
2572
+ getAdapterSessionId: () => Promise<string>;
2573
+ /** Live event metadata defaults resolved from current runtime state. */
2574
+ getEventMetadataDefaults: () => AgentPayloadEventMetadata;
2575
+ }
2576
+ /**
2577
+ * Handles agent context enrichment and global bus emissions.
2578
+ */
2579
+ declare class AgentPayloadEmitter {
2580
+ private readonly config;
2581
+ /**
2582
+ * Create a payload emitter with context resolution dependencies.
2583
+ * @param config - Config controlling agent-context enrichment and global emissions
2584
+ */
2585
+ constructor(config: AgentPayloadEmitterConfig);
2586
+ /**
2587
+ * Enrich payload with agent context fields.
2588
+ * @param payload - Base payload to enrich
2589
+ * @param overrideMessageId - Explicit messageId override from caller payload
2590
+ * @param options - Enrichment controls for optional analytics metadata defaults
2591
+ * @returns Enriched payload with agent context
2592
+ */
2593
+ enrichPayload<T extends object>(payload: T, overrideMessageId?: string, options?: EmitGlobalOptions): Promise<T & AgentContext & AgentPayloadEventFields>;
2594
+ /**
2595
+ * Emit enriched payload to global bus.
2596
+ * @param subject - Subject definition to emit
2597
+ * @param payload - Payload without AgentContext fields
2598
+ * @param options - Enrichment controls for optional analytics metadata defaults
2599
+ */
2600
+ emitGlobal<S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext> & {
2601
+ messageId?: string;
2602
+ }, options?: EmitGlobalOptions): Promise<void>;
2603
+ }
2604
+ //#endregion
2605
+ //#region adapters/core/src/agent/agent-bus-handler-registrar.d.ts
2606
+ /**
2607
+ * Handler bundle required to register all `agent.*` request handlers.
2608
+ */
2609
+ interface AgentBusHandlerRegistrarConfig {
2610
+ /** Global bus instance where handlers are registered. */
2611
+ globalBus: IMakaioBus;
2612
+ /** Target agent identity for filter scoping. */
2613
+ agentId: string;
2614
+ /** Handler for `agent.sendMessage`. */
2615
+ onSendMessage: (ctx: RequestContext<SendMessageRequestPayload, SendMessageResponsePayload>) => Promise<void>;
2616
+ /** Handler for `agent.interrupt`. */
2617
+ onInterrupt: (ctx: RequestContext<AgentInterruptRequestPayload, AgentInterruptResponsePayload>) => Promise<void>;
2618
+ /** Provider for `agent.getCapabilities` response payload. */
2619
+ getCapabilities: () => GetCapabilitiesResponsePayload;
2620
+ /** Handler for `agent.cwd.change`. */
2621
+ onCwdChange: (ctx: RequestContext<AgentCwdChangeRequestPayload, AgentCwdChangeResponsePayload>) => Promise<void>;
2622
+ /** Handler for `agent.model.change`. */
2623
+ onModelChange: (ctx: RequestContext<AgentModelChangeRequestPayload, AgentModelChangeResponsePayload>) => Promise<void>;
2624
+ /** Handler for `agent.mcp.servers.set`. */
2625
+ onMcpServersSet: (ctx: RequestContext<AgentMcpServersSetRequestPayload, AgentMcpServersSetResponsePayload>) => Promise<void>;
2626
+ /** Handler for `agent.credential.change`. */
2627
+ onCredentialChange: (ctx: RequestContext<AgentCredentialChangeRequestPayload, AgentCredentialChangeResponsePayload>) => Promise<void>;
2628
+ }
2629
+ /**
2630
+ * Register all stable `agent.*` bus handlers for a single agent instance.
2631
+ * @param config - Registration configuration with handlers
2632
+ * @returns Cleanup functions for all registrations
2633
+ */
2634
+ declare function registerAgentBusHandlers(config: AgentBusHandlerRegistrarConfig): Array<() => void>;
2635
+ //#endregion
2636
+ //#region adapters/core/src/agent/agent-runtime-mutation-manager-config.d.ts
2637
+ /** Connector fields that can be overridden during runtime connector swaps. */
2638
+ interface AgentRuntimeConnectorOverrides {
2639
+ cwd: string;
2640
+ model: string;
2641
+ providerContext: ProviderContext;
2642
+ mcpSessionContext: McpRuntimeSessionContext | McpSessionContext | LedgerSessionContext;
2643
+ }
2644
+ /** Dependencies for runtime mutation handling. */
2645
+ interface AgentRuntimeMutationManagerConfig {
2646
+ /** Stable agent identifier. */
2647
+ agentId: string;
2648
+ /** Optional Makaio session identifier. */
2649
+ sessionId?: string;
2650
+ /** Global bus for persistence and events. */
2651
+ globalBus: IMakaioBus;
2652
+ /** Read current connector. */
2653
+ getConnector: () => AIAgentConnector;
2654
+ /** Swap connector with runtime overrides. */
2655
+ swapConnector: (configOverrides?: Partial<AgentRuntimeConnectorOverrides>) => Promise<void>;
2656
+ /** Emit cwd.changed payload. */
2657
+ emitCwdChanged: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.cwd.changed>, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2658
+ /** Emit model.changed payload. */
2659
+ emitModelChanged: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.model.changed>, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2660
+ /** Read the agent's current provider context for no-op detection. */
2661
+ getProviderContext: () => ProviderContext | undefined;
2662
+ /** Persist provider context changes on agent config for sequential swaps. */
2663
+ setProviderContext: (providerContext: ProviderContext) => void;
2664
+ /** Persist reasoning effort changes on agent config for sequential swaps. */
2665
+ setReasoningEffort: (reasoningEffort: AIReasoningLevel$1 | undefined) => void;
2666
+ /** Persist MCP session context changes on agent config for sequential swaps. */
2667
+ setMcpSessionContext: (mcpSessionContext: McpRuntimeSessionContext | McpSessionContext | LedgerSessionContext | undefined) => void;
2668
+ /** Resolve supported reasoning levels for a model from the agent's available models. */
2669
+ resolveSupportedReasoningLevels: (model: string) => ReasoningLevelMap$1 | undefined;
2670
+ }
2671
+ //#endregion
2672
+ //#region adapters/core/src/agent/agent-runtime-mutation-manager.d.ts
2673
+ /**
2674
+ * Handles runtime mutation requests for AIAgent (cwd/model/credential changes).
2675
+ */
2676
+ declare class AgentRuntimeMutationManager {
2677
+ private readonly agentId;
2678
+ private readonly sessionId?;
2679
+ private readonly globalBus;
2680
+ private readonly getConnector;
2681
+ private readonly swapConnector;
2682
+ private readonly emitCwdChanged;
2683
+ private readonly emitModelChanged;
2684
+ private readonly getProviderContext;
2685
+ private readonly setProviderContext;
2686
+ private readonly setReasoningEffort;
2687
+ private readonly setMcpSessionContext;
2688
+ private readonly resolveSupportedReasoningLevels;
2689
+ private readonly mcpServersMutationManager;
2690
+ private readonly credentialChangeSequencer;
2691
+ private stagedModelChange?;
2692
+ constructor(config: AgentRuntimeMutationManagerConfig);
2693
+ /**
2694
+ * Handle `agent.cwd.change` request.
2695
+ * @param payload - CWD change request payload
2696
+ * @returns CWD mutation response payload
2697
+ */
2698
+ handleCwdChange(payload: AgentCwdChangeRequestPayload): Promise<AgentCwdChangeResponsePayload>;
2699
+ /**
2700
+ * Apply staged runtime mutations before dispatching the next user turn.
2701
+ *
2702
+ * Staged changes are accepted while a turn is active, but they must not touch
2703
+ * the live connector until the next turn boundary. The turn executor calls
2704
+ * this before handing a new message to the connector, when the connector is
2705
+ * expected to be idle.
2706
+ */
2707
+ applyStagedMutations(): Promise<void>;
2708
+ /**
2709
+ * Handle `agent.mcp.servers.set` request.
2710
+ * @param payload - MCP server replacement request payload
2711
+ * @returns MCP mutation response payload
2712
+ */
2713
+ handleMcpServersSet(payload: AgentMcpServersSetRequestPayload): Promise<AgentMcpServersSetResponsePayload>;
2714
+ /**
2715
+ * Handle `agent.model.change` request.
2716
+ *
2717
+ * Implements a four-branch decision tree based on the presence of `newModel`
2718
+ * and `reasoningEffort` in the request payload:
2719
+ *
2720
+ * - Both present → change model, then apply reasoningEffort (with fallback)
2721
+ * - Model only → change model, run fallback chain for reasoning
2722
+ * - Effort only → change reasoning in-place, no model swap logic
2723
+ * - Neither → no-op (return current state)
2724
+ * @param payload - Model change request payload
2725
+ * @returns Model mutation response payload
2726
+ */
2727
+ handleModelChange(payload: AgentModelChangeRequestPayload): Promise<AgentModelChangeResponsePayload>;
2728
+ /**
2729
+ * Apply an in-place reasoning-effort change when no model swap is requested.
2730
+ * @param connector - The active connector
2731
+ * @param currentModel - Current model identifier
2732
+ * @param previousReasoningEffort - Reasoning effort before this change
2733
+ * @param reasoningEffort - Requested effort level
2734
+ * @returns Model mutation response payload
2735
+ */
2736
+ private handleReasoningOnlyChange;
2737
+ /**
2738
+ * Execute the model-swap path, settling the connector then resolving reasoning.
2739
+ *
2740
+ * **Fallback chain** for reasoning when the request does not specify an effort level:
2741
+ * 1. Previous connector's `currentReasoningEffort` — if supported by the new model
2742
+ * 2. `'medium'` — if supported by the new model
2743
+ * 3. First key declared in the new model's `supportedReasoningLevels`
2744
+ * 4. `undefined` — model does not support reasoning
2745
+ * @param options - Swap options bundle
2746
+ * @returns Model mutation response payload
2747
+ */
2748
+ private handleModelSwap;
2749
+ /**
2750
+ * Resolve the reasoning effort to apply after a model change.
2751
+ *
2752
+ * Fallback chain:
2753
+ * 1. Requested `effort` — if supported by the new model
2754
+ * 2. Previous connector's `currentReasoningEffort` — if supported by the new model
2755
+ * 3. `'medium'` — if supported by the new model
2756
+ * 4. First key declared in `supportedReasoningLevels`
2757
+ * 5. `undefined` — model does not support reasoning
2758
+ * @param requestedEffort - Effort level from the change request (may be absent)
2759
+ * @param previousEffort - Current connector's reasoning effort before the change
2760
+ * @param supportedLevels - Reasoning levels declared by the new model
2761
+ * @returns The resolved reasoning level, or `undefined` if unsupported
2762
+ */
2763
+ private resolveReasoningEffort;
2764
+ /**
2765
+ * Confirm a connector swap when the model itself changes.
2766
+ *
2767
+ * Provider-only swaps skip the dialog because there is no model transition to
2768
+ * explain to the user. Model changes retain the existing warning/edit-history
2769
+ * workflow.
2770
+ * @param currentModel - Active model before the requested swap
2771
+ * @param newModel - Requested target model
2772
+ * @param skipWarning - Whether trusted callers opted out of the warning UI
2773
+ * @returns Proceed/result tuple for the caller
2774
+ */
2775
+ private confirmConnectorSwap;
2776
+ /**
2777
+ * Compare provider contexts using the full public-bus shape.
2778
+ *
2779
+ * Provider switches are not limited to config identity. Endpoint overrides,
2780
+ * credential refs, and env-var mappings all influence connector behaviour, so
2781
+ * callers that mutate any of those fields must force a connector rebuild.
2782
+ * @param current - Persisted agent provider context
2783
+ * @param next - Incoming provider context from the mutation request
2784
+ * @returns True when the effective provider configuration changed
2785
+ */
2786
+ private hasProviderContextChanged;
2787
+ /**
2788
+ * Compare two string-keyed records, treating absent and empty consistently.
2789
+ * @param left - First record
2790
+ * @param right - Second record
2791
+ * @returns True when both records contain the same keys and values
2792
+ */
2793
+ private haveEqualStringRecords;
2794
+ /**
2795
+ * Handle a credential rotation request.
2796
+ *
2797
+ * When a turn is active, returns `{ success: false, reason: 'turn_active' }`.
2798
+ * Otherwise:
2799
+ * 1. Rebuilds provider context from storage (validates providerConfigId)
2800
+ * 2. Fires `credential.activate` so extensions prepare native stores
2801
+ * 3. Swaps the connector with updated providerContext (forces re-resolution)
2802
+ * @param payload - Credential change request payload
2803
+ * @returns Success/failure result
2804
+ */
2805
+ handleCredentialChanged(payload: AgentCredentialChangeRequestPayload): Promise<AgentCredentialChangeResponsePayload>;
2806
+ /**
2807
+ * Persist runtime field updates to agent storage.
2808
+ * @param changes - CWD/model/provider mutations to persist
2809
+ */
2810
+ private persistRuntimeMutation;
2811
+ }
2812
+ //#endregion
2813
+ //#region adapters/core/src/agent/mcp-call-extractor.d.ts
2814
+ /**
2815
+ * Utilities for identifying and extracting target information from `mcp_call`
2816
+ * tool invocations.
2817
+ *
2818
+ * The `mcp_call` meta-tool carries its real target as the `tool` field in the
2819
+ * parsed JSON arguments. These helpers centralise that extraction logic so
2820
+ * every consumer (ledger, event bridge, analytics) uses a single, tested path.
2821
+ * @packageDocumentation
2822
+ */
2823
+ /**
2824
+ * Extract the target MCP tool name from parsed `mcp_call` arguments.
2825
+ *
2826
+ * Conforms to the `mcp_call` input schema which defines `{ tool: z.string() }`.
2827
+ * Returns `undefined` for any non-conformant argument shape so callers can
2828
+ * skip processing without throwing.
2829
+ * @param args - Parsed JSON arguments object from the tool call
2830
+ * @returns The namespaced target tool name, or `undefined` if not conformant
2831
+ */
2832
+ declare function extractMcpCallTarget(args: Record<string, unknown>): string | undefined;
2833
+ /**
2834
+ * Check whether a tool call name refers to the `mcp_call` meta-tool.
2835
+ *
2836
+ * Uses the canonical {@link MCP_CALL_TOOL_NAME} constant so the comparison
2837
+ * stays in sync with the toolset definition automatically.
2838
+ *
2839
+ * Callers are responsible for stripping provider-specific prefixes before
2840
+ * calling this function (e.g., Gemini's `default_api.` prefix must be
2841
+ * removed at the call site — see `execute-tool-calls.ts` normalizedToolName).
2842
+ * @param toolName - Normalized tool name from the tool call
2843
+ * @returns `true` if this is an `mcp_call` invocation
2844
+ */
2845
+ declare function isMcpCallTool(toolName: string): boolean;
2846
+ //#endregion
2847
+ //#region adapters/core/src/adapter/ai-adapter.d.ts
2848
+ /**
2849
+ * Base class for AI adapters.
2850
+ *
2851
+ * An adapter manages a set of agents, handles adapter.* subjects as RPC endpoints,
2852
+ * and provides clear file-to-subject mapping.
2853
+ *
2854
+ * Three-layer architecture:
2855
+ * - AIAdapter: Handles adapter.* global subjects, owns agent tracking
2856
+ * - AIAgent: Handles agent.* global subjects (filtered by agentId), wraps connector
2857
+ * - AIAgentConnector: Owns adapter-specific namespace, SDK-level bridge
2858
+ *
2859
+ * Subject Ownership:
2860
+ * - `adapter.startAgent` - Creates and starts new agents (owned by AIAdapter)
2861
+ * - `adapter.initialized` - Emitted when adapter is ready (owned by AIAdapter)
2862
+ * - `adapter.session.created` - Emitted after agent starts (owned by AIAdapter)
2863
+ * - `session.agent.added` - Emitted to notify global session service (owned by AIAdapter)
2864
+ * - `agent.*` subjects - Owned by agent instances (see ai-agent.ts)
2865
+ * @typeParam TBus - Scoped bus type for adapter-specific events
2866
+ * @typeParam TConnector - Connector type bridging to the AI SDK
2867
+ * @typeParam TAgent - Agent implementation type (must extend AIAgent)
2868
+ */
2869
+ declare abstract class AIAdapter<TBus extends ScopedBus<string> = ScopedBus<string>, TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>, TAgent extends AIAgent<TBus, TConnector> = AIAgent<TBus, TConnector>> {
2870
+ /** Unique identifier for this adapter instance. */
2871
+ readonly adapterId: string;
2872
+ /** Adapter name (e.g., 'openai-node', 'claude-code'). */
2873
+ readonly name: string;
2874
+ /** Adapter capabilities for runtime feature detection. */
2875
+ readonly capabilities: string[];
2876
+ /** Native tools built into the adapter (e.g., ['shell_command', 'apply_patch']). */
2877
+ readonly nativeTools: string[];
2878
+ /** Adapter namespace for creating scoped bus. */
2879
+ protected readonly namespace: AdapterNamespace;
2880
+ /** Global bus for cross-adapter communication. */
2881
+ protected readonly globalBus: IMakaioBus;
2882
+ /** Scoped bus for adapter-specific communication. Created in init(). */
2883
+ protected adapterBus: TBus;
2884
+ /** Registry of active agents with session info and usage totals. */
2885
+ private readonly registry;
2886
+ /** Cleanup functions for bus subscriptions. */
2887
+ private cleanupFns;
2888
+ /** Manages agent rehydration with single-flight deduplication. */
2889
+ private readonly rehydrationManager;
2890
+ /** Tracks whether the adapter has been initialized. */
2891
+ private initialized;
2892
+ /** Client identifier for the application this adapter belongs to (e.g., 'claude-code', 'codex'). */
2893
+ protected readonly clientId?: string;
2894
+ /** Platform-provided defaults (cwd, env) injected by runtime. Lowest priority. */
2895
+ protected platformDefaults?: PlatformDefaults;
2896
+ /** Provider definitions for model lookup. Injected by runtime. */
2897
+ protected readonly definitionProviders: readonly AdapterProviderDefinition[];
2898
+ protected agentFactory: (agentConfig: AIAgentConfig<TBus, TConnector>) => TAgent;
2899
+ /** Config factory - transforms partial input into full adapter-specific config (includes adapterId) */
2900
+ protected configFactory: (input: ConfigFactoryInput<TBus>) => Promise<BaseAgentConnectorConfig<TBus> & {
2901
+ adapterId: string;
2902
+ }>;
2903
+ /** Connector factory - creates connector from full config (includes adapterId) */
2904
+ protected connectorFactory: (config: BaseAgentConnectorConfig<TBus> & {
2905
+ adapterId: string;
2906
+ }) => TConnector | Promise<TConnector>;
2907
+ /**
2908
+ * Create a new AIAdapter instance.
2909
+ * Constructor is synchronous - stores config only. Call init() to complete setup.
2910
+ * @param config - Adapter configuration
2911
+ */
2912
+ protected constructor(config: AIAdapterConstructorConfig<TBus, TConnector, TAgent>);
2913
+ /** Set up RPC handlers and event listeners. */
2914
+ private setupHandlers;
2915
+ /**
2916
+ * Handle agent.session.closed - cleanup agent + re-emit as adapter.session.closed.
2917
+ * @param ctx - Event context with session closed payload
2918
+ */
2919
+ private handleSessionClosed;
2920
+ /**
2921
+ * Handle session.closed - evict agents when their session is closed.
2922
+ * @param ctx - Event context with the closed session's ID
2923
+ */
2924
+ private handleSessionClosedByService;
2925
+ /**
2926
+ * Handle agent.usage - aggregate and emit session totals.
2927
+ * @param ctx - Event context with usage payload
2928
+ */
2929
+ private handleUsage;
2930
+ /**
2931
+ * Initialize adapter - call after construction.
2932
+ * Creates scoped bus, sets up handlers, and emits adapter.initialized event.
2933
+ * Safe to call multiple times - subsequent calls are no-ops.
2934
+ *
2935
+ * Note: Agents are NOT eagerly rehydrated on startup. They are rehydrated
2936
+ * on-demand when messages arrive (lazy rehydration via handleRehydrateAgent).
2937
+ */
2938
+ init(): Promise<void>;
2939
+ /** Hook for subclass initialization. Override to perform async setup (connections, auth, etc.). */
2940
+ protected onInit(): Promise<void>;
2941
+ /**
2942
+ * Create an agent instance.
2943
+ *
2944
+ * Subclasses implement this to instantiate their specific AIAgent subclass.
2945
+ * The agent should NOT be started yet - that's handled by startAgent after creation.
2946
+ * @param agentId - Pre-generated agent ID (use this, don't generate your own)
2947
+ * @param sessionId - Makaio session ID (created or provided based on mode)
2948
+ * @param request - The startAgent request payload
2949
+ * @returns The agent instance (NOT started yet)
2950
+ */
2951
+ protected createAgent(agentId: string, sessionId: string, request: AgentCreationOptions): Promise<TAgent>;
2952
+ /**
2953
+ * Asynchronous cleanup for awaitable shutdown.
2954
+ * Runs cleanup functions, aborts agents, allows subclass cleanup via onClose hook.
2955
+ * @returns Promise that resolves when cleanup is complete
2956
+ */
2957
+ closeAsync(): Promise<void>;
2958
+ /**
2959
+ * Cleanup resources and unsubscribe from bus.
2960
+ * Runs cleanup functions, aborts agents, allows subclass cleanup via onClose hook.
2961
+ */
2962
+ close(): void;
2963
+ /** Hook for subclass cleanup. Override to perform async teardown (close connections, etc.). */
2964
+ protected onClose(): Promise<void>;
2965
+ /**
2966
+ * Get an agent by ID with session info.
2967
+ * @param agentId - Agent identifier
2968
+ * @returns Agent with session info, or undefined if not found
2969
+ */
2970
+ getAgent(agentId: string): (TAgent & {
2971
+ sessionId: string;
2972
+ adapterSessionId: string;
2973
+ }) | undefined;
2974
+ /**
2975
+ * Dispose resources for an agent.
2976
+ *
2977
+ * Aborts the agent and removes it from the tracking map.
2978
+ * @param agentId - Agent identifier
2979
+ * @returns true if agent was found and disposed, false otherwise
2980
+ */
2981
+ disposeAgent(agentId: string): boolean;
2982
+ /**
2983
+ * Get all active agents managed by this adapter.
2984
+ * @returns Array of active agents with session info
2985
+ */
2986
+ getActiveAgents(): Array<TAgent & {
2987
+ sessionId: string;
2988
+ adapterSessionId: string;
2989
+ }>;
2990
+ /**
2991
+ * Check if the adapter has been initialized.
2992
+ * @returns true if init() has been called successfully
2993
+ */
2994
+ isInitialized(): boolean;
2995
+ }
2996
+ //#endregion
2997
+ //#region adapters/core/src/types/ai-adapter-definition.d.ts
2998
+ /**
2999
+ * Definition for registering adapters with the runtime.
3000
+ *
3001
+ * Extends {@link AdapterDefinitionContract} with narrowed generic type parameters
3002
+ * so the `providers` array and `createAdapter` factory are typed against the
3003
+ * concrete adapter, connector, and bus types for this implementation.
3004
+ *
3005
+ * Used for dynamic adapter loading and registry.
3006
+ * @typeParam TBus - The scoped bus type for this adapter
3007
+ * @typeParam TConnector - The connector type
3008
+ * @typeParam TAgent - The agent type
3009
+ * @example
3010
+ * ```typescript
3011
+ * export const adapterDefinition: AIAdapterDefinition<OpenAINodeBus, OpenAINodeConnector, OpenAIAgent> = {
3012
+ * name: 'openai-node',
3013
+ * displayName: 'OpenAI',
3014
+ * description: 'OpenAI chat completions with streaming and tool calling',
3015
+ * createAdapter: (options) => createOpenAINodeAdapter({ adapterId: options?.adapterId }),
3016
+ * };
3017
+ * ```
3018
+ */
3019
+ interface AIAdapterDefinition<TBus extends ScopedBus<string> = ScopedBus<string>, TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>, TAgent extends AIAgent<TBus, TConnector> = AIAgent<TBus, TConnector>> extends AdapterDefinitionContract<AIAdapter<TBus, TConnector, TAgent>, AIAdapterInitOptions> {
3020
+ /**
3021
+ * Client packages this adapter can delegate to.
3022
+ *
3023
+ * Each reference names a client extension by stable ID and declares the
3024
+ * compatible client package version range. Runtime initialization still
3025
+ * receives a selected `clientId` through {@link AIAdapterInitOptions}; this
3026
+ * definition field is the adapter-to-client capability declaration.
3027
+ */
3028
+ readonly clients?: readonly AdapterClientRef[];
3029
+ /**
3030
+ * Adapter definitions declare client compatibility through {@link clients}.
3031
+ *
3032
+ * `AIAdapterInitOptions.clientId` remains the runtime-selected client
3033
+ * override passed to adapter factories for existing client-backed adapters.
3034
+ */
3035
+ readonly clientId?: never;
3036
+ /**
3037
+ * Factory that creates and initializes the adapter instance.
3038
+ *
3039
+ * Inherits the typed {@link AIAdapterInitOptions} parameter from the base
3040
+ * contract's `TOptions` generic, carrying platform defaults, log import
3041
+ * config, and provider definitions injected at runtime.
3042
+ * @param options - Optional initialization options injected by the runtime.
3043
+ * @returns The initialized adapter instance.
3044
+ */
3045
+ readonly createAdapter: (options?: AIAdapterInitOptions) => Promise<AIAdapter<TBus, TConnector, TAgent>>;
3046
+ }
3047
+ //#endregion
3048
+ //#region adapters/core/src/types/messaging.d.ts
3049
+ /**
3050
+ * Options for `AIAdapter.promptText()`.
3051
+ *
3052
+ * Minimal universal parameters with provider-specific escape hatch.
3053
+ * @example
3054
+ * ```typescript
3055
+ * await adapter.promptText("Build an auth system", {
3056
+ * model: "gpt-4o",
3057
+ * sessionId: "user-123-conv-456",
3058
+ * providerOptions: { temperature: 0.7 }
3059
+ * });
3060
+ * ```
3061
+ * @see {@link AIAdapterPromptResult} for response type
3062
+ * @see `AIAdapter.promptText` for usage
3063
+ * @see [Message Handling Guide](../../docs/message-handling.md)
3064
+ */
3065
+ interface AIAdapterPromptOptions {
3066
+ /** Model identifier (provider-specific). Defaults to adapter's configured model if omitted. */
3067
+ model?: string;
3068
+ /** Session ID for conversation continuity. Creates new session if omitted. Check `caps.sessionResume` for persistence support. */
3069
+ sessionId?: string;
3070
+ /** Provider-specific options (temperature, tools, system prompts, etc.). Type explicitly in adapter implementations. */
3071
+ providerOptions?: unknown;
3072
+ }
3073
+ /**
3074
+ * Successful prompt result with text response.
3075
+ * @see {@link AIAdapterPromptResult} for discriminated union
3076
+ */
3077
+ interface AIAdapterPromptSuccessResult {
3078
+ /** Complete text response from AI model. For streaming events, contains final assembled text. */
3079
+ text: string;
3080
+ }
3081
+ /**
3082
+ * Failed prompt result. Adapters return errors as values rather than throwing.
3083
+ * @see {@link AIAdapterPromptResult} for discriminated union
3084
+ */
3085
+ interface AIAdapterPromptFailureResult {
3086
+ /** Error message (string) or Error object describing failure. */
3087
+ error: string | Error;
3088
+ }
3089
+ /**
3090
+ * Result from `AIAdapter.promptText()`. Discriminated union of success/failure.
3091
+ * @example
3092
+ * ```typescript
3093
+ * const result = await adapter.promptText("Build auth");
3094
+ *
3095
+ * if ('error' in result) {
3096
+ * console.error('Failed:', result.error);
3097
+ * } else {
3098
+ * console.debug('Success:', result.text);
3099
+ * }
3100
+ * ```
3101
+ * @see {@link AIAdapterPromptSuccessResult} for success structure
3102
+ * @see {@link AIAdapterPromptFailureResult} for failure structure
3103
+ * @see `AIAdapter.promptText` for usage
3104
+ * @see [Message Handling Guide](../../docs/message-handling.md)
3105
+ */
3106
+ type AIAdapterPromptResult = AIAdapterPromptFailureResult | AIAdapterPromptSuccessResult;
3107
+ //#endregion
3108
+ //#region adapters/core/src/types/mcp-integration.d.ts
3109
+ /**
3110
+ * Describes a change to the MCP tool set mid-session.
3111
+ * Delivered to adapters that support mid-session tool changes.
3112
+ */
3113
+ interface McpToolChange {
3114
+ /** Tools newly available */
3115
+ readonly added: readonly McpToolState[];
3116
+ /** Tools no longer available */
3117
+ readonly removed: readonly string[];
3118
+ }
3119
+ /**
3120
+ * Discriminated union of resources an adapter receives from McpService.
3121
+ * Uses Makaio-native types, NOT SDK-specific types.
3122
+ * Each adapter converts to its SDK's format internally.
3123
+ */
3124
+ type McpSessionResources = {
3125
+ readonly mode: 'native-passthrough';
3126
+ readonly servers: Record<string, McpResolvedServer>;
3127
+ } | {
3128
+ readonly mode: 'tool-injection';
3129
+ readonly tools: readonly ToolListItem[];
3130
+ } | {
3131
+ readonly mode: 'observe-only';
3132
+ };
3133
+ /**
3134
+ * Adapter-specific MCP consumption strategy.
3135
+ *
3136
+ * Each adapter that supports MCP implements this interface to declare
3137
+ * how it consumes MCP tools. Defined in adapter-core to avoid circular
3138
+ * dependencies (McpService imports this interface, adapters implement it).
3139
+ */
3140
+ interface McpIntegrationStrategy {
3141
+ /** What this adapter needs from McpService */
3142
+ readonly mode: 'native-passthrough' | 'tool-injection' | 'observe-only';
3143
+ /**
3144
+ * Whether this adapter supports mid-session tool list changes.
3145
+ * If false, deferred injection is used (bridge current turn, native next turn).
3146
+ */
3147
+ readonly supportsMidSessionToolChange: boolean;
3148
+ /**
3149
+ * Called when a session starts. Returns adapter-specific resources.
3150
+ * @param context - Resolved MCP config for this session (post-visibility-chain)
3151
+ * @returns Resources the adapter needs to consume MCP tools
3152
+ */
3153
+ prepareMcpForSession(context: McpSessionContext): Promise<McpSessionResources>;
3154
+ /**
3155
+ * Called when MCP tools change mid-session (server reconnect, dynamic enable).
3156
+ * Only invoked if `supportsMidSessionToolChange` is true.
3157
+ * @param changes - Description of what tools changed
3158
+ */
3159
+ onToolsChanged?(changes: McpToolChange): Promise<void>;
3160
+ }
3161
+ //#endregion
3162
+ //#region adapters/core/src/types/conformance-test-config.d.ts
3163
+ /**
3164
+ * Identifies a specific model offering for test execution.
3165
+ *
3166
+ * Resolves to a provider definition ID + model name, optionally with a default
3167
+ * reasoning effort level for tests that exercise reasoning.
3168
+ */
3169
+ interface TestModelRef {
3170
+ /** Provider definition ID to test against (e.g., 'anthropic', 'nanogpt'). */
3171
+ definitionId: string;
3172
+ /** Model identifier within the provider (e.g., 'haiku', 'gpt-4o-mini'). */
3173
+ modelName: string;
3174
+ /** Default reasoning effort for tests that exercise reasoning. */
3175
+ reasoningEffort?: AIReasoningLevel$1;
3176
+ }
3177
+ /**
3178
+ * Provider definitions supplied by the conformance harness.
3179
+ *
3180
+ * Adapter packages should declare provider compatibility by stable provider ID
3181
+ * and let the harness supply full definitions from provider contributions.
3182
+ */
3183
+ interface CreateConformanceTestConfigOptions {
3184
+ /** Full provider definitions available to conformance tests. */
3185
+ providerDefinitions?: readonly ProviderDefinitionInput[];
3186
+ }
3187
+ /**
3188
+ * Options for creating test agent instances.
3189
+ * Omits 'bus' (provided by test config) and makes 'adapterName'/'agentId' optional (factories provide defaults).
3190
+ */
3191
+ type CreateTestAgentOptions = Omit<BaseAgentConnectorConfig, 'bus' | 'adapterName' | 'model'> & {
3192
+ adapterName?: string;
3193
+ model?: string; /** Override the default test provider context when testing endpoint/credential behavior. */
3194
+ providerContext?: ProviderContext;
3195
+ };
3196
+ interface ConformanceTestConfig<TBus extends ScopedBus<string> = ScopedBus<string>, TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>, TAgent extends AIAgent<TBus, TConnector> = AIAgent<TBus, TConnector>> {
3197
+ /**
3198
+ * Factory function for creating fresh agent instances.
3199
+ *
3200
+ * **Important**: Return a **new instance** on each call. The conformance
3201
+ * suite decides when to instantiate based on isolation requirements.
3202
+ *
3203
+ * **DO NOT** instantiate eagerly or return a singleton—tests may run
3204
+ * concurrently or require pristine state.
3205
+ * @returns Fresh connector instance configured for testing
3206
+ * @example
3207
+ * ```typescript
3208
+ * createConnector: () => new ClaudeCodeConnector({
3209
+ * bus: testBus,
3210
+ * agentId: `test-${Date.now()}`,
3211
+ * sessionId: undefined, // Let adapter generate
3212
+ * })
3213
+ * ```
3214
+ */
3215
+ createConnector: (options?: CreateTestAgentOptions) => Promise<TConnector>;
3216
+ /**
3217
+ * Register a tool approval handler scoped to a specific connector.
3218
+ *
3219
+ * The handler will only receive approval requests from the given connector
3220
+ * (filtered by agentId). Returns an unsubscribe function for cleanup.
3221
+ * @param connector - The connector to scope approval handling to
3222
+ * @param context - Optional approval context (e.g., allowed tools, policies)
3223
+ * @returns Unsubscribe function to remove the handler
3224
+ */
3225
+ registerToolApprovalHandler(connector: TConnector, context: ToolApprovalContext | (() => Promise<ToolApprovalContext>)): () => void;
3226
+ /**
3227
+ * Scoped bus instance for the adapter's namespace.
3228
+ *
3229
+ * This bus is used to emit events and handle requests in the adapter's
3230
+ * domain (e.g., 'claude-code', 'codex'). The conformance suite observes
3231
+ * events on this bus to verify behavior.
3232
+ *
3233
+ * **Namespace Isolation**: Each adapter should use a dedicated namespace
3234
+ * to prevent cross-talk between concurrent test suites.
3235
+ * @example
3236
+ * ```typescript
3237
+ * import { MakaioBus } from '@makaio/framework/bus';
3238
+ *
3239
+ * const scopedBus = MakaioBus.scoped('claude-code');
3240
+ * ```
3241
+ */
3242
+ bus: ScopedBus<string>;
3243
+ /**
3244
+ * Optional capability flags indicating adapter-specific features.
3245
+ *
3246
+ * These flags allow conformance tests to:
3247
+ * - Skip tests for unsupported features (e.g., replace mode)
3248
+ * - Verify optional behaviors when supported
3249
+ * - Provide clear capability documentation
3250
+ *
3251
+ * **Default**: All capabilities are `false` (core features only)
3252
+ *
3253
+ * ## When to Enable
3254
+ *
3255
+ * - `supportsReplace`: Adapter implements 'replace' delivery mode
3256
+ * (clears pending queue before enqueuing message)
3257
+ * - `supportsInterrupt`: Adapter exposes `interrupt()` method
3258
+ * (cancels active turn mid-execution)
3259
+ * - `supportsUsageMetrics`: Adapter emits `agent.usage` events
3260
+ * (token counts, cost tracking)
3261
+ * @example Full Capabilities
3262
+ * ```typescript
3263
+ * capabilities: {
3264
+ * supportsReplace: true, // Claude Code's replace mode
3265
+ * supportsInterrupt: true, // Claude Code's interrupt()
3266
+ * supportsUsageMetrics: true, // Usage tracking
3267
+ * }
3268
+ * ```
3269
+ * @example Core Features Only
3270
+ * ```typescript
3271
+ * capabilities: undefined // or omit entirely
3272
+ * // Tests will skip replace, interrupt, tool approval, and usage tests
3273
+ * ```
3274
+ */
3275
+ capabilities?: {
3276
+ /**
3277
+ * Supports 'replace' message delivery mode.
3278
+ *
3279
+ * When enabled, the adapter clears the pending message queue before
3280
+ * enqueuing a new message. This is useful for "superseding" interactions.
3281
+ *
3282
+ * **Claude Code**: `true` (implements replace via MCP SDK)
3283
+ * **Basic Adapters**: `false` (enqueue/immediate only)
3284
+ */
3285
+ supportsReplace?: boolean;
3286
+ /**
3287
+ * Supports `interrupt()` method for cancelling active turns.
3288
+ *
3289
+ * When enabled, the adapter can abort mid-turn execution (e.g., during
3290
+ * a long-running tool call or reasoning phase).
3291
+ *
3292
+ * **Claude Code**: `true` (exposes interrupt via MCP SDK)
3293
+ * **Stateless Adapters**: `false` (no turn state to interrupt)
3294
+ */
3295
+ supportsInterrupt?: boolean;
3296
+ /**
3297
+ * Supports usage metrics via `agent.usage` events.
3298
+ *
3299
+ * When enabled, the adapter emits token counts and cost data after
3300
+ * turns or at session completion.
3301
+ *
3302
+ * **Claude Code**: `true` (exposes MCP usage data)
3303
+ * **Free-Tier Adapters**: `false` (no usage tracking)
3304
+ */
3305
+ supportsUsageMetrics?: boolean;
3306
+ };
3307
+ /**
3308
+ * Test configuration and environment options.
3309
+ *
3310
+ * These options tune test behavior without affecting adapter functionality.
3311
+ * All fields are optional with sensible defaults.
3312
+ * @example
3313
+ * ```typescript
3314
+ * options: {
3315
+ * defaultTimeout: 30000, // 30s for slow CI
3316
+ * fastModel: 'claude-3-haiku-20240307', // Fast model for tests
3317
+ * tmpDir: '/tmp/conformance-tests', // Isolated temp directory
3318
+ * }
3319
+ * ```
3320
+ */
3321
+ options?: {
3322
+ /**
3323
+ * Default timeout for tests in milliseconds.
3324
+ *
3325
+ * Applies to async operations like agent.start() and message delivery.
3326
+ * Individual tests can override via Vitest's `{ timeout: ... }`.
3327
+ * @defaultValue 10000 (10 seconds)
3328
+ * @example
3329
+ * ```typescript
3330
+ * defaultTimeout: 30000 // 30s for slow CI environments
3331
+ * ```
3332
+ */
3333
+ defaultTimeout?: number;
3334
+ /**
3335
+ * Maximum concurrent test FILES for this adapter.
3336
+ *
3337
+ * Controls how many conformance test files run simultaneously when using
3338
+ * the programmatic test runner (scripts/test-adapters.ts). Each adapter
3339
+ * can specify its own concurrency based on rate limits or resource constraints.
3340
+ *
3341
+ * **How it works:**
3342
+ * - Test runner creates a per-adapter queue with this concurrency limit
3343
+ * - Test files for this adapter run through the queue
3344
+ * - Multiple adapters can run in parallel, each with its own queue
3345
+ *
3346
+ * **vs testConcurrency:**
3347
+ * - `concurrency`: Limits concurrent TEST FILES
3348
+ * - `testConcurrency`: Limits concurrent OPERATIONS within test helpers
3349
+ * @defaultValue 2 (when not specified)
3350
+ * @example
3351
+ * ```typescript
3352
+ * // Rate-limited API (e.g., Gemini free tier)
3353
+ * concurrency: 1 // Run test files sequentially
3354
+ *
3355
+ * // High-throughput API
3356
+ * concurrency: 4 // Run 4 test files in parallel
3357
+ * ```
3358
+ */
3359
+ concurrency?: number;
3360
+ /**
3361
+ * Cheap/fast model for cost-sensitive test execution.
3362
+ *
3363
+ * Used by most conformance tests that make real API calls.
3364
+ * Derived from the default provider preset's `fastModel` (or `defaultModel` as fallback).
3365
+ *
3366
+ * **Claude**: `{ definitionId: 'anthropic', modelName: 'haiku' }`
3367
+ * **Gemini**: `{ definitionId: 'gemini', modelName: 'gemini-2.5-flash' }`
3368
+ * @example
3369
+ * ```typescript
3370
+ * primaryModel: { definitionId: 'anthropic', modelName: 'haiku' }
3371
+ * ```
3372
+ */
3373
+ primaryModel?: TestModelRef;
3374
+ /**
3375
+ * Secondary model for model-switching tests.
3376
+ *
3377
+ * Used as the target model in model-change conformance tests.
3378
+ * Derived from the default provider preset's `defaultModel`.
3379
+ *
3380
+ * **Claude**: `{ definitionId: 'anthropic', modelName: 'sonnet' }`
3381
+ * **Gemini**: `{ definitionId: 'gemini', modelName: 'gemini-2.5-pro' }`
3382
+ * @example
3383
+ * ```typescript
3384
+ * secondaryModel: { definitionId: 'anthropic', modelName: 'sonnet' }
3385
+ * ```
3386
+ */
3387
+ secondaryModel?: TestModelRef;
3388
+ /**
3389
+ * Temporary directory for file operations during tests.
3390
+ *
3391
+ * Used for tests that create artifacts (logs, cached responses, etc.).
3392
+ * Should be isolated per test suite to prevent collisions.
3393
+ * @defaultValue OS temp dir + random suffix
3394
+ * @example
3395
+ * ```typescript
3396
+ * tmpDir: '/tmp/conformance-tests-claude-code'
3397
+ * ```
3398
+ */
3399
+ tmpDir?: string;
3400
+ /**
3401
+ * Maximum concurrent test operations for this adapter.
3402
+ *
3403
+ * When set, test infrastructure serializes context creation and key
3404
+ * operations through a per-adapter queue. Useful for adapters with
3405
+ * aggressive rate limits (e.g., Gemini free tier).
3406
+ *
3407
+ * **Default**: undefined (no throttling - tests run fully concurrent)
3408
+ * @example
3409
+ * ```typescript
3410
+ * testConcurrency: 1 // Serialize all test operations
3411
+ * ```
3412
+ */
3413
+ testConcurrency?: number;
3414
+ };
3415
+ /**
3416
+ * Factory function for creating full adapter instances (orchestration tests).
3417
+ *
3418
+ * **Orchestration vs Agent Tests:**
3419
+ * - Agent tests (`createAgent`): Direct agent instantiation, bypass session manager
3420
+ * - Orchestration tests (`createAdapter`): Full pipeline via MakaioBus.request()
3421
+ *
3422
+ * When provided, enables orchestration-level conformance tests that verify:
3423
+ * - Bus request/response flow (AdapterSubjects.sendMessage, etc.)
3424
+ * - Session manager lifecycle
3425
+ * - Event transformation pipeline (SDK to Adapter to Global)
3426
+ * - Multi-adapter coordination
3427
+ *
3428
+ * **Important**: Each call should return a fresh instance with unique adapterId
3429
+ * for test isolation. The factory receives optional init options to allow
3430
+ * passing a specific adapterId.
3431
+ * @returns Fresh AIAdapter instance configured for orchestration testing
3432
+ * @example
3433
+ * ```typescript
3434
+ * createAdapter: (options) => createClaudeAdapter({
3435
+ * adapterId: options?.adapterId ?? `test-${crypto.randomUUID()}`,
3436
+ * ...options
3437
+ * })
3438
+ * ```
3439
+ */
3440
+ createAdapter?: (options?: AIAdapterInitOptions) => Promise<AIAdapter<TBus, TConnector, TAgent>>;
3441
+ /**
3442
+ * Adapter type name for orchestration tests (e.g., 'claude-code').
3443
+ * Required when createAdapter is provided.
3444
+ */
3445
+ adapterName?: string;
3446
+ /**
3447
+ * Unresolved provider context for the test provider.
3448
+ *
3449
+ * Contains credential refs (e.g. `env:ANTHROPIC_API_KEY`) built from the test
3450
+ * provider definition's `credentialEnvVars`. Used by orchestration tests that
3451
+ * call `startAgent` directly (bypassing the conformance `createConnector` path
3452
+ * where `resolveTestConfig` handles credential ref building).
3453
+ *
3454
+ * The conformance test infrastructure registers a credential channel handler
3455
+ * that resolves `env:` refs from `process.env` so connectors can call
3456
+ * `resolveConnectorCredentials()` without a real credential store.
3457
+ */
3458
+ testProviderContext?: ProviderContext;
3459
+ /**
3460
+ * Optional cleanup hook for adapter-specific test infrastructure.
3461
+ *
3462
+ * Use this for resources created by `createTestConfig()` that outlive
3463
+ * individual connectors/adapters (for example shared test servers).
3464
+ */
3465
+ cleanup?: () => Promise<void> | void;
3466
+ }
3467
+ //#endregion
3468
+ //#region adapters/core/src/session/utilities.d.ts
3469
+ /**
3470
+ * Manages session lifecycle and abort handling.
3471
+ *
3472
+ * Provides coordinated abort signal management:
3473
+ * - Idempotent abort()
3474
+ * - Cleanup hook execution
3475
+ * - Termination state tracking
3476
+ *
3477
+ * ## Design Philosophy
3478
+ *
3479
+ * SessionLifecycle is a simple composition utility that encapsulates
3480
+ * abort signal coordination. It avoids inheritance coupling while providing
3481
+ * a clean API for session termination.
3482
+ *
3483
+ * ## Example Usage
3484
+ *
3485
+ * ```typescript
3486
+ * class MySession {
3487
+ * private lifecycle = new SessionLifecycle();
3488
+ *
3489
+ * abort() {
3490
+ * this.lifecycle.abort(() => this.transport.close());
3491
+ * }
3492
+ *
3493
+ * async sendMessage(msg: string) {
3494
+ * if (this.lifecycle.isTerminated) {
3495
+ * throw new Error('Session terminated');
3496
+ * }
3497
+ * // ... send logic
3498
+ * }
3499
+ *
3500
+ * getAbortSignal(): AbortSignal {
3501
+ * return this.lifecycle.signal;
3502
+ * }
3503
+ * }
3504
+ * ```
3505
+ */
3506
+ declare class SessionLifecycle {
3507
+ private readonly abortController;
3508
+ private terminated;
3509
+ /**
3510
+ * Create a new SessionLifecycle
3511
+ * @param abortController - Optional AbortController to use (creates new if not provided)
3512
+ */
3513
+ constructor(abortController?: AbortController);
3514
+ /**
3515
+ * Get abort signal for provider integration
3516
+ * @returns The abort signal
3517
+ */
3518
+ get signal(): AbortSignal;
3519
+ /**
3520
+ * Get termination state
3521
+ * @returns True if session has been terminated
3522
+ */
3523
+ get isTerminated(): boolean;
3524
+ /**
3525
+ * Abort session and run cleanup.
3526
+ * Idempotent - safe to call multiple times.
3527
+ * @param cleanup - Cleanup function (sync or async)
3528
+ */
3529
+ abort(cleanup?: () => void | Promise<void>): void;
3530
+ /**
3531
+ * Register abort listener
3532
+ * @param handler - Callback to invoke when session is aborted
3533
+ */
3534
+ onAbort(handler: () => void): void;
3535
+ }
3536
+ //#endregion
3537
+ //#region adapters/core/src/log-importer/base-importer.d.ts
3538
+ /**
3539
+ * Abstract base class for log importers.
3540
+ *
3541
+ * Provides default processLogFile() implementation that composes
3542
+ * extractSessionContext() + processRecords(). Adapters implement
3543
+ * the abstract methods for their specific log format.
3544
+ * @typeParam TRecord - The tool's native log record type
3545
+ * @typeParam TState - The resumable state type
3546
+ */
3547
+ declare abstract class BaseLogImporter<TRecord, TState = unknown> implements LogImporter<TRecord, TState> {
3548
+ abstract canHandle(sample: string | JsonObject): boolean | {
3549
+ confidence: number;
3550
+ };
3551
+ abstract getLogDirectory(): string;
3552
+ /**
3553
+ * Parse a single log record from raw input.
3554
+ * @param line - Raw log line or parsed JSON object to parse
3555
+ * @param sourceFilePath - Optional source file path for format-specific context
3556
+ * @returns Parsed record or null when the input does not match the adapter format
3557
+ */
3558
+ abstract parseRecord(line: string | JsonObject, sourceFilePath?: string): TRecord | null;
3559
+ abstract isMakaioManaged(sessionId: string): Promise<boolean>;
3560
+ /**
3561
+ * Extract discovery metadata from a log file without importing full message history.
3562
+ * @param filePath - Absolute path to the source log file
3563
+ * @returns Discovery metadata when parsing succeeds; rejects on unrecoverable read/parse errors
3564
+ */
3565
+ abstract extractDiscoveryMetadata(filePath: string): Promise<DiscoveryMetadata>;
3566
+ abstract extractSessionContext(records: TRecord[]): LogImportSessionContext<TState>;
3567
+ abstract processRecords(records: TRecord[], context: LogImportSessionContext<TState>): NormalizedEvent[];
3568
+ abstract serializeState(state: TState): JsonObject;
3569
+ abstract deserializeState(raw: JsonObject): TState;
3570
+ /**
3571
+ * Process a complete log file in a single call.
3572
+ *
3573
+ * Composes extractSessionContext + processRecords + message extraction.
3574
+ * Adapters that need special handling (fork detection, field normalization)
3575
+ * should override this method.
3576
+ * @param records - All parsed records from the log file
3577
+ * @returns Combined session metadata, events, and message payloads
3578
+ */
3579
+ processLogFile(records: TRecord | TRecord[]): ProcessLogFileResult;
3580
+ }
3581
+ //#endregion
3582
+ //#region adapters/core/src/log-importer/cursor-storage.d.ts
3583
+ /**
3584
+ * Zod schema for import cursor position.
3585
+ *
3586
+ * Mirrors the {@link ImportCursorPosition} interface for runtime validation.
3587
+ * Used in storage requests and responses.
3588
+ */
3589
+ declare const ImportCursorPositionSchema: z.ZodObject<{
3590
+ filePath: z.ZodString;
3591
+ bytesRead: z.ZodNumber;
3592
+ lastModified: z.ZodString;
3593
+ sessionContext: z.ZodOptional<z.ZodCustom<{
3594
+ model: string | null;
3595
+ cwd: string | null;
3596
+ } & {
3597
+ adapterSessionId: string;
3598
+ sessionEvent: NormalizedEvent;
3599
+ startedEvent: NormalizedEvent;
3600
+ state: _$type_fest0.JsonObject;
3601
+ }, {
3602
+ model: string | null;
3603
+ cwd: string | null;
3604
+ } & {
3605
+ adapterSessionId: string;
3606
+ sessionEvent: NormalizedEvent;
3607
+ startedEvent: NormalizedEvent;
3608
+ state: _$type_fest0.JsonObject;
3609
+ }>>;
3610
+ }, z.core.$strip>;
3611
+ /**
3612
+ * Import cursor storage namespace.
3613
+ *
3614
+ * Provides bus subjects for tracking import progress within external log files.
3615
+ * Cursors enable resumption from the last successfully processed position
3616
+ * after restarts, preventing duplicate event emission.
3617
+ * @remarks
3618
+ * Storage domain: `storage:importCursor`
3619
+ *
3620
+ * Cursors track byte offsets rather than line numbers for efficiency.
3621
+ * The `lastModified` timestamp enables detection of file truncation/rotation:
3622
+ * if the file's mtime is older than the stored cursor, the file was likely
3623
+ * rotated and should be re-read from the beginning.
3624
+ * @example
3625
+ * ```typescript
3626
+ * import { ImportCursorStorageSubjects } from '@makaio/framework/adapters';
3627
+ *
3628
+ * // Get cursor for file (returns null if not found)
3629
+ * const result = await bus.request(ImportCursorStorageSubjects.get, {
3630
+ * filePath: '/home/user/.claude/projects/foo/session.jsonl',
3631
+ * });
3632
+ *
3633
+ * if (result.cursor) {
3634
+ * console.log(`Resuming from byte ${result.cursor.bytesRead}`);
3635
+ * }
3636
+ *
3637
+ * // Update cursor after processing
3638
+ * await bus.request(ImportCursorStorageSubjects.set, {
3639
+ * filePath: '/home/user/.claude/projects/foo/session.jsonl',
3640
+ * bytesRead: 12345,
3641
+ * lastModified: '2025-12-09T10:30:00Z',
3642
+ * });
3643
+ * ```
3644
+ * @see {@link ImportCursorPosition} - Type definition for cursor positions
3645
+ */
3646
+ declare const ImportCursorStorageNamespace: _$_makaio_storage_core0.StorageNamespaceDefinition<"importCursor", {
3647
+ /**
3648
+ * Get the cursor position for a log file.
3649
+ *
3650
+ * Subject: `storage:importCursor.get`
3651
+ * Type: Request (RPC)
3652
+ * @returns Cursor position or null if not found
3653
+ */
3654
+ get: {
3655
+ request: z.ZodObject<{
3656
+ filePath: z.ZodString;
3657
+ }, z.core.$strip>;
3658
+ response: z.ZodObject<{
3659
+ cursor: z.ZodNullable<z.ZodObject<{
3660
+ filePath: z.ZodString;
3661
+ bytesRead: z.ZodNumber;
3662
+ lastModified: z.ZodString;
3663
+ sessionContext: z.ZodOptional<z.ZodCustom<{
3664
+ model: string | null;
3665
+ cwd: string | null;
3666
+ } & {
3667
+ adapterSessionId: string;
3668
+ sessionEvent: NormalizedEvent;
3669
+ startedEvent: NormalizedEvent;
3670
+ state: _$type_fest0.JsonObject;
3671
+ }, {
3672
+ model: string | null;
3673
+ cwd: string | null;
3674
+ } & {
3675
+ adapterSessionId: string;
3676
+ sessionEvent: NormalizedEvent;
3677
+ startedEvent: NormalizedEvent;
3678
+ state: _$type_fest0.JsonObject;
3679
+ }>>;
3680
+ }, z.core.$strip>>;
3681
+ }, z.core.$strip>;
3682
+ };
3683
+ /**
3684
+ * Set or update the cursor position for a log file.
3685
+ *
3686
+ * Subject: `storage:importCursor.set`
3687
+ * Type: Request (RPC)
3688
+ */
3689
+ set: {
3690
+ request: z.ZodObject<{
3691
+ filePath: z.ZodString;
3692
+ bytesRead: z.ZodNumber;
3693
+ lastModified: z.ZodString;
3694
+ sessionContext: z.ZodOptional<z.ZodCustom<{
3695
+ model: string | null;
3696
+ cwd: string | null;
3697
+ } & {
3698
+ adapterSessionId: string;
3699
+ sessionEvent: NormalizedEvent;
3700
+ startedEvent: NormalizedEvent;
3701
+ state: _$type_fest0.JsonObject;
3702
+ }, {
3703
+ model: string | null;
3704
+ cwd: string | null;
3705
+ } & {
3706
+ adapterSessionId: string;
3707
+ sessionEvent: NormalizedEvent;
3708
+ startedEvent: NormalizedEvent;
3709
+ state: _$type_fest0.JsonObject;
3710
+ }>>;
3711
+ }, z.core.$strip>;
3712
+ response: z.ZodObject<{
3713
+ success: z.ZodBoolean;
3714
+ }, z.core.$strip>;
3715
+ };
3716
+ /**
3717
+ * Delete the cursor for a log file.
3718
+ *
3719
+ * Subject: `storage:importCursor.delete`
3720
+ * Type: Request (RPC)
3721
+ * @remarks
3722
+ * Useful when a file is detected as rotated/truncated and needs
3723
+ * to be re-read from the beginning.
3724
+ */
3725
+ delete: {
3726
+ request: z.ZodObject<{
3727
+ filePath: z.ZodString;
3728
+ }, z.core.$strip>;
3729
+ response: z.ZodObject<{
3730
+ success: z.ZodBoolean;
3731
+ }, z.core.$strip>;
3732
+ };
3733
+ }, _$_makaio_storage_core0.StorageNamespaceExtensions>;
3734
+ /**
3735
+ * Typed subjects for import cursor storage operations.
3736
+ *
3737
+ * Provides type-safe access to cursor storage subjects for bus requests.
3738
+ * @example
3739
+ * ```typescript
3740
+ * // Get cursor
3741
+ * const { cursor } = await bus.request(ImportCursorStorageSubjects.get, {
3742
+ * filePath: '/path/to/log.jsonl',
3743
+ * });
3744
+ *
3745
+ * // Set cursor
3746
+ * await bus.request(ImportCursorStorageSubjects.set, {
3747
+ * filePath: '/path/to/log.jsonl',
3748
+ * bytesRead: 1024,
3749
+ * lastModified: new Date().toISOString(),
3750
+ * });
3751
+ *
3752
+ * // Delete cursor (on file rotation)
3753
+ * await bus.request(ImportCursorStorageSubjects.delete, {
3754
+ * filePath: '/path/to/log.jsonl',
3755
+ * });
3756
+ * ```
3757
+ */
3758
+ declare const ImportCursorStorageSubjects: _$_makaio_core0.BusSubjects<_$_makaio_core0.FlatSubjectDefinitions<"storage:importCursor", {
3759
+ /**
3760
+ * Get the cursor position for a log file.
3761
+ *
3762
+ * Subject: `storage:importCursor.get`
3763
+ * Type: Request (RPC)
3764
+ * @returns Cursor position or null if not found
3765
+ */
3766
+ get: {
3767
+ request: z.ZodObject<{
3768
+ filePath: z.ZodString;
3769
+ }, z.core.$strip>;
3770
+ response: z.ZodObject<{
3771
+ cursor: z.ZodNullable<z.ZodObject<{
3772
+ filePath: z.ZodString;
3773
+ bytesRead: z.ZodNumber;
3774
+ lastModified: z.ZodString;
3775
+ sessionContext: z.ZodOptional<z.ZodCustom<{
3776
+ model: string | null;
3777
+ cwd: string | null;
3778
+ } & {
3779
+ adapterSessionId: string;
3780
+ sessionEvent: NormalizedEvent;
3781
+ startedEvent: NormalizedEvent;
3782
+ state: _$type_fest0.JsonObject;
3783
+ }, {
3784
+ model: string | null;
3785
+ cwd: string | null;
3786
+ } & {
3787
+ adapterSessionId: string;
3788
+ sessionEvent: NormalizedEvent;
3789
+ startedEvent: NormalizedEvent;
3790
+ state: _$type_fest0.JsonObject;
3791
+ }>>;
3792
+ }, z.core.$strip>>;
3793
+ }, z.core.$strip>;
3794
+ };
3795
+ /**
3796
+ * Set or update the cursor position for a log file.
3797
+ *
3798
+ * Subject: `storage:importCursor.set`
3799
+ * Type: Request (RPC)
3800
+ */
3801
+ set: {
3802
+ request: z.ZodObject<{
3803
+ filePath: z.ZodString;
3804
+ bytesRead: z.ZodNumber;
3805
+ lastModified: z.ZodString;
3806
+ sessionContext: z.ZodOptional<z.ZodCustom<{
3807
+ model: string | null;
3808
+ cwd: string | null;
3809
+ } & {
3810
+ adapterSessionId: string;
3811
+ sessionEvent: NormalizedEvent;
3812
+ startedEvent: NormalizedEvent;
3813
+ state: _$type_fest0.JsonObject;
3814
+ }, {
3815
+ model: string | null;
3816
+ cwd: string | null;
3817
+ } & {
3818
+ adapterSessionId: string;
3819
+ sessionEvent: NormalizedEvent;
3820
+ startedEvent: NormalizedEvent;
3821
+ state: _$type_fest0.JsonObject;
3822
+ }>>;
3823
+ }, z.core.$strip>;
3824
+ response: z.ZodObject<{
3825
+ success: z.ZodBoolean;
3826
+ }, z.core.$strip>;
3827
+ };
3828
+ /**
3829
+ * Delete the cursor for a log file.
3830
+ *
3831
+ * Subject: `storage:importCursor.delete`
3832
+ * Type: Request (RPC)
3833
+ * @remarks
3834
+ * Useful when a file is detected as rotated/truncated and needs
3835
+ * to be re-read from the beginning.
3836
+ */
3837
+ delete: {
3838
+ request: z.ZodObject<{
3839
+ filePath: z.ZodString;
3840
+ }, z.core.$strip>;
3841
+ response: z.ZodObject<{
3842
+ success: z.ZodBoolean;
3843
+ }, z.core.$strip>;
3844
+ };
3845
+ }>, "storage:importCursor">;
3846
+ //#endregion
3847
+ //#region adapters/core/src/log-importer/cursor-memory-handler.d.ts
3848
+ /**
3849
+ * Register in-memory import cursor storage handlers.
3850
+ *
3851
+ * Suitable for development, testing, and single-instance deployments.
3852
+ * For production with persistence, implement a file-based or database-backed handler.
3853
+ * @param bus - The bus instance to register handlers on
3854
+ * @returns Cleanup function to unsubscribe all handlers
3855
+ * @example
3856
+ * ```typescript
3857
+ * import { registerMemoryImportCursorStorage } from '@makaio/framework/adapters';
3858
+ *
3859
+ * const cleanup = registerMemoryImportCursorStorage(bus);
3860
+ *
3861
+ * // Later, when shutting down:
3862
+ * cleanup();
3863
+ * ```
3864
+ */
3865
+ declare function registerMemoryImportCursorStorage(bus: IMakaioBus): () => void;
3866
+ //#endregion
3867
+ //#region adapters/core/src/log-importer/turn-tracker.d.ts
3868
+ /**
3869
+ * Turn lifecycle state.
3870
+ * @remarks
3871
+ * - `idle`: No active turn, waiting for a turn to start
3872
+ * - `active`: Turn in progress, waiting for completion
3873
+ */
3874
+ type TurnState = 'idle' | 'active';
3875
+ /**
3876
+ * Synthetic turn event to be emitted during log import.
3877
+ * @remarks
3878
+ * These events are synthesized by the state machine when it detects
3879
+ * turn boundaries (e.g., user message starts a turn, final text completes it).
3880
+ * @see {@link TurnTracker} - State machine that produces these events
3881
+ */
3882
+ interface TurnEvent {
3883
+ /** Type of turn event */
3884
+ type: 'turn.started' | 'turn.completed';
3885
+ /** Session ID for this turn (from the record that triggered the transition) */
3886
+ sessionId: string;
3887
+ /** Unique identifier for this turn instance */
3888
+ turnId: string;
3889
+ }
3890
+ /**
3891
+ * Configuration options for the turn tracker.
3892
+ * @remarks
3893
+ * Adapters provide detection functions specific to their log format:
3894
+ * - Claude Code: `detectTurnStart` triggers on user messages,
3895
+ * `detectTurnComplete` triggers on final text content blocks
3896
+ * - Copilot: Explicit `turn_start`/`turn_end` events, may bypass this tracker
3897
+ * @typeParam TRecord - The adapter's native log record type
3898
+ * @see {@link TurnTracker} - Uses these options
3899
+ */
3900
+ interface TurnTrackerOptions<TRecord> {
3901
+ /**
3902
+ * Detect if a record indicates the start of a turn.
3903
+ * @param record - Log record to check
3904
+ * @returns True if this record starts a new turn
3905
+ * @example
3906
+ * ```typescript
3907
+ * // Claude Code: user message starts a turn
3908
+ * detectTurnStart: (record) => record.type === 'user'
3909
+ * ```
3910
+ */
3911
+ detectTurnStart: (record: TRecord) => boolean;
3912
+ /**
3913
+ * Detect if a record indicates the completion of a turn.
3914
+ * @param record - Log record to check
3915
+ * @returns True if this record completes the current turn
3916
+ * @example
3917
+ * ```typescript
3918
+ * // Claude Code: final text block completes a turn
3919
+ * detectTurnComplete: (record) =>
3920
+ * record.type === 'assistant' &&
3921
+ * record.message?.content?.some((b) => b.type === 'text')
3922
+ * ```
3923
+ */
3924
+ detectTurnComplete: (record: TRecord) => boolean;
3925
+ /**
3926
+ * Extract the session ID from a log record.
3927
+ * @param record - Log record to extract session ID from
3928
+ * @returns Session ID string
3929
+ * @example
3930
+ * ```typescript
3931
+ * getSessionId: (record) => record.sessionId
3932
+ * ```
3933
+ */
3934
+ getSessionId: (record: TRecord) => string;
3935
+ /**
3936
+ * Optional custom function to generate turn IDs.
3937
+ * @defaultValue Uses `crypto.randomUUID()`
3938
+ * @remarks
3939
+ * Override this for deterministic testing or custom ID schemes.
3940
+ * @param sessionId - The session ID for context
3941
+ * @returns Unique turn ID string
3942
+ */
3943
+ generateTurnId?: (sessionId: string) => string;
3944
+ }
3945
+ /**
3946
+ * Serialized form of TurnTracker state for persistence across chunks/restarts.
3947
+ * @remarks
3948
+ * Used by {@link TurnTracker.serialize} and {@link TurnTracker.restore} to
3949
+ * enable incremental log imports that can resume processing.
3950
+ */
3951
+ interface TurnTrackerSerializedState {
3952
+ /** Session states keyed by session ID */
3953
+ sessions: Record<string, {
3954
+ state: TurnState;
3955
+ currentTurnId?: string;
3956
+ }>;
3957
+ }
3958
+ /**
3959
+ * Zod schema for validating serialized TurnTracker state.
3960
+ *
3961
+ * Used by adapter log importers to safely deserialize cursor state
3962
+ * without unsafe `as` casts.
3963
+ * @see {@link TurnTrackerSerializedState} - TypeScript interface this validates
3964
+ */
3965
+ declare const TurnTrackerSerializedStateSchema: z.ZodDefault<z.ZodObject<{
3966
+ sessions: z.ZodRecord<z.ZodString, z.ZodObject<{
3967
+ state: z.ZodEnum<{
3968
+ active: "active";
3969
+ idle: "idle";
3970
+ }>;
3971
+ currentTurnId: z.ZodOptional<z.ZodString>;
3972
+ }, z.core.$strip>>;
3973
+ }, z.core.$strip>>;
3974
+ /**
3975
+ * State machine for tracking turn boundaries during log import.
3976
+ *
3977
+ * ## Purpose
3978
+ *
3979
+ * Some external tools (like Claude Code) don't emit explicit turn start/end events.
3980
+ * This tracker synthesizes these events based on adapter-specific detection logic.
3981
+ *
3982
+ * ## State Transitions
3983
+ *
3984
+ * ```
3985
+ * idle --[turn start detected]--> active (emit turn.started)
3986
+ * active --[turn complete detected]--> idle (emit turn.completed)
3987
+ * ```
3988
+ *
3989
+ * ## Multi-Session Support
3990
+ *
3991
+ * The tracker maintains independent state per session ID, enabling
3992
+ * concurrent processing of multiple sessions from the same log file.
3993
+ * @remarks
3994
+ * - Thread-safe for single-threaded async processing (no mutex needed)
3995
+ * - Stateless between sessions (each session tracked independently)
3996
+ * - Idempotent: processing the same record twice produces consistent results
3997
+ * @typeParam TRecord - The adapter's native log record type
3998
+ * @example
3999
+ * ```typescript
4000
+ * // Create tracker for Claude Code logs
4001
+ * const tracker = new TurnTracker({
4002
+ * detectTurnStart: (record) => record.type === 'user',
4003
+ * detectTurnComplete: (record) =>
4004
+ * record.type === 'assistant' &&
4005
+ * record.message?.content?.some((b) => b.type === 'text'),
4006
+ * getSessionId: (record) => record.sessionId,
4007
+ * });
4008
+ *
4009
+ * // Process records
4010
+ * for (const record of records) {
4011
+ * const turnEvents = tracker.processRecord(record);
4012
+ * for (const event of turnEvents) {
4013
+ * // Emit turn.started or turn.completed events
4014
+ * console.log(event.type, event.turnId);
4015
+ * }
4016
+ * }
4017
+ * ```
4018
+ * @see {@link TurnTrackerOptions} - Configuration options
4019
+ * @see {@link TurnEvent} - Emitted turn events
4020
+ */
4021
+ declare class TurnTracker<TRecord> {
4022
+ private readonly options;
4023
+ private readonly sessions;
4024
+ private readonly generateTurnId;
4025
+ /**
4026
+ * Create a new turn tracker.
4027
+ * @param options - Tracker configuration with detection functions
4028
+ */
4029
+ constructor(options: TurnTrackerOptions<TRecord>);
4030
+ /**
4031
+ * Process a log record and return any turn events that should be emitted.
4032
+ * @param record - Log record to process
4033
+ * @returns Array of turn events (may be empty, one, or two if turn completes and new one starts)
4034
+ * @remarks
4035
+ * ## Transition Rules
4036
+ *
4037
+ * 1. **idle + turn start detected** emits `turn.started`, transitions to active
4038
+ * 2. **active + turn complete detected** emits `turn.completed`, transitions to idle
4039
+ * 3. **active + turn start detected** emits `turn.completed` for previous turn,
4040
+ * then emits `turn.started` for new turn (implicit completion)
4041
+ * 4. **idle + turn complete detected** is a no-op (no active turn to complete)
4042
+ *
4043
+ * Rule 3 handles cases where a user sends another message before the assistant
4044
+ * finishes responding (rare but possible in log replays).
4045
+ */
4046
+ processRecord(record: TRecord): TurnEvent[];
4047
+ /**
4048
+ * Get the current turn state for a session.
4049
+ * @param sessionId - Session identifier
4050
+ * @returns Current turn state ('idle' if session not tracked)
4051
+ */
4052
+ getState(sessionId: string): TurnState;
4053
+ /**
4054
+ * Get the current turn ID for a session.
4055
+ * @param sessionId - Session identifier
4056
+ * @returns Current turn ID or undefined if no active turn
4057
+ */
4058
+ getCurrentTurnId(sessionId: string): string | undefined;
4059
+ /**
4060
+ * Check if a session has an active turn.
4061
+ * @param sessionId - Session identifier
4062
+ * @returns True if the session has an active (non-idle) turn
4063
+ */
4064
+ hasActiveTurn(sessionId: string): boolean;
4065
+ /**
4066
+ * Reset state for a specific session.
4067
+ * @remarks
4068
+ * Use this when a session is known to be complete or when re-processing.
4069
+ * @param sessionId - Session identifier
4070
+ * @returns True if the session was tracked and removed
4071
+ */
4072
+ resetSession(sessionId: string): boolean;
4073
+ /**
4074
+ * Reset all tracked session state.
4075
+ * @remarks
4076
+ * Use this for cleanup or when starting fresh.
4077
+ */
4078
+ resetAll(): void;
4079
+ /**
4080
+ * Serialize the tracker state for persistence.
4081
+ * @remarks
4082
+ * Use this to save state between chunks or before process shutdown
4083
+ * for incremental log imports.
4084
+ * @returns JSON-serializable state object
4085
+ * @see {@link restore} - Restore state from serialized form
4086
+ */
4087
+ serialize(): TurnTrackerSerializedState;
4088
+ /**
4089
+ * Restore tracker state from a serialized form.
4090
+ * @remarks
4091
+ * Clears all current state before restoring. Use this to resume
4092
+ * processing after a restart or between chunks.
4093
+ * @param serialized - State object from {@link serialize}
4094
+ * @see {@link serialize} - Create serialized state
4095
+ */
4096
+ restore(serialized: TurnTrackerSerializedState): void;
4097
+ /**
4098
+ * Get all currently tracked session IDs.
4099
+ * @returns Array of session IDs being tracked
4100
+ */
4101
+ getTrackedSessions(): string[];
4102
+ /**
4103
+ * Manually complete the current turn for a session.
4104
+ * @remarks
4105
+ * Use this for cleanup when processing ends mid-turn (e.g., end of file
4106
+ * with an incomplete conversation). Does nothing if no active turn.
4107
+ * @param sessionId - Session identifier
4108
+ * @returns Turn completed event or undefined if no active turn
4109
+ */
4110
+ forceCompleteTurn(sessionId: string): TurnEvent | undefined;
4111
+ /**
4112
+ * Get or create session state for a session ID.
4113
+ * @param sessionId - Session identifier
4114
+ * @returns Session state (creates new idle state if not exists)
4115
+ */
4116
+ private getOrCreateSessionState;
4117
+ }
4118
+ //#endregion
4119
+ //#region adapters/core/src/namespaces/schemas/lifecycle.d.ts
4120
+ /**
4121
+ * Schema for agent started event.
4122
+ * Emitted when agent begins processing a user message.
4123
+ */
4124
+ declare const AgentStartedEventSchema: z.ZodObject<{
4125
+ eventType: z.ZodLiteral<"agent_started">;
4126
+ model: z.ZodOptional<z.ZodString>;
4127
+ }, z.core.$strip>;
4128
+ /**
4129
+ * Schema for agent complete event.
4130
+ * Emitted when agent finishes processing (success or error).
4131
+ */
4132
+ declare const AgentCompleteEventSchema: z.ZodObject<{
4133
+ eventType: z.ZodLiteral<"agent_complete">;
4134
+ message: z.ZodOptional<z.ZodString>;
4135
+ error: z.ZodOptional<z.ZodString>;
4136
+ }, z.core.$strip>;
4137
+ /**
4138
+ * Schema for error event.
4139
+ * Emitted when an error occurs during processing.
4140
+ */
4141
+ declare const ErrorEventSchema: z.ZodObject<{
4142
+ eventType: z.ZodLiteral<"error">;
4143
+ message: z.ZodString;
4144
+ code: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodNumber]>>;
4145
+ type: z.ZodOptional<z.ZodString>;
4146
+ }, z.core.$strip>;
4147
+ type AgentStartedEvent = z.infer<typeof AgentStartedEventSchema>;
4148
+ type AgentCompleteEvent = z.infer<typeof AgentCompleteEventSchema>;
4149
+ type ErrorEvent = z.infer<typeof ErrorEventSchema>;
4150
+ //#endregion
4151
+ //#region adapters/core/src/namespaces/schemas/tool-lifecycle.d.ts
4152
+ /**
4153
+ * Schema for tool started event.
4154
+ * Emitted when tool execution begins.
4155
+ */
4156
+ declare const ToolStartedEventSchema: z.ZodObject<{
4157
+ eventType: z.ZodLiteral<"tool_started">;
4158
+ toolName: z.ZodString;
4159
+ toolCallId: z.ZodString;
4160
+ }, z.core.$strip>;
4161
+ /**
4162
+ * Schema for tool completed event.
4163
+ * Emitted when tool execution finishes (success or failure).
4164
+ */
4165
+ declare const ToolCompletedEventSchema: z.ZodObject<{
4166
+ eventType: z.ZodLiteral<"tool_completed">;
4167
+ toolName: z.ZodString;
4168
+ toolCallId: z.ZodString;
4169
+ result: z.ZodString;
4170
+ success: z.ZodBoolean;
4171
+ }, z.core.$strip>;
4172
+ type ToolStartedEvent = z.infer<typeof ToolStartedEventSchema>;
4173
+ type ToolCompletedEvent = z.infer<typeof ToolCompletedEventSchema>;
4174
+ //#endregion
4175
+ export { AIAdapter, type AIAdapterCapabilities, type AIAdapterCapability, type AIAdapterCapabilityRegistry, type AIAdapterConfig, type AIAdapterConstructorConfig, type AIAdapterContext, type AIAdapterDefinition, type AIAdapterInitOptions, type AIAdapterPromptFailureResult, type AIAdapterPromptOptions, type AIAdapterPromptResult, type AIAdapterPromptSuccessResult, AIAgent, type AIAgentConfig, AIAgentConnector, type AIModel, type AIReasoningLevel, type AdapterNamespace, type AdapterProviderDefinition, type AgentBusHandlerRegistrarConfig, type AgentCompleteEvent, AgentCompleteEventSchema, AgentConnectorLifecycleManager, type AgentConnectorLifecycleManagerConfig, type AgentContext, AgentEventBridge, type AgentEventBridgeConfig, type AgentIdentity, AgentLifecycleEmitter, type AgentLifecycleEmitterConfig, AgentPayloadEmitter, type AgentPayloadEmitterConfig, type AgentRuntimeCreationResult, AgentRuntimeMutationManager, type AgentRuntimeMutationManagerConfig, type AgentSendMessageOptions, type AgentStartResult, type AgentStartedEvent, AgentStartedEventSchema, AgentTurnExecutor, type AgentTurnExecutorConfig, type AgentUsageTotals, type BaseAgentConnectorConfig, BaseConnectorSession, BaseConnectorTurn, BaseLogImporter, type CompactionMetadata, type ConfigFactoryInput, type ConformanceEnvReader, type ConformanceTestConfig, type ConnectorSendMessageOptions, type ConnectorSessionConfig, type ConnectorStartOptions, type CreateConformanceTestConfigOptions, type CreateTestAgentOptions, type DiscoveryMetadata, type DiscriminatedHandler, type DiscriminatedHandlersConfig, type DiscriminatedHandlersMap, type ErrorEvent, ErrorEventSchema, type ExecutionContext, type ExternalToolIdentifier, type ExternalToolIdentifiers, type ExternalToolMeta, type FromGlobalToolApprovalFn, type GeneratedCapabilityProperties, type HarnessRequester, type IAdapterConfigFactory, type ISessionToolLedger, type ImportCursorPosition, ImportCursorPositionSchema, ImportCursorStorageNamespace, ImportCursorStorageSubjects, type ImportMetadata, type ImportSegment, type ImportSegmentLineage, type LedgerSessionContext, type LogImportConfig, type LogImportOrchestrator, type LogImportRegistration, type LogImportSessionContext, type LogImportTestConfig, type LogImporter, type LogImporterConfig, type LogImporterConstructor, type LogOrchestratorConfig, type LogOrchestratorConstructor, MAKAIO_CONFORMANCE_PRIMARY_MODEL_ENV, MAKAIO_CONFORMANCE_PROVIDER_DEFINITIONS_ENV, MAKAIO_CONFORMANCE_PROVIDER_ENV, MAKAIO_CONFORMANCE_SECONDARY_MODEL_ENV, type McpIntegrationStrategy, type McpSessionResources, type McpToolChange, type MergeResult, type MergeScopedToolApprovalOptions, type MessageDeliveryMode, MessageHandle, MessageLifecycleTracker, type MessageResult, type MessageState, type NormalizedCallUsage, type NormalizedEvent, type NormalizedMessageInput, type ParseFileResult, type PauseResult, type PlatformDefaults, ProceduralAgentConnector, type ProceduralConnectorSession, ProceduralConnectorTurn, type ProceduralTurnConfig, type ProceduralTurnState, type ProcessLogFileResult, type ProcessQueueCallbacks, type ProcessingState, type QueueableTurn, type ReasoningLevelMap, type ResolveConformanceTestPresetOptions, type ResolveHints, type ResolvedConformanceTestPreset, type ScopedBusFor, type ScopedToolApprovalRequest, type ScopedToolApprovalResponse, ScopedToolApprovalSchema, type SendMessageOptions, type SendMessageRequest, type SendMessageResponse, type SerializedContextBlock, SessionLifecycle, SessionToolLedger, type ShouldUseNativeResumeFn, type StartAgentOptions, type StartAgentRequest, type StartAgentResponse, type StorageMessagePayload, type SyncDiscriminatedHandler, type SyncDiscriminatedHandlersConfig, type SyncDiscriminatedHandlersMap, type SyncTypedEmitFn, type TestModelRef, type ToGlobalToolApprovalFn, type ToolApprovalContext, ToolCallTracker, type ToolCompletedEvent, ToolCompletedEventSchema, type ToolLedgerEntry, type ToolStartedEvent, ToolStartedEventSchema, type TurnEvent, type TurnState, type TurnSubjects, TurnTracker, type TurnTrackerOptions, type TurnTrackerSerializedState, TurnTrackerSerializedStateSchema, type TypedEmitFn, UserMessageQueue, type ValidCapability, type WireSessionConfig, type WireSessionSubjects, cleanEnvForAdapter, createAdapterNamespace, createTestProviderContext, createToolApprovalHandler, defineDiscriminatedHandlers, defineDiscriminatedHandlersSync, extractMcpCallTarget, formatContextBlockAsText, formatContextBlocksAsText, formatMessageHistoryAsTranscript, isMcpCallTool, isTextLikeMimeType, mergeScopedToolApproval, normalizeEnvValue, normalizeMessageInput, normalizeMimeType, parseAIAdapterCapabilities, processDiscriminatedItems, processDiscriminatedItemsSync, processQueueMessages, registerAgentBusHandlers, registerMemoryImportCursorStorage, resolveConformanceTestPreset, resolveDisabledNativeTools, resolvePresetCredentials, resolveRequiredSessionId, resolveTestConfig, safeJsonStringify, serializeBlockToText, serializeTurnContext, toImportSegment };