@makaio/framework 1.0.0-dev-1783687982716 → 1.0.0-dev-1783940945655

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 (447) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/account-identity-BYfeWLe-.mjs +1 -0
  3. package/dist/adapter-auth-runtime-a4O7cSNP.mjs +1 -0
  4. package/dist/adapter-binding-DDUyv1JK.d.mts +254 -0
  5. package/dist/{adapter-CA8rPIUz.mjs → adapter-nl_xz9dz.mjs} +1 -1
  6. package/dist/adapter-subsystem/index.d.mts +110 -5
  7. package/dist/adapter-subsystem/index.mjs +1 -1
  8. package/dist/adapters/acp-client/index.d.mts +10 -0
  9. package/dist/adapters/acp-client/index.mjs +2 -2
  10. package/dist/adapters/config/index.d.mts +176 -153
  11. package/dist/adapters/config/index.mjs +1 -1
  12. package/dist/adapters/index.d.mts +1179 -1020
  13. package/dist/adapters/index.mjs +6 -6
  14. package/dist/adapters/node.d.mts +1 -1
  15. package/dist/adapters/node.mjs +1 -1
  16. package/dist/adapters/stream-session/index.d.mts +7 -5
  17. package/dist/adapters/stream-session/index.mjs +1 -1
  18. package/dist/auth-C3NOWqTU.mjs +1 -0
  19. package/dist/{base-orchestrator-J1WKAUkF.d.mts → base-orchestrator-BiShpVKL.d.mts} +6 -0
  20. package/dist/bus/index.d.mts +21 -21
  21. package/dist/bus/index.mjs +1 -1
  22. package/dist/{canonical-model-DV-Z8gsb.mjs → canonical-model-CVRCW9h7.mjs} +1 -1
  23. package/dist/client-BkpLM8Fx.mjs +1 -0
  24. package/dist/client-binary-version-verifier-BK_vIjIo.mjs +2 -0
  25. package/dist/client-binary-version-verifier-BwrMTAh2.d.mts +179 -0
  26. package/dist/clients/index.d.mts +74 -90
  27. package/dist/clients/index.mjs +1 -2
  28. package/dist/clients/managed-install.d.mts +2 -0
  29. package/dist/clients/managed-install.mjs +1 -0
  30. package/dist/{clients-namespace-Bt_VTkEU.d.mts → clients-namespace-B96QIJOs.d.mts} +224 -21
  31. package/dist/compression-CZ_6fYq8.mjs +1 -0
  32. package/dist/config-namespace-DTA6EQL8.mjs +1 -0
  33. package/dist/{config-namespace-DqdFE6zk.d.mts → config-namespace-x0fuhEXe.d.mts} +73 -1
  34. package/dist/contracts/adapter/index.d.mts +3 -3
  35. package/dist/contracts/adapter/index.mjs +1 -1
  36. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  37. package/dist/contracts/artifact/index.d.mts +1 -1
  38. package/dist/contracts/auth/index.d.mts +3 -0
  39. package/dist/contracts/auth/index.mjs +1 -0
  40. package/dist/contracts/canonical-model/index.d.mts +1 -1
  41. package/dist/contracts/canonical-model/index.mjs +1 -1
  42. package/dist/contracts/client/index.d.mts +3 -3
  43. package/dist/contracts/client/index.mjs +1 -1
  44. package/dist/contracts/common/index.d.mts +1 -1
  45. package/dist/contracts/config/index.d.mts +30 -103
  46. package/dist/contracts/config/index.mjs +1 -1
  47. package/dist/contracts/extension/index.d.mts +3 -3
  48. package/dist/contracts/extension/index.mjs +1 -1
  49. package/dist/contracts/facet/index.d.mts +1 -1
  50. package/dist/contracts/facet/index.mjs +1 -1
  51. package/dist/contracts/harness/index.d.mts +1 -1
  52. package/dist/contracts/harness/index.mjs +1 -1
  53. package/dist/contracts/host/index.d.mts +1 -1
  54. package/dist/contracts/host/index.mjs +1 -1
  55. package/dist/contracts/index.d.mts +1227 -274
  56. package/dist/contracts/index.mjs +1 -1
  57. package/dist/contracts/materialization/index.d.mts +3 -3
  58. package/dist/contracts/materialization/index.mjs +1 -1
  59. package/dist/contracts/model-registry/index.d.mts +1 -1
  60. package/dist/contracts/model-registry/index.mjs +1 -1
  61. package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
  62. package/dist/contracts/native-session-supervisor/index.mjs +1 -1
  63. package/dist/contracts/platform/index.d.mts +1 -1
  64. package/dist/contracts/platform/index.mjs +1 -1
  65. package/dist/contracts/provider/index.d.mts +2 -2
  66. package/dist/contracts/provider/index.mjs +1 -1
  67. package/dist/contracts/session/index.d.mts +2 -2
  68. package/dist/contracts/session/index.mjs +1 -1
  69. package/dist/contracts/shared/index.d.mts +2 -2
  70. package/dist/contracts/shared/index.mjs +1 -1
  71. package/dist/contracts/skill/index.d.mts +1 -1
  72. package/dist/contracts/skill/index.mjs +1 -1
  73. package/dist/contracts/telemetry/index.d.mts +1 -1
  74. package/dist/contracts/telemetry/index.mjs +1 -1
  75. package/dist/contracts/timeout/index.d.mts +1 -1
  76. package/dist/contracts/timeout/index.mjs +1 -1
  77. package/dist/contracts/toast/index.mjs +1 -1
  78. package/dist/contracts/variant/index.d.mts +1 -1
  79. package/dist/contracts/variant/index.mjs +1 -1
  80. package/dist/contracts/workflow/index.d.mts +2 -2
  81. package/dist/contracts/workflow/index.mjs +1 -1
  82. package/dist/{definition-s9PIua2B.d.mts → definition-Bj9Vr16H.d.mts} +1 -1
  83. package/dist/{definition-Cllhr9mi.d.mts → definition-BsTlOz99.d.mts} +36 -4
  84. package/dist/{definition-CuJvtYeG.d.mts → definition-Cbl0k6Fc.d.mts} +31 -1
  85. package/dist/definition-K3m51lgO.mjs +1 -0
  86. package/dist/definitions-C1pgx0Nq.mjs +1 -0
  87. package/dist/{detached-extension-handle-Cx6-0eqg.mjs → detached-extension-handle-CTaQoolf.mjs} +1 -1
  88. package/dist/execution-target-Bg2wpfML.mjs +1 -0
  89. package/dist/{extension-CJClssfp.mjs → extension-CjTu6mzW.mjs} +1 -1
  90. package/dist/extension-D4iKUUMG.mjs +1 -0
  91. package/dist/{filesystem-service-Bmyqo6po.mjs → filesystem-service-maY_P3yA.mjs} +1 -1
  92. package/dist/git/index.mjs +1 -1
  93. package/dist/{globby-D4SANVoq.mjs → globby-CisClzat.mjs} +1 -1
  94. package/dist/handlers-RGs3eC9X.mjs +57 -0
  95. package/dist/{harness-DkUpbsuY.mjs → harness-DflvHAGV.mjs} +1 -1
  96. package/dist/{index-C23g_M_J2.d.mts → index-5s_dN3cg2.d.mts} +18 -1
  97. package/dist/index-9dISOTLT.d.mts +174 -0
  98. package/dist/{index-B9d_8_V2.d.mts → index-9g0agW_p.d.mts} +55 -55
  99. package/dist/{index-DsLpP5ek.d.mts → index-BcejR1Jc.d.mts} +3 -3
  100. package/dist/index-BsEvzFey.d.mts +1175 -0
  101. package/dist/{index-ntS1EXlf.d.mts → index-BtL7ONuM.d.mts} +1 -1
  102. package/dist/index-BxuiHVFi.d.mts +284 -0
  103. package/dist/{index-DTkGyKKA.d.mts → index-C9Q1E8Y-.d.mts} +75 -62
  104. package/dist/{index-NkNbYFud.d.mts → index-CB2XTzvd.d.mts} +2 -2
  105. package/dist/{index-Bc82MC0z.d.mts → index-CVs0Qxks.d.mts} +8 -8
  106. package/dist/{index-WHUV7neB.d.mts → index-CW6-0k3Z.d.mts} +105 -105
  107. package/dist/index-CagRgpXI2.d.mts +84 -0
  108. package/dist/{index-CmHdpW0E.d.mts → index-Cw3cjGAT.d.mts} +4 -4
  109. package/dist/{index-DNfNwGu6.d.mts → index-D5IEq4_E.d.mts} +33 -29
  110. package/dist/{index-h5go5Dtd.d.mts → index-D75FnT0B.d.mts} +1 -1
  111. package/dist/{index-Di84JjS0.d.mts → index-DfVSWBBp.d.mts} +2 -2
  112. package/dist/{index-CAhKyxfm.d.mts → index-DlUPWOh4.d.mts} +725 -85
  113. package/dist/{index-DLDQDXhD.d.mts → index-Do7Wgio_2.d.mts} +36 -13
  114. package/dist/{index-D4gn93gL.d.mts → index-DxatNFz7.d.mts} +120 -18
  115. package/dist/{index-BvTd61i5.d.mts → index-T96ydgVk.d.mts} +260 -160
  116. package/dist/{index-D94cDExW2.d.mts → index-j2YlW_Fc.d.mts} +16 -16
  117. package/dist/{index-B4ZddkPI.d.mts → index-p6dWV52m.d.mts} +527 -387
  118. package/dist/{index-oePgeOph.d.mts → index-sCOlgPyj.d.mts} +1586 -479
  119. package/dist/kernel/cli/index.d.mts +2 -2
  120. package/dist/kernel/cli/index.mjs +1 -1
  121. package/dist/kernel/cli/register.d.mts +1 -1
  122. package/dist/kernel/cli/register.mjs +1 -1
  123. package/dist/kernel/cli/schemas.mjs +1 -1
  124. package/dist/kernel/extension/index.d.mts +1 -1
  125. package/dist/kernel/extension/index.mjs +1 -1
  126. package/dist/kernel/index.d.mts +5 -5
  127. package/dist/kernel/index.mjs +1 -1
  128. package/dist/kernel/namespace/index.d.mts +1 -1
  129. package/dist/kernel/namespace/index.mjs +1 -1
  130. package/dist/kernel/observability/index.d.mts +1 -1
  131. package/dist/kernel/observability/index.mjs +1 -1
  132. package/dist/kernel/providers/index.d.mts +1 -1
  133. package/dist/kernel/providers/index.mjs +1 -1
  134. package/dist/kernel/window/index.d.mts +1 -1
  135. package/dist/kernel/window/index.mjs +1 -1
  136. package/dist/{lib-BOmKyjWD.mjs → lib-DIVnpS8e.mjs} +1 -1
  137. package/dist/{lib-DLZYp5z3.mjs → lib-DymjnkAP.mjs} +1 -1
  138. package/dist/{load-extensions-Cze1RHcG.mjs → load-extensions-BtUrq2_t.mjs} +1 -1
  139. package/dist/{load-extensions-DNRIy4zC.d.mts → load-extensions-_EnedkUp.d.mts} +1 -1
  140. package/dist/{loop-gate-handlers-o2B5FPdF.mjs → loop-gate-handlers-0a3dIY8O.mjs} +1 -1
  141. package/dist/mcp-http-server/index.mjs +1 -1
  142. package/dist/model-uE5IyUFJ.mjs +1 -0
  143. package/dist/{namespace-3yGm4WF9.d.mts → namespace-Bl1UhLnK.d.mts} +2 -2
  144. package/dist/namespace-C05pkLbN.mjs +1 -0
  145. package/dist/{namespace-6sIu5nBI2.d.mts → namespace-CGgOLxiW2.d.mts} +2 -2
  146. package/dist/{namespace-BGIeqwfU.d.mts → namespace-CQBSXm1U.d.mts} +20 -20
  147. package/dist/{namespace-BLER-Qom.d.mts → namespace-CfgtqUWS.d.mts} +156 -156
  148. package/dist/{namespace-Dm454cNM.d.mts → namespace-CpyL93kW.d.mts} +18 -18
  149. package/dist/{namespace-B9V9R3AY.d.mts → namespace-D3SQQgxa2.d.mts} +21 -21
  150. package/dist/namespace-D7pE2QWv.mjs +1 -0
  151. package/dist/{namespace-dFBD2ZmS.mjs → namespace-DwQtzlY-.mjs} +1 -1
  152. package/dist/namespace-HsI0Jbbr.mjs +1 -0
  153. package/dist/namespace-VmsT_tLJ.d.mts +3729 -0
  154. package/dist/namespace-Xp9-g_r-.mjs +1 -0
  155. package/dist/{native-session-supervisor-7ElwM6Is.mjs → native-session-supervisor-CdtVGWA9.mjs} +1 -1
  156. package/dist/node/bus-server/index.d.mts +1 -1
  157. package/dist/node/bus-server/index.mjs +1 -1
  158. package/dist/node/bus-server/server-lifecycle.d.mts +1 -1
  159. package/dist/node/bus-server/server-lifecycle.mjs +1 -1
  160. package/dist/node/transports/index.d.mts +36 -1
  161. package/dist/node/transports/index.mjs +2 -2
  162. package/dist/{orchestrator-shared-ChygCvR1.mjs → orchestrator-shared-DAkGOu9H.mjs} +1 -1
  163. package/dist/{orchestrator-shared-DFLb1otg.d.mts → orchestrator-shared-pxtyNu3W.d.mts} +13 -6
  164. package/dist/{package-Co_GO3UD.mjs → package-0gVhAVkO.mjs} +1 -1
  165. package/dist/package-BwvGaKwn.mjs +1 -0
  166. package/dist/package.json +1 -1
  167. package/dist/{profile-BMBXUqqh.mjs → profile-D2m94ZYD.mjs} +1 -1
  168. package/dist/provider-context-BYkMl--1.mjs +1 -0
  169. package/dist/provider-context-DOsjOjiR.mjs +1 -0
  170. package/dist/{providers-namespace-5GoTlHXz.d.mts → providers-namespace-O4de1tgO.d.mts} +161 -14
  171. package/dist/resolved-O2XXjTeu.mjs +1 -0
  172. package/dist/rules/index.d.mts +1 -1
  173. package/dist/rules/index.mjs +1 -1
  174. package/dist/rules/schemas.d.mts +1 -1
  175. package/dist/runtime-bun/index.mjs +1 -1
  176. package/dist/runtime-node/client-binary-strategy-dependencies.d.mts +34 -0
  177. package/dist/runtime-node/client-binary-strategy-dependencies.mjs +1 -0
  178. package/dist/runtime-node/extension-discovery.d.mts +1 -1
  179. package/dist/runtime-node/extension-validation.d.mts +1 -1
  180. package/dist/runtime-node/extension-validation.mjs +1 -1
  181. package/dist/runtime-node/index.d.mts +32 -6
  182. package/dist/runtime-node/index.mjs +24 -24
  183. package/dist/runtime-node/makaio-config.d.mts +1 -1
  184. package/dist/runtime-node/makaio-config.mjs +1 -1
  185. package/dist/runtime-node/workflow-worker/index.d.mts +1 -1
  186. package/dist/runtime-node/workflow-worker/index.mjs +1 -1
  187. package/dist/runtime-node/workflow-worker/worker-entry.mjs +1 -1
  188. package/dist/{schema-7aKBGB7S.mjs → schema-BI0aCHvV.mjs} +1 -1
  189. package/dist/{schema-B5vHi7Uu.d.mts → schema-BnTOFCdU.d.mts} +1 -1
  190. package/dist/{schemas-CNUk34qC2.d.mts → schemas--uwN5dfK2.d.mts} +11 -11
  191. package/dist/schemas-C-J4W1ID.mjs +1 -0
  192. package/dist/{schemas-B_t6oOK-.d.mts → schemas-C17AifUQ.d.mts} +156 -156
  193. package/dist/schemas-D6lj9NMg.mjs +1 -0
  194. package/dist/schemas-K3Td_WdR.d.mts +3175 -0
  195. package/dist/schemas-n9Ff6_RX.mjs +1 -0
  196. package/dist/{schemas-CscdPqCt.d.mts → schemas-qpo1Goit.d.mts} +3 -3
  197. package/dist/selection-YRuVSdck.mjs +1 -0
  198. package/dist/services/adapter-runtime/index.d.mts +3 -3
  199. package/dist/services/adapter-runtime/index.mjs +1 -1
  200. package/dist/services/adapter-runtime/namespace.d.mts +1 -1
  201. package/dist/services/adapter-runtime/schemas.d.mts +1 -1
  202. package/dist/services/adapter-subsystem/index.d.mts +4 -3
  203. package/dist/services/adapter-subsystem/index.mjs +1 -1
  204. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  205. package/dist/services/adapter-subsystem/namespace.mjs +1 -1
  206. package/dist/services/agent-runtime/index.d.mts +2 -2
  207. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  208. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  209. package/dist/services/capability/index.d.mts +1 -1
  210. package/dist/services/capability/index.mjs +1 -1
  211. package/dist/services/codebase/index.d.mts +2 -2
  212. package/dist/services/codebase/namespace.d.mts +1 -1
  213. package/dist/services/codebase/schemas.d.mts +1 -1
  214. package/dist/services/compression/index.d.mts +2 -2
  215. package/dist/services/compression/namespace.d.mts +1 -1
  216. package/dist/services/compression/schemas.d.mts +1 -1
  217. package/dist/services/context-rules/index.d.mts +15 -15
  218. package/dist/services/context-rules/index.mjs +1 -1
  219. package/dist/services/definition/namespace.d.mts +1 -19
  220. package/dist/services/definition/schemas.d.mts +0 -9
  221. package/dist/services/definition/schemas.mjs +1 -1
  222. package/dist/services/execution-target/index.d.mts +4 -4
  223. package/dist/services/execution-target/index.mjs +1 -1
  224. package/dist/services/execution-target/namespace.d.mts +1 -1
  225. package/dist/services/execution-target/namespace.mjs +1 -1
  226. package/dist/services/execution-target/schemas.d.mts +1 -1
  227. package/dist/services/execution-target/schemas.mjs +1 -1
  228. package/dist/services/filesystem/index.d.mts +1 -1
  229. package/dist/services/filesystem/index.mjs +1 -1
  230. package/dist/services/git/namespace.mjs +1 -1
  231. package/dist/services/git/schemas.mjs +1 -1
  232. package/dist/services/harness/index.d.mts +3 -3
  233. package/dist/services/harness/index.mjs +1 -1
  234. package/dist/services/index.d.mts +1705 -287
  235. package/dist/services/index.mjs +1 -1
  236. package/dist/services/log-import/browser.d.mts +2 -2
  237. package/dist/services/log-import/index.d.mts +2 -2
  238. package/dist/services/log-import/log-import.d.mts +1 -1
  239. package/dist/services/log-import/log-import.mjs +1 -1
  240. package/dist/services/log-import/namespace.mjs +1 -1
  241. package/dist/services/log-import/schemas.mjs +1 -1
  242. package/dist/services/model-registry/index.d.mts +1 -1
  243. package/dist/services/model-registry/index.mjs +1 -1
  244. package/dist/services/preferences/index.d.mts +2 -2
  245. package/dist/services/preferences/schemas.d.mts +1 -1
  246. package/dist/services/preferences/storage-namespace.d.mts +2 -2
  247. package/dist/services/provider-context/index.d.mts +2 -2
  248. package/dist/services/provider-context/index.mjs +1 -1
  249. package/dist/services/provider-runtime/index.d.mts +18 -0
  250. package/dist/services/provider-runtime/index.mjs +1 -1
  251. package/dist/services/session/handlers/index.d.mts +1 -1
  252. package/dist/services/session/handlers/index.mjs +1 -1
  253. package/dist/services/session/index.d.mts +10 -10
  254. package/dist/services/session/index.mjs +1 -1
  255. package/dist/services/session/messages/namespace.d.mts +1 -1
  256. package/dist/services/session/messages/namespace.mjs +1 -1
  257. package/dist/services/session/orchestrator-testing/index.d.mts +1 -1
  258. package/dist/services/session/orchestrator-testing/index.mjs +1 -1
  259. package/dist/services/session/session-events/namespace.d.mts +1 -1
  260. package/dist/services/session/session-events/namespace.mjs +1 -1
  261. package/dist/services/session/storage/namespace.d.mts +1 -1
  262. package/dist/services/session/storage/schema.d.mts +1 -1
  263. package/dist/services/session/testing/index.d.mts +2 -2
  264. package/dist/services/session/testing/index.mjs +10 -10
  265. package/dist/services/session/testing/orchestrator-shared.d.mts +1 -1
  266. package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
  267. package/dist/services/session/turns/namespace.d.mts +1 -1
  268. package/dist/services/session/turns/namespace.mjs +1 -1
  269. package/dist/services/session-editor/index.d.mts +1 -1
  270. package/dist/services/session-editor/index.mjs +1 -1
  271. package/dist/services/settings/index.d.mts +3 -3
  272. package/dist/services/settings/index.mjs +1 -1
  273. package/dist/services/settings/namespace.d.mts +18 -25
  274. package/dist/services/settings/namespace.mjs +1 -1
  275. package/dist/services/settings/storage/clients-namespace.d.mts +1 -1
  276. package/dist/services/settings/storage/clients-namespace.mjs +1 -1
  277. package/dist/services/settings/storage/index.d.mts +3 -3
  278. package/dist/services/settings/storage/index.mjs +1 -1
  279. package/dist/services/settings/storage/providers-namespace.d.mts +1 -1
  280. package/dist/services/settings/storage/providers-namespace.mjs +1 -1
  281. package/dist/services/subagent/index.d.mts +2 -2
  282. package/dist/services/subagent/index.mjs +1 -1
  283. package/dist/services/subagent-template/index.d.mts +2 -2
  284. package/dist/services/subagent-template/namespace.d.mts +1 -1
  285. package/dist/services/subagent-template/schemas.d.mts +1 -1
  286. package/dist/services/tool-approval/index.d.mts +1 -1
  287. package/dist/services/tool-approval/index.mjs +1 -1
  288. package/dist/services/tools/index.d.mts +1 -1
  289. package/dist/services/tools/index.mjs +1 -1
  290. package/dist/services/tray-menu/index.d.mts +3 -3
  291. package/dist/services/tray-menu/index.mjs +1 -1
  292. package/dist/services/tray-menu/namespace.d.mts +1 -1
  293. package/dist/services/tray-menu/schemas.d.mts +1 -1
  294. package/dist/services/turn/index.d.mts +1 -1
  295. package/dist/services/turn/namespace.d.mts +1 -1
  296. package/dist/session-CAjudDuJ.mjs +76 -0
  297. package/dist/{session-DBfQkgdy.mjs → session-lRd8HZNZ.mjs} +1 -1
  298. package/dist/{session-lineage-C1M7-O3C.d.mts → session-lineage-BLw8iWAj.d.mts} +1 -1
  299. package/dist/{shared-BVW-3Dhy.mjs → shared-RP_KARKF.mjs} +1 -1
  300. package/dist/{skill-N-ttlp1i.mjs → skill-CpNjWFuE.mjs} +1 -1
  301. package/dist/{src-Ck2sbaDa.mjs → src-Bo2eA51B.mjs} +1 -1
  302. package/dist/storage/drizzle/client.d.mts +1 -1
  303. package/dist/storage/drizzle/client.mjs +1 -1
  304. package/dist/storage/drizzle/index.d.mts +1 -1
  305. package/dist/storage/drizzle/index.mjs +1 -1
  306. package/dist/storage/handlers/drizzle/index.d.mts +1 -1
  307. package/dist/storage/handlers/drizzle/index.mjs +1 -1
  308. package/dist/storage/handlers/index.d.mts +1 -1
  309. package/dist/storage/handlers/index.mjs +1 -1
  310. package/dist/{tool-approval-service-DEiMKTv9.mjs → tool-approval-service-Dh0XI21f.mjs} +1 -1
  311. package/dist/tools-C8vqn1KY.mjs +1 -0
  312. package/dist/{transition-OzGXyy3p.d.mts → transition-Bfe8VVc1.d.mts} +2 -2
  313. package/dist/{types-BWduCvRU.d.mts → types-B-xY9WW2.d.mts} +1 -1
  314. package/dist/{types-BMS6yfLS.d.mts → types-DWNoZ3Sd.d.mts} +1 -1
  315. package/dist/{types-1a2D10yb.d.mts → types-DvKaEOOn.d.mts} +265 -19
  316. package/dist/{types-BSilhlYE.d.mts → types-q95p55BF.d.mts} +434 -284
  317. package/dist/ui-hooks/index.d.mts +103 -14
  318. package/dist/ui-hooks/index.mjs +1 -1
  319. package/dist/ui-kernel/index.d.mts +3 -3
  320. package/dist/ui-kernel/pages/schemas.d.mts +1 -1
  321. package/dist/utils/keychain.mjs +1 -1
  322. package/dist/{version-DoV_pSzT.mjs → version-C1-VD-XL.mjs} +1 -1
  323. package/dist/workflow-CvVAZ89A.mjs +1 -0
  324. package/dist/workflow-engine/index.d.mts +24 -24
  325. package/dist/workflow-engine/index.mjs +1 -1
  326. package/dist/workflow-engine/package.d.mts +1 -1
  327. package/dist/workflow-engine/package.mjs +1 -1
  328. package/dist/workflow-engine/workflow-orchestrator.mjs +1 -1
  329. package/dist/{workflow-worker-dH70EbjE.mjs → workflow-worker-CudfEstp.mjs} +1 -1
  330. package/package.json +5 -1
  331. package/dist/account-identity-C7Kx_ieU.mjs +0 -1
  332. package/dist/cleanEnvForAdapter-BooAgM2R.mjs +0 -1
  333. package/dist/client-DaR4mzqn.mjs +0 -1
  334. package/dist/compression-C5JAWdgZ.mjs +0 -1
  335. package/dist/config-namespace-CY9leBnE.mjs +0 -1
  336. package/dist/credential-ref-YWQQENEo.mjs +0 -1
  337. package/dist/definition-C-GVz7uw.mjs +0 -1
  338. package/dist/execution-target-BR8bLkCR.mjs +0 -1
  339. package/dist/extension-BS_4BOeO.mjs +0 -1
  340. package/dist/handlers-B74FvKlA.mjs +0 -57
  341. package/dist/index-BUrNl0QJ.d.mts +0 -997
  342. package/dist/index-DtwGhFFQ.d.mts +0 -40
  343. package/dist/index-mU2lnU7O.d.mts +0 -749
  344. package/dist/namespace-BO3tODGC.mjs +0 -1
  345. package/dist/namespace-CVMZVqB5.mjs +0 -1
  346. package/dist/namespace-DBHwyhME.mjs +0 -1
  347. package/dist/namespace-DibbhCPP.mjs +0 -1
  348. package/dist/namespace-d_0I6P7N.d.mts +0 -1317
  349. package/dist/package-CF_Zm2v4.mjs +0 -1
  350. package/dist/provider-context-CqMgPOWF.mjs +0 -1
  351. package/dist/provider-context-DC_eq7es.mjs +0 -1
  352. package/dist/schemas-CVo8qAK-.mjs +0 -1
  353. package/dist/schemas-CuG17U3L.mjs +0 -1
  354. package/dist/session-CX6QDhi2.mjs +0 -76
  355. package/dist/tools-CGFZkB7F.mjs +0 -1
  356. package/dist/workflow-C3dgVwTY.mjs +0 -1
  357. /package/dist/{ajv-B5dPIck0.mjs → ajv-DfHhgdS5.mjs} +0 -0
  358. /package/dist/{await-trigger-DwVldnMt.mjs → await-trigger-D623tvig.mjs} +0 -0
  359. /package/dist/{capability-service-XlymTzz1.mjs → capability-service-Dg2bU8qc.mjs} +0 -0
  360. /package/dist/{client-CebV_fZc.d.mts → client-DmJwprw1.d.mts} +0 -0
  361. /package/dist/{create-static-mount-DkK28kKW.mjs → create-static-mount-CBTXRtbN.mjs} +0 -0
  362. /package/dist/{cross-spawn-CDXy3BjE.mjs → cross-spawn-D9WWFl2a.mjs} +0 -0
  363. /package/dist/{cursor-storage-luQAg7E_.mjs → cursor-storage-Bw-7ROzx.mjs} +0 -0
  364. /package/dist/{descriptor-to-package-DdpjpT7n.mjs → descriptor-to-package-D5SWf6TL.mjs} +0 -0
  365. /package/dist/{drizzle-DVTAl7Us.mjs → drizzle-DYfaDzlO.mjs} +0 -0
  366. /package/dist/{esm-CQG9Pc7n.mjs → esm-oHhRYTEn.mjs} +0 -0
  367. /package/dist/{event-DguYjV6D.mjs → event-DTM0-qWP.mjs} +0 -0
  368. /package/dist/{extension-discovery-CIZn5bkq.d.mts → extension-discovery-APMf1Tes.d.mts} +0 -0
  369. /package/dist/{extension-namespace-v3K0qVry.mjs → extension-namespace-vrh4ERXR.mjs} +0 -0
  370. /package/dist/{facet-BM4y4aQP.mjs → facet-DqPBpqkl.mjs} +0 -0
  371. /package/dist/{filesystem-service-Cwp0sWNc.d.mts → filesystem-service-Bx0bR2Lb.d.mts} +0 -0
  372. /package/dist/{handler-BFNvtv5t.mjs → handler-4pKQi3eo.mjs} +0 -0
  373. /package/dist/{host-vY07gek-.mjs → host-BfgdjlII.mjs} +0 -0
  374. /package/dist/{identity-DC3Pk0ps.mjs → identity-2qUT1NME.mjs} +0 -0
  375. /package/dist/{index-COI1tjAf.d.mts → index-BZ_DSGnE.d.mts} +0 -0
  376. /package/dist/{index-D7rWAEY0.d.mts → index-Bd52mmj9.d.mts} +0 -0
  377. /package/dist/{index-Dfi8Rorw.d.mts → index-BkAKfh4d.d.mts} +0 -0
  378. /package/dist/{index-CuHqL95P.d.mts → index-Bv9lm0Kf.d.mts} +0 -0
  379. /package/dist/{index-C4nStEdA.d.mts → index-C18Pn3zP.d.mts} +0 -0
  380. /package/dist/{index-Cr9lh21j.d.mts → index-CarbJsC92.d.mts} +0 -0
  381. /package/dist/{index-BjoOSg95.d.mts → index-Ctw617Tj.d.mts} +0 -0
  382. /package/dist/{index-DUD7wikz2.d.mts → index-D0eUQjTU2.d.mts} +0 -0
  383. /package/dist/{index-DTBQOCar.d.mts → index-DNc1yLQs.d.mts} +0 -0
  384. /package/dist/{index-D3ahzHwb.d.mts → index-DnWZdG6C.d.mts} +0 -0
  385. /package/dist/{index-CpKikwK4.d.mts → index-DoLdETfR.d.mts} +0 -0
  386. /package/dist/{index-B92mToDo2.d.mts → index-DvaPrL6C.d.mts} +0 -0
  387. /package/dist/{index-D7Hkmrr3.d.mts → index-DwDBa2mb.d.mts} +0 -0
  388. /package/dist/{index-Y8rMeYYX.d.mts → index-FDyqQIt5.d.mts} +0 -0
  389. /package/dist/{index-BWIkf5oJ.d.mts → index-Lp0T_V1W.d.mts} +0 -0
  390. /package/dist/{index-OGIC4puQ.d.mts → index-Rhcr4YNA.d.mts} +0 -0
  391. /package/dist/{index-BvLXySoB2.d.mts → index-S-mAqWwq.d.mts} +0 -0
  392. /package/dist/{index-DOOrKin9.d.mts → index-_zsihEmk.d.mts} +0 -0
  393. /package/dist/{index-wq7XeqyG.d.mts → index-iJP-l15K.d.mts} +0 -0
  394. /package/dist/{json-value-DtIkQN7g.d.mts → json-value-C8duSh9X.d.mts} +0 -0
  395. /package/dist/{jsonl-transport-CGPgD8iU.mjs → jsonl-transport-l5NPcQ_2.mjs} +0 -0
  396. /package/dist/{lib-ZKtnbCqH.mjs → lib-ClRTNIuz.mjs} +0 -0
  397. /package/dist/{materialization-CUYxZCfk.mjs → materialization-BwTORtBr.mjs} +0 -0
  398. /package/dist/{model-registry-C2VXobZj.mjs → model-registry-BneK5SGo.mjs} +0 -0
  399. /package/dist/{model-registry-rYICIwyR.mjs → model-registry-C8MInDtX.mjs} +0 -0
  400. /package/dist/{namespace-65uwTpbg.d.mts → namespace-3YVLQ_bM.d.mts} +0 -0
  401. /package/dist/{namespace-CQ8uza7o.d.mts → namespace-BcDHt-ww.d.mts} +0 -0
  402. /package/dist/{namespace-BigVYQyx.d.mts → namespace-BhVlHfoO.d.mts} +0 -0
  403. /package/dist/{namespace-Dk4OslmY.d.mts → namespace-BsEoWXV_.d.mts} +0 -0
  404. /package/dist/{namespace-DYSFDC2G.mjs → namespace-C238RqwB.mjs} +0 -0
  405. /package/dist/{namespace-BdO4e1Fm.mjs → namespace-CDO4rY11.mjs} +0 -0
  406. /package/dist/{namespace-wke7juzy.mjs → namespace-DDx4NVJm.mjs} +0 -0
  407. /package/dist/{namespace-D1_9WVCo.d.mts → namespace-Dar3O6iT.d.mts} +0 -0
  408. /package/dist/{namespace-DAj_riOn.d.mts → namespace-DoNigVgx.d.mts} +0 -0
  409. /package/dist/{namespace-D2s-4pyg.d.mts → namespace-Dvi66QS6.d.mts} +0 -0
  410. /package/dist/{out-BoEZjBNz.mjs → out-BB6Kb4Xu.mjs} +0 -0
  411. /package/dist/{package-DmVZxufT.d.mts → package-CdBiknf3.d.mts} +0 -0
  412. /package/dist/{platform-DnbSvm2u.mjs → platform-CWhGFQFX.mjs} +0 -0
  413. /package/dist/{providers-Bd7BOZs0.mjs → providers-CUnrif24.mjs} +0 -0
  414. /package/dist/{quick-lru-6e7I1Bgf.mjs → quick-lru-BLaSzINB.mjs} +0 -0
  415. /package/dist/{registry-U_3aYSin.mjs → registry-TJjQgTgp.mjs} +0 -0
  416. /package/dist/{schema-CHp6I33k.mjs → schema-cus0dJ81.mjs} +0 -0
  417. /package/dist/{schema-introspection-B7xODt4I.mjs → schema-introspection-BsWLmoFp.mjs} +0 -0
  418. /package/dist/{schemas-KlH1hB7u.d.mts → schemas-9QJf1FtS.d.mts} +0 -0
  419. /package/dist/{schemas-CJ2JvA7d.d.mts → schemas-BolSW7pQ.d.mts} +0 -0
  420. /package/dist/{schemas-D4zaFE2p.d.mts → schemas-CLsbsX1W.d.mts} +0 -0
  421. /package/dist/{schemas-XeIBqwvE.mjs → schemas-CMyv7l7-.mjs} +0 -0
  422. /package/dist/{schemas-CPI00yvh.mjs → schemas-CWxf_Yut.mjs} +0 -0
  423. /package/dist/{schemas-BemsLc_V.d.mts → schemas-D_9X_CRo.d.mts} +0 -0
  424. /package/dist/{schemas-DZGnr9Tl.mjs → schemas-DwfTUQIa.mjs} +0 -0
  425. /package/dist/{schemas-B6tEKf9T.d.mts → schemas-XRhqOgVE.d.mts} +0 -0
  426. /package/dist/{schemas-DKncXGnb.d.mts → schemas-fRLDhefF.d.mts} +0 -0
  427. /package/dist/{schemas-DWfo0wp4.d.mts → schemas-jDRSOXJL.d.mts} +0 -0
  428. /package/dist/{schemas-t6h9oSct.d.mts → schemas-qt5QTjVc.d.mts} +0 -0
  429. /package/dist/{semver-CIhHqMkw.mjs → semver-BccS1s9R.mjs} +0 -0
  430. /package/dist/{server-lifecycle-C5Z5PSMD.mjs → server-lifecycle-D-jxVr_0.mjs} +0 -0
  431. /package/dist/{server-lifecycle-_AA6EfzL.d.mts → server-lifecycle-r5Tkk8bU.d.mts} +0 -0
  432. /package/dist/{shared-schemas-BEVG96xW.mjs → shared-schemas-BNCPgGYP.mjs} +0 -0
  433. /package/dist/{src-_VODAJnf.mjs → src-Ci_WY9uw.mjs} +0 -0
  434. /package/dist/{storage-namespace-D5q9CrBp.mjs → storage-namespace-BzE2M4Hq.mjs} +0 -0
  435. /package/dist/{storage-namespace-Di1A3DMm.d.mts → storage-namespace-DWKFqEW-.d.mts} +0 -0
  436. /package/dist/{storage-namespace-definition-CzXPW45M.mjs → storage-namespace-definition-4UYuij1r.mjs} +0 -0
  437. /package/dist/{storage-namespace-definition-BffdI5Bz.d.mts → storage-namespace-definition-BZJGSaX3.d.mts} +0 -0
  438. /package/dist/{supports-color-DcXkvGDF.mjs → supports-color-Dzp6WuF5.mjs} +0 -0
  439. /package/dist/{telemetry-Cvi4rxiE.mjs → telemetry-B42EMbZt.mjs} +0 -0
  440. /package/dist/{timeout-XsYIOKrc.mjs → timeout-CvONPl0l.mjs} +0 -0
  441. /package/dist/{tray-menu-service-B2AxiQqL.mjs → tray-menu-service-Bonl2KXf.mjs} +0 -0
  442. /package/dist/{types-Bo78h9e3.d.mts → types-BCW9kr4L.d.mts} +0 -0
  443. /package/dist/{types-DCvp_swt.d.mts → types-CrJ7KEZ0.d.mts} +0 -0
  444. /package/dist/{ui-config-9bDRwFZr.mjs → ui-config-B2L3Xgqo.mjs} +0 -0
  445. /package/dist/{variant-5huHjUTm.mjs → variant-ByI-RZua.mjs} +0 -0
  446. /package/dist/{window-registry-PkrFIwX2.mjs → window-registry-DsWnCc8z.mjs} +0 -0
  447. /package/dist/{window-registry-ofIUQnfo.d.mts → window-registry-WsWu-rcK.d.mts} +0 -0
@@ -1,10 +1,10 @@
1
- import { A as MessageDeliveryMode, B as AIReasoningLevel, C as NormalizedCallUsage, D as ConfigFactoryInput, E as StartAgentOptions, F as MessageResult, G as ToolLedgerEntry, H as ISessionToolLedger, I as MessageState, L as ProcessingState, M as markCompletedWithFinalResult, N as NormalizedMessageInput, O as IAdapterConfigFactory, P as normalizeMessageInput, R as SendMessageOptions, S as GetCapabilitiesResponsePayload, T as SendMessageResponsePayload, U as LedgerSessionContext, V as ReasoningLevelMap, W as SessionToolLedger, _ as BaseAgentConnectorConfig, a as AgentCredentialChangeResponsePayload, b as ContextWindowInput, c as AgentIdentity, d as AgentMcpServersSetRequestPayload, f as AgentMcpServersSetResponsePayload, g as AgentStartResult, h as AgentSendMessageOptions, i as AgentCredentialChangeRequestPayload, j as MessageHandle, k as AIAgentConnector, l as AgentInterruptRequestPayload, m as AgentModelChangeResponsePayload, n as AgentConnectorConfigOverrides, o as AgentCwdChangeRequestPayload, p as AgentModelChangeRequestPayload, r as AgentContext, s as AgentCwdChangeResponsePayload, t as AIAgentConfig, u as AgentInterruptResponsePayload, v as ConnectorSendMessageOptions, w as SendMessageRequestPayload, x as ExecutionContext, y as ConnectorStartOptions, z as AIModel } from "../types-1a2D10yb.mjs";
2
- import { S as toImportSegment, _ as LogImporter, a as CompactionMetadata, b as ProcessLogFileResult, c as ExternalToolIdentifiers, d as ImportMetadata, f as ImportSegment, g as LogImportTestConfig, h as LogImportSessionContext, l as ExternalToolMeta, m as ImportSegmentTurn, n as LogOrchestratorConfig, o as DiscoveryMetadata, p as ImportSegmentLineage, r as ParseFileResult, s as ExternalToolIdentifier, u as ImportCursorPosition, v as LogImporterConfig, x as StorageMessagePayload, y as NormalizedEvent } from "../base-orchestrator-J1WKAUkF.mjs";
1
+ import { $ as NormalizedMessageInput, C as NormalizedCallUsage, D as AdapterAuthLeaseHandle, E as StartAgentOptions, J as IAdapterConfigFactory, K as AdapterProviderDefinition, O as AdapterAuthRuntimePreparer, Q as markCompletedWithFinalResult, S as GetCapabilitiesResponsePayload, T as SendMessageResponsePayload, X as MessageDeliveryMode, Y as AIAgentConnector, Z as MessageHandle, _ as BaseAgentConnectorConfig, a as AgentCredentialChangeResponsePayload, at as AIModel, b as ContextWindowInput, c as AgentIdentity, ct as ISessionToolLedger, d as AgentMcpServersSetRequestPayload, dt as ToolLedgerEntry, et as normalizeMessageInput, f as AgentMcpServersSetResponsePayload, g as AgentStartResult, h as AgentSendMessageOptions, i as AgentCredentialChangeRequestPayload, it as SendMessageOptions, j as ResolvedAdapterRuntimeConfig, k as BoundAdapterRuntimeConfig, l as AgentInterruptRequestPayload, lt as LedgerSessionContext, m as AgentModelChangeResponsePayload, n as AgentConnectorConfigOverrides, nt as MessageState, o as AgentCwdChangeRequestPayload, ot as AIReasoningLevel, p as AgentModelChangeRequestPayload, q as ConfigFactoryInput, r as AgentContext, rt as ProcessingState, s as AgentCwdChangeResponsePayload, st as ReasoningLevelMap, t as AIAgentConfig, tt as MessageResult, u as AgentInterruptResponsePayload, ut as SessionToolLedger, v as ConnectorSendMessageOptions, w as SendMessageRequestPayload, x as ExecutionContext, y as ConnectorStartOptions } from "../types-DvKaEOOn.mjs";
2
+ import { S as toImportSegment, _ as LogImporter, a as CompactionMetadata, b as ProcessLogFileResult, c as ExternalToolIdentifiers, d as ImportMetadata, f as ImportSegment, g as LogImportTestConfig, h as LogImportSessionContext, l as ExternalToolMeta, m as ImportSegmentTurn, n as LogOrchestratorConfig, o as DiscoveryMetadata, p as ImportSegmentLineage, r as ParseFileResult, s as ExternalToolIdentifier, u as ImportCursorPosition, v as LogImporterConfig, x as StorageMessagePayload, y as NormalizedEvent } from "../base-orchestrator-BiShpVKL.mjs";
3
3
  import { z } from "zod";
4
4
  import * as _$_makaio_core0 from "@makaio/framework/core";
5
5
  import { CreateBusNamespaceOptions, ExtractSubjectPayload, FilterablePayloadIntersection, HandlerForSubjectDefinition, RegistrableBusNamespaceDefinition, RequestContext, SchemaRecord, ScopedSubjectDefinition, SubjectDefinition, SubjectRecordFromSchemaRecord } from "@makaio/framework/core";
6
6
  import { BusNamespace, IMakaioBus, 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, NativeForkDirective, ProviderContext, ProviderDefinitionInput, ReasoningLevelMap as ReasoningLevelMap$1, RequestCorrelationContext, ResponseSchemaDescriptor, SendMessageRequest, SendMessageResponse, SessionContext, SessionMessageBlock, StartAgentRequest, StartAgentResponse, StartMode, StepType, SystemPrompt, ToolListItem } from "@makaio/framework/contracts";
7
+ import { AIReasoningLevel as AIReasoningLevel$1, AdapterClientRef, AdapterDefinitionContract, AdapterProviderAuth, AdapterProviderRef, AdapterSubjects, AgentSchemas, AgentStarted, AgentSubjects, AgentToolApproveRequest, AgentToolApproveResponse, BlockData, HarnessDefinition, HarnessSubjects, JsonValue, McpResolvedServer, McpRuntimeSessionContext, McpSessionContext, McpToolState, Message, MessageInput, NativeForkDirective, ProtocolId, ProviderContext, ProviderDefinitionInput, ReasoningLevelMap as ReasoningLevelMap$1, RequestCorrelationContext, ResponseSchemaDescriptor, SendMessageRequest, SendMessageResponse, SessionContext, SessionMessageBlock, StartAgentRequest, StartAgentResponse, StartMode, StepType, SystemPrompt, ToolListItem } from "@makaio/framework/contracts";
8
8
  import * as _$_makaio_storage_core0 from "@makaio/framework/storage";
9
9
  import * as _$_makaio_ai_adapters_core0 from "@makaio/framework/adapters";
10
10
  import * as _$type_fest0 from "type-fest";
@@ -80,56 +80,6 @@ interface LogImportRegistration {
80
80
  clientId?: string;
81
81
  }
82
82
  //#endregion
83
- //#region adapters/core/src/types/provider-definition.d.ts
84
- /**
85
- * Runtime adapter provider definition pairing a serializable provider definition
86
- * with optional runtime-only schemas.
87
- *
88
- * Extends {@link AdapterProviderDefinitionContract} from `@makaio/contracts` which
89
- * is the single source of truth for the `definition`, `configSchema`, and
90
- * `credentialSchema` fields. All fields are inherited from the contract — this
91
- * type exists to give the shape a domain-specific name used throughout
92
- * adapter implementation packages and to allow future additions specific to
93
- * `ai-adapters-core`.
94
- *
95
- * Each adapter exports an array of these from its `definition.ts` (via `providers`).
96
- * The `definition` field contains serializable data (models, endpoints, etc.).
97
- * The schema fields are runtime-only — used for UI form generation, never serialized.
98
- * @example
99
- * ```typescript
100
- * const anthropicProvider: AdapterProviderDefinition = {
101
- * definition: {
102
- * id: 'anthropic',
103
- * name: 'Anthropic',
104
- * endpoints: { anthropic: 'https://api.anthropic.com' },
105
- * defaultModel: 'sonnet',
106
- * availableModels: [...]
107
- * },
108
- * credentialSchema: z.object({
109
- * apiKey: z.string().describe('Anthropic API Key')
110
- * })
111
- * };
112
- * ```
113
- */
114
- interface AdapterProviderDefinition extends AdapterProviderDefinitionContract {
115
- /**
116
- * Provider-specific config schema for UI form generation (runtime-only).
117
- *
118
- * Defines provider-specific configuration fields like debugging flags,
119
- * rate limiting options, or provider-specific features.
120
- * Not serialized — used for dynamic form generation in the settings UI.
121
- */
122
- readonly configSchema?: z.ZodObject<z.ZodRawShape>;
123
- /**
124
- * Provider-specific credential schema for secure credential capture (runtime-only).
125
- *
126
- * Defines credential fields (apiKey, apiSecret, etc.) for secure input.
127
- * Credentials are stored separately via the credential service, never in plain config.
128
- * Not serialized — used for dynamic form generation in the settings UI.
129
- */
130
- readonly credentialSchema?: z.ZodObject<z.ZodRawShape>;
131
- }
132
- //#endregion
133
83
  //#region adapters/core/src/types/ai-adapter-init-options.d.ts
134
84
  /**
135
85
  * Platform-provided defaults injected by the runtime.
@@ -147,7 +97,7 @@ interface PlatformDefaults {
147
97
  * ```typescript
148
98
  * await adapter.init({
149
99
  * defaultModel: "claude-3.5-sonnet",
150
- * providerOptions: { apiKey: process.env.API_KEY }
100
+ * providerOptions: { baseUrl: "https://api.example.com" }
151
101
  * });
152
102
  * ```
153
103
  * @see {@link AIAdapterPromptOptions} for per-message config
@@ -156,7 +106,7 @@ interface PlatformDefaults {
156
106
  interface AIAdapterInitOptions {
157
107
  /** Default model when not specified per-message. Provider-specific identifier. */
158
108
  defaultModel?: string;
159
- /** Provider-specific config (API keys, base URLs, defaults, etc.). Type explicitly in adapter implementations. */
109
+ /** Provider-specific non-secret config (base URLs, defaults, etc.). Type explicitly in adapter implementations. */
160
110
  providerOptions?: unknown;
161
111
  adapterId?: string;
162
112
  /**
@@ -177,6 +127,8 @@ interface AIAdapterInitOptions {
177
127
  definitionProviders?: AdapterProviderDefinition[];
178
128
  /** Client identifier for the application this adapter belongs to (e.g., 'claude-code', 'codex'). Omit for API-only adapters. */
179
129
  clientId?: string;
130
+ /** Trusted non-serializable normalized auth preparer injected by the host. */
131
+ prepareAuthRuntime?: AdapterAuthRuntimePreparer;
180
132
  }
181
133
  //#endregion
182
134
  //#region adapters/core/src/utils/safeJsonStringify.d.ts
@@ -564,47 +516,43 @@ type InjectedTestFields<TBus extends ScopedBus<string>> = {
564
516
  adapterName: string;
565
517
  bus: TBus;
566
518
  /**
567
- * Unresolved provider context for conformance tests.
568
- *
569
- * When a `testProviderDefinition` is supplied, credential refs are built
570
- * from the definition's `credentialEnvVars` mapping using `env:VAR_NAME`
571
- * format. Connectors resolve these refs locally via `resolveConnectorCredentials()`
572
- * — which reads from `process.env` for `env:` refs — mirroring the full
573
- * credential-resolution chain without requiring a database or bus handlers.
519
+ * Refs-only normalized provider context for conformance tests.
574
520
  *
575
- * Falls back to a minimal sentinel (empty `credentialRefs`) when no definition
576
- * is provided.
521
+ * A missing definition or auth method remains the closed unresolved state.
577
522
  */
578
- providerContext: ProviderContext;
523
+ providerContext: ProviderContext; /** Exact selected adapter/provider protocol for endpoint resolution. */
524
+ providerProtocol?: ProtocolId; /** Exact selected adapter/provider auth declaration. */
525
+ adapterProviderAuth?: AdapterProviderAuth; /** Other compatible auth declarations contributing to environment scrubbing. */
526
+ compatibleProviderAuths: AdapterProviderAuth[];
579
527
  };
580
528
  /** Result type: options merged with injected fields (handles undefined options) */
581
- type ResolvedTestConfig<TOptions, TBus extends ScopedBus<string>> = (TOptions extends undefined ? object : TOptions) & InjectedTestFields<TBus>;
529
+ type TestConfigOptionsInput = Omit<CreateTestAgentOptions, 'providerContext'> & {
530
+ providerContext?: unknown;
531
+ };
532
+ type ResolvedTestConfig<TBus extends ScopedBus<string>> = Omit<TestConfigOptionsInput, 'providerContext'> & InjectedTestFields<TBus>;
582
533
  /**
583
- * Build an unresolved provider context for conformance tests.
534
+ * Build a normalized provider context for conformance tests.
584
535
  *
585
- * When a provider definition is supplied, builds credential refs in `env:VAR_NAME`
586
- * format from `credentialEnvVars`. Connectors resolve these refs locally via
587
- * `resolveConnectorCredentials()`. Otherwise returns a minimal sentinel.
536
+ * Explicit fields use their first declared environment source hint. Definitions
537
+ * without a selectable provider-owned method remain unresolved; tests for
538
+ * client-owned auth provide a context explicitly.
588
539
  * @param definition - Optional provider definition to build credential refs from
589
- * @param ambientCredentialDefinitions - Provider definitions whose credential
590
- * env vars should be stripped from ambient subprocess environments
591
- * @returns Fresh unresolved provider context per call to prevent cross-test mutation leaks
540
+ * @returns Fresh refs-only provider context per call.
592
541
  */
593
- declare function createTestProviderContext(definition?: ProviderDefinitionInput, ambientCredentialDefinitions?: readonly ProviderDefinitionInput[]): ProviderContext;
542
+ declare function createTestProviderContext(definition?: ProviderDefinitionInput): ProviderContext;
594
543
  /**
595
544
  * Resolves test configuration by adding required fields (bus, agentId, adapterId, adapterName, providerContext).
596
545
  *
597
- * When `testProviderDefinition` is supplied, credential refs and endpoint overrides
598
- * are built from the definition's `credentialEnvVars` and `endpoints` — so
546
+ * When `testProviderDefinition` is supplied, normalized auth refs and endpoint overrides
547
+ * are built from the definition's auth methods and endpoints — so
599
548
  * conformance tests can run against real providers without the full orchestrator.
600
549
  * @param options - Partial test agent options (undefined = empty config)
601
550
  * @param bus - Scoped bus instance for the adapter
602
551
  * @param testProviderDefinition - Optional provider definition for credential ref building
603
- * @param ambientCredentialDefinitions - Provider definitions whose credential
604
- * env vars should be stripped from ambient subprocess environments
552
+ * @param adapterProviderRefs - Exact adapter/provider declarations under test
605
553
  * @returns Complete test config with required fields injected
606
554
  */
607
- declare function resolveTestConfig<TOptions extends CreateTestAgentOptions | undefined, TBus extends ScopedBus<string>>(options: TOptions, bus: TBus, testProviderDefinition?: ProviderDefinitionInput, ambientCredentialDefinitions?: readonly ProviderDefinitionInput[]): ResolvedTestConfig<TOptions, TBus>;
555
+ declare function resolveTestConfig<TBus extends ScopedBus<string>>(options: TestConfigOptionsInput | undefined, bus: TBus, testProviderDefinition?: ProviderDefinitionInput, adapterProviderRefs?: readonly AdapterProviderRef[]): ResolvedTestConfig<TBus>;
608
556
  //#endregion
609
557
  //#region adapters/core/src/utils/resolveConformanceTestPreset.d.ts
610
558
  /** Default environment variable for selecting a conformance provider preset. */
@@ -623,8 +571,8 @@ type ConformanceEnvReader = (name: string) => string | undefined;
623
571
  interface ResolveConformanceTestPresetOptions {
624
572
  /** Adapter name used in configuration error messages. */
625
573
  adapterName: string;
626
- /** Provider ID used when no env override is supplied. */
627
- defaultProviderId: string;
574
+ /** Test provider definition ID used when no environment override is supplied. */
575
+ testProviderDefinitionId: string;
628
576
  /** Provider IDs accepted by this adapter's conformance config. */
629
577
  providerIds: readonly string[];
630
578
  /** Full provider definitions supplied by the conformance harness. */
@@ -658,7 +606,7 @@ interface ResolvedConformanceTestPreset {
658
606
  /**
659
607
  * Resolve a conformance test provider preset from defaults plus MAKAIO_CONFORMANCE_* overrides.
660
608
  *
661
- * Provider, primary model, secondary model, credentials, and endpoint overrides
609
+ * Provider, primary model, secondary model, authentication, and endpoint overrides
662
610
  * are resolved together so CI can swap test economics without changing local
663
611
  * OAuth/default behavior.
664
612
  * @param options - Resolver inputs and optional env variable names
@@ -751,6 +699,8 @@ interface ConnectorSessionConfig<TBus extends ScopedBus<string> = ScopedBus<stri
751
699
  cwd: string;
752
700
  model: string;
753
701
  env: Record<string, string>;
702
+ /** Auth-free environment safe for bus-routable tool and MCP contexts. */
703
+ contextEnv?: Readonly<Record<string, string>>;
754
704
  }
755
705
  /**
756
706
  * Interface for turn-like objects that support pause/abort operations.
@@ -775,7 +725,39 @@ declare abstract class BaseConnectorSession<TConfig extends ConnectorSessionConf
775
725
  protected readonly bus: TConfig['bus'];
776
726
  protected sessionId?: string;
777
727
  protected currentTurn?: PausableTurn;
728
+ /**
729
+ * True once `close()` or `abort()` has begun; gates queue processing.
730
+ *
731
+ * ## Shutdown vs queue processing invariant
732
+ *
733
+ * Once `close()` or `abort()` begins, no new turn may start.
734
+ * `processQueue` implementations must refuse to dequeue or start turns
735
+ * when `this.closing` is `true`, and drain all remaining queued handles
736
+ * with an error outcome so that callers awaiting `waitForCompletion()`
737
+ * resolve deterministically instead of hanging.
738
+ *
739
+ * A dequeued handle that has entered the start-turn path either starts
740
+ * its turn before `close()` begins, or is completed with the closing
741
+ * error at every await point where `close()` can interleave. This is
742
+ * enforced by {@link completeHandleIfClosing}, which rechecks the flag
743
+ * after each awaited setup step and completes the handle with the same
744
+ * error contract used by {@link rejectQueuedHandles}.
745
+ */
746
+ protected closing: boolean;
778
747
  constructor(config: TConfig);
748
+ /**
749
+ * Recheck the shutdown flag after an awaited setup step in the start path.
750
+ *
751
+ * When `close()` sets `this.closing` while the subclass start-turn method
752
+ * is awaiting an async setup step (schema rotation, query creation, MCP
753
+ * registration, env resolution), the dequeued handle is no longer in the
754
+ * queue and {@link rejectQueuedHandles} cannot reach it. This helper
755
+ * completes the handle with the same error contract so callers see a
756
+ * consistent shutdown outcome.
757
+ * @param handle - Dequeued message handle currently being set up
758
+ * @returns `true` when the session is closing and the handle was completed
759
+ */
760
+ protected completeHandleIfClosing(handle: MessageHandle): boolean;
779
761
  /**
780
762
  * Abort the session and cleanup resources.
781
763
  * Pauses the current turn if one is active.
@@ -1081,6 +1063,16 @@ declare class UserMessageQueue {
1081
1063
  }
1082
1064
  //#endregion
1083
1065
  //#region adapters/core/src/session/process-queue.d.ts
1066
+ /**
1067
+ * Canonical error message used when a queued message cannot be processed
1068
+ * because the session has entered the shutdown path.
1069
+ *
1070
+ * Shared between {@link rejectQueuedHandles} (queue drain) and the per-handle
1071
+ * shutdown gate ({@link BaseConnectorSession.completeHandleIfClosing}) so that
1072
+ * callers see a consistent error contract regardless of whether the handle was
1073
+ * still in the queue or had already been dequeued when `close()` interleaved.
1074
+ */
1075
+ declare const SESSION_CLOSED_QUEUE_ERROR = "Session closed before queued message could be processed";
1084
1076
  /**
1085
1077
  * Minimal turn interface required by processQueue orchestration.
1086
1078
  *
@@ -1141,11 +1133,18 @@ interface ProcessQueueCallbacks<TExtra = unknown> {
1141
1133
  onBeforeImmediateTurn?: () => Promise<void>;
1142
1134
  /**
1143
1135
  * Start a new turn with the given message and optional merge data.
1136
+ *
1137
+ * Returns `void` (or `undefined`) when the turn was started normally.
1138
+ * Returns `false` explicitly when the turn was **not** started (e.g.,
1139
+ * shutdown interleaved during setup and the handle was completed with
1140
+ * an error). `processQueueMessages` propagates this so callers see an
1141
+ * accurate "no turn started" result and can transition to idle.
1144
1142
  * @param handle - The message handle to process
1145
1143
  * @param mergedContent - Text content from superseded/merged messages
1146
1144
  * @param extra - Adapter-specific extra merge data
1145
+ * @returns `false` when the turn was skipped; `void` otherwise
1147
1146
  */
1148
- startNewTurn: (handle: MessageHandle, mergedContent?: string[], extra?: TExtra) => Promise<void>;
1147
+ startNewTurn: (handle: MessageHandle, mergedContent?: string[], extra?: TExtra) => Promise<void | false>;
1149
1148
  }
1150
1149
  /**
1151
1150
  * Shared processQueue orchestration for all session implementations.
@@ -1170,6 +1169,16 @@ interface ProcessQueueCallbacks<TExtra = unknown> {
1170
1169
  * @typeParam TExtra - Type of adapter-specific extra merge data
1171
1170
  */
1172
1171
  declare function processQueueMessages<TExtra = unknown>(queue: UserMessageQueue, callbacks: ProcessQueueCallbacks<TExtra>): Promise<boolean>;
1172
+ /**
1173
+ * Drain all remaining handles from the queue and complete each with an error
1174
+ * outcome so callers awaiting `waitForCompletion()` resolve deterministically.
1175
+ *
1176
+ * Used by session implementations during shutdown to prevent queued messages
1177
+ * from hanging indefinitely when the session refuses to start new turns.
1178
+ * @param queue - User message queue to drain
1179
+ * @param message - Error message to attach to each rejected handle
1180
+ */
1181
+ declare function rejectQueuedHandles(queue: UserMessageQueue, message?: string): void;
1173
1182
  //#endregion
1174
1183
  //#region adapters/core/src/connector/procedural-agent-connector.d.ts
1175
1184
  /**
@@ -1498,17 +1507,6 @@ declare function normalizeMimeType(mimeType: string | undefined | null): string;
1498
1507
  */
1499
1508
  declare function isTextLikeMimeType(mimeType: string | undefined | null): boolean;
1500
1509
  //#endregion
1501
- //#region adapters/core/src/utils/resolvePresetCredentials.d.ts
1502
- /**
1503
- * Resolve credentials from environment variables using a provider definition's credential mapping.
1504
- *
1505
- * Reads `definition.credentialEnvVars` and checks `process.env` for each declared variable.
1506
- * Only includes fields where the env var is actually set.
1507
- * @param definition - Provider definition with optional credentialEnvVars mapping
1508
- * @returns Object mapping credential field names to resolved values, or undefined if none resolved
1509
- */
1510
- declare function resolvePresetCredentials(definition: ProviderDefinitionInput): Record<string, string> | undefined;
1511
- //#endregion
1512
1510
  //#region adapters/core/src/utils/createConnectorEventMapping.d.ts
1513
1511
  /**
1514
1512
  * Emit helper passed to handler functions for emitting to global subjects.
@@ -1576,21 +1574,93 @@ interface MessageLifecycleTrackOptions {
1576
1574
  *
1577
1575
  * This provides a clean separation between message lifecycle tracking
1578
1576
  * and the core AIAgent functionality.
1577
+ *
1578
+ * ## Turn pairing contract
1579
+ *
1580
+ * `agent.turn.started` and `agent.turn.completed` are emitted **only as a
1581
+ * matched pair** for handles that actually start a provider turn (i.e. whose
1582
+ * acknowledgment is delivered). The pairing decision is derived from
1583
+ * `handle.wasDelivered` — `acknowledge()` ensures the handle is marked as
1584
+ * delivered, so `complete()` can gate `turn.completed` emission without
1585
+ * maintaining parallel tracking state. Handles completed before dispatch —
1586
+ * merged, superseded, or rejected while queued — never receive `turn.started`
1587
+ * and therefore never receive `turn.completed`. The message-level event
1588
+ * `user_message.completed` always fires regardless of delivery, carrying the
1589
+ * terminal outcome so downstream consumers (storage, UI cleanup) can react
1590
+ * to every message disposition.
1591
+ *
1592
+ * ## Correlation source contract
1593
+ *
1594
+ * The "active" handle (`currentMessageHandle`) is the correlation source for
1595
+ * usage events emitted by the provider. The invariant:
1596
+ *
1597
+ * 1. A handle becomes the active correlation source **only when no other
1598
+ * tracked handle is still in-flight**. This ensures usage from the executing
1599
+ * turn is attributed to the correct request.
1600
+ * 2. When a handle is tracked via `track()` while another handle is already
1601
+ * active, it is appended to `pendingTrackedHandles` (a FIFO queue). It does
1602
+ * NOT become the correlation source until all handles ahead of it in the
1603
+ * queue have been promoted or removed.
1604
+ * 3. When the active handle completes, the head of the pending queue (if any)
1605
+ * is promoted to active — making its correlation visible for usage emitted
1606
+ * by its turn. This preserves FIFO ordering with the connector's
1607
+ * `UserMessageQueue`.
1608
+ * 4. A pending handle that completes before promotion (e.g. cancelled or
1609
+ * superseded while queued) is removed from wherever it sits in the queue,
1610
+ * without disrupting the order of remaining pending handles.
1611
+ * 5. For the first handle dispatched (no prior active), the handle is set
1612
+ * eagerly so that usage arriving before the provider acknowledges the
1613
+ * message is still correlated (closes the early-close / result-only stream
1614
+ * window from the previous fix).
1615
+ * 6. A handle that is already processed (`isProcessed === true`) at `track()`
1616
+ * time — e.g. completed by shutdown gates before the agent's
1617
+ * `onMessageHandle` callback ran — **never becomes the correlation source**.
1618
+ * It is neither promoted to active nor queued as pending. Completion
1619
+ * transforms are skipped (the pipeline already ran), but the completion
1620
+ * subscription still fires and `onTerminal` is still called, preserving
1621
+ * the terminal lifecycle contract for the caller.
1579
1622
  */
1580
1623
  declare class MessageLifecycleTracker {
1581
- /** Current messageId being processed (set on acknowledgment, cleared on completion) */
1582
- private currentMessageId?;
1624
+ /** Handle of the currently executing turn the active correlation source. */
1625
+ private currentMessageHandle?;
1626
+ /**
1627
+ * FIFO queue of handles tracked while another turn was still in-flight.
1628
+ * The head of the queue is promoted to `currentMessageHandle` when the
1629
+ * active handle completes. Handles that complete while queued (e.g.
1630
+ * cancelled or superseded) are removed from wherever they sit without
1631
+ * disrupting the order of remaining entries.
1632
+ */
1633
+ private readonly pendingTrackedHandles;
1583
1634
  /** Current turnId from the session orchestrator (set at sendMessage entry, cleared on completion) */
1584
1635
  private currentTurnId?;
1636
+ /**
1637
+ * Per-handle turnIds captured at {@link track} time. `currentTurnId` is a
1638
+ * shared field that a concurrent `sendMessage` overwrites while an earlier
1639
+ * turn is still streaming, so enrichment resolves the turnId from the
1640
+ * active handle; the shared field only covers the window between
1641
+ * `setCurrentTurnId` and `track`.
1642
+ *
1643
+ * Explicitly-undefined turnIds are recorded too (map presence, not value,
1644
+ * gates the fallback): a handle intentionally tracked without a turn
1645
+ * (e.g. `start()`) must keep its events turn-less instead of inheriting a
1646
+ * later queued turn's id from the shared field.
1647
+ */
1648
+ private readonly handleTurnIds;
1585
1649
  /** Emit function injected from AIAgent */
1586
1650
  private readonly emitGlobal;
1587
1651
  constructor(config: MessageLifecycleTrackerConfig);
1588
1652
  /**
1589
1653
  * Get the current messageId being processed.
1654
+ * Derived from the active message handle to avoid dual state.
1590
1655
  * Used by enrichPayload() to add messageId to intermediate events.
1591
1656
  * @returns The current messageId or undefined if no message is being processed
1592
1657
  */
1593
1658
  getCurrentMessageId(): string | undefined;
1659
+ /**
1660
+ * Get the active message handle being processed.
1661
+ * @returns The active message handle or undefined if no message is being processed
1662
+ */
1663
+ getCurrentMessageHandle(): MessageHandle | undefined;
1594
1664
  /**
1595
1665
  * Set the current turnId from the session orchestrator.
1596
1666
  * Called at the start of sendMessage processing.
@@ -1602,14 +1672,27 @@ declare class MessageLifecycleTracker {
1602
1672
  */
1603
1673
  clearCurrentTurnId(): void;
1604
1674
  /**
1605
- * Get the current turnId being processed.
1675
+ * Get the turnId of the turn that is actually executing.
1606
1676
  * Used by enrichPayload() to add turnId to intermediate events.
1607
- * @returns The current turnId or undefined if not set
1677
+ *
1678
+ * Resolves from the active handle's captured turnId so that a concurrent
1679
+ * `sendMessage` (which overwrites the shared `currentTurnId` before its
1680
+ * handle is promoted) cannot mislabel — or, downstream, drop — events of
1681
+ * the still-streaming turn. Falls back to the shared field for the window
1682
+ * between `setCurrentTurnId` and `track`, when no handle is active yet.
1683
+ * @returns The executing turn's turnId or undefined if not set
1608
1684
  */
1609
1685
  getCurrentTurnId(): string | undefined;
1610
1686
  /**
1611
1687
  * Acknowledge a message - marks turn start.
1612
1688
  *
1689
+ * This should only be called for handles whose acknowledgment was
1690
+ * genuinely delivered (i.e. `waitForAcknowledgment()` resolved with
1691
+ * `true`). Handles completed before dispatch (merged, superseded, or
1692
+ * rejected) resolve acknowledgment with `false` — calling acknowledge()
1693
+ * for those would steal the active correlation slot from the real
1694
+ * in-flight turn.
1695
+ *
1613
1696
  * Emits:
1614
1697
  * - user_message.acknowledged
1615
1698
  * - agent.turn.started
@@ -1621,13 +1704,19 @@ declare class MessageLifecycleTracker {
1621
1704
  * Complete a message - marks turn end.
1622
1705
  *
1623
1706
  * Emits:
1624
- * - agent.turn.completed (always, with outcome paired with agent.turn.started)
1625
- * - user_message.completed (always, with outcome)
1707
+ * - agent.turn.completed — **only** when `acknowledge()` emitted
1708
+ * `agent.turn.started` for this handle (turn pairing contract)
1709
+ * - user_message.completed — always, with outcome details
1626
1710
  * @param handle - The message handle being completed
1627
1711
  * @param result - The completion result with outcome
1628
1712
  * @param turnId - Turn ID captured when the handle was registered
1629
1713
  */
1630
1714
  complete(handle: MessageHandle, result: MessageResult, turnId?: string): void;
1715
+ /**
1716
+ * Remove a handle from the pending queue if present.
1717
+ * @param handle - The handle to remove
1718
+ */
1719
+ private removePendingHandle;
1631
1720
  /**
1632
1721
  * Wire up a message handle for lifecycle tracking.
1633
1722
  *
@@ -1635,6 +1724,15 @@ declare class MessageLifecycleTracker {
1635
1724
  * and emits the appropriate events. When `transformTerminal` is provided,
1636
1725
  * it is registered on the handle so validation or other post-processing
1637
1726
  * amends the public completion result before lifecycle events fire.
1727
+ *
1728
+ * **Already-processed handles:** When a handle is already completed or
1729
+ * cancelled at `track()` time (e.g. shutdown gates completed it before
1730
+ * the agent's `onMessageHandle` callback ran), it is never promoted to
1731
+ * the active correlation source and never queued as pending. The
1732
+ * completion transform is skipped (the handle already ran its transform
1733
+ * pipeline), but the completion and terminal subscriptions still fire so
1734
+ * the caller receives the full lifecycle contract (events emitted,
1735
+ * `onTerminal` called).
1638
1736
  * @param handle - The message handle to track
1639
1737
  * @param onTerminal - Optional callback for any terminal outcome (emits agent.complete)
1640
1738
  * @param transformTerminal - Optional async transform applied before public completion resolves
@@ -1681,28 +1779,38 @@ declare class ToolCallTracker {
1681
1779
  /**
1682
1780
  * Register a tool.use event. Returns correlation ID to use.
1683
1781
  * If nativeId provided, uses that. Otherwise generates UUID.
1782
+ * @param messageId - Message that owns this pending call
1684
1783
  * @param toolName - Name of the tool being invoked
1685
1784
  * @param args - Tool arguments (optional, for future correlation strategies)
1686
1785
  * @param nativeId - Native provider ID if available
1687
1786
  * @returns Correlation ID to use for this tool call
1688
1787
  */
1689
- register(toolName: string, args?: Record<string, unknown>, nativeId?: string): string;
1788
+ register(messageId: string, toolName: string, args?: Record<string, unknown>, nativeId?: string): string;
1690
1789
  /**
1691
1790
  * Find correlation ID for a tool output.
1692
1791
  * Tries native ID first, then falls back to FIFO by tool name,
1693
1792
  * and finally to the oldest pending tool call.
1793
+ * @param messageId - Message whose pending calls may be resolved
1694
1794
  * @param hints - Available hints for correlation
1695
1795
  * @returns Correlation result with strategy metadata
1696
1796
  */
1697
- resolve(hints: ResolveHints): ResolveResult;
1797
+ resolve(messageId: string, hints: ResolveHints): ResolveResult;
1698
1798
  /**
1699
1799
  * Clear all pending entries.
1700
- * Call on turn end to prevent stale entries from leaking across turns.
1800
+ * Reserved for fatal agent teardown; normal terminal messages use {@link clearMessage}.
1701
1801
  */
1702
- clear(): void;
1802
+ clearAll(): void;
1803
+ /**
1804
+ * Clear pending entries owned by one terminal message.
1805
+ * @param messageId - Message whose correlation state reached a terminal outcome
1806
+ */
1807
+ clearMessage(messageId: string): void;
1703
1808
  }
1704
1809
  //#endregion
1705
1810
  //#region adapters/core/src/agent/agent-event-bridge.d.ts
1811
+ type MessageOwnedPayload<T> = Omit<T, keyof AgentContext> & {
1812
+ messageId: string;
1813
+ };
1706
1814
  /**
1707
1815
  * Dependencies for AgentEventBridge.
1708
1816
  */
@@ -1712,15 +1820,15 @@ interface AgentEventBridgeConfig {
1712
1820
  /** Emit context window status payload. */
1713
1821
  emitContextWindowUpdated: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.contextWindow.updated>, keyof AgentContext>) => Promise<void>;
1714
1822
  /** Emit tool.use payload. */
1715
- emitToolUse: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.tool.use>, keyof AgentContext>) => Promise<void>;
1823
+ emitToolUse: (payload: MessageOwnedPayload<ExtractSubjectPayload<typeof AgentSubjects.tool.use>>) => Promise<void>;
1716
1824
  /** Emit tool.output payload. */
1717
- emitToolOutput: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.tool.output>, keyof AgentContext>) => Promise<void>;
1825
+ emitToolOutput: (payload: MessageOwnedPayload<ExtractSubjectPayload<typeof AgentSubjects.tool.output>>) => Promise<void>;
1718
1826
  /** Emit adapter log payload. */
1719
1827
  emitAdapterLog: (payload: Omit<ExtractSubjectPayload<typeof AdapterSubjects.log>, 'adapterId' | 'adapterName'>) => Promise<void>;
1720
1828
  /** Emit step.started payload. */
1721
- emitStepStarted: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.step.started>, keyof AgentContext>) => Promise<void>;
1829
+ emitStepStarted: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.step.started>, keyof AgentContext> | MessageOwnedPayload<ExtractSubjectPayload<typeof AgentSubjects.step.started>>) => Promise<void>;
1722
1830
  /** Emit step.finished payload. */
1723
- emitStepFinished: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.step.finished>, keyof AgentContext>) => Promise<void>;
1831
+ emitStepFinished: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.step.finished>, keyof AgentContext> | MessageOwnedPayload<ExtractSubjectPayload<typeof AgentSubjects.step.finished>>) => Promise<void>;
1724
1832
  /** Correlation tracker for tool.use -\> tool.output. */
1725
1833
  toolCallTracker: ToolCallTracker;
1726
1834
  /** Current content block index getter. */
@@ -1729,6 +1837,8 @@ interface AgentEventBridgeConfig {
1729
1837
  incrementBlockIndex: () => void;
1730
1838
  /** Resolve model name for usage events. */
1731
1839
  getUsageModel: () => string | undefined;
1840
+ /** Get the message handle whose provider request is currently active. */
1841
+ getActiveMessageHandle: () => MessageHandle | undefined;
1732
1842
  }
1733
1843
  /**
1734
1844
  * Resolution metadata returned when emitting tool output.
@@ -1756,6 +1866,7 @@ declare class AgentEventBridge {
1756
1866
  private readonly getBlockIndex;
1757
1867
  private readonly incrementBlockIndex;
1758
1868
  private readonly getUsageModel;
1869
+ private readonly getActiveMessageHandle;
1759
1870
  /**
1760
1871
  * Create an event bridge with emission and correlation dependencies.
1761
1872
  * @param config - Event bridge dependencies (emitters, tracker, and block-index accessors)
@@ -1773,19 +1884,21 @@ declare class AgentEventBridge {
1773
1884
  emitContextWindowUpdate(input: ContextWindowInput): Promise<void>;
1774
1885
  /**
1775
1886
  * Emit tool.use event with correlation tracking.
1887
+ * @param messageId - Message that owns the tool call
1776
1888
  * @param toolName - Tool identifier
1777
1889
  * @param args - Tool arguments
1778
1890
  * @param nativeId - Provider-native call ID
1779
1891
  * @returns Correlation ID for the call
1780
1892
  */
1781
- emitToolUse(toolName: string, args?: Record<string, unknown>, nativeId?: string): Promise<string>;
1893
+ emitToolUse(messageId: string, toolName: string, args?: Record<string, unknown>, nativeId?: string): Promise<string>;
1782
1894
  /**
1783
1895
  * Emit tool.output event with best-effort correlation resolution.
1896
+ * @param messageId - Message that owns the tool output
1784
1897
  * @param output - Tool output text
1785
1898
  * @param hints - Correlation hints from adapter events
1786
1899
  * @returns Resolved toolCallId, toolName (falls back to 'unknown'), and args from the matched tool.use call
1787
1900
  */
1788
- emitToolOutput(output: string, hints: ResolveHints): Promise<ToolOutputResult>;
1901
+ emitToolOutput(messageId: string, output: string, hints: ResolveHints): Promise<ToolOutputResult>;
1789
1902
  /**
1790
1903
  * Emit step.started for the current block index.
1791
1904
  * @param stepType - Block step type
@@ -1793,604 +1906,612 @@ declare class AgentEventBridge {
1793
1906
  * @param content - Optional immediate block content
1794
1907
  */
1795
1908
  emitStepStarted(stepType: StepType, blockData?: BlockData, content?: SessionMessageBlock): Promise<void>;
1909
+ /**
1910
+ * Emit step.started with an explicit originating message identity.
1911
+ * @param messageId - Message that owns the step
1912
+ * @param stepType - Block step type
1913
+ * @param blockData - Optional step metadata
1914
+ * @param content - Optional immediate block content
1915
+ */
1916
+ emitStepStartedForMessage(messageId: string, stepType: StepType, blockData?: BlockData, content?: SessionMessageBlock): Promise<void>;
1917
+ /**
1918
+ * Emit step.started with optional explicit message ownership.
1919
+ * @param messageId - Optional message that owns the step.
1920
+ * @param stepType - Semantic step kind.
1921
+ * @param blockData - Optional block metadata.
1922
+ * @param content - Optional initial block content.
1923
+ */
1924
+ private emitOwnedStepStarted;
1796
1925
  /**
1797
1926
  * Emit step.finished and advance block index.
1798
1927
  * @param stepType - Completed step type
1799
1928
  * @param content - Final block content
1800
1929
  */
1801
1930
  emitStepFinished(stepType: StepType, content: SessionMessageBlock): Promise<void>;
1931
+ /**
1932
+ * Emit step.finished with an explicit originating message identity and advance the block index.
1933
+ * @param messageId - Message that owns the step
1934
+ * @param stepType - Completed step type
1935
+ * @param content - Final block content
1936
+ */
1937
+ emitStepFinishedForMessage(messageId: string, stepType: StepType, content: SessionMessageBlock): Promise<void>;
1938
+ /**
1939
+ * Emit step.finished with optional explicit message ownership and advance the block index.
1940
+ * @param messageId - Optional message that owns the step.
1941
+ * @param stepType - Semantic step kind.
1942
+ * @param content - Completed block content.
1943
+ */
1944
+ private emitOwnedStepFinished;
1802
1945
  }
1803
1946
  //#endregion
1804
- //#region adapters/core/src/agent/ai-agent.d.ts
1947
+ //#region adapters/core/src/factory/create-adapter-namespace.d.ts
1805
1948
  /**
1806
- * Abstract base class for AI agents.
1949
+ * Adapter namespace extends BusNamespace with additional metadata for adapters.
1807
1950
  *
1808
- * Bridges adapter/agent bus subjects to connector sessions.
1809
- * @typeParam TBus - The scoped bus type for this adapter
1810
- * @typeParam TConnector - The connector type this agent wraps
1951
+ * Provides:
1952
+ * - All BusNamespace features (subjects, scoped bus factory)
1953
+ * - Raw schema access for adapter factory internals
1954
+ * - Domain name for debugging/logging
1955
+ * @typeParam N - Namespace domain string
1811
1956
  */
1812
- declare abstract class AIAgent<TBus extends ScopedBus<string> = ScopedBus<string>, TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>> {
1813
- /** The underlying connector instance (created in init) */
1814
- protected connector: TConnector;
1815
- protected confirmedModel?: string;
1816
- protected initialModel?: string;
1817
- /** Cached adapterSessionId from the last connector that had a session — survives connector swaps. */
1818
- private lastKnownAdapterSessionId?;
1819
- /** Cleanup functions for bus subscriptions (stable, survive connector swap) */
1820
- private busHandlerCleanups;
1821
- /** Whether init() has been called */
1822
- private initialized;
1823
- /** Runtime system prompt captured from start/initialize, preserved across connector swaps. */
1824
- private runtimeSystemPrompt?;
1825
- /** Tracks message lifecycle and emits turn events (emission is lazy — safe as field initializer). */
1826
- protected readonly lifecycleTracker: MessageLifecycleTracker;
1827
- /** Tracks tool.use → tool.output correlation across adapters. */
1828
- protected readonly toolCallTracker: ToolCallTracker;
1829
- /** Event-focused helper for usage/tool/step emissions. */
1830
- private readonly eventBridge;
1831
- /** Shared turn pipeline for start/sendMessage paths. */
1832
- private readonly turnExecutor;
1833
- /** Runtime mutation helper for cwd/model change handlers. */
1834
- private readonly runtimeMutationManager;
1835
- /** Connector lifecycle helper for swap/wiring ownership. */
1836
- private readonly connectorLifecycleManager;
1837
- /** Payload enrichment and global emission helper. */
1838
- private readonly payloadEmitter;
1839
- /** Stateful lifecycle emitter for start/complete/error/session.closed. */
1840
- private readonly lifecycleEmitter;
1841
- /** Validates structured output before public terminal results and lifecycle events resolve. */
1842
- private readonly structuredOutputManager;
1843
- /** Latest tracked message completion with agent-level terminal transforms applied. */
1844
- private latestMessageCompletion?;
1845
- /** Current content block index within the turn, reset on each turn start */
1846
- private currentBlockIndex;
1957
+ type AdapterNamespace<Domain extends string = string> = Omit<BusNamespace<Domain>, 'subjects'> & {
1958
+ /** Original namespace definition for registration on host-provided bus instances. */readonly definition: RegistrableBusNamespaceDefinition;
1959
+ };
1960
+ /**
1961
+ * Creates an adapter namespace with typed subject definitions.
1962
+ *
1963
+ * **Seam:** Thin wrapper around MakaioBus.registerNamespace that:
1964
+ * - Delegates to bus-core for namespace registration
1965
+ * - Preserves FilterPayload type for type-safe withFilter()
1966
+ * - Provides extension point for future adapter-specific features
1967
+ * @param domain - Namespace domain (e.g., 'adapter:claudeCode')
1968
+ * @param schemas - Record of subject schemas (events and requests)
1969
+ * @param options - Registration and routing options (e.g., busValidationMode for Zod version conflicts)
1970
+ * @returns Adapter namespace with typed subjects and pre-computed FilterPayload
1971
+ * @example
1972
+ * ```typescript
1973
+ * const ClaudeCodeNamespace = createAdapterNamespace('adapter:claudeCode', {
1974
+ * thinking: z.object({ content: z.string() }),
1975
+ * getContext: {
1976
+ * request: z.object({ path: z.string() }),
1977
+ * response: z.object({ content: z.string() }),
1978
+ * },
1979
+ * });
1980
+ *
1981
+ * // Access typed subjects
1982
+ * ClaudeCodeNamespace.subjects.thinking;
1983
+ *
1984
+ * // Get scoped bus with type-safe filtering
1985
+ * const bus = await ClaudeCodeNamespace.scopedBus();
1986
+ * bus.withFilter({ content: 'test' }); // Type-checked
1987
+ *
1988
+ * // For adapters with bundled Zod v3 (e.g., @github/copilot-sdk):
1989
+ * const CopilotNamespace = createAdapterNamespace('adapter:copilot', schemas, {
1990
+ * busValidationMode: 'skip', // Skip validation due to Zod version conflict
1991
+ * });
1992
+ *
1993
+ * // For adapters with lenient validation (schema drift triggers warnings, not crashes):
1994
+ * const ClaudeNamespace = createAdapterNamespace('adapter:claude-code', schemas, {
1995
+ * busValidationMode: 'lenient',
1996
+ * onSchemaViolation: (report) => console.warn(report),
1997
+ * });
1998
+ * ```
1999
+ */
2000
+ declare function createAdapterNamespace<N extends string, Schemas extends SchemaRecord>(domain: N, schemas: Schemas, options?: CreateBusNamespaceOptions): BusNamespace<N, SubjectRecordFromSchemaRecord<Schemas>, FilterablePayloadIntersection<SubjectRecordFromSchemaRecord<Schemas>>, Schemas> & {
2001
+ readonly definition: RegistrableBusNamespaceDefinition;
2002
+ };
2003
+ //#endregion
2004
+ //#region adapters/core/src/agent/agent-turn-executor.d.ts
2005
+ /**
2006
+ * Runtime dependencies for AgentTurnExecutor.
2007
+ */
2008
+ type AgentMessageHandleCallback = (messageHandle: MessageHandle, turnId: string | undefined) => Promise<void>;
2009
+ interface AgentTurnExecutorConfig {
2010
+ /** Stable agent identifier. */
2011
+ agentId: string;
2012
+ /** Stable adapter identifier. */
2013
+ adapterId: string;
2014
+ /** Optional Makaio session identifier. */
2015
+ sessionId?: string;
2016
+ /** Capability tags reported by the adapter (e.g. `'structuredOutput'`). */
2017
+ adapterCapabilities?: string[];
2018
+ /** Global bus instance for hooks. */
2019
+ globalBus: IMakaioBus;
2020
+ /** Current connector reference resolver. */
2021
+ getConnector: () => AIAgentConnector;
2022
+ /** Native resume decision function. */
2023
+ shouldUseNativeResume: ShouldUseNativeResumeFn;
1847
2024
  /**
1848
- * Start mode for the next `emitStart()` call (consume-on-read).
2025
+ * Whether the agent config carries a concrete resume target
2026
+ * (`resumeAdapterSessionId`).
1849
2027
  *
1850
- * Set before dispatch; {@link emitStart} reads and clears the slot so
1851
- * subsequent calls within the same dispatch (e.g. Copilot SDK sub-turns)
1852
- * fall back to `'rotation'`. The `undefined` initial value is safe —
1853
- * every first-start path sets the mode before the connector fires.
2028
+ * Used by {@link AgentTurnExecutor.deriveStartMode} to distinguish
2029
+ * native-attach starts (resume target, no sessionContext) from
2030
+ * truly sessionless/ephemeral starts (no resume target, no context).
1854
2031
  */
1855
- private pendingStartMode;
1856
- /** Normalized config with defaults applied */
1857
- protected readonly config: SetRequired<AIAgentConfig<TBus, TConnector>, 'globalBus'>;
1858
- /** Available models for context window lookup */
1859
- protected readonly availableModels?: AIModel[];
2032
+ hasResumeTarget: () => boolean;
1860
2033
  /**
1861
- * Create an AIAgent instance.
2034
+ * Set the start mode on the owning agent before connector dispatch.
1862
2035
  *
1863
- * Note: Does NOT create the connector yet - call init() after construction.
1864
- * @param config - Agent configuration
2036
+ * The turn executor computes the mode from session context signals and
2037
+ * calls this so `emitStart()` can include it in the `agent.started`
2038
+ * payload when the connector fires its lifecycle event.
2039
+ * @param mode - Derived start mode for this turn
1865
2040
  */
1866
- constructor(config: AIAgentConfig<TBus, TConnector>);
1867
- private getAgentContextBase;
1868
- private getEventMetadataDefaults;
1869
- /** @returns Unique agent identifier */
1870
- get agentId(): string;
1871
- /** @returns Adapter instance identifier */
1872
- get adapterId(): string;
1873
- /** @returns Adapter type name (e.g., 'claude-code', 'gemini-sdk') */
1874
- get adapterName(): string;
1875
- /** @returns Adapter capabilities for runtime feature detection */
1876
- get capabilities(): string[];
1877
- /** @returns Native tools built into the adapter */
1878
- get nativeTools(): string[];
1879
- /** @returns Shared Makaio sessionId */
1880
- get sessionId(): string | undefined;
1881
- /** @returns Initial adapter session ID from config (may differ from connector's resolved session ID) */
1882
- protected get adapterSessionId(): string | undefined;
1883
- /** @returns Global bus for cross-namespace communication (defaulted in constructor) */
1884
- protected get globalBus(): IMakaioBus;
2041
+ setPendingStartMode: (mode: StartMode) => void;
2042
+ /** Completion/lifecycle tracker hook. */
2043
+ onMessageHandle: AgentMessageHandleCallback;
2044
+ /** Side-effect callback to mark agent status active before dispatch. */
2045
+ onBeforeDispatch?: () => void | Promise<void>;
2046
+ /** Serialize the complete pre-hook-to-send boundary with credential mutations. */
2047
+ runDispatch?: <T>(dispatch: () => Promise<T>) => Promise<T>;
2048
+ /** When true, PreUserMessage hooks are skipped. */
2049
+ ephemeral?: boolean;
2050
+ }
2051
+ /**
2052
+ * Function type for native resume decision.
2053
+ */
2054
+ type ShouldUseNativeResumeFn = (sessionContext?: StartAgentOptions['sessionContext']) => boolean;
2055
+ /**
2056
+ * Shared start/send-message execution pipeline for AIAgent.
2057
+ */
2058
+ declare class AgentTurnExecutor {
2059
+ private readonly agentId;
2060
+ private readonly adapterId;
2061
+ private readonly sessionId?;
2062
+ private readonly adapterCapabilities;
2063
+ private readonly globalBus;
2064
+ private readonly getConnector;
2065
+ private readonly shouldUseNativeResume;
2066
+ private readonly hasResumeTarget;
2067
+ private readonly setPendingStartMode;
2068
+ private readonly onMessageHandle;
2069
+ private readonly onBeforeDispatch?;
2070
+ private readonly runDispatch;
2071
+ private readonly ephemeral;
2072
+ constructor(config: AgentTurnExecutorConfig);
1885
2073
  /**
1886
- * Initialize the agent.
2074
+ * Derive the {@link StartMode} from session context, resume decision, and
2075
+ * resume-target presence.
1887
2076
  *
1888
- * Creates the connector via the abstract createConnector() method
1889
- * and sets up handlers for agent.* subjects with agentId filtering.
1890
- * @throws Error if already initialized
1891
- */
1892
- init(): Promise<void>;
1893
- /**
1894
- * Emit `agent.started` with the pending start mode (consume-on-read).
1895
- *
1896
- * Reads and clears {@link pendingStartMode}; subsequent calls within
1897
- * the same dispatch fall back to `'rotation'`.
1898
- * @param event - Optional additional fields to merge into the payload
1899
- */
1900
- protected emitStart(event?: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId' | 'model' | 'cwd' | 'startMode'>): Promise<void>;
1901
- /**
1902
- * Set the start mode for the next `emitStart()` invocation.
2077
+ * Decision table (evaluated top-to-bottom, first match wins):
1903
2078
  *
1904
- * Called by the turn executor or `initialize()` before dispatching to
1905
- * the connector. The value is consumed (cleared) by the first
1906
- * `emitStart()` call, enforcing the one-shot invariant.
1907
- * @param mode - The start mode to embed in the next `agent.started` event
1908
- */
1909
- setPendingStartMode(mode: StartMode): void;
1910
- protected emitCompletion(result: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>): Promise<void>;
1911
- /**
1912
- * Stash error metadata for the next emitCompletion call.
2079
+ * | sessionContext | nativeFork | hasResumeTarget | useNativeResume | isFirstTurn | Mode |
2080
+ * |----------------|------------|-----------------|-----------------|-------------|------------|
2081
+ * | present | yes | — | — | — | `fork` |
2082
+ * | absent | — | yes | — | — | `resume` |
2083
+ * | absent | — | no | — | — | `fresh` |
2084
+ * | present | no | — | true | — | `resume` |
2085
+ * | present | no | — | false | true | `fresh` |
2086
+ * | present | no | — | false | false | `rotation` |
1913
2087
  *
1914
- * The lifecycle tracker emits `agent.complete` with `outcome: 'error'` when the
1915
- * message handle completes. This method runs first (from the connector's errorHandler)
1916
- * and stashes `errorCategory` so emitCompletion can include it in the complete payload.
2088
+ * The `hasResumeTarget` rule distinguishes native-attach starts (concrete
2089
+ * provider session to reconnect to, but no orchestrator session context) from
2090
+ * truly sessionless/ephemeral starts. Without this signal, both cases
2091
+ * collapsed to `'fresh'` — causing SDK SessionStart hooks to run
2092
+ * initialization logic on a resumed conversation.
1917
2093
  *
1918
- * No longer emits `agent.error` all terminal events flow through `agent.complete`.
1919
- * @param result - Error payload from the connector
2094
+ * `hasResumeTarget` fires only when sessionContext is absent. Once the
2095
+ * orchestrator supplies context (turn 2+), rules 4-6 take over and the
2096
+ * resume target on the config has no further effect on mode derivation.
2097
+ * @param sessionContext - Session context signals from the orchestrator
2098
+ * @param useNativeResume - Whether native resume was selected for this turn
2099
+ * @param hasResumeTarget - Whether a concrete resume target
2100
+ * (`resumeAdapterSessionId`) exists on the agent config
2101
+ * @returns The derived start mode
1920
2102
  */
1921
- protected emitError(result: Pick<z.infer<typeof AgentSchemas.complete>, 'error' | 'errorCategory'>): void;
2103
+ static deriveStartMode(sessionContext: SessionContext | undefined, useNativeResume: boolean, hasResumeTarget?: boolean): StartMode;
1922
2104
  /**
1923
- * Emit agent session closed event. Emits only once per session.
1924
- * AIAdapter listens to cleanup agent and re-emit as AdapterSubjects.session.closed.
1925
- * @param reason - Reason for session closure (e.g., 'aborted', 'closed')
2105
+ * Derive the start mode for the given resolved session context, stash it
2106
+ * as the pending mode for the next lifecycle start emission, and return
2107
+ * the native-resume decision shared by the dispatch that follows.
2108
+ * @param sessionContext - Session context after pre-user-message hooks
2109
+ * @returns Whether the connector should rely on native resume
1926
2110
  */
1927
- protected emitSessionClosed(reason?: string): void;
2111
+ private deriveAndSetPendingStartMode;
1928
2112
  /**
1929
- * Enrich a payload with agent context fields.
1930
- * @param payload - The base payload to enrich
1931
- * @returns Payload with AgentContext fields and optional messageId added
2113
+ * Execute the turn pipeline for agent.sendMessage.
2114
+ * @param payload - agent.sendMessage request payload
2115
+ * @returns Resolved messageId from connector handle
1932
2116
  */
1933
- protected enrichPayload<T extends object>(payload: T): Promise<T & AgentIdentity & {
1934
- messageId?: string;
2117
+ executeSendMessage(payload: SendMessageRequestPayload): Promise<{
2118
+ messageId: string;
1935
2119
  }>;
1936
2120
  /**
1937
- * Emit to a global subject with automatic payload enrichment.
1938
- * @param subject - The subject to emit to
1939
- * @param payload - The payload (without AgentContext fields - they're added automatically)
2121
+ * Execute the turn pipeline for agent.start.
2122
+ * @param message - Initial message payload
2123
+ * @param options - Start options from caller
2124
+ * @param systemPrompt - Runtime system prompt chosen by AIAgent
2125
+ * @param responseSchema - Runtime structured output descriptor chosen by AIAgent
2126
+ * @returns Agent start result from connector
1940
2127
  */
1941
- protected emitGlobal<S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext> & {
1942
- messageId?: string;
1943
- }): Promise<void>;
2128
+ executeStart(message: NormalizedMessageInput | MessageInput, options: StartAgentOptions | undefined, systemPrompt: StartAgentOptions['systemPrompt'], responseSchema?: ResponseSchemaDescriptor): Promise<AgentStartResult>;
1944
2129
  /**
1945
- * Track usage and emit to global bus.
1946
- * AIAdapter aggregates session totals from per-call usage events.
1947
- * @param normalized - Normalized usage metrics from adapter-specific normalizer
2130
+ * Resolve the pre-user hook result or preserve the caller payload for ephemeral turns.
2131
+ * @param input - Message and context for the outgoing user turn
2132
+ * @returns Message and session context to dispatch to the connector
1948
2133
  */
1949
- protected trackUsage(normalized: NormalizedCallUsage): Promise<void>;
2134
+ private resolvePreUserMessageTurn;
1950
2135
  /**
1951
- * Get context window size for a model.
1952
- *
1953
- * Looks up the context window size from availableModels based on model name.
1954
- * @param modelName - Model name to look up (defaults to confirmedModel or initialModel)
1955
- * @returns Context window size in tokens, or undefined if not found
2136
+ * Fire PostUserMessage hooks without blocking the turn.
2137
+ * @param messageId - Message ID for correlation
1956
2138
  */
1957
- protected getContextWindowSize(modelName?: string): number | undefined;
2139
+ private firePostUserMessageHooks;
1958
2140
  /**
1959
- * Emit context window status for compression trigger decisions.
1960
- *
1961
- * Calculates fill percentage and warning level from raw metrics.
1962
- * Called by subclasses after usage tracking with provider-specific metrics.
1963
- * @param input - Raw metrics: currentTokens, maxTokens, optional cachedTokens
2141
+ * Enforce the connector contract for an orchestrator-assigned message identity.
2142
+ * @param expectedMessageId - Canonical caller identity, when one was supplied.
2143
+ * @param handle - Connector handle returned for the dispatched message.
2144
+ * @param connector - Connector that owns fatal teardown for a violated dispatch contract.
2145
+ * @param operation - Connector operation that produced the handle.
1964
2146
  */
1965
- protected emitContextWindowUpdate(input: ContextWindowInput): Promise<void>;
2147
+ private assertCanonicalMessageId;
2148
+ }
2149
+ //#endregion
2150
+ //#region adapters/core/src/agent/connector-runtime.d.ts
2151
+ /** Connector instance paired with its explicit client config lease. */
2152
+ interface ConnectorRuntimeHandle<TConnector extends Pick<AIAgentConnector, 'close'>> {
2153
+ /** Live connector instance. */
2154
+ readonly connector: TConnector;
2155
+ /** Lease whose lifetime exactly matches this connector. */
2156
+ readonly lease?: AdapterAuthLeaseHandle;
2157
+ }
2158
+ /** Dependencies for creating one managed connector runtime. */
2159
+ interface CreateConnectorRuntimeOptions<TBus extends ScopedBus<string>, TConnector extends AIAgentConnector<TBus>, TConfig extends BaseAgentConnectorConfig<TBus> = BaseAgentConnectorConfig<TBus>> {
2160
+ /** Refs-only config emitted by the common adapter factory. */
2161
+ readonly config: BoundAdapterRuntimeConfig<TBus, TConfig>;
2162
+ /** Adapter connector constructor. */
2163
+ readonly connectorFactory: (config: ResolvedAdapterRuntimeConfig<TBus, TConfig>) => TConnector | Promise<TConnector>;
2164
+ /** Optional user-message callback attached only after auth preparation. */
2165
+ readonly onMessageSent?: (handle: MessageHandle) => void;
2166
+ /** Trusted host-local auth preparer; defaults to DirectChannel + client lease. */
2167
+ readonly prepareAuthRuntime?: AdapterAuthRuntimePreparer<TBus, TConfig>;
2168
+ }
2169
+ //#endregion
2170
+ //#region adapters/core/src/agent/agent-lifecycle-emitter.d.ts
2171
+ /**
2172
+ * Dependencies for AgentLifecycleEmitter.
2173
+ */
2174
+ interface AgentLifecycleEmitterConfig {
2175
+ /** Stable agent identifier for persistence updates. */
2176
+ agentId: string;
2177
+ /** Global bus for best-effort status updates. */
2178
+ globalBus: IMakaioBus;
2179
+ /** Emit callback for `agent.started`. */
2180
+ emitStarted: (payload: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2181
+ /** Emit callback for `agent.complete`. */
2182
+ emitComplete: (payload: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>) => Promise<void>;
2183
+ /** Emit callback for `agent.session.closed`. */
2184
+ emitSessionClosed: (payload: {
2185
+ reason?: string;
2186
+ }) => Promise<void>;
2187
+ /** Hook executed before terminal completion emission. */
2188
+ onBeforeEmitCompletion: () => Promise<void>;
2189
+ /** Clear tool-call tracker entries owned by one terminal message. */
2190
+ clearMessageToolCalls: (messageId: string) => void;
2191
+ }
2192
+ /**
2193
+ * Stateful lifecycle emitter for AIAgent terminal/start/session events.
2194
+ */
2195
+ declare class AgentLifecycleEmitter {
2196
+ private static readonly COMPLETION_DEDUP_LIMIT;
2197
+ /** Tracks whether session.closed has been emitted (emit only once). */
2198
+ private sessionClosedEmitted;
2199
+ /** Terminal messages already emitted; overlapping handles must not share a mutable turn guard. */
2200
+ private readonly completedMessageIds;
2201
+ private readonly completedMessageOrder;
2202
+ private readonly config;
2203
+ constructor(config: AgentLifecycleEmitterConfig);
1966
2204
  /**
1967
- * Emit tool.use event with automatic correlation tracking.
1968
- * Registers the tool call with ToolCallTracker and emits to global bus.
1969
- * Use this instead of directly emitting to AgentSubjects.tool.use.
1970
- * @param toolName - Name of the tool being invoked
1971
- * @param args - Tool arguments
1972
- * @param nativeId - Native provider ID if available (e.g., toolu_*, call_*)
1973
- * @returns The correlation ID used (nativeId if provided, else generated UUID)
2205
+ * Emit `agent.started`.
2206
+ * @param event - Start payload without auto-enriched AgentContext fields
1974
2207
  */
1975
- protected emitToolUse(toolName: string, args?: Record<string, unknown>, nativeId?: string): Promise<string>;
2208
+ emitStart(event: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>): Promise<void>;
1976
2209
  /**
1977
- * Emit tool.output event with automatic correlation resolution.
1978
- * Resolves the correlation ID from ToolCallTracker using provided hints.
1979
- * Use this instead of directly emitting to AgentSubjects.tool.output.
1980
- * @param output - Tool output content
1981
- * @param hints - Hints for correlation (nativeId and/or toolName)
1982
- * @returns Resolved toolCallId, toolName (falls back to 'unknown'), and args from the matched tool.use call
2210
+ * Emit a terminal completion event for one message handle.
2211
+ * @param result - Completion payload without AgentContext fields
1983
2212
  */
1984
- protected emitToolOutput(output: string, hints: ResolveHints): Promise<ToolOutputResult>;
2213
+ emitCompletion(result: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>): Promise<void>;
1985
2214
  /**
1986
- * Emit step.started event with automatic block index management.
1987
- * Call this when a content block begins processing.
1988
- * @param stepType - The type of step (text, reasoning, tool_use)
1989
- * @param blockData - Optional metadata for the block (e.g., toolName for tool_use)
1990
- * @param content - Optional content for the step (e.g., tool_call block for tool_use)
2215
+ * Emit `agent.session.closed` once for this agent lifecycle.
2216
+ * @param reason - Optional closure reason
1991
2217
  */
1992
- protected emitStepStarted(stepType: StepType, blockData?: BlockData, content?: SessionMessageBlock): Promise<void>;
2218
+ emitSessionClosed(reason?: string): void;
2219
+ }
2220
+ //#endregion
2221
+ //#region adapters/core/src/agent/agent-payload-emitter.d.ts
2222
+ interface AgentPayloadEventMetadata {
2223
+ clientId?: string;
2224
+ providerConfigId?: string;
2225
+ occurredAt?: number;
2226
+ }
2227
+ interface AgentPayloadEventFields extends AgentPayloadEventMetadata {
2228
+ messageId?: string;
2229
+ turnId?: string;
2230
+ sessionId?: string;
2231
+ }
2232
+ interface EmitGlobalOptions {
2233
+ includeEventMetadata?: boolean;
2234
+ }
2235
+ /**
2236
+ * Dependencies for AgentPayloadEmitter.
2237
+ */
2238
+ interface AgentPayloadEmitterConfig {
2239
+ /** Global bus for outbound emissions. */
2240
+ globalBus: IMakaioBus;
2241
+ /** Stable agent identity fields. */
2242
+ getAgentContextBase: () => Pick<AgentContext, 'agentId' | 'adapterId' | 'adapterName'> & {
2243
+ sessionId?: string;
2244
+ };
2245
+ /** Current messageId from lifecycle tracker, if any. */
2246
+ getCurrentMessageId: () => string | undefined;
2247
+ /** Current turnId from lifecycle tracker, if any. */
2248
+ getCurrentTurnId: () => string | undefined;
2249
+ /** Connector adapterSessionId, if currently available. */
2250
+ getConnectorAdapterSessionId: () => string | undefined;
2251
+ /** Last known adapterSessionId cached across connector swaps. */
2252
+ getLastKnownAdapterSessionId: () => string | undefined;
2253
+ /** Persist latest adapterSessionId after resolution. */
2254
+ setLastKnownAdapterSessionId: (adapterSessionId: string | undefined) => void;
2255
+ /** Live event metadata defaults resolved from current runtime state. */
2256
+ getEventMetadataDefaults: () => AgentPayloadEventMetadata;
2257
+ }
2258
+ /**
2259
+ * Handles agent context enrichment and global bus emissions.
2260
+ */
2261
+ declare class AgentPayloadEmitter {
2262
+ private readonly config;
1993
2263
  /**
1994
- * Emit step.finished event with content and increment block index.
1995
- * Call this when a content block completes processing.
1996
- * @param stepType - The type of step that finished
1997
- * @param content - The complete content of the step (text, reasoning, tool_call, or tool_output)
2264
+ * Create a payload emitter with context resolution dependencies.
2265
+ * @param config - Config controlling agent-context enrichment and global emissions
1998
2266
  */
1999
- protected emitStepFinished(stepType: StepType, content: SessionMessageBlock): Promise<void>;
2267
+ constructor(config: AgentPayloadEmitterConfig);
2000
2268
  /**
2001
- * Get the current block index (for adapters that need to track it externally).
2002
- * @returns Current block index within the turn
2269
+ * Resolve the confirmed adapter session ID from synchronous sources.
2270
+ *
2271
+ * `getConnectorAdapterSessionId` delegates to `getConfirmedAdapterSessionId()`
2272
+ * which returns `undefined` for unconfirmed fork sessions — the provider has
2273
+ * not yet assigned the child session ID. For non-fork sessions (fresh, resume,
2274
+ * non-Claude adapters) the locally-determined ID is authoritative and returned
2275
+ * immediately.
2276
+ *
2277
+ * The `lastKnownAdapterSessionId` bridges connector swaps: when the old
2278
+ * connector is gone and the new one is not yet wired, the cached value carries
2279
+ * the confirmed ID from the previous connector.
2280
+ *
2281
+ * No async fallback is used. `connector.getAdapterSessionId()` may resolve
2282
+ * with a provisional placeholder for fork sessions. Enrichment must never
2283
+ * stamp unconfirmed IDs — omitting the field is safe since R8 schemas allow
2284
+ * it optional.
2285
+ * @returns Confirmed adapter session ID or `undefined`
2003
2286
  */
2004
- protected getBlockIndex(): number;
2287
+ private resolveConfirmedAdapterSessionId;
2005
2288
  /**
2006
- * Increment block index (for adapters using SDK-provided indices).
2007
- * Call after emitting step.finished if managing index externally.
2289
+ * Resolve event metadata fields, merging caller-provided values over live defaults.
2290
+ * @param payload - Payload fields that may carry metadata overrides
2291
+ * @param includeMetadata - Whether to include analytics metadata at all
2292
+ * @returns Resolved metadata fields
2008
2293
  */
2009
- protected incrementBlockIndex(): void;
2294
+ private resolveEventMetadata;
2010
2295
  /**
2011
- * Handle agent.sendMessage request.
2012
- * The filter has already been applied at subscription time - this method
2013
- * only receives messages intended for this agent.
2014
- * Runs PreUserMessage hooks before delegating to the connector's sendMessage method.
2015
- * Uses sessionContext signals to decide between native resume and fresh with history.
2016
- * HookAbortError propagates to caller (session layer handles lifecycle).
2017
- * Subclasses can override for custom handling.
2018
- * @param ctx - Request context with payload and response methods
2296
+ * Enrich payload with agent context fields.
2297
+ * @param payload - Base payload to enrich
2298
+ * @param overrideMessageId - Explicit messageId override from caller payload
2299
+ * @param options - Enrichment controls for optional analytics metadata defaults
2300
+ * @returns Enriched payload with agent context
2019
2301
  */
2020
- protected sendMessage(ctx: RequestContext<SendMessageRequestPayload, SendMessageResponsePayload>): Promise<void>;
2302
+ enrichPayload<T extends object>(payload: T, overrideMessageId?: string, options?: EmitGlobalOptions): Promise<T & AgentIdentity & AgentPayloadEventFields>;
2021
2303
  /**
2022
- * Handle agent.interrupt request.
2023
- * Delegates to the connector's native interrupt behavior.
2024
- * @param ctx - Request context with interrupt payload
2304
+ * Emit enriched payload to global bus.
2305
+ * @param subject - Subject definition to emit
2306
+ * @param payload - Payload without AgentContext fields
2307
+ * @param options - Enrichment controls for optional analytics metadata defaults
2025
2308
  */
2026
- private handleInterrupt;
2027
- /**
2028
- * Register a cleanup function for connector wiring.
2029
- * These cleanups are cleared on connector swap but preserved across bus handler changes.
2030
- * @param cleanup - Cleanup function to register
2031
- */
2032
- protected addConnectorWiringCleanup(cleanup: () => void): void;
2033
- /**
2034
- * Registers a cleanup function for a global bus subscription.
2035
- * These survive connector swaps and are cleaned up in close().
2036
- * @param cleanup - Function to unsubscribe from the bus
2037
- */
2038
- protected addBusHandlerCleanup(cleanup: () => void): void;
2039
- /**
2040
- * Replace the current connector with a fresh one.
2041
- *
2042
- * Uses create-before-close pattern with rollback for safety:
2043
- * 1. Create new connector first (old connector still alive)
2044
- * 2. Wire events to new connector (accumulate cleanups separately)
2045
- * 3. If successful: close old connector, assign new one
2046
- * 4. If failed: close new connector, restore old wiring, throw
2047
- *
2048
- * This ensures the agent always has a working connector, even if factory or wiring fails.
2049
- *
2050
- * Preserves runtime overrides across sequential swaps by using current connector values
2051
- * as baseline for non-overridden fields.
2052
- * @param configOverrides - Optional config overrides (e.g., new cwd, model)
2053
- * @throws Error if connector is currently processing a turn
2054
- */
2055
- swapConnector(configOverrides?: AgentConnectorConfigOverrides): Promise<void>;
2056
- /**
2057
- * Build config factory input from agent config with optional overrides.
2058
- *
2059
- * Delegates to {@link buildConfigFactoryInput} with live connector-derived
2060
- * values (reasoning effort) and the agent's error sink.
2061
- * @param overrides - Optional field overrides (e.g., cwd, model, adapterSessionId)
2062
- * @returns ConfigFactoryInput ready for config factory
2063
- */
2064
- private buildConfigInput;
2065
- /**
2066
- * Create the onMessageSent callback for connector factories.
2067
- *
2068
- * Returns a callback that emits user_message.sent events to the global bus.
2069
- * @returns Callback function for connector config
2070
- */
2071
- private createOnMessageSent;
2072
- /**
2073
- * Wire adapter-specific connector events.
2074
- * Called automatically during init() and connector swap.
2075
- * Subclasses implement this to set up their event mappings.
2076
- * @param connector - Connector instance to wire
2077
- */
2078
- protected abstract wireEvents(connector: TConnector): void | Promise<void>;
2079
- /**
2080
- * Subscribe to a connector subject and register its cleanup as connector wiring.
2081
- *
2082
- * Use this in adapter `wireEvents()` implementations so connector swaps can
2083
- * remove old listeners before rewiring the new connector.
2084
- * @param connector - Connector instance to subscribe on
2085
- * @param subject - Subject definition to subscribe to
2086
- * @param handler - Subject handler
2087
- * @param options - Optional bus subscription options
2088
- */
2089
- protected subscribeConnector<Subject extends ScopedSubjectDefinition<TConnector extends AIAgentConnector<infer TBus> ? TBus['namespace'] : never>>(connector: TConnector, subject: Subject, handler: HandlerForSubjectDefinition<Subject>, options?: OnOptions): void;
2090
- /**
2091
- * Clean up resources and emit session closed event.
2092
- *
2093
- * Emits session.closed event (once per session) unless explicitly suppressed,
2094
- * then unsubscribes from all bus handlers and aborts the connector if available.
2095
- * @param options - Cleanup options; ephemeral agents suppress session-close lifecycle events because they never join a session.
2096
- */
2097
- close(options?: {
2098
- emitSessionClosed?: boolean;
2099
- }): Promise<void>;
2100
- /**
2101
- * Ensure the connector is initialized, throwing if not.
2102
- * @returns The initialized connector instance
2103
- */
2104
- private ensureConnector;
2105
- /**
2106
- * Determine whether to use native session resume (SDK manages history) or
2107
- * fresh-with-history (new session, injected messageHistory).
2108
- * @param sessionContext - Context signals from SessionOrchestrator
2109
- * @returns true if native resume should be used
2110
- */
2111
- protected shouldUseNativeResume(sessionContext?: SessionContext): boolean;
2112
- /**
2113
- * Whether this adapter supports native session resume. Override in concrete agents.
2114
- * @returns true if native resume is supported
2115
- */
2116
- protected supportsNativeResume(): boolean;
2117
- /**
2118
- * Whether this adapter supports provider-native session fork.
2119
- * Override in concrete agents that can branch from an existing provider session.
2120
- * @returns true if native fork is supported
2121
- */
2122
- protected supportsNativeFork(): boolean;
2123
- /**
2124
- * Start the agent with an initial message.
2125
- *
2126
- * Ensures the agent is initialized (idempotent), runs PreUserMessage hooks,
2127
- * and uses sessionContext signals to decide between native resume and fresh
2128
- * with history. HookAbortError propagates to caller.
2129
- * @param message - User message (normalized or unnormalized)
2130
- * @param options - Optional start options (e.g., delivery mode, sessionContext)
2131
- * @returns Session ID, agent ID, and message handle for tracking
2132
- */
2133
- start(message: NormalizedMessageInput | MessageInput, options?: StartAgentOptions): Promise<AgentStartResult>;
2134
- /**
2135
- * Initialize idle (no message). Returns confirmed adapter session ID or `undefined`
2136
- * when the provider has not yet confirmed (idle fork sessions).
2137
- * @param options - Optional initialization options (system prompt, sessionContext)
2138
- * @returns Confirmed adapter session ID, or `undefined` for unconfirmed fork sessions.
2139
- */
2140
- initialize(options?: StartAgentOptions): Promise<string | undefined>;
2141
- protected onBeforeEmitCompletion(): Promise<void>;
2142
- protected onMessageHandle(messageHandle: MessageHandle, turnId?: string): Promise<void>;
2143
- /**
2144
- * Abort the agent immediately (panic mode).
2145
- * Triggers AbortController which may cause provider errors.
2146
- * Use close() for graceful shutdown instead.
2147
- *
2148
- * Emits session.closed event (once per session) then delegates
2149
- * to the underlying connector's abort method.
2150
- * @throws Error if connector is not initialized
2151
- */
2152
- abort(): void;
2153
- /**
2154
- * Get session ID, waiting for provider to generate it if not yet available.
2155
- *
2156
- * Delegates to the underlying connector's getSessionId method.
2157
- * @returns Session ID from provider
2158
- * @throws Error if connector is not initialized
2159
- */
2160
- getAdapterSessionId(): Promise<string>;
2161
- /**
2162
- * Complete the agent session by waiting for all messages to finish.
2163
- *
2164
- * Waits for the connector to finish, then returns the agent-level terminal
2165
- * result so structured-output transforms are reflected in direct callers.
2166
- * @returns Last message result or null if no messages processed
2167
- * @throws Error if connector is not initialized
2168
- */
2169
- complete(): Promise<MessageResult | null>;
2170
- /**
2171
- * Creates a type-safe event mapping from connector events to scoped subjects or handlers.
2172
- * @param sourceSubject - The connector subject to subscribe to
2173
- * @param discriminator - The discriminator key within the message (e.g., 'type')
2174
- * @param handlers - Map of discriminator values to target subjects or handler functions
2175
- * @param nestedMessageProp - Property containing the discriminated union (e.g., 'msg'), or undefined for top-level
2176
- * @returns Unsubscribe function for the connector event mapping subscription
2177
- */
2178
- 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;
2309
+ emitGlobal<S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext> & {
2310
+ messageId?: string;
2311
+ turnId?: string;
2312
+ }, options?: EmitGlobalOptions): Promise<void>;
2179
2313
  }
2180
2314
  //#endregion
2181
- //#region adapters/core/src/factory/create-adapter-namespace.d.ts
2182
- /**
2183
- * Adapter namespace extends BusNamespace with additional metadata for adapters.
2184
- *
2185
- * Provides:
2186
- * - All BusNamespace features (subjects, scoped bus factory)
2187
- * - Raw schema access for adapter factory internals
2188
- * - Domain name for debugging/logging
2189
- * @typeParam N - Namespace domain string
2190
- */
2191
- type AdapterNamespace<Domain extends string = string> = Omit<BusNamespace<Domain>, 'subjects'> & {
2192
- /** Original namespace definition for registration on host-provided bus instances. */readonly definition: RegistrableBusNamespaceDefinition;
2193
- };
2194
- /**
2195
- * Creates an adapter namespace with typed subject definitions.
2196
- *
2197
- * **Seam:** Thin wrapper around MakaioBus.registerNamespace that:
2198
- * - Delegates to bus-core for namespace registration
2199
- * - Preserves FilterPayload type for type-safe withFilter()
2200
- * - Provides extension point for future adapter-specific features
2201
- * @param domain - Namespace domain (e.g., 'adapter:claudeCode')
2202
- * @param schemas - Record of subject schemas (events and requests)
2203
- * @param options - Registration and routing options (e.g., busValidationMode for Zod version conflicts)
2204
- * @returns Adapter namespace with typed subjects and pre-computed FilterPayload
2205
- * @example
2206
- * ```typescript
2207
- * const ClaudeCodeNamespace = createAdapterNamespace('adapter:claudeCode', {
2208
- * thinking: z.object({ content: z.string() }),
2209
- * getContext: {
2210
- * request: z.object({ path: z.string() }),
2211
- * response: z.object({ content: z.string() }),
2212
- * },
2213
- * });
2214
- *
2215
- * // Access typed subjects
2216
- * ClaudeCodeNamespace.subjects.thinking;
2217
- *
2218
- * // Get scoped bus with type-safe filtering
2219
- * const bus = await ClaudeCodeNamespace.scopedBus();
2220
- * bus.withFilter({ content: 'test' }); // ✅ Type-checked
2221
- *
2222
- * // For adapters with bundled Zod v3 (e.g., @github/copilot-sdk):
2223
- * const CopilotNamespace = createAdapterNamespace('adapter:copilot', schemas, {
2224
- * busValidationMode: 'skip', // Skip validation due to Zod version conflict
2225
- * });
2226
- *
2227
- * // For adapters with lenient validation (schema drift triggers warnings, not crashes):
2228
- * const ClaudeNamespace = createAdapterNamespace('adapter:claude-code', schemas, {
2229
- * busValidationMode: 'lenient',
2230
- * onSchemaViolation: (report) => console.warn(report),
2231
- * });
2232
- * ```
2233
- */
2234
- declare function createAdapterNamespace<N extends string, Schemas extends SchemaRecord>(domain: N, schemas: Schemas, options?: CreateBusNamespaceOptions): BusNamespace<N, SubjectRecordFromSchemaRecord<Schemas>, FilterablePayloadIntersection<SubjectRecordFromSchemaRecord<Schemas>>, Schemas> & {
2235
- readonly definition: RegistrableBusNamespaceDefinition;
2236
- };
2237
- //#endregion
2238
- //#region adapters/core/src/factory/adapter-context.d.ts
2315
+ //#region adapters/core/src/agent/agent-bus-handler-registrar.d.ts
2239
2316
  /**
2240
- * Context provided to adapter implementations.
2241
- *
2242
- * Contains shared infrastructure and configuration that all adapters need:
2243
- * - Adapter name and capabilities from config
2244
- * - Local event bus for emitting events
2317
+ * Handler bundle required to register all `agent.*` request handlers.
2245
2318
  */
2246
- interface AIAdapterContext<Scope extends ScopedBus<string>> {
2247
- /** Unique adapter instance identifier. */
2248
- adapterId: string;
2249
- /** Unique adapter name (kebab-case). */
2250
- name: string;
2251
- /** Adapter capabilities (unparsed). Use parseAIAdapterCapabilities() to parse. */
2252
- capabilities: AIAdapterCapability[];
2253
- /** Scoped bus for adapter-level events. */
2254
- adapterBus: Scope;
2255
- /** Global event bus. */
2319
+ interface AgentBusHandlerRegistrarConfig {
2320
+ /** Global bus instance where handlers are registered. */
2256
2321
  globalBus: IMakaioBus;
2322
+ /** Target agent identity for filter scoping. */
2323
+ agentId: string;
2324
+ /** Makaio session identity for canonical turn-number observation. */
2325
+ sessionId?: string;
2326
+ /** Handler for `agent.sendMessage`. */
2327
+ onSendMessage: (ctx: RequestContext<SendMessageRequestPayload, SendMessageResponsePayload>) => Promise<void>;
2328
+ /** Handler for `agent.interrupt`. */
2329
+ onInterrupt: (ctx: RequestContext<AgentInterruptRequestPayload, AgentInterruptResponsePayload>) => Promise<void>;
2330
+ /** Provider for `agent.getCapabilities` response payload. */
2331
+ getCapabilities: () => GetCapabilitiesResponsePayload;
2332
+ /** Apply an `agent.cwd.change` payload. */
2333
+ onCwdChange: (payload: AgentCwdChangeRequestPayload) => Promise<AgentCwdChangeResponsePayload>;
2334
+ /** Apply an `agent.model.change` payload. */
2335
+ onModelChange: (payload: AgentModelChangeRequestPayload) => Promise<AgentModelChangeResponsePayload>;
2336
+ /** Apply an `agent.mcp.servers.set` payload. */
2337
+ onMcpServersSet: (payload: AgentMcpServersSetRequestPayload) => Promise<AgentMcpServersSetResponsePayload>;
2338
+ /** Apply an `agent.credential.change` payload. */
2339
+ onCredentialChange: (payload: AgentCredentialChangeRequestPayload) => Promise<AgentCredentialChangeResponsePayload>;
2340
+ /** Observe the canonical session turn number. */
2341
+ onTurnStarted: (turnNumber: number) => void;
2342
+ /** Mark connector tools stale after an MCP catalog mutation. */
2343
+ onMcpToolsChanged: () => void;
2257
2344
  }
2258
- //#endregion
2259
- //#region adapters/core/src/agent/agent-turn-executor.d.ts
2260
2345
  /**
2261
- * Runtime dependencies for AgentTurnExecutor.
2346
+ * Register all stable `agent.*` bus handlers for a single agent instance.
2347
+ * @param config - Registration configuration with handlers
2348
+ * @returns Cleanup functions for all registrations
2262
2349
  */
2263
- type AgentMessageHandleCallback = (messageHandle: MessageHandle, turnId: string | undefined) => Promise<void>;
2264
- interface AgentTurnExecutorConfig {
2350
+ declare function registerAgentBusHandlers(config: AgentBusHandlerRegistrarConfig): Array<() => void>;
2351
+ //#endregion
2352
+ //#region adapters/core/src/agent/agent-runtime-mutation-manager-config.d.ts
2353
+ /** Dependencies for runtime mutation handling. */
2354
+ interface AgentRuntimeMutationManagerConfig {
2265
2355
  /** Stable agent identifier. */
2266
2356
  agentId: string;
2267
- /** Stable adapter identifier. */
2268
- adapterId: string;
2269
2357
  /** Optional Makaio session identifier. */
2270
2358
  sessionId?: string;
2271
- /** Capability tags reported by the adapter (e.g. `'structuredOutput'`). */
2272
- adapterCapabilities?: string[];
2273
- /** Global bus instance for hooks. */
2359
+ /** Global bus for persistence and events. */
2274
2360
  globalBus: IMakaioBus;
2275
- /** Current connector reference resolver. */
2361
+ /** Read current connector. */
2276
2362
  getConnector: () => AIAgentConnector;
2277
- /** Native resume decision function. */
2278
- shouldUseNativeResume: ShouldUseNativeResumeFn;
2279
- /**
2280
- * Whether the agent config carries a concrete resume target
2281
- * (`resumeAdapterSessionId`).
2282
- *
2283
- * Used by {@link AgentTurnExecutor.deriveStartMode} to distinguish
2284
- * native-attach starts (resume target, no sessionContext) from
2285
- * truly sessionless/ephemeral starts (no resume target, no context).
2286
- */
2287
- hasResumeTarget: () => boolean;
2288
- /**
2289
- * Set the start mode on the owning agent before connector dispatch.
2290
- *
2291
- * The turn executor computes the mode from session context signals and
2292
- * calls this so `emitStart()` can include it in the `agent.started`
2293
- * payload when the connector fires its lifecycle event.
2294
- * @param mode - Derived start mode for this turn
2295
- */
2296
- setPendingStartMode: (mode: StartMode) => void;
2297
- /** Completion/lifecycle tracker hook. */
2298
- onMessageHandle: AgentMessageHandleCallback;
2299
- /** Side-effect callback to mark agent status active before dispatch. */
2300
- onBeforeDispatch?: () => void | Promise<void>;
2301
- /** When true, PreUserMessage hooks are skipped. */
2302
- ephemeral?: boolean;
2363
+ /** Agent-wide exclusivity boundary for connector-affecting operations. */
2364
+ runExclusive: <T>(action: () => Promise<T>) => Promise<T>;
2365
+ /** Swap connector while the caller already owns the agent-wide runtime barrier. */
2366
+ swapConnectorUnlocked: (configOverrides?: AgentConnectorConfigOverrides, beforeCommit?: ConnectorSwapCommitGuard) => Promise<void>;
2367
+ /** Emit cwd.changed payload. */
2368
+ emitCwdChanged: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.cwd.changed>, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2369
+ /** Emit model.changed payload. */
2370
+ emitModelChanged: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.model.changed>, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2371
+ /** Read the agent's current provider context for no-op detection. */
2372
+ getProviderContext: () => ProviderContext | undefined;
2373
+ /** Persist provider context changes on agent config for sequential swaps. */
2374
+ setProviderContext: (providerContext: ProviderContext) => void;
2375
+ /** Persist reasoning effort changes on agent config for sequential swaps. */
2376
+ setReasoningEffort: (reasoningEffort: AIReasoningLevel$1 | undefined) => void;
2377
+ /** Persist MCP session context changes on agent config for sequential swaps. */
2378
+ setMcpSessionContext: (mcpSessionContext: McpRuntimeSessionContext | McpSessionContext | LedgerSessionContext | undefined) => void;
2379
+ /** Resolve supported reasoning levels for a model from the agent's available models. */
2380
+ resolveSupportedReasoningLevels: (model: string) => ReasoningLevelMap$1 | undefined;
2303
2381
  }
2304
- /**
2305
- * Function type for native resume decision.
2306
- */
2307
- type ShouldUseNativeResumeFn = (sessionContext?: StartAgentOptions['sessionContext']) => boolean;
2308
- /**
2309
- * Shared start/send-message execution pipeline for AIAgent.
2310
- */
2311
- declare class AgentTurnExecutor {
2382
+ //#endregion
2383
+ //#region adapters/core/src/agent/agent-runtime-mutation-manager.d.ts
2384
+ /** Coordinate every runtime mutation through one agent-wide exclusivity seam. */
2385
+ declare class AgentRuntimeMutationManager {
2312
2386
  private readonly agentId;
2313
- private readonly adapterId;
2314
- private readonly sessionId?;
2315
- private readonly adapterCapabilities;
2316
2387
  private readonly globalBus;
2317
2388
  private readonly getConnector;
2318
- private readonly shouldUseNativeResume;
2319
- private readonly hasResumeTarget;
2320
- private readonly setPendingStartMode;
2321
- private readonly onMessageHandle;
2322
- private readonly onBeforeDispatch?;
2323
- private readonly ephemeral;
2324
- constructor(config: AgentTurnExecutorConfig);
2389
+ private readonly runExclusive;
2390
+ private readonly swapConnectorUnlocked;
2391
+ private readonly emitCwdChanged;
2392
+ private readonly mcpServersMutationManager;
2393
+ private readonly modelMutationManager;
2394
+ private readonly credentialChangeManager;
2395
+ private readonly credentialChangeSequencer;
2325
2396
  /**
2326
- * Derive the {@link StartMode} from session context, resume decision, and
2327
- * resume-target presence.
2328
- *
2329
- * Decision table (evaluated top-to-bottom, first match wins):
2330
- *
2331
- * | sessionContext | nativeFork | hasResumeTarget | useNativeResume | isFirstTurn | Mode |
2332
- * |----------------|------------|-----------------|-----------------|-------------|------------|
2333
- * | present | yes | — | — | — | `fork` |
2334
- * | absent | — | yes | — | — | `resume` |
2335
- * | absent | — | no | — | — | `fresh` |
2336
- * | present | no | — | true | — | `resume` |
2337
- * | present | no | — | false | true | `fresh` |
2338
- * | present | no | — | false | false | `rotation` |
2339
- *
2340
- * The `hasResumeTarget` rule distinguishes native-attach starts (concrete
2341
- * provider session to reconnect to, but no orchestrator session context) from
2342
- * truly sessionless/ephemeral starts. Without this signal, both cases
2343
- * collapsed to `'fresh'` — causing SDK SessionStart hooks to run
2344
- * initialization logic on a resumed conversation.
2345
- *
2346
- * `hasResumeTarget` fires only when sessionContext is absent. Once the
2347
- * orchestrator supplies context (turn 2+), rules 4-6 take over and the
2348
- * resume target on the config has no further effect on mode derivation.
2349
- * @param sessionContext - Session context signals from the orchestrator
2350
- * @param useNativeResume - Whether native resume was selected for this turn
2351
- * @param hasResumeTarget - Whether a concrete resume target
2352
- * (`resumeAdapterSessionId`) exists on the agent config
2353
- * @returns The derived start mode
2397
+ * Create the agent-level runtime mutation coordinator.
2398
+ * @param config - Runtime collaborators and the shared exclusivity function
2354
2399
  */
2355
- static deriveStartMode(sessionContext: SessionContext | undefined, useNativeResume: boolean, hasResumeTarget?: boolean): StartMode;
2400
+ constructor(config: AgentRuntimeMutationManagerConfig);
2356
2401
  /**
2357
- * Derive the start mode for the given resolved session context, stash it
2358
- * as the pending mode for the next lifecycle start emission, and return
2359
- * the native-resume decision shared by the dispatch that follows.
2360
- * @param sessionContext - Session context after pre-user-message hooks
2361
- * @returns Whether the connector should rely on native resume
2402
+ * Handle `agent.cwd.change` through the shared runtime barrier.
2403
+ * @param payload - CWD change request payload
2404
+ * @returns CWD mutation response payload
2362
2405
  */
2363
- private deriveAndSetPendingStartMode;
2406
+ handleCwdChange(payload: AgentCwdChangeRequestPayload): Promise<AgentCwdChangeResponsePayload>;
2364
2407
  /**
2365
- * Execute the turn pipeline for agent.sendMessage.
2366
- * @param payload - agent.sendMessage request payload
2367
- * @returns Resolved messageId from connector handle
2408
+ * Apply one CWD change while the agent-wide runtime barrier is held.
2409
+ * @param payload - CWD change request payload
2410
+ * @returns CWD mutation response payload
2368
2411
  */
2369
- executeSendMessage(payload: SendMessageRequestPayload): Promise<{
2370
- messageId: string;
2371
- }>;
2412
+ private handleCwdChangeUnlocked;
2413
+ /** Apply all staged replacements while the enclosing turn barrier is held. */
2414
+ private applyStagedMutationsUnlocked;
2372
2415
  /**
2373
- * Execute the turn pipeline for agent.start.
2374
- * @param message - Initial message payload
2375
- * @param options - Start options from caller
2376
- * @param systemPrompt - Runtime system prompt chosen by AIAgent
2377
- * @param responseSchema - Runtime structured output descriptor chosen by AIAgent
2378
- * @returns Agent start result from connector
2416
+ * Serialize staged mutations and the complete turn pre-hook-to-send boundary.
2417
+ * @param dispatch - Turn dispatch work that must observe one connector generation
2418
+ * @returns Dispatch result
2379
2419
  */
2380
- executeStart(message: NormalizedMessageInput | MessageInput, options: StartAgentOptions | undefined, systemPrompt: StartAgentOptions['systemPrompt'], responseSchema?: ResponseSchemaDescriptor): Promise<AgentStartResult>;
2420
+ runTurnDispatch<T>(dispatch: () => Promise<T>): Promise<T>;
2381
2421
  /**
2382
- * Resolve the pre-user hook result or preserve the caller payload for ephemeral turns.
2383
- * @param input - Message and context for the outgoing user turn
2384
- * @returns Message and session context to dispatch to the connector
2422
+ * Handle `agent.mcp.servers.set` through the shared runtime barrier.
2423
+ * @param payload - MCP server replacement request payload
2424
+ * @returns MCP mutation response payload
2385
2425
  */
2386
- private resolvePreUserMessageTurn;
2426
+ handleMcpServersSet(payload: AgentMcpServersSetRequestPayload): Promise<AgentMcpServersSetResponsePayload>;
2387
2427
  /**
2388
- * Fire PostUserMessage hooks without blocking the turn.
2389
- * @param messageId - Message ID for correlation
2428
+ * Handle `agent.model.change` through the shared runtime barrier.
2429
+ * @param payload - Model/provider/reasoning mutation request
2430
+ * @returns Model mutation response payload
2390
2431
  */
2391
- private firePostUserMessageHooks;
2432
+ handleModelChange(payload: AgentModelChangeRequestPayload): Promise<AgentModelChangeResponsePayload>;
2433
+ /**
2434
+ * Handle credential rotation through the same turn/mutation barrier.
2435
+ * @param payload - Credential change request payload
2436
+ * @returns Credential mutation response payload
2437
+ */
2438
+ handleCredentialChanged(payload: AgentCredentialChangeRequestPayload): Promise<AgentCredentialChangeResponsePayload>;
2439
+ /**
2440
+ * Persist committed runtime fields and require an affirmative storage result.
2441
+ * @param changes - CWD/model/provider mutations to persist
2442
+ */
2443
+ private persistRuntimeMutation;
2392
2444
  }
2393
2445
  //#endregion
2446
+ //#region adapters/core/src/agent/mcp-call-extractor.d.ts
2447
+ /**
2448
+ * Utilities for identifying and extracting target information from `mcp_call`
2449
+ * tool invocations.
2450
+ *
2451
+ * The `mcp_call` meta-tool carries its real target as the `tool` field in the
2452
+ * parsed JSON arguments. These helpers centralise that extraction logic so
2453
+ * every consumer (ledger, event bridge, analytics) uses a single, tested path.
2454
+ * @packageDocumentation
2455
+ */
2456
+ /**
2457
+ * Extract the target MCP tool name from parsed `mcp_call` arguments.
2458
+ *
2459
+ * Conforms to the `mcp_call` input schema which defines `{ tool: z.string() }`.
2460
+ * Returns `undefined` for any non-conformant argument shape so callers can
2461
+ * skip processing without throwing.
2462
+ * @param args - Parsed JSON arguments object from the tool call
2463
+ * @returns The namespaced target tool name, or `undefined` if not conformant
2464
+ */
2465
+ declare function extractMcpCallTarget(args: Record<string, unknown>): string | undefined;
2466
+ /**
2467
+ * Check whether a tool call name refers to the `mcp_call` meta-tool.
2468
+ *
2469
+ * Uses the canonical {@link MCP_CALL_TOOL_NAME} constant so the comparison
2470
+ * stays in sync with the toolset definition automatically.
2471
+ *
2472
+ * Callers are responsible for stripping provider-specific prefixes before
2473
+ * calling this function (e.g., Gemini's `default_api.` prefix must be
2474
+ * removed at the call site — see `execute-tool-calls.ts` normalizedToolName).
2475
+ * @param toolName - Normalized tool name from the tool call
2476
+ * @returns `true` if this is an `mcp_call` invocation
2477
+ */
2478
+ declare function isMcpCallTool(toolName: string): boolean;
2479
+ //#endregion
2480
+ //#region adapters/core/src/agent/request-correlation.d.ts
2481
+ /** Exact Factory Gateway headers accepted by its content-free usage boundary. */
2482
+ declare const FactoryUsageCorrelationHeaders: {
2483
+ readonly sessionId: "x-factory-session-id";
2484
+ readonly turnId: "x-factory-turn-id";
2485
+ readonly messageId: "x-factory-message-id";
2486
+ readonly llmCallId: "x-factory-llm-call-id";
2487
+ readonly executionId: "x-factory-execution-id";
2488
+ readonly frameId: "x-factory-frame-id";
2489
+ };
2490
+ type ProviderRequestCorrelation = RequestCorrelationContext & {
2491
+ llmCallId: string;
2492
+ };
2493
+ /**
2494
+ * Bind caller correlation to identifiers owned by the active runtime request.
2495
+ * Runtime values always win, preventing stale or spoofed session/message IDs.
2496
+ * @param context - Optional orchestrator-supplied workflow correlation
2497
+ * @param runtime - IDs known by the connector for this concrete API request
2498
+ * @returns Fully bound correlation including one LLM-call ID
2499
+ */
2500
+ declare function bindProviderRequestCorrelation(context: RequestCorrelationContext | undefined, runtime: {
2501
+ sessionId?: string;
2502
+ messageId: string;
2503
+ llmCallId: string;
2504
+ }): ProviderRequestCorrelation;
2505
+ /**
2506
+ * Project a validated correlation context to the Factory Gateway allowlist.
2507
+ *
2508
+ * No arbitrary metadata or headers can cross this boundary. Callers must also
2509
+ * explicitly opt into the `factory-v1` transport mode before using the result.
2510
+ * @param correlation - Content-free runtime and workflow identifiers
2511
+ * @returns Header record accepted by the Factory Gateway usage boundary
2512
+ */
2513
+ declare function buildFactoryUsageCorrelationHeaders(correlation: ProviderRequestCorrelation): Record<string, string>;
2514
+ //#endregion
2394
2515
  //#region adapters/core/src/adapter/types.d.ts
2395
2516
  /** Payload type for adapter.startAgent requests. */
2396
2517
  type StartAgentRequestPayload = ExtractSubjectPayload<typeof AdapterSubjects.startAgent>;
@@ -2494,6 +2615,8 @@ interface AIAdapterConfig<TBus extends ScopedBus<string> = ScopedBus<string>> {
2494
2615
  definitionProviders?: readonly AdapterProviderDefinition[];
2495
2616
  /** Client identifier for the application this adapter belongs to (e.g., 'claude-code', 'codex'). Omit for API-only adapters. */
2496
2617
  clientId?: string;
2618
+ /** Trusted non-serializable normalized auth preparer injected by the host. */
2619
+ prepareAuthRuntime?: AdapterAuthRuntimePreparer<TBus>;
2497
2620
  }
2498
2621
  /**
2499
2622
  * Full constructor config including factory injections.
@@ -2522,6 +2645,17 @@ interface AIAdapterConstructorConfig<TBus extends ScopedBus<string>, TConnector
2522
2645
  }
2523
2646
  //#endregion
2524
2647
  //#region adapters/core/src/agent/agent-connector-lifecycle-manager.d.ts
2648
+ /** Sanitized lifecycle diagnostic emitted after a replacement became primary. */
2649
+ interface ConnectorCleanupDiagnostic {
2650
+ /** Stable machine-readable failure category. */
2651
+ readonly code: 'previous-connector-cleanup-failed';
2652
+ /** Lifecycle stage whose cleanup failed. */
2653
+ readonly stage: 'swap-old-runtime';
2654
+ /** Agent owning the replacement connector. */
2655
+ readonly agentId: string;
2656
+ }
2657
+ /** Final async guard run after the replacement is ready but before it becomes primary. */
2658
+ type ConnectorSwapCommitGuard = () => void | Promise<void>;
2525
2659
  /**
2526
2660
  * Dependencies for connector lifecycle management.
2527
2661
  */
@@ -2538,20 +2672,24 @@ interface AgentConnectorLifecycleManagerConfig<TBus extends ScopedBus<string>, T
2538
2672
  connectorFactory: (config: BaseAgentConnectorConfig<TBus> & {
2539
2673
  adapterId: string;
2540
2674
  }) => Promise<TConnector> | TConnector;
2675
+ /** Trusted host-local auth preparer shared by every connector generation. */
2676
+ prepareAuthRuntime?: AdapterAuthRuntimePreparer<TBus>;
2541
2677
  /** Build onMessageSent callback for connector creation. */
2542
2678
  createOnMessageSent: () => (handle: MessageHandle) => void;
2543
2679
  /** Wire adapter-specific events on a connector instance. */
2544
2680
  wireEvents: (connector: TConnector) => void | Promise<void>;
2545
2681
  /** Emit idle lifecycle event on processing-state idle transitions. */
2546
2682
  emitIdle: () => Promise<void>;
2547
- /** Get current connector for swap guards/baseline values. */
2548
- getConnector: () => TConnector;
2549
- /** Replace active connector reference on successful swap. */
2550
- setConnector: (connector: TConnector) => void;
2683
+ /** Get current connector plus its explicit client config lease. */
2684
+ getConnectorRuntime: () => ConnectorRuntimeHandle<TConnector>;
2685
+ /** Replace active connector and lease together on successful swap. */
2686
+ setConnectorRuntime: (runtime: ConnectorRuntimeHandle<TConnector>) => void;
2551
2687
  /** Get runtime system prompt to preserve across swaps. */
2552
2688
  getRuntimeSystemPrompt: () => SystemPrompt | undefined;
2553
2689
  /** Store latest adapter session ID for enrichment after swaps. */
2554
2690
  setLastKnownAdapterSessionId: (adapterSessionId: string | undefined) => void;
2691
+ /** Publish a sanitized cleanup diagnostic without exposing connector errors. */
2692
+ reportCleanupFailure: (diagnostic: ConnectorCleanupDiagnostic) => void | Promise<void>;
2555
2693
  }
2556
2694
  /**
2557
2695
  * Manages connector lifecycle for AIAgent.
@@ -2578,452 +2716,436 @@ declare class AgentConnectorLifecycleManager<TBus extends ScopedBus<string>, TCo
2578
2716
  */
2579
2717
  wireAllConnectorEvents(connector: TConnector): Promise<void>;
2580
2718
  /**
2581
- * Replace the active connector with a fresh instance.
2719
+ * Replace the active connector with a fresh instance.
2720
+ *
2721
+ * Uses create-before-close pattern with rollback to preserve availability.
2722
+ * @param configOverrides - Optional runtime override fields
2723
+ * @param beforeCommit - Final guard after replacement initialization and before publication
2724
+ */
2725
+ swapConnector(configOverrides?: AgentConnectorConfigOverrides, beforeCommit?: ConnectorSwapCommitGuard): Promise<void>;
2726
+ /**
2727
+ * Build and materialize the replacement connector runtime.
2728
+ * @param currentConnector - Active connector whose runtime values provide defaults
2729
+ * @param configOverrides - Optional requested runtime changes
2730
+ * @returns Prepared replacement connector and auth lease
2731
+ */
2732
+ private createReplacementRuntime;
2733
+ /**
2734
+ * Wire and initialize a replacement, restoring the current wiring on failure.
2735
+ * @param newRuntime - Replacement connector and auth lease
2736
+ * @param oldWiringCleanups - Wiring still owned by the active connector
2737
+ * @param beforeCommit - Optional final publication guard
2738
+ * @returns Provider-confirmed session ID, when the replacement has one
2739
+ */
2740
+ private initializeReplacement;
2741
+ /**
2742
+ * Run superseded connector wiring cleanups without failing the committed swap.
2743
+ * @param cleanups - Previous connector wiring cleanups
2744
+ */
2745
+ private runWiringCleanups;
2746
+ /**
2747
+ * Close the superseded runtime and publish only a sanitized diagnostic on failure.
2748
+ * @param currentRuntime - Superseded connector and auth lease
2749
+ */
2750
+ private closePreviousRuntime;
2751
+ }
2752
+ //#endregion
2753
+ //#region adapters/core/src/agent/ai-agent.d.ts
2754
+ /**
2755
+ * Abstract base class for AI agents.
2756
+ *
2757
+ * Bridges adapter/agent bus subjects to connector sessions.
2758
+ * @typeParam TBus - The scoped bus type for this adapter
2759
+ * @typeParam TConnector - The connector type this agent wraps
2760
+ */
2761
+ declare abstract class AIAgent<TBus extends ScopedBus<string> = ScopedBus<string>, TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>> {
2762
+ /** The underlying connector instance (created in init) */
2763
+ protected connector: TConnector;
2764
+ /** Connector and auth lease are replaced and released as one lifecycle unit. */
2765
+ private connectorRuntime;
2766
+ protected confirmedModel?: string;
2767
+ protected initialModel?: string;
2768
+ /** Cached adapterSessionId from the last connector that had a session — survives connector swaps. */
2769
+ private lastKnownAdapterSessionId?;
2770
+ /** Cleanup functions for bus subscriptions (stable, survive connector swap) */
2771
+ private busHandlerCleanups;
2772
+ /** Whether init() has been called */
2773
+ private initialized;
2774
+ /** Runtime system prompt captured from start/initialize, preserved across connector swaps. */
2775
+ private runtimeSystemPrompt?;
2776
+ /** Tracks message lifecycle and emits turn events (emission is lazy — safe as field initializer). */
2777
+ protected readonly lifecycleTracker: MessageLifecycleTracker;
2778
+ /** Tracks tool.use → tool.output correlation across adapters. */
2779
+ protected readonly toolCallTracker: ToolCallTracker;
2780
+ /** Event-focused helper for usage/tool/step emissions. */
2781
+ protected readonly eventBridge: AgentEventBridge;
2782
+ /** Shared turn pipeline for start/sendMessage paths. */
2783
+ private readonly turnExecutor;
2784
+ /** Runtime mutation helper for cwd/model change handlers. */
2785
+ private readonly runtimeMutationManager;
2786
+ /** Connector lifecycle helper for swap/wiring ownership. */
2787
+ private readonly connectorLifecycleManager;
2788
+ /** Serialized connector replacement and runtime-config publication owner. */
2789
+ private readonly connectorSwapCoordinator;
2790
+ /** Payload enrichment and global emission helper. */
2791
+ private readonly payloadEmitter;
2792
+ /** Stateful lifecycle emitter for start/complete/error/session.closed. */
2793
+ private readonly lifecycleEmitter;
2794
+ /** Validates structured output before public terminal results and lifecycle events resolve. */
2795
+ private readonly structuredOutputManager;
2796
+ /** Latest tracked message completion with agent-level terminal transforms applied. */
2797
+ private latestMessageCompletion?;
2798
+ /** Current content block index within the turn, reset on each turn start */
2799
+ private currentBlockIndex;
2800
+ /**
2801
+ * Start mode for the next `emitStart()` call (consume-on-read).
2802
+ *
2803
+ * Set before dispatch; {@link emitStart} reads and clears the slot so
2804
+ * subsequent calls within the same dispatch (e.g. Copilot SDK sub-turns)
2805
+ * fall back to `'rotation'`. The `undefined` initial value is safe —
2806
+ * every first-start path sets the mode before the connector fires.
2807
+ */
2808
+ private pendingStartMode;
2809
+ /** Normalized config with defaults applied */
2810
+ protected readonly config: SetRequired<AIAgentConfig<TBus, TConnector>, 'globalBus'>;
2811
+ /** Available models for context window lookup */
2812
+ protected readonly availableModels?: AIModel[];
2813
+ /**
2814
+ * Create an AIAgent instance.
2815
+ *
2816
+ * Note: Does NOT create the connector yet - call init() after construction.
2817
+ * @param config - Agent configuration
2818
+ */
2819
+ constructor(config: AIAgentConfig<TBus, TConnector>);
2820
+ /**
2821
+ * Create the connector lifecycle collaborator bound to this agent instance.
2822
+ * @param emitGlobal - Enriched global event emitter
2823
+ * @param setLastKnownAdapterSessionId - Sink for the latest confirmed provider session
2824
+ * @returns Connector lifecycle manager for this agent
2825
+ */
2826
+ private createConnectorLifecycleManager;
2827
+ private getEventMetadataDefaults;
2828
+ /** @returns Unique agent identifier */
2829
+ get agentId(): string;
2830
+ /** @returns Adapter instance identifier */
2831
+ get adapterId(): string;
2832
+ /** @returns Adapter type name (e.g., 'claude-code', 'gemini-sdk') */
2833
+ get adapterName(): string;
2834
+ /** @returns Adapter capabilities for runtime feature detection */
2835
+ get capabilities(): string[];
2836
+ /** @returns Native tools built into the adapter */
2837
+ get nativeTools(): string[];
2838
+ /** @returns Shared Makaio sessionId */
2839
+ get sessionId(): string | undefined;
2840
+ /** @returns Initial adapter session ID from config (may differ from connector's resolved session ID) */
2841
+ protected get adapterSessionId(): string | undefined;
2842
+ /** @returns Global bus for cross-namespace communication (defaulted in constructor) */
2843
+ protected get globalBus(): IMakaioBus;
2844
+ /**
2845
+ * Initialize the agent.
2582
2846
  *
2583
- * Uses create-before-close pattern with rollback to preserve availability.
2584
- * @param configOverrides - Optional runtime override fields
2847
+ * Creates the connector via the abstract createConnector() method
2848
+ * and sets up handlers for agent.* subjects with agentId filtering.
2849
+ * @throws Error if already initialized
2585
2850
  */
2586
- swapConnector(configOverrides?: AgentConnectorConfigOverrides): Promise<void>;
2587
- }
2588
- //#endregion
2589
- //#region adapters/core/src/agent/agent-lifecycle-emitter.d.ts
2590
- /**
2591
- * Dependencies for AgentLifecycleEmitter.
2592
- */
2593
- interface AgentLifecycleEmitterConfig {
2594
- /** Stable agent identifier for persistence updates. */
2595
- agentId: string;
2596
- /** Global bus for best-effort status updates. */
2597
- globalBus: IMakaioBus;
2598
- /** Emit callback for `agent.started`. */
2599
- emitStarted: (payload: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2600
- /** Emit callback for `agent.complete`. */
2601
- emitComplete: (payload: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>) => Promise<void>;
2602
- /** Emit callback for `agent.session.closed`. */
2603
- emitSessionClosed: (payload: {
2604
- reason?: string;
2605
- }) => Promise<void>;
2606
- /** Hook executed before terminal completion emission. */
2607
- onBeforeEmitCompletion: () => Promise<void>;
2608
- /** Clear tool-call tracker entries on terminal outcomes. */
2609
- clearToolCallTracker: () => void;
2610
- }
2611
- /**
2612
- * Stateful lifecycle emitter for AIAgent terminal/start/session events.
2613
- */
2614
- declare class AgentLifecycleEmitter {
2615
- /** Tracks whether session.closed has been emitted (emit only once). */
2616
- private sessionClosedEmitted;
2617
- /** Tracks whether agent.started has been emitted (lifecycle invariant). */
2618
- private agentStartedEmitted;
2619
- /** Tracks whether agent.complete has been emitted for the current turn. */
2620
- private agentCompleteEmitted;
2621
- /** Stashed error category consumed by the next emitCompletion call. */
2622
- private pendingErrorCategory?;
2623
- private readonly config;
2624
- constructor(config: AgentLifecycleEmitterConfig);
2851
+ init(): Promise<void>;
2625
2852
  /**
2626
- * Emit `agent.started` and reset per-turn lifecycle state.
2627
- * @param event - Start payload without auto-enriched AgentContext fields
2853
+ * Emit `agent.started` with the pending start mode (consume-on-read).
2854
+ *
2855
+ * Reads and clears {@link pendingStartMode}; subsequent calls within
2856
+ * the same dispatch fall back to `'rotation'`.
2857
+ * @param event - Optional additional fields to merge into the payload
2628
2858
  */
2629
- emitStart(event: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>): Promise<void>;
2859
+ protected emitStart(event?: Omit<AgentStarted, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId' | 'model' | 'cwd' | 'startMode'>): Promise<void>;
2630
2860
  /**
2631
- * Reset per-turn dedup state so the next completion can fire.
2861
+ * Set the start mode for the next `emitStart()` invocation.
2632
2862
  *
2633
- * Called when a new message handle is tracked guarantees the guard
2634
- * resets per-turn even for adapters that don't emit `agent.started`
2635
- * on every turn (e.g., codex emits `thread_started` once per thread).
2863
+ * Called by the turn executor or `initialize()` before dispatching to
2864
+ * the connector. The value is consumed (cleared) by the first
2865
+ * `emitStart()` call, enforcing the one-shot invariant.
2866
+ * @param mode - The start mode to embed in the next `agent.started` event
2636
2867
  */
2637
- resetTurnState(): void;
2868
+ setPendingStartMode(mode: StartMode): void;
2869
+ protected emitCompletion(result: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>): Promise<void>;
2638
2870
  /**
2639
- * Emit terminal completion event with deferred error-category propagation.
2640
- * @param result - Completion payload without AgentContext fields
2871
+ * Emit agent session closed event. Emits only once per session.
2872
+ * AIAdapter listens to cleanup agent and re-emit as AdapterSubjects.session.closed.
2873
+ * @param reason - Reason for session closure (e.g., 'aborted', 'closed')
2641
2874
  */
2642
- emitCompletion(result: Omit<z.infer<typeof AgentSchemas.complete>, keyof AgentContext>): Promise<void>;
2875
+ protected emitSessionClosed(reason?: string): void;
2643
2876
  /**
2644
- * Stash error metadata for the next completion emission.
2645
- * @param result - Error payload from connector/runtime error handler
2877
+ * Enrich a payload with agent context fields.
2878
+ * @param payload - The base payload to enrich
2879
+ * @returns Payload with AgentContext fields and optional messageId added
2646
2880
  */
2647
- emitError(result: Pick<z.infer<typeof AgentSchemas.complete>, 'error' | 'errorCategory'>): void;
2881
+ protected enrichPayload<T extends object>(payload: T): Promise<T & AgentIdentity & {
2882
+ messageId?: string;
2883
+ }>;
2648
2884
  /**
2649
- * Emit `agent.session.closed` once for this agent lifecycle.
2650
- * @param reason - Optional closure reason
2885
+ * Emit to a global subject with automatic payload enrichment.
2886
+ * @param subject - The subject to emit to
2887
+ * @param payload - The payload (without AgentContext fields - they're added automatically)
2651
2888
  */
2652
- emitSessionClosed(reason?: string): void;
2653
- }
2654
- //#endregion
2655
- //#region adapters/core/src/agent/agent-payload-emitter.d.ts
2656
- interface AgentPayloadEventMetadata {
2657
- clientId?: string;
2658
- providerConfigId?: string;
2659
- occurredAt?: number;
2660
- }
2661
- interface AgentPayloadEventFields extends AgentPayloadEventMetadata {
2662
- messageId?: string;
2663
- turnId?: string;
2664
- sessionId?: string;
2665
- }
2666
- interface EmitGlobalOptions {
2667
- includeEventMetadata?: boolean;
2668
- }
2669
- /**
2670
- * Dependencies for AgentPayloadEmitter.
2671
- */
2672
- interface AgentPayloadEmitterConfig {
2673
- /** Global bus for outbound emissions. */
2674
- globalBus: IMakaioBus;
2675
- /** Stable agent identity fields. */
2676
- getAgentContextBase: () => Pick<AgentContext, 'agentId' | 'adapterId' | 'adapterName'> & {
2677
- sessionId?: string;
2678
- };
2679
- /** Current messageId from lifecycle tracker, if any. */
2680
- getCurrentMessageId: () => string | undefined;
2681
- /** Current turnId from lifecycle tracker, if any. */
2682
- getCurrentTurnId: () => string | undefined;
2683
- /** Connector adapterSessionId, if currently available. */
2684
- getConnectorAdapterSessionId: () => string | undefined;
2685
- /** Last known adapterSessionId cached across connector swaps. */
2686
- getLastKnownAdapterSessionId: () => string | undefined;
2687
- /** Persist latest adapterSessionId after resolution. */
2688
- setLastKnownAdapterSessionId: (adapterSessionId: string | undefined) => void;
2689
- /** Live event metadata defaults resolved from current runtime state. */
2690
- getEventMetadataDefaults: () => AgentPayloadEventMetadata;
2691
- }
2692
- /**
2693
- * Handles agent context enrichment and global bus emissions.
2694
- */
2695
- declare class AgentPayloadEmitter {
2696
- private readonly config;
2889
+ protected emitGlobal<S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext> & {
2890
+ messageId?: string;
2891
+ }): Promise<void>;
2697
2892
  /**
2698
- * Create a payload emitter with context resolution dependencies.
2699
- * @param config - Config controlling agent-context enrichment and global emissions
2893
+ * Track usage and emit to global bus.
2894
+ * AIAdapter aggregates session totals from per-call usage events.
2895
+ * @param normalized - Normalized usage metrics from adapter-specific normalizer
2700
2896
  */
2701
- constructor(config: AgentPayloadEmitterConfig);
2897
+ protected trackUsage(normalized: NormalizedCallUsage): Promise<void>;
2702
2898
  /**
2703
- * Resolve the confirmed adapter session ID from synchronous sources.
2704
- *
2705
- * `getConnectorAdapterSessionId` delegates to `getConfirmedAdapterSessionId()`
2706
- * which returns `undefined` for unconfirmed fork sessions — the provider has
2707
- * not yet assigned the child session ID. For non-fork sessions (fresh, resume,
2708
- * non-Claude adapters) the locally-determined ID is authoritative and returned
2709
- * immediately.
2899
+ * Get context window size for a model.
2710
2900
  *
2711
- * The `lastKnownAdapterSessionId` bridges connector swaps: when the old
2712
- * connector is gone and the new one is not yet wired, the cached value carries
2713
- * the confirmed ID from the previous connector.
2901
+ * Looks up the context window size from availableModels based on model name.
2902
+ * @param modelName - Model name to look up (defaults to confirmedModel or initialModel)
2903
+ * @returns Context window size in tokens, or undefined if not found
2904
+ */
2905
+ protected getContextWindowSize(modelName?: string): number | undefined;
2906
+ /**
2907
+ * Emit context window status for compression trigger decisions.
2714
2908
  *
2715
- * No async fallback is used. `connector.getAdapterSessionId()` may resolve
2716
- * with a provisional placeholder for fork sessions. Enrichment must never
2717
- * stamp unconfirmed IDs omitting the field is safe since R8 schemas allow
2718
- * it optional.
2719
- * @returns Confirmed adapter session ID or `undefined`
2909
+ * Calculates fill percentage and warning level from raw metrics.
2910
+ * Called by subclasses after usage tracking with provider-specific metrics.
2911
+ * @param input - Raw metrics: currentTokens, maxTokens, optional cachedTokens
2720
2912
  */
2721
- private resolveConfirmedAdapterSessionId;
2913
+ protected emitContextWindowUpdate(input: ContextWindowInput): Promise<void>;
2722
2914
  /**
2723
- * Resolve event metadata fields, merging caller-provided values over live defaults.
2724
- * @param payload - Payload fields that may carry metadata overrides
2725
- * @param includeMetadata - Whether to include analytics metadata at all
2726
- * @returns Resolved metadata fields
2915
+ * Emit a tool.use event for an explicitly identified originating message.
2916
+ * @param messageId - Message that owns the tool call
2917
+ * @param toolName - Name of the tool being invoked
2918
+ * @param args - Tool arguments
2919
+ * @param nativeId - Provider-native tool call identifier
2920
+ * @returns Correlation identifier used for the call
2727
2921
  */
2728
- private resolveEventMetadata;
2922
+ protected emitToolUse(messageId: string, toolName: string, args?: Record<string, unknown>, nativeId?: string): Promise<string>;
2729
2923
  /**
2730
- * Enrich payload with agent context fields.
2731
- * @param payload - Base payload to enrich
2732
- * @param overrideMessageId - Explicit messageId override from caller payload
2733
- * @param options - Enrichment controls for optional analytics metadata defaults
2734
- * @returns Enriched payload with agent context
2924
+ * Emit a tool.output event for an explicitly identified originating message.
2925
+ * @param messageId - Message that owns the tool call
2926
+ * @param output - Tool output content
2927
+ * @param hints - Provider correlation hints
2928
+ * @returns Resolved tool-call metadata
2735
2929
  */
2736
- enrichPayload<T extends object>(payload: T, overrideMessageId?: string, options?: EmitGlobalOptions): Promise<T & AgentIdentity & AgentPayloadEventFields>;
2930
+ protected emitToolOutput(messageId: string, output: string, hints: ResolveHints): Promise<ToolOutputResult>;
2737
2931
  /**
2738
- * Emit enriched payload to global bus.
2739
- * @param subject - Subject definition to emit
2740
- * @param payload - Payload without AgentContext fields
2741
- * @param options - Enrichment controls for optional analytics metadata defaults
2932
+ * Emit step.started event with automatic block index management.
2933
+ * Call this when a content block begins processing.
2934
+ * @param stepType - The type of step (text, reasoning, tool_use)
2935
+ * @param blockData - Optional metadata for the block (e.g., toolName for tool_use)
2936
+ * @param content - Optional content for the step (e.g., tool_call block for tool_use)
2742
2937
  */
2743
- emitGlobal<S extends SubjectDefinition>(subject: S, payload: Omit<ExtractSubjectPayload<S>, keyof AgentContext> & {
2744
- messageId?: string;
2745
- turnId?: string;
2746
- }, options?: EmitGlobalOptions): Promise<void>;
2747
- }
2748
- //#endregion
2749
- //#region adapters/core/src/agent/agent-bus-handler-registrar.d.ts
2750
- /**
2751
- * Handler bundle required to register all `agent.*` request handlers.
2752
- */
2753
- interface AgentBusHandlerRegistrarConfig {
2754
- /** Global bus instance where handlers are registered. */
2755
- globalBus: IMakaioBus;
2756
- /** Target agent identity for filter scoping. */
2757
- agentId: string;
2758
- /** Handler for `agent.sendMessage`. */
2759
- onSendMessage: (ctx: RequestContext<SendMessageRequestPayload, SendMessageResponsePayload>) => Promise<void>;
2760
- /** Handler for `agent.interrupt`. */
2761
- onInterrupt: (ctx: RequestContext<AgentInterruptRequestPayload, AgentInterruptResponsePayload>) => Promise<void>;
2762
- /** Provider for `agent.getCapabilities` response payload. */
2763
- getCapabilities: () => GetCapabilitiesResponsePayload;
2764
- /** Handler for `agent.cwd.change`. */
2765
- onCwdChange: (ctx: RequestContext<AgentCwdChangeRequestPayload, AgentCwdChangeResponsePayload>) => Promise<void>;
2766
- /** Handler for `agent.model.change`. */
2767
- onModelChange: (ctx: RequestContext<AgentModelChangeRequestPayload, AgentModelChangeResponsePayload>) => Promise<void>;
2768
- /** Handler for `agent.mcp.servers.set`. */
2769
- onMcpServersSet: (ctx: RequestContext<AgentMcpServersSetRequestPayload, AgentMcpServersSetResponsePayload>) => Promise<void>;
2770
- /** Handler for `agent.credential.change`. */
2771
- onCredentialChange: (ctx: RequestContext<AgentCredentialChangeRequestPayload, AgentCredentialChangeResponsePayload>) => Promise<void>;
2772
- }
2773
- /**
2774
- * Register all stable `agent.*` bus handlers for a single agent instance.
2775
- * @param config - Registration configuration with handlers
2776
- * @returns Cleanup functions for all registrations
2777
- */
2778
- declare function registerAgentBusHandlers(config: AgentBusHandlerRegistrarConfig): Array<() => void>;
2779
- //#endregion
2780
- //#region adapters/core/src/agent/agent-runtime-mutation-manager-config.d.ts
2781
- /** Connector fields that can be overridden during runtime connector swaps. */
2782
- interface AgentRuntimeConnectorOverrides {
2783
- cwd: string;
2784
- model: string;
2785
- providerContext: ProviderContext;
2786
- adapterSessionId: string;
2787
- resumeAdapterSessionId: string;
2788
- mcpSessionContext: McpRuntimeSessionContext | McpSessionContext | LedgerSessionContext;
2789
- }
2790
- /** Dependencies for runtime mutation handling. */
2791
- interface AgentRuntimeMutationManagerConfig {
2792
- /** Stable agent identifier. */
2793
- agentId: string;
2794
- /** Optional Makaio session identifier. */
2795
- sessionId?: string;
2796
- /** Global bus for persistence and events. */
2797
- globalBus: IMakaioBus;
2798
- /** Read current connector. */
2799
- getConnector: () => AIAgentConnector;
2800
- /** Swap connector with runtime overrides. */
2801
- swapConnector: (configOverrides?: Partial<AgentRuntimeConnectorOverrides>) => Promise<void>;
2802
- /** Emit cwd.changed payload. */
2803
- emitCwdChanged: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.cwd.changed>, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2804
- /** Emit model.changed payload. */
2805
- emitModelChanged: (payload: Omit<ExtractSubjectPayload<typeof AgentSubjects.model.changed>, 'agentId' | 'adapterId' | 'adapterName' | 'adapterSessionId'>) => Promise<void>;
2806
- /** Read the agent's current provider context for no-op detection. */
2807
- getProviderContext: () => ProviderContext | undefined;
2808
- /** Persist provider context changes on agent config for sequential swaps. */
2809
- setProviderContext: (providerContext: ProviderContext) => void;
2810
- /** Persist reasoning effort changes on agent config for sequential swaps. */
2811
- setReasoningEffort: (reasoningEffort: AIReasoningLevel$1 | undefined) => void;
2812
- /** Persist MCP session context changes on agent config for sequential swaps. */
2813
- setMcpSessionContext: (mcpSessionContext: McpRuntimeSessionContext | McpSessionContext | LedgerSessionContext | undefined) => void;
2814
- /** Resolve supported reasoning levels for a model from the agent's available models. */
2815
- resolveSupportedReasoningLevels: (model: string) => ReasoningLevelMap$1 | undefined;
2816
- }
2817
- //#endregion
2818
- //#region adapters/core/src/agent/agent-runtime-mutation-manager.d.ts
2819
- /**
2820
- * Handles runtime mutation requests for AIAgent (cwd/model/credential changes).
2821
- */
2822
- declare class AgentRuntimeMutationManager {
2823
- private readonly agentId;
2824
- private readonly sessionId?;
2825
- private readonly globalBus;
2826
- private readonly getConnector;
2827
- private readonly swapConnector;
2828
- private readonly emitCwdChanged;
2829
- private readonly emitModelChanged;
2830
- private readonly getProviderContext;
2831
- private readonly setProviderContext;
2832
- private readonly setReasoningEffort;
2833
- private readonly setMcpSessionContext;
2834
- private readonly resolveSupportedReasoningLevels;
2835
- private readonly mcpServersMutationManager;
2836
- private readonly credentialChangeSequencer;
2837
- private stagedModelChange?;
2838
- constructor(config: AgentRuntimeMutationManagerConfig);
2938
+ protected emitStepStarted(stepType: StepType, blockData?: BlockData, content?: SessionMessageBlock): Promise<void>;
2939
+ /**
2940
+ * Emit step.finished event with content and increment block index.
2941
+ * Call this when a content block completes processing.
2942
+ * @param stepType - The type of step that finished
2943
+ * @param content - The complete content of the step (text, reasoning, tool_call, or tool_output)
2944
+ */
2945
+ protected emitStepFinished(stepType: StepType, content: SessionMessageBlock): Promise<void>;
2839
2946
  /**
2840
- * Handle `agent.cwd.change` request.
2841
- * @param payload - CWD change request payload
2842
- * @returns CWD mutation response payload
2947
+ * Get the current block index (for adapters that need to track it externally).
2948
+ * @returns Current block index within the turn
2843
2949
  */
2844
- handleCwdChange(payload: AgentCwdChangeRequestPayload): Promise<AgentCwdChangeResponsePayload>;
2950
+ protected getBlockIndex(): number;
2845
2951
  /**
2846
- * Apply staged runtime mutations before dispatching the next user turn.
2847
- *
2848
- * Staged changes are accepted while a turn is active, but they must not touch
2849
- * the live connector until the next turn boundary. The turn executor calls
2850
- * this before handing a new message to the connector, when the connector is
2851
- * expected to be idle.
2952
+ * Increment block index (for adapters using SDK-provided indices).
2953
+ * Call after emitting step.finished if managing index externally.
2852
2954
  */
2853
- applyStagedMutations(): Promise<void>;
2955
+ protected incrementBlockIndex(): void;
2854
2956
  /**
2855
- * Handle `agent.mcp.servers.set` request.
2856
- * @param payload - MCP server replacement request payload
2857
- * @returns MCP mutation response payload
2957
+ * Handle agent.sendMessage request.
2958
+ * The filter has already been applied at subscription time - this method
2959
+ * only receives messages intended for this agent.
2960
+ * Runs PreUserMessage hooks before delegating to the connector's sendMessage method.
2961
+ * Uses sessionContext signals to decide between native resume and fresh with history.
2962
+ * HookAbortError propagates to caller (session layer handles lifecycle).
2963
+ * Subclasses can override for custom handling.
2964
+ * @param ctx - Request context with payload and response methods
2858
2965
  */
2859
- handleMcpServersSet(payload: AgentMcpServersSetRequestPayload): Promise<AgentMcpServersSetResponsePayload>;
2966
+ protected sendMessage(ctx: RequestContext<SendMessageRequestPayload, SendMessageResponsePayload>): Promise<void>;
2967
+ /**
2968
+ * Handle agent.interrupt request.
2969
+ * Delegates to the connector's native interrupt behavior.
2970
+ * @param ctx - Request context with interrupt payload
2971
+ */
2972
+ private handleInterrupt;
2973
+ /**
2974
+ * Register a cleanup function for connector wiring.
2975
+ * These cleanups are cleared on connector swap but preserved across bus handler changes.
2976
+ * @param cleanup - Cleanup function to register
2977
+ */
2978
+ protected addConnectorWiringCleanup(cleanup: () => void): void;
2979
+ /**
2980
+ * Registers a cleanup function for a global bus subscription.
2981
+ * These survive connector swaps and are cleaned up in close().
2982
+ * @param cleanup - Function to unsubscribe from the bus
2983
+ */
2984
+ protected addBusHandlerCleanup(cleanup: () => void): void;
2860
2985
  /**
2861
- * Handle `agent.model.change` request.
2986
+ * Replace the current connector with a fresh one.
2862
2987
  *
2863
- * Implements a four-branch decision tree based on the presence of `newModel`
2864
- * and `reasoningEffort` in the request payload:
2988
+ * Serializes the complete create-before-close pattern with rollback for safety:
2989
+ * 1. Create new connector first (old connector still alive)
2990
+ * 2. Wire and initialize the replacement (accumulate cleanups separately)
2991
+ * 3. Run the final guard and commit any selected managed account
2992
+ * 4. Synchronously publish the ready replacement, then close the old runtime
2993
+ * 5. On any pre-publication failure: close the replacement, restore old wiring, and roll back account selection
2865
2994
  *
2866
- * - Both present → change model, then apply reasoningEffort (with fallback)
2867
- * - Model only → change model, run fallback chain for reasoning
2868
- * - Effort only → change reasoning in-place, no model swap logic
2869
- * - Neither → no-op (return current state)
2870
- * @param payload - Model change request payload
2871
- * @returns Model mutation response payload
2995
+ * This ensures the agent always has a working connector, even if factory or wiring fails.
2996
+ *
2997
+ * Preserves runtime overrides across sequential swaps by using current connector values
2998
+ * as baseline for non-overridden fields.
2999
+ * @param configOverrides - Optional config overrides (e.g., new cwd, model)
3000
+ * @param beforeCommit - Optional guard executed before replacing the active connector
3001
+ * @throws Error if connector is currently processing a turn
2872
3002
  */
2873
- handleModelChange(payload: AgentModelChangeRequestPayload): Promise<AgentModelChangeResponsePayload>;
3003
+ swapConnector(configOverrides?: AgentConnectorConfigOverrides, beforeCommit?: ConnectorSwapCommitGuard): Promise<void>;
2874
3004
  /**
2875
- * Apply an in-place reasoning-effort change when no model swap is requested.
2876
- * @param connector - The active connector
2877
- * @param currentModel - Current model identifier
2878
- * @param previousReasoningEffort - Reasoning effort before this change
2879
- * @param reasoningEffort - Requested effort level
2880
- * @returns Model mutation response payload
3005
+ * Build config factory input from agent config with optional overrides.
3006
+ *
3007
+ * Delegates to {@link buildConfigFactoryInput} with live connector-derived
3008
+ * values (reasoning effort) and the agent's error sink.
3009
+ * @param overrides - Optional field overrides (e.g., cwd, model, adapterSessionId)
3010
+ * @returns ConfigFactoryInput ready for config factory
2881
3011
  */
2882
- private handleReasoningOnlyChange;
3012
+ private buildConfigInput;
2883
3013
  /**
2884
- * Execute the model-swap path, settling the connector then resolving reasoning.
3014
+ * Create the onMessageSent callback for connector factories.
2885
3015
  *
2886
- * **Fallback chain** for reasoning when the request does not specify an effort level:
2887
- * 1. Previous connector's `currentReasoningEffort` if supported by the new model
2888
- * 2. `'medium'` — if supported by the new model
2889
- * 3. First key declared in the new model's `supportedReasoningLevels`
2890
- * 4. `undefined` — model does not support reasoning
2891
- * @param options - Swap options bundle
2892
- * @returns Model mutation response payload
3016
+ * Returns a callback that emits user_message.sent events to the global bus.
3017
+ * @returns Callback function for connector config
3018
+ */
3019
+ private createOnMessageSent;
3020
+ /**
3021
+ * Wire adapter-specific connector events.
3022
+ * Called automatically during init() and connector swap.
3023
+ * Subclasses implement this to set up their event mappings.
3024
+ * @param connector - Connector instance to wire
3025
+ */
3026
+ protected abstract wireEvents(connector: TConnector): void | Promise<void>;
3027
+ /**
3028
+ * Subscribe to a connector subject and register its cleanup as connector wiring.
3029
+ *
3030
+ * Use this in adapter `wireEvents()` implementations so connector swaps can
3031
+ * remove old listeners before rewiring the new connector.
3032
+ * @param connector - Connector instance to subscribe on
3033
+ * @param subject - Subject definition to subscribe to
3034
+ * @param handler - Subject handler
3035
+ * @param options - Optional bus subscription options
2893
3036
  */
2894
- private handleModelSwap;
3037
+ protected subscribeConnector<Subject extends ScopedSubjectDefinition<TConnector extends AIAgentConnector<infer TBus> ? TBus['namespace'] : never>>(connector: TConnector, subject: Subject, handler: HandlerForSubjectDefinition<Subject>, options?: OnOptions): void;
2895
3038
  /**
2896
- * Resolve the reasoning effort to apply after a model change.
3039
+ * Clean up resources and emit session closed event.
2897
3040
  *
2898
- * Fallback chain:
2899
- * 1. Requested `effort` if supported by the new model
2900
- * 2. Previous connector's `currentReasoningEffort` if supported by the new model
2901
- * 3. `'medium'` — if supported by the new model
2902
- * 4. First key declared in `supportedReasoningLevels`
2903
- * 5. `undefined` — model does not support reasoning
2904
- * @param requestedEffort - Effort level from the change request (may be absent)
2905
- * @param previousEffort - Current connector's reasoning effort before the change
2906
- * @param supportedLevels - Reasoning levels declared by the new model
2907
- * @returns The resolved reasoning level, or `undefined` if unsupported
2908
- */
2909
- private resolveReasoningEffort;
2910
- /**
2911
- * Confirm a connector swap when the model itself changes.
3041
+ * Emits session.closed event (once per session) unless explicitly suppressed,
3042
+ * then unsubscribes from all bus handlers and aborts the connector if available.
3043
+ * @param options - Cleanup options; ephemeral agents suppress session-close lifecycle events because they never join a session.
3044
+ */
3045
+ close(options?: {
3046
+ emitSessionClosed?: boolean;
3047
+ }): Promise<void>;
3048
+ /**
3049
+ * Ensure the connector is initialized, throwing if not.
3050
+ * @returns The initialized connector instance
3051
+ */
3052
+ private ensureConnector;
3053
+ /**
3054
+ * Determine whether to use native session resume (SDK manages history) or
3055
+ * fresh-with-history (new session, injected messageHistory).
3056
+ * @param sessionContext - Context signals from SessionOrchestrator
3057
+ * @returns true if native resume should be used
3058
+ */
3059
+ protected shouldUseNativeResume(sessionContext?: SessionContext): boolean;
3060
+ /**
3061
+ * Whether this adapter supports native session resume. Override in concrete agents.
3062
+ * @returns true if native resume is supported
3063
+ */
3064
+ protected supportsNativeResume(): boolean;
3065
+ /**
3066
+ * Whether this adapter supports provider-native session fork.
3067
+ * Override in concrete agents that can branch from an existing provider session.
3068
+ * @returns true if native fork is supported
3069
+ */
3070
+ protected supportsNativeFork(): boolean;
3071
+ /**
3072
+ * Start the agent with an initial message.
2912
3073
  *
2913
- * Provider-only swaps skip the dialog because there is no model transition to
2914
- * explain to the user. Model changes retain the existing warning/edit-history
2915
- * workflow.
2916
- * @param currentModel - Active model before the requested swap
2917
- * @param newModel - Requested target model
2918
- * @param skipWarning - Whether trusted callers opted out of the warning UI
2919
- * @returns Proceed/result tuple for the caller
3074
+ * Ensures the agent is initialized (idempotent), runs PreUserMessage hooks,
3075
+ * and uses sessionContext signals to decide between native resume and fresh
3076
+ * with history. HookAbortError propagates to caller.
3077
+ * @param message - User message (normalized or unnormalized)
3078
+ * @param options - Optional start options (e.g., delivery mode, sessionContext)
3079
+ * @returns Session ID, agent ID, and message handle for tracking
3080
+ */
3081
+ start(message: NormalizedMessageInput | MessageInput, options?: StartAgentOptions): Promise<AgentStartResult>;
3082
+ /**
3083
+ * Initialize idle (no message). Returns confirmed adapter session ID or `undefined`
3084
+ * when the provider has not yet confirmed (idle fork sessions).
3085
+ * @param options - Optional initialization options (system prompt, sessionContext)
3086
+ * @returns Confirmed adapter session ID, or `undefined` for unconfirmed fork sessions.
2920
3087
  */
2921
- private confirmConnectorSwap;
3088
+ initialize(options?: StartAgentOptions): Promise<string | undefined>;
3089
+ protected onBeforeEmitCompletion(): Promise<void>;
3090
+ protected onMessageHandle(messageHandle: MessageHandle, turnId?: string): Promise<void>;
2922
3091
  /**
2923
- * Compare provider contexts using the full public-bus shape.
3092
+ * Abort the agent immediately (panic mode).
3093
+ * Triggers AbortController which may cause provider errors.
3094
+ * Use close() for graceful shutdown instead.
2924
3095
  *
2925
- * Provider switches are not limited to config identity. Endpoint overrides,
2926
- * credential refs, and env-var mappings all influence connector behaviour, so
2927
- * callers that mutate any of those fields must force a connector rebuild.
2928
- * @param current - Persisted agent provider context
2929
- * @param next - Incoming provider context from the mutation request
2930
- * @returns True when the effective provider configuration changed
3096
+ * Emits session.closed event (once per session) then delegates
3097
+ * to the underlying connector's abort method.
3098
+ * @throws Error if connector is not initialized
2931
3099
  */
2932
- private hasProviderContextChanged;
3100
+ abort(): void;
2933
3101
  /**
2934
- * Compare two string-keyed records, treating absent and empty consistently.
2935
- * @param left - First record
2936
- * @param right - Second record
2937
- * @returns True when both records contain the same keys and values
3102
+ * Get session ID, waiting for provider to generate it if not yet available.
3103
+ *
3104
+ * Delegates to the underlying connector's getSessionId method.
3105
+ * @returns Session ID from provider
3106
+ * @throws Error if connector is not initialized
2938
3107
  */
2939
- private haveEqualStringRecords;
3108
+ getAdapterSessionId(): Promise<string>;
2940
3109
  /**
2941
- * Handle a credential rotation request.
3110
+ * Complete the agent session by waiting for all messages to finish.
2942
3111
  *
2943
- * When a turn is active, returns `{ success: false, reason: 'turn_active' }`.
2944
- * Otherwise:
2945
- * 1. Rebuilds provider context from storage (validates providerConfigId)
2946
- * 2. Fires `credential.activate` so extensions prepare native stores
2947
- * 3. Swaps the connector with updated providerContext (forces re-resolution)
2948
- * @param payload - Credential change request payload
2949
- * @returns Success/failure result
3112
+ * Waits for the connector to finish, then returns the agent-level terminal
3113
+ * result so structured-output transforms are reflected in direct callers.
3114
+ * @returns Last message result or null if no messages processed
3115
+ * @throws Error if connector is not initialized
2950
3116
  */
2951
- handleCredentialChanged(payload: AgentCredentialChangeRequestPayload): Promise<AgentCredentialChangeResponsePayload>;
3117
+ complete(): Promise<MessageResult | null>;
2952
3118
  /**
2953
- * Persist runtime field updates to agent storage.
2954
- * @param changes - CWD/model/provider mutations to persist
3119
+ * Creates a type-safe event mapping from connector events to scoped subjects or handlers.
3120
+ * @param sourceSubject - The connector subject to subscribe to
3121
+ * @param discriminator - The discriminator key within the message (e.g., 'type')
3122
+ * @param handlers - Map of discriminator values to target subjects or handler functions
3123
+ * @param nestedMessageProp - Property containing the discriminated union (e.g., 'msg'), or undefined for top-level
3124
+ * @returns Unsubscribe function for the connector event mapping subscription
2955
3125
  */
2956
- private persistRuntimeMutation;
3126
+ 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;
2957
3127
  }
2958
3128
  //#endregion
2959
- //#region adapters/core/src/agent/mcp-call-extractor.d.ts
2960
- /**
2961
- * Utilities for identifying and extracting target information from `mcp_call`
2962
- * tool invocations.
2963
- *
2964
- * The `mcp_call` meta-tool carries its real target as the `tool` field in the
2965
- * parsed JSON arguments. These helpers centralise that extraction logic so
2966
- * every consumer (ledger, event bridge, analytics) uses a single, tested path.
2967
- * @packageDocumentation
2968
- */
2969
- /**
2970
- * Extract the target MCP tool name from parsed `mcp_call` arguments.
2971
- *
2972
- * Conforms to the `mcp_call` input schema which defines `{ tool: z.string() }`.
2973
- * Returns `undefined` for any non-conformant argument shape so callers can
2974
- * skip processing without throwing.
2975
- * @param args - Parsed JSON arguments object from the tool call
2976
- * @returns The namespaced target tool name, or `undefined` if not conformant
2977
- */
2978
- declare function extractMcpCallTarget(args: Record<string, unknown>): string | undefined;
2979
- /**
2980
- * Check whether a tool call name refers to the `mcp_call` meta-tool.
2981
- *
2982
- * Uses the canonical {@link MCP_CALL_TOOL_NAME} constant so the comparison
2983
- * stays in sync with the toolset definition automatically.
2984
- *
2985
- * Callers are responsible for stripping provider-specific prefixes before
2986
- * calling this function (e.g., Gemini's `default_api.` prefix must be
2987
- * removed at the call site — see `execute-tool-calls.ts` normalizedToolName).
2988
- * @param toolName - Normalized tool name from the tool call
2989
- * @returns `true` if this is an `mcp_call` invocation
2990
- */
2991
- declare function isMcpCallTool(toolName: string): boolean;
2992
- //#endregion
2993
- //#region adapters/core/src/agent/request-correlation.d.ts
2994
- /** Exact Factory Gateway headers accepted by its content-free usage boundary. */
2995
- declare const FactoryUsageCorrelationHeaders: {
2996
- readonly sessionId: "x-factory-session-id";
2997
- readonly turnId: "x-factory-turn-id";
2998
- readonly messageId: "x-factory-message-id";
2999
- readonly llmCallId: "x-factory-llm-call-id";
3000
- readonly executionId: "x-factory-execution-id";
3001
- readonly frameId: "x-factory-frame-id";
3002
- };
3003
- type ProviderRequestCorrelation = RequestCorrelationContext & {
3004
- llmCallId: string;
3005
- };
3006
- /**
3007
- * Bind caller correlation to identifiers owned by the active runtime request.
3008
- * Runtime values always win, preventing stale or spoofed session/message IDs.
3009
- * @param context - Optional orchestrator-supplied workflow correlation
3010
- * @param runtime - IDs known by the connector for this concrete API request
3011
- * @returns Fully bound correlation including one LLM-call ID
3012
- */
3013
- declare function bindProviderRequestCorrelation(context: RequestCorrelationContext | undefined, runtime: {
3014
- sessionId?: string;
3015
- messageId: string;
3016
- llmCallId: string;
3017
- }): ProviderRequestCorrelation;
3129
+ //#region adapters/core/src/factory/adapter-context.d.ts
3018
3130
  /**
3019
- * Project a validated correlation context to the Factory Gateway allowlist.
3131
+ * Context provided to adapter implementations.
3020
3132
  *
3021
- * No arbitrary metadata or headers can cross this boundary. Callers must also
3022
- * explicitly opt into the `factory-v1` transport mode before using the result.
3023
- * @param correlation - Content-free runtime and workflow identifiers
3024
- * @returns Header record accepted by the Factory Gateway usage boundary
3133
+ * Contains shared infrastructure and configuration that all adapters need:
3134
+ * - Adapter name and capabilities from config
3135
+ * - Local event bus for emitting events
3025
3136
  */
3026
- declare function buildFactoryUsageCorrelationHeaders(correlation: ProviderRequestCorrelation): Record<string, string>;
3137
+ interface AIAdapterContext<Scope extends ScopedBus<string>> {
3138
+ /** Unique adapter instance identifier. */
3139
+ adapterId: string;
3140
+ /** Unique adapter name (kebab-case). */
3141
+ name: string;
3142
+ /** Adapter capabilities (unparsed). Use parseAIAdapterCapabilities() to parse. */
3143
+ capabilities: AIAdapterCapability[];
3144
+ /** Scoped bus for adapter-level events. */
3145
+ adapterBus: Scope;
3146
+ /** Global event bus. */
3147
+ globalBus: IMakaioBus;
3148
+ }
3027
3149
  //#endregion
3028
3150
  //#region adapters/core/src/adapter/ai-adapter.d.ts
3029
3151
  /**
@@ -3076,6 +3198,8 @@ declare abstract class AIAdapter<TBus extends ScopedBus<string> = ScopedBus<stri
3076
3198
  protected platformDefaults?: PlatformDefaults;
3077
3199
  /** Provider definitions for model lookup. Injected by runtime. */
3078
3200
  protected readonly definitionProviders: readonly AdapterProviderDefinition[];
3201
+ /** Trusted host-local normalized auth preparation strategy. */
3202
+ protected readonly prepareAuthRuntime?: AdapterAuthRuntimePreparer<TBus>;
3079
3203
  protected agentFactory: (agentConfig: AIAgentConfig<TBus, TConnector>) => TAgent;
3080
3204
  /** Config factory - transforms partial input into full adapter-specific config (includes adapterId) */
3081
3205
  protected configFactory: (input: ConfigFactoryInput<TBus>) => Promise<BaseAgentConnectorConfig<TBus> & {
@@ -3087,7 +3211,6 @@ declare abstract class AIAdapter<TBus extends ScopedBus<string> = ScopedBus<stri
3087
3211
  }) => TConnector | Promise<TConnector>;
3088
3212
  /**
3089
3213
  * Create a new AIAdapter instance.
3090
- * Constructor is synchronous - stores config only. Call init() to complete setup.
3091
3214
  * @param config - Adapter configuration
3092
3215
  */
3093
3216
  protected constructor(config: AIAdapterConstructorConfig<TBus, TConnector, TAgent>);
@@ -3367,9 +3490,11 @@ interface CreateConformanceTestConfigOptions {
3367
3490
  * Options for creating test agent instances.
3368
3491
  * Omits 'bus' (provided by test config) and makes 'adapterName'/'agentId' optional (factories provide defaults).
3369
3492
  */
3370
- type CreateTestAgentOptions = Omit<BaseAgentConnectorConfig, 'bus' | 'adapterName' | 'model'> & {
3493
+ type CreateTestAgentOptions = Omit<BaseAgentConnectorConfig, 'bus' | 'agentId' | 'adapterName' | 'model' | 'cwd' | 'providerContext'> & {
3494
+ agentId?: string;
3371
3495
  adapterName?: string;
3372
- model?: string; /** Override the default test provider context when testing endpoint/credential behavior. */
3496
+ model?: string;
3497
+ cwd?: string; /** Override the default test provider context when testing endpoint/credential behavior. */
3373
3498
  providerContext?: ProviderContext;
3374
3499
  };
3375
3500
  interface ConformanceTestConfig<TBus extends ScopedBus<string> = ScopedBus<string>, TConnector extends AIAgentConnector<TBus> = AIAgentConnector<TBus>, TAgent extends AIAgent<TBus, TConnector> = AIAgent<TBus, TConnector>> {
@@ -3648,7 +3773,7 @@ interface ConformanceTestConfig<TBus extends ScopedBus<string> = ScopedBus<strin
3648
3773
  * Unresolved provider context for the test provider.
3649
3774
  *
3650
3775
  * Contains credential refs (e.g. `env:ANTHROPIC_API_KEY`) built from the test
3651
- * provider definition's `credentialEnvVars`. Used by orchestration tests that
3776
+ * provider definition's explicit auth method source hints. Used by orchestration tests that
3652
3777
  * call `startAgent` directly (bypassing the conformance `createConnector` path
3653
3778
  * where `resolveTestConfig` handles credential ref building).
3654
3779
  *
@@ -3666,6 +3791,40 @@ interface ConformanceTestConfig<TBus extends ScopedBus<string> = ScopedBus<strin
3666
3791
  cleanup?: () => Promise<void> | void;
3667
3792
  }
3668
3793
  //#endregion
3794
+ //#region adapters/core/src/testing/conformance-connector-runtime-registry.d.ts
3795
+ /**
3796
+ * Own every connector runtime created by one conformance test configuration.
3797
+ *
3798
+ * The registry routes connector creation through the same normalized auth,
3799
+ * binary, and client-config lease path as production. It replaces the public
3800
+ * connector `close()` method with an idempotent managed close, so a test that
3801
+ * closes its connector releases the lease immediately while `closeAll()` can
3802
+ * still clean up abandoned connectors at suite teardown.
3803
+ */
3804
+ declare class ConformanceConnectorRuntimeRegistry<TBus extends ScopedBus<string>, TConnector extends AIAgentConnector<TBus>> {
3805
+ private readonly runtimes;
3806
+ /**
3807
+ * Create a connector through the production runtime preparation seam.
3808
+ * @param options - Bound config and adapter connector factory
3809
+ * @returns Managed connector with lease-aware idempotent `close()`
3810
+ */
3811
+ create<TConfig extends BaseAgentConnectorConfig<TBus>>(options: CreateConnectorRuntimeOptions<TBus, TConnector, TConfig>): Promise<TConnector>;
3812
+ /**
3813
+ * Close every connector still owned by this configuration.
3814
+ * @throws The single close failure, or an AggregateError containing all failures
3815
+ */
3816
+ closeAll(): Promise<void>;
3817
+ }
3818
+ //#endregion
3819
+ //#region adapters/core/src/testing/provider-context.d.ts
3820
+ /**
3821
+ * Build a resolved provider context that deliberately requires no authentication.
3822
+ * @param providerConfigId - Provider config identity for the test
3823
+ * @param definitionId - Provider definition identity for the test
3824
+ * @returns Fresh normalized no-auth provider context
3825
+ */
3826
+ declare function createNoAuthTestProviderContext(providerConfigId?: string, definitionId?: string): ProviderContext;
3827
+ //#endregion
3669
3828
  //#region adapters/core/src/session/utilities.d.ts
3670
3829
  /**
3671
3830
  * Manages session lifecycle and abort handling.
@@ -4373,4 +4532,4 @@ declare const ToolCompletedEventSchema: z.ZodObject<{
4373
4532
  type ToolStartedEvent = z.infer<typeof ToolStartedEventSchema>;
4374
4533
  type ToolCompletedEvent = z.infer<typeof ToolCompletedEventSchema>;
4375
4534
  //#endregion
4376
- 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, FactoryUsageCorrelationHeaders, type FromGlobalToolApprovalFn, type GeneratedCapabilityProperties, type HarnessRequester, type IAdapterConfigFactory, type ISessionToolLedger, type ImportCursorPosition, ImportCursorPositionSchema, ImportCursorStorageNamespace, ImportCursorStorageSubjects, type ImportMetadata, type ImportSegment, type ImportSegmentLineage, type ImportSegmentTurn, 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 ProviderRequestCorrelation, 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, bindProviderRequestCorrelation, buildFactoryUsageCorrelationHeaders, cleanEnvForAdapter, createAdapterNamespace, createTestProviderContext, createToolApprovalHandler, defineDiscriminatedHandlers, defineDiscriminatedHandlersSync, extractMcpCallTarget, formatContextBlockAsText, formatContextBlocksAsText, formatMessageHistoryAsTranscript, isMcpCallTool, isTextLikeMimeType, markCompletedWithFinalResult, mergeScopedToolApproval, normalizeEnvValue, normalizeMessageInput, normalizeMimeType, parseAIAdapterCapabilities, processDiscriminatedItems, processDiscriminatedItemsSync, processQueueMessages, registerAgentBusHandlers, registerMemoryImportCursorStorage, resolveConformanceTestPreset, resolveDisabledNativeTools, resolvePresetCredentials, resolveRequiredSessionId, resolveTestConfig, safeJsonStringify, serializeBlockToText, serializeTurnContext, toImportSegment };
4535
+ 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, ConformanceConnectorRuntimeRegistry, 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, FactoryUsageCorrelationHeaders, type FromGlobalToolApprovalFn, type GeneratedCapabilityProperties, type HarnessRequester, type IAdapterConfigFactory, type ISessionToolLedger, type ImportCursorPosition, ImportCursorPositionSchema, ImportCursorStorageNamespace, ImportCursorStorageSubjects, type ImportMetadata, type ImportSegment, type ImportSegmentLineage, type ImportSegmentTurn, 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 ProviderRequestCorrelation, type QueueableTurn, type ReasoningLevelMap, type ResolveConformanceTestPresetOptions, type ResolveHints, type ResolvedConformanceTestPreset, SESSION_CLOSED_QUEUE_ERROR, 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, bindProviderRequestCorrelation, buildFactoryUsageCorrelationHeaders, cleanEnvForAdapter, createAdapterNamespace, createNoAuthTestProviderContext, createTestProviderContext, createToolApprovalHandler, defineDiscriminatedHandlers, defineDiscriminatedHandlersSync, extractMcpCallTarget, formatContextBlockAsText, formatContextBlocksAsText, formatMessageHistoryAsTranscript, isMcpCallTool, isTextLikeMimeType, markCompletedWithFinalResult, mergeScopedToolApproval, normalizeEnvValue, normalizeMessageInput, normalizeMimeType, parseAIAdapterCapabilities, processDiscriminatedItems, processDiscriminatedItemsSync, processQueueMessages, registerAgentBusHandlers, registerMemoryImportCursorStorage, rejectQueuedHandles, resolveConformanceTestPreset, resolveDisabledNativeTools, resolveRequiredSessionId, resolveTestConfig, safeJsonStringify, serializeBlockToText, serializeTurnContext, toImportSegment };