@makaio/framework 1.0.0-dev-1779046984397 → 1.0.0-dev-1779051654000

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 (216) hide show
  1. package/README.md +32 -315
  2. package/dist/{account-identity-Ce1Bwrqi.mjs → account-identity-Bg_vKkcs.mjs} +1 -1
  3. package/dist/{adapter-CbyjCE2d.mjs → adapter-CpF2aK_-.mjs} +1 -1
  4. package/dist/adapters/config/index.d.mts +1 -1
  5. package/dist/adapters/config/index.mjs +1 -1
  6. package/dist/adapters/index.d.mts +2 -2
  7. package/dist/adapters/index.mjs +1 -1
  8. package/dist/adapters/node.d.mts +1 -1
  9. package/dist/adapters/node.mjs +1 -1
  10. package/dist/client-DMWXCWhM.mjs +1 -0
  11. package/dist/clients/index.d.mts +122 -347
  12. package/dist/clients/index.mjs +2 -1
  13. package/dist/{clients-namespace-B0xAPZ6J.d.mts → clients-namespace-UHj5wt-l.d.mts} +7 -7
  14. package/dist/contracts/adapter/index.d.mts +2 -2
  15. package/dist/contracts/adapter/index.mjs +1 -1
  16. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  17. package/dist/contracts/client/index.d.mts +3 -3
  18. package/dist/contracts/client/index.mjs +1 -1
  19. package/dist/contracts/common/index.d.mts +1 -1
  20. package/dist/contracts/config/index.d.mts +6 -6
  21. package/dist/contracts/config/index.mjs +1 -1
  22. package/dist/contracts/extension/index.d.mts +2 -2
  23. package/dist/contracts/extension/index.mjs +1 -1
  24. package/dist/contracts/harness/index.d.mts +1 -1
  25. package/dist/contracts/harness/index.mjs +1 -1
  26. package/dist/contracts/host/index.mjs +1 -1
  27. package/dist/contracts/index.d.mts +64 -63
  28. package/dist/contracts/index.mjs +1 -1
  29. package/dist/contracts/model-registry/index.mjs +1 -1
  30. package/dist/contracts/native-session-supervisor/index.mjs +1 -1
  31. package/dist/contracts/platform/index.mjs +1 -1
  32. package/dist/contracts/session/index.d.mts +2 -2
  33. package/dist/contracts/session/index.mjs +1 -1
  34. package/dist/contracts/shared/index.d.mts +1 -1
  35. package/dist/contracts/shared/index.mjs +1 -1
  36. package/dist/contracts/skill/index.mjs +1 -1
  37. package/dist/contracts/timeout/index.d.mts +2 -0
  38. package/dist/contracts/timeout/index.mjs +1 -0
  39. package/dist/contracts/toast/index.mjs +1 -1
  40. package/dist/contracts/variant/index.mjs +1 -1
  41. package/dist/{definition-DxvZ9e22.d.mts → definition-DB7bbFSa.d.mts} +84 -91
  42. package/dist/{extension-COqwS-2Q.mjs → extension-53GerdGg.mjs} +1 -1
  43. package/dist/extension-fJmv8Yri.mjs +1 -0
  44. package/dist/{handlers-iGKUJ380.mjs → handlers-DR_4_rAT.mjs} +1 -1
  45. package/dist/{harness-CEq1Zkf9.mjs → harness-B6lGP9rm.mjs} +1 -1
  46. package/dist/{index-DBQtpFLE.d.mts → index-BnSQE7z7.d.mts} +3 -3
  47. package/dist/{index-CVA0m1g9.d.mts → index-CnmPtjnA.d.mts} +4 -4
  48. package/dist/{index-hapw9_En.d.mts → index-Cq8B7cwK.d.mts} +67 -67
  49. package/dist/{index-BJOfdtbw.d.mts → index-DGTFJB_8.d.mts} +3 -3
  50. package/dist/{index-DubqLGH8.d.mts → index-DaEp4UWW.d.mts} +56 -62
  51. package/dist/{index-C9F3Fc1A.d.mts → index-DwCA1HWa.d.mts} +133 -79
  52. package/dist/index-E8d_RwaF.d.mts +28 -0
  53. package/dist/{index-BB419vv-.d.mts → index-e5C62_M3.d.mts} +31 -11
  54. package/dist/{index-Bv15sNLn.d.mts → index-sBob9D25.d.mts} +1 -1
  55. package/dist/{index-BAKM2GMH2.d.mts → index-tKvu34DJ2.d.mts} +6 -6
  56. package/dist/{index-BdPwu6c0.d.mts → index-yvN8UcEH.d.mts} +110 -110
  57. package/dist/kernel/cli/index.mjs +1 -1
  58. package/dist/kernel/cli/schemas.mjs +1 -1
  59. package/dist/kernel/extension/index.d.mts +1 -1
  60. package/dist/kernel/extension/index.mjs +1 -1
  61. package/dist/kernel/index.d.mts +2 -2
  62. package/dist/kernel/index.mjs +1 -1
  63. package/dist/kernel/namespace/index.mjs +1 -1
  64. package/dist/kernel/observability/index.d.mts +1 -1
  65. package/dist/kernel/observability/index.mjs +1 -1
  66. package/dist/kernel/providers/index.mjs +1 -1
  67. package/dist/kernel/window/index.mjs +1 -1
  68. package/dist/{namespace-CkLUtc0g.d.mts → namespace-B1E57soL.d.mts} +22 -22
  69. package/dist/{namespace-bq4Prtzn.d.mts → namespace-B5ZCshBw.d.mts} +75 -75
  70. package/dist/{namespace-CCDEOwmW.d.mts → namespace-BCRNwPnw.d.mts} +6 -6
  71. package/dist/{namespace-ptv-pw_g.d.mts → namespace-BKrV_2gZ.d.mts} +9 -9
  72. package/dist/{namespace-O5SNY-LV.d.mts → namespace-BpIE-jQW.d.mts} +14 -14
  73. package/dist/{namespace-8cNguvIp.mjs → namespace-DGMO2E8f.mjs} +1 -1
  74. package/dist/{namespace-FWx6HxaW.d.mts → namespace-DXnMk3U8.d.mts} +14 -14
  75. package/dist/{namespace-xkvVw3hf2.d.mts → namespace-DwCyOaZn2.d.mts} +2 -2
  76. package/dist/{namespace-C2ufjgaQ.d.mts → namespace-Ysg1N6rR.d.mts} +24 -24
  77. package/dist/{native-session-supervisor-L-UIaEfd.mjs → native-session-supervisor-zPt624Tp.mjs} +1 -1
  78. package/dist/node/bus-server/index.d.mts +1 -1
  79. package/dist/node/bus-server/index.mjs +1 -1
  80. package/dist/node/bus-server/server-lifecycle.d.mts +1 -1
  81. package/dist/node/bus-server/server-lifecycle.mjs +1 -1
  82. package/dist/{orchestrator-shared-Wv1GI2mW.mjs → orchestrator-shared-D2txLAUs.mjs} +1 -1
  83. package/dist/profile-Cq4A7kQa.mjs +1 -0
  84. package/dist/{provider-context-CNRQ4d5m.mjs → provider-context-BB4eD8ON.mjs} +1 -1
  85. package/dist/{schema-BwzXEtT2.d.mts → schema-B295yplx.d.mts} +1 -1
  86. package/dist/{schema-CAw_BqaG.mjs → schema-C4iznV0q.mjs} +1 -1
  87. package/dist/{schema-introspection-D61TT_7b.mjs → schema-introspection-DCYC47_d.mjs} +1 -1
  88. package/dist/{schemas-BdMU-gew.d.mts → schemas-BWvuaL0w.d.mts} +4 -4
  89. package/dist/{schemas-D9108Iv1.d.mts → schemas-BfMZAwff.d.mts} +7 -7
  90. package/dist/{schemas-BXstpWVp.mjs → schemas-Bn8aqDIE.mjs} +1 -1
  91. package/dist/{schemas-qmn5SWPU.d.mts → schemas-C31qbb0s.d.mts} +4 -4
  92. package/dist/{schemas-DbWs_hj8.d.mts → schemas-DYqKRNju.d.mts} +3 -3
  93. package/dist/{schemas-DENVYyds.d.mts → schemas-Ra8pz5M-.d.mts} +14 -14
  94. package/dist/services/adapter-runtime/index.mjs +1 -1
  95. package/dist/services/adapter-subsystem/index.d.mts +2 -2
  96. package/dist/services/adapter-subsystem/index.mjs +1 -1
  97. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  98. package/dist/services/adapter-subsystem/namespace.mjs +1 -1
  99. package/dist/services/capability/index.mjs +1 -1
  100. package/dist/services/context-rules/index.mjs +1 -1
  101. package/dist/services/execution-target/index.d.mts +3 -3
  102. package/dist/services/execution-target/index.mjs +1 -1
  103. package/dist/services/execution-target/namespace.d.mts +1 -1
  104. package/dist/services/execution-target/schemas.d.mts +1 -1
  105. package/dist/services/filesystem/namespace.d.mts +6 -6
  106. package/dist/services/filesystem/schemas.d.mts +3 -3
  107. package/dist/services/harness/index.d.mts +34 -34
  108. package/dist/services/harness/index.mjs +1 -1
  109. package/dist/services/harness/storage/schema.d.mts +4 -4
  110. package/dist/services/index.d.mts +70 -71
  111. package/dist/services/index.mjs +1 -1
  112. package/dist/services/log-import/log-import.mjs +1 -1
  113. package/dist/services/log-import/namespace.mjs +1 -1
  114. package/dist/services/log-import/schemas.mjs +1 -1
  115. package/dist/services/model-registry/index.mjs +1 -1
  116. package/dist/services/preferences/index.d.mts +2 -2
  117. package/dist/services/preferences/schemas.d.mts +1 -1
  118. package/dist/services/preferences/storage-namespace.d.mts +2 -2
  119. package/dist/services/provider-context/index.mjs +1 -1
  120. package/dist/services/provider-runtime/index.mjs +1 -1
  121. package/dist/services/session/handlers/index.mjs +1 -1
  122. package/dist/services/session/index.d.mts +7 -7
  123. package/dist/services/session/index.mjs +1 -1
  124. package/dist/services/session/messages/namespace.d.mts +1 -1
  125. package/dist/services/session/messages/namespace.mjs +1 -1
  126. package/dist/services/session/orchestrator-testing/index.mjs +1 -1
  127. package/dist/services/session/session-events/namespace.d.mts +1 -1
  128. package/dist/services/session/session-events/namespace.mjs +1 -1
  129. package/dist/services/session/storage/namespace.d.mts +1 -1
  130. package/dist/services/session/storage/schema.d.mts +1 -1
  131. package/dist/services/session/testing/index.mjs +1 -1
  132. package/dist/services/session/testing/orchestrator-shared.mjs +1 -1
  133. package/dist/services/session/turns/namespace.d.mts +1 -1
  134. package/dist/services/session/turns/namespace.mjs +1 -1
  135. package/dist/services/session-editor/index.mjs +1 -1
  136. package/dist/services/settings/index.d.mts +1 -1
  137. package/dist/services/settings/index.mjs +1 -1
  138. package/dist/services/settings/namespace.d.mts +9 -9
  139. package/dist/services/settings/namespace.mjs +1 -1
  140. package/dist/services/settings/storage/clients-namespace.d.mts +1 -1
  141. package/dist/services/settings/storage/clients-namespace.mjs +1 -1
  142. package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
  143. package/dist/services/settings/storage/index.d.mts +1 -1
  144. package/dist/services/settings/storage/index.mjs +1 -1
  145. package/dist/services/settings/storage/providers-namespace.mjs +1 -1
  146. package/dist/services/tool-approval/index.mjs +1 -1
  147. package/dist/services/tools/index.mjs +1 -1
  148. package/dist/services/tray-menu/index.d.mts +2 -2
  149. package/dist/services/tray-menu/index.mjs +1 -1
  150. package/dist/services/tray-menu/namespace.d.mts +1 -1
  151. package/dist/services/tray-menu/schemas.d.mts +1 -1
  152. package/dist/services/turn/index.d.mts +1 -1
  153. package/dist/services/turn/namespace.d.mts +1 -1
  154. package/dist/services/turn/schemas.d.mts +11 -11
  155. package/dist/services/worker/index.d.mts +1 -1
  156. package/dist/services/worker/schemas.d.mts +1 -1
  157. package/dist/{session-piI1R5rP.mjs → session-BCSf-Fgj.mjs} +1 -1
  158. package/dist/{session-Do6lDZM4.mjs → session-BNo_cIiz.mjs} +1 -1
  159. package/dist/{shared-DxHLl9UP.mjs → shared-BhuSHZXH.mjs} +1 -1
  160. package/dist/{skill-CB5h-ZFQ.mjs → skill-20_SBXaI.mjs} +1 -1
  161. package/dist/storage/handlers/drizzle/index.mjs +1 -1
  162. package/dist/storage/handlers/index.mjs +1 -1
  163. package/dist/{storage-namespace-DAm8iWEj.d.mts → storage-namespace-DoH-Wkjp.d.mts} +10 -10
  164. package/dist/timeout-D33CUZ0M.mjs +1 -0
  165. package/dist/{tool-approval-service-BcBSUZCO.mjs → tool-approval-service-CZCPfvVy.mjs} +1 -1
  166. package/dist/{tools-CDSgj0ee.mjs → tools-Cid9D99F.mjs} +1 -1
  167. package/dist/{types-BjToUrHp.d.mts → types--nrtGZ1V.d.mts} +24 -24
  168. package/dist/ui-kernel/index.d.mts +4 -4
  169. package/dist/ui-kernel/pages/namespace.d.mts +4 -4
  170. package/dist/ui-kernel/pages/schemas.d.mts +1 -1
  171. package/package.json +5 -1
  172. package/dist/client-Dh4x4GQN.mjs +0 -1
  173. package/dist/extension-Cbrl4YGX.mjs +0 -1
  174. package/dist/index-CNxS4Tlu.d.mts +0 -1
  175. package/dist/profile-4StaDQW0.mjs +0 -1
  176. package/dist/schemas-CGZy_rU6.d.mts +0 -13
  177. /package/dist/{base-orchestrator-9z8TuA5a.d.mts → base-orchestrator-BOAPgqF7.d.mts} +0 -0
  178. /package/dist/{capability-service-tnpR_TaB.mjs → capability-service-DV32ecwR.mjs} +0 -0
  179. /package/dist/{cleanEnvForAdapter-DvcIGXTG.mjs → cleanEnvForAdapter-hTPNvPU5.mjs} +0 -0
  180. /package/dist/{config-namespace-DLSs83zr.d.mts → config-namespace-ChZOpi1W.d.mts} +0 -0
  181. /package/dist/{config-namespace-MJT8P0Ud.mjs → config-namespace-wJ2CakDB.mjs} +0 -0
  182. /package/dist/{cursor-storage-DOQdvo9j.mjs → cursor-storage-BoNI7OAR.mjs} +0 -0
  183. /package/dist/{drizzle-CWVVw7Er.mjs → drizzle-Bn2GtW8c.mjs} +0 -0
  184. /package/dist/{execution-target-BW_uiBVe.mjs → execution-target-D6MgthYs.mjs} +0 -0
  185. /package/dist/{extension-namespace-zaGKi6Qj.mjs → extension-namespace-CTd9kOtt.mjs} +0 -0
  186. /package/dist/{host-CXAUGGN0.mjs → host-CvEht5RT.mjs} +0 -0
  187. /package/dist/{identity-B_A0mE63.mjs → identity-DBST3-XO.mjs} +0 -0
  188. /package/dist/{index-PdUSmPT2.d.mts → index-D2jejYlV.d.mts} +0 -0
  189. /package/dist/{index-T0471kWA.d.mts → index-DQWMu5fS.d.mts} +0 -0
  190. /package/dist/{model-registry-CIscwC52.mjs → model-registry-Dzpssh9j.mjs} +0 -0
  191. /package/dist/{model-registry-BNzpR6TU.mjs → model-registry-xINyxQUT.mjs} +0 -0
  192. /package/dist/{namespace-Bmc7AW4J2.mjs → namespace-C_h7scWx2.mjs} +0 -0
  193. /package/dist/{namespace-N0dfwSg6.mjs → namespace-DBw9BYr8.mjs} +0 -0
  194. /package/dist/{namespace-pNcSglBS.mjs → namespace-DUVgMfTR.mjs} +0 -0
  195. /package/dist/{namespace-0yuzAKlr.mjs → namespace-OwAf1Brw.mjs} +0 -0
  196. /package/dist/{namespace-CfEWMXBx.mjs → namespace-Zb8HAbyF.mjs} +0 -0
  197. /package/dist/{namespace-Db-p67Rg.mjs → namespace-aALq9tnE.mjs} +0 -0
  198. /package/dist/{namespace-D5Wrt7YU.mjs → namespace-yxIxUsjo.mjs} +0 -0
  199. /package/dist/{platform-BbSLVg5b.mjs → platform-BMFUpmTA.mjs} +0 -0
  200. /package/dist/{providers-Cr4Za8a1.mjs → providers-DhiW_fx4.mjs} +0 -0
  201. /package/dist/{schema-uSGW-6oM.mjs → schema-D3ZG13h9.mjs} +0 -0
  202. /package/dist/{schemas-C40ZAJ33.mjs → schemas-CEBe89yE.mjs} +0 -0
  203. /package/dist/{schemas-Co_sVhzz.mjs → schemas-COnLJnt_.mjs} +0 -0
  204. /package/dist/{schemas-CLxtoKFy.mjs → schemas-CrnlCRep.mjs} +0 -0
  205. /package/dist/{server-lifecycle-Cf_SZ27k.d.mts → server-lifecycle-BC6FRn86.d.mts} +0 -0
  206. /package/dist/{server-lifecycle-DbFwlrTW.mjs → server-lifecycle-Dx5WgfoS.mjs} +0 -0
  207. /package/dist/{session-lineage-Eev4uo4I.d.mts → session-lineage-B0cpHfuc.d.mts} +0 -0
  208. /package/dist/{shared-schemas-BgQv_tnu.mjs → shared-schemas-Byah36lG.mjs} +0 -0
  209. /package/dist/{storage-namespace-ADwyijoe.mjs → storage-namespace-BIDs9LPb.mjs} +0 -0
  210. /package/dist/{storage-namespace-definition-CHu2k14q.mjs → storage-namespace-definition-BjK9nZAN.mjs} +0 -0
  211. /package/dist/{tray-menu-service-CTXC1Elg.mjs → tray-menu-service-BAYtLdAg.mjs} +0 -0
  212. /package/dist/{types-CD1LJwPc.d.mts → types-C11LvekX.d.mts} +0 -0
  213. /package/dist/{ui-config-CXmbsqZV.mjs → ui-config-zawaoEfB.mjs} +0 -0
  214. /package/dist/{variant-D5kSrL3m.mjs → variant-BZWfmS0q.mjs} +0 -0
  215. /package/dist/{version-CjS20oXi.mjs → version-D8S4O22A.mjs} +0 -0
  216. /package/dist/{window-registry-CUftmDr3.mjs → window-registry-B_-hBEcV.mjs} +0 -0
@@ -1 +1,2 @@
1
- import{z as e}from"zod";import*as t from"node:path";import{createBusNamespace as n}from"@makaio/framework/core";import{MakaioBus as r}from"@makaio/framework/bus";import{extensionToken as i,isUniversalRange as a,versionSatisfies as o}from"@makaio/framework/contracts";import{BaseService as s}from"@makaio/framework/service-base";import{index as c,integer as l,sqliteTable as u,text as d,unique as f,uniqueIndex as p}from"drizzle-orm/sqlite-core";import{and as m,eq as h,gt as ee,sql as te}from"drizzle-orm";import{executeTransaction as g,registerDrizzleHandlers as ne}from"@makaio/framework/storage/drizzle";import{ClientProfileNameSchema as _,ClientProfileSchema as re,ClientSubjects as ie,ClientSubjects as v,ClientWiringEntrySchema as y,LatestVersionSourceStatusSchema as ae,ManagedInstallDescriptorSchema as oe,SessionConfigIdSchema as se}from"@makaio/framework/contracts/client";import{randomUUID as b}from"node:crypto";import*as x from"node:fs/promises";import*as S from"node:os";import{CLIDetectionSubjects as ce}from"@makaio/framework/services/cli-detection/namespace";import{ClientStorageSubjects as le}from"@makaio/framework/services/settings/storage";import{SessionSubjects as ue}from"@makaio/framework/contracts/session";async function de(e,t,n,r,i){let a,o=(n.get(e)??Promise.resolve()).then(async()=>{let n=await i(r(await fe(e,t)));n.changed&&await pe(e,n.content),a=n.result}),s=o.then(()=>void 0,()=>void 0);n.set(e,s);try{await o}finally{n.get(e)===s&&n.delete(e)}return a}async function fe(e,t){let n;try{n=await x.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return t;throw e}return JSON.parse(n)}async function pe(e,n){let r=t.dirname(e),i=t.join(r,`${t.basename(e)}.${b()}.tmp`);await x.mkdir(r,{recursive:!0});try{await x.writeFile(i,`${JSON.stringify(n,null,2)}\n`,`utf-8`),await x.rename(i,e)}catch(e){throw await x.unlink(i).catch(()=>void 0),e}}var me=class e extends Error{code=`BINARY_NOT_FOUND`;constructor(t){super(`client.resolveBinary: no binary found for client '${t}' — install a managed version or ensure the binary is on PATH`),this.name=`BinaryNotFoundError`,Error.captureStackTrace?.(this,e)}},he=class{nextAccountSequence=1;accountIdsByIdentifier=new Map;accounts=new Map;upsertAccount(e){let t=_e(e.displayLabel),n=new Map;for(let t of e.identifiers)n.set(ge(e.clientId,t.scheme,t.value),t);let r=ve(n,this.accountIdsByIdentifier,`strong`),i=ve(n,this.accountIdsByIdentifier,`alias`),a=r[0]??(i.length===1?i[0]:i.length>1?ye(i):this.createAccount()),o=(r.length>0?xe(a,r,i):[]).flatMap(e=>this.mergeInto(a,e)),s=this.accounts.get(a);if(!s)throw Error(`Client account registry invariant violated: missing account ${a}`);for(let[e,t]of n){let n=this.accountIdsByIdentifier.get(e);r.length===0&&t.strength===`alias`&&n!==void 0&&n!==a||(s.identifiers.set(e,t),this.accountIdsByIdentifier.set(e,a))}return t!==void 0&&(s.displayLabel=t),{clientAccountId:a,displayLabel:s.displayLabel,mergedAccountIds:o}}clear(){this.accountIdsByIdentifier.clear(),this.accounts.clear(),this.nextAccountSequence=1}createAccount(){let e=`client-account-${this.nextAccountSequence}`;return this.nextAccountSequence+=1,this.accounts.set(e,{clientAccountId:e,identifiers:new Map}),e}mergeInto(e,t){if(e===t)return[];let n=this.accounts.get(e),r=this.accounts.get(t);if(!n||!r)return[];for(let[t,i]of r.identifiers)n.identifiers.set(t,i),this.accountIdsByIdentifier.set(t,e);return n.displayLabel===void 0&&r.displayLabel!==void 0&&(n.displayLabel=r.displayLabel),this.accounts.delete(t),[t]}};function ge(e,t,n){return`${e}\u0000${t}\u0000${n}`}function _e(e){return e?.trim()||void 0}function ve(e,t,n){let r=new Set;for(let[i,a]of e){if(a.strength!==n)continue;let e=t.get(i);e!==void 0&&r.add(e)}return Array.from(r).sort(C)}function ye(e){return[...e].sort(C)[0]}function C(e,t){let n=be(e),r=be(t);return n!==null&&r!==null&&n!==r?n-r:e.localeCompare(t)}function be(e){let t=e.match(/^client-account-(\d+)$/);return t?Number(t[1]):null}function xe(e,t,n){let r=new Set([...t,...n]);return r.delete(e),Array.from(r).sort(C)}const w=e.object({id:e.string(),clientId:e.string(),version:e.string(),installPath:e.string(),installedAt:e.number().int().nonnegative(),createdAt:e.number().int().nonnegative()}),T=e.object({clientId:e.string(),activeVersion:e.string().nullable(),latestAvailableVersion:e.string().nullable(),latestVersionLastCheckedAt:e.number().int().nonnegative().nullable(),latestVersionSourceStatus:ae,updatedAt:e.number().int().nonnegative()}),E=e.object({previousActiveVersion:e.string().nullable(),activeVersion:e.string().nullable()}),D=n(`client-binary:storage`,{insertVersion:{request:w,response:e.object({success:e.boolean()})},recordInstalledVersion:{request:e.object({versionRecord:w,makeActive:e.boolean(),updatedAt:e.number().int().nonnegative()}),response:E},listVersions:{request:e.object({clientId:e.string()}),response:e.object({versions:e.array(w)})},getSnapshot:{request:e.object({clientId:e.string()}),response:e.object({state:T.nullable(),versions:e.array(w)})},loadAllVersions:{request:e.object({}),response:e.object({versions:e.array(w)})},upsertState:{request:T,response:e.object({success:e.boolean()})},setActiveVersion:{request:e.object({clientId:e.string(),activeVersion:e.string().nullable(),updatedAt:e.number().int().nonnegative()}),response:E},getState:{request:e.object({clientId:e.string()}),response:e.object({state:T.nullable()})},loadAllState:{request:e.object({}),response:e.object({states:e.array(T)})},loadSnapshot:{request:e.object({}),response:e.object({states:e.array(T),versions:e.array(w)})},updateFeedCache:{request:e.object({clientId:e.string(),latestAvailableVersion:e.string().nullable(),latestVersionLastCheckedAt:e.number().int().nonnegative().nullable(),latestVersionSourceStatus:ae,updatedAt:e.number().int().nonnegative()}),response:e.object({success:e.boolean()})},removeVersionAndClearActive:{request:e.object({clientId:e.string(),version:e.string(),updatedAt:e.number().int().nonnegative()}),response:E.extend({removedVersion:e.string().nullable()})}}),O=D.subjects;var Se=class{cache=new Map;bus;constructor(e){this.bus=e}async hydrate(){let{states:e}=await this.bus.request(O.loadAllState,{});for(let t of e)this.cache.set(t.clientId,{latestAvailableVersion:t.latestAvailableVersion,lastCheckedAt:t.latestVersionLastCheckedAt,sourceStatus:t.latestVersionSourceStatus===`fresh`?`cached`:t.latestVersionSourceStatus});return e}async update(e,t,n){let r=Date.now(),i=n!==`error`,a={latestAvailableVersion:t,lastCheckedAt:i?r:this.cache.get(e)?.lastCheckedAt??null,sourceStatus:n};await this.bus.request(O.updateFeedCache,{clientId:e,latestAvailableVersion:t,latestVersionLastCheckedAt:i?r:null,latestVersionSourceStatus:n,updatedAt:r}),this.cache.set(e,a)}};function Ce(){let e=e=>async()=>{throw Error(`StrategyDependencies.${e} is not implemented`)};return{fetchText:e(`fetchText`),fetchJson:e(`fetchJson`),downloadFile:e(`downloadFile`),exec:e(`exec`),extractArchive:e(`extractArchive`),deleteFile:e(`deleteFile`),computeChecksum:e(`computeChecksum`),removeDirectory:e(`removeDirectory`)}}var we=class{feedFetcher;cache=new Map;constructor(e){this.feedFetcher=e}async resolveInstallVersion(e,t,n){if(n!==void 0)return{version:this.#e(n,`Explicit version`),explicit:!0};let r=this.cache.get(e);if(r!==void 0)return{version:r.version,explicit:!1};let i=this.#e(await this.feedFetcher.fetchLatestVersion(t),`FeedFetcher`);return this.cache.set(e,{version:i,checkedAt:Date.now(),status:`fresh`}),{version:i,explicit:!1}}async refresh(e,t){try{let n=this.#e(await this.feedFetcher.fetchLatestVersion(t),`FeedFetcher`);return this.cache.set(e,{version:n,checkedAt:Date.now(),status:`fresh`}),!0}catch{let t=this.cache.get(e);return t!==void 0&&this.cache.set(e,{...t,status:`error`}),!1}}getLatestVersionMeta(e){let t=this.cache.get(e);return t===void 0?{latestAvailableVersion:null,latestVersionLastCheckedAt:null,latestVersionSourceStatus:`error`}:{latestAvailableVersion:t.version,latestVersionLastCheckedAt:t.checkedAt,latestVersionSourceStatus:t.status}}seedFromStorage(e,t,n,r=`cached`){this.cache.set(e,{version:this.#e(t,`Storage version`),checkedAt:n,status:r===`fresh`?`cached`:r})}clear(){this.cache.clear()}#e(e,t){let n=e.trim();if(!n)throw Error(`${t} returned an empty version string`);return n}};function Te(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be a JSON object`)}function Ee(e){if(e!==void 0)return(t,n)=>{n!==null&&n>0?e(`downloading`,t/n*100):e(`downloading`,null)}}function De(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.browser_download_url==`string`}const Oe=`https://api.github.com`;var ke=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async resolveLatestVersion(){let e=`${Oe}/repos/${this.#e.repo}/releases/latest`,t=await this.#t.fetchJson(e);return this.#r(t,e).tag_name}async execute(e,n,r){r?.(`resolving`,null);let i=this.#n(),a=this.#e.assetPattern[i];if(a===void 0)throw Error(`No asset pattern for platform key "${i}" in github-release descriptor for ${this.#e.repo}`);let o=`${Oe}/repos/${this.#e.repo}/releases/tags/${e}`,s=await this.#t.fetchJson(o),c=this.#r(s,o),l=c.assets.filter(e=>e.name.includes(a));if(l.length!==1){let t=c.assets.map(e=>e.name).join(`, `);throw Error(l.length===0?`No release asset matching "${a}" for platform "${i}" in ${this.#e.repo}@${e}. Available: ${t}`:`Ambiguous release asset pattern "${a}" for platform "${i}" in ${this.#e.repo}@${e}. Matches: ${l.map(e=>e.name).join(`, `)}`)}let[u]=l;this.#i(u,e),r?.(`downloading`,null);let d=t.join(n,t.basename(u.name));return await this.#t.downloadFile(u.browser_download_url,d,Ee(r)),r?.(`extracting`,null),await this.#t.extractArchive(d,n,this.#e.archiveFormat),await this.#t.deleteFile(d).catch(()=>void 0),r?.(`installing`,100),{installPath:n,version:e,strategy:`github-release`}}#n(){return`${process.platform}-${process.arch}`}#r(e,t){if(Te(e,`GitHub API response at ${t}`),typeof e.tag_name!=`string`||!Array.isArray(e.assets))throw Error(`Unexpected response from GitHub API at ${t}: ${JSON.stringify(e)}`);let n=e.assets,r=n.filter(De);if(r.length!==n.length){let e=n.length-r.length;throw Error(`GitHub API response at ${t} contained ${e} asset entr${e===1?`y`:`ies`} missing required "name" or "browser_download_url" string fields`)}return{tag_name:e.tag_name,assets:r}}#i(e,n){if(typeof e.name!=`string`||e.name.length===0)throw Error(`Matched release asset for ${this.#e.repo}@${n} has an invalid or missing "name" field`);let r=t.basename(e.name);if(r===`.`||r===`..`)throw Error(`Matched release asset for ${this.#e.repo}@${n} has a path-traversal "name" field: "${e.name}"`);if(typeof e.browser_download_url!=`string`||e.browser_download_url.length===0)throw Error(`Matched release asset "${e.name}" for ${this.#e.repo}@${n} has an invalid or missing "browser_download_url" field`)}},Ae=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async resolveLatestVersion(){let{baseUrl:e,versionIndex:t}=this.#e.config,n=`${e}/${t.latest}`,r=(await this.#t.fetchText(n)).trim();if(r.length===0)throw Error(`Version index at ${n} returned an empty version`);return r}async execute(e,n,r){let{baseUrl:i,manifestPath:a,manifestChecksumField:o,binaryPath:s,archiveFormat:c}=this.#e.config;r?.(`resolving`,null);let l=`${i}/${e}/${a}`,u=await this.#t.fetchJson(l);Te(u,`Manifest at ${l}`);let d=this.#n(u,o,l),f=`${i}/${e}/${s}`,p=t.join(n,this.#r(s));r?.(`downloading`,null),await this.#t.downloadFile(f,p,Ee(r)),r?.(`verifying`,null);let m=await this.#t.computeChecksum(p);if(m!==d)throw Error(`Checksum mismatch for ${f}: expected ${d}, got ${m}`);r?.(`extracting`,null);let h=c??`raw`;return(h===`tar.gz`||h===`zip`)&&(await this.#t.extractArchive(p,n,h),await this.#t.deleteFile(p).catch(()=>void 0)),r?.(`installing`,100),{installPath:n,version:e,strategy:`manifest-bucket`}}#n(e,t,n){let r=e[t];if(typeof r!=`string`)throw Error(`Manifest at ${n} is missing a non-empty string field "${t}"`);let i=r.trim().toLowerCase();if(i.length===0)throw Error(`Manifest at ${n} is missing a non-empty string field "${t}"`);return i}#r(e){let n=t.posix.basename(e);if(n.length===0||n===`.`||n===`..`)throw Error(`Invalid binaryPath "${e}" for manifest-bucket strategy`);return n}},je=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async resolveLatestVersion(){return(await this.#t.exec(`npm`,[`view`,this.#e.package,`version`,`--json`])).trim().replace(/^"|"$/g,``)}async execute(e,t,n){n?.(`installing`,null);let r=`${this.#e.package}@${e}`;return await this.#t.exec(`npm`,[`install`,r,`--prefix`,t,`--no-save`,`--ignore-scripts`]),n?.(`installing`,100),{installPath:t,version:e,strategy:`npm`}}};function Me(e,t){let n=oe.safeParse(e);if(n.success)switch(n.data.type){case`manifest-bucket`:return new Ae(n.data,t);case`npm`:return new je(n.data,t);case`github-release`:return new ke(n.data,t)}}function Ne(e,n){let r=t.relative(e,n);return r!==``&&!r.startsWith(`..${t.sep}`)&&r!==`..`&&!t.isAbsolute(r)}function k(e,n){return!t.isAbsolute(e)||!t.isAbsolute(n)?!1:Ne(t.resolve(e),t.resolve(n))}function A(e,n){if(!e||!t.isAbsolute(e))throw Error(`${n} requires a non-empty absolute basePath`);return t.resolve(e)}async function Pe(e,n,r,i){let[a,...o]=r;if(Ie(a))throw Error(`versionCommand[0] must be a relative path; received absolute path "${a}"`);if(a.split(/[/\\]/).includes(`..`))throw Error(`versionCommand[0] must not contain path traversal segments; received "${a}"`);let s=t.normalize(a),c=t.join(n,s),l=await x.realpath(n),u=await x.realpath(c);if(!Ne(l,u))throw Error(`versionCommand[0] must not escape the install directory; "${a}" resolves outside installPath`);let d;try{d=await e(u,o,{cwd:l})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Version verification failed: command "${c}" exited with an error: ${t}`,{cause:e})}let f=Fe(i);if(!Le(d,f))throw Error(`Version mismatch: expected "${i}" but command output was "${d.trim()}"`)}function Fe(e){return e[0]===`v`||e[0]===`V`?e.slice(1):e}function Ie(e){return e.startsWith(`/`)||/^[A-Za-z]:[/\\]/.test(e)||e.startsWith(`\\`)}function Le(e,t){return(e.match(/[A-Za-z0-9][A-Za-z0-9._+-]*/g)??[]).some(e=>Fe(e)===t)}var Re=class{strategyDeps;config;jobs=new Map;#e=!1;resolvedBasePath;constructor(e,t){this.strategyDeps=e,this.config=t,this.resolvedBasePath=A(t.basePath,`ClientBinaryJobRunner`)}startJob(e,t,n,r,i,a,o){let s={...e,status:`running`};return this.jobs.set(e.jobId,s),this.runJob(s,t,n,r,i,a,o),e.jobId}cancelAll(){this.#e=!0,this.jobs.clear()}safeOnProgress(e,t){try{e(t)}catch{}}emitProgressIfActive(e,t){return this.#e?!1:(this.safeOnProgress(e,t),!this.#e)}async runJob(e,t,n,r,i,a,o){try{let s=this.resolveTargetDir(e.clientId,e.version),c=Me(t,this.strategyDeps);if(c===void 0)throw Error(`Unsupported managed install descriptor type: ${t.type}`);let l=await c.execute(e.version,s,(t,r)=>{this.emitProgressIfActive(n,{jobId:e.jobId,clientId:e.clientId,version:e.version,strategy:e.strategy,stage:t,progress:r,installPath:t===`installing`?s:void 0,activeAfterCompletion:e.makeActive})});if(this.#e)return;let u;try{if(u=await this.runPostInstall(e,l.installPath,a,n),this.#e)return;o!==void 0&&await this.runVersionVerification(e,l.installPath,o,n)}catch(e){throw this.#e||await this.cleanupStagedArtifact(l.installPath),e}if(this.#e)return;await this.finalizeSuccess(e,l,u,n,r,i)}catch(t){if(this.#e)return;let n=t instanceof Error?t.message:String(t),r=t instanceof Error&&`code`in t?String(t.code):void 0;try{await i({jobId:e.jobId,clientId:e.clientId,version:e.version,strategy:e.strategy,status:`error`,activeVersion:null,error:{message:n,...r===void 0?{}:{code:r}}})}catch{}}finally{this.jobs.delete(e.jobId)}}async finalizeSuccess(e,t,n,r,i,a){if(!(e.makeActive&&!this.emitProgressIfActive(r,{jobId:e.jobId,clientId:e.clientId,version:t.version,strategy:e.strategy,stage:`activating`,progress:null,installPath:t.installPath,activeAfterCompletion:!0}))&&!this.#e){try{await i({jobId:e.jobId,clientId:e.clientId,version:t.version,installPath:t.installPath,makeActive:e.makeActive,reason:e.reason})}catch(e){try{await this.strategyDeps.removeDirectory(t.installPath)}catch{}throw e}if(!this.#e)try{await a({jobId:e.jobId,clientId:e.clientId,version:t.version,strategy:e.strategy,status:`success`,installPath:t.installPath,activeVersion:e.makeActive?t.version:null,...n===void 0?{}:{metadata:{postInstall:n}}})}catch{}}}async cleanupStagedArtifact(e){try{await this.strategyDeps.removeDirectory(e)}catch{}}async runPostInstall(e,t,n,r){if(n===void 0)return;let i=this.resolvePostInstallHandler(n),a=this.buildProgressPayload(e,`post-install`,null,t,{kind:n.kind});if(!this.emitProgressIfActive(r,a))return;let o=await i({clientId:e.clientId,version:e.version,installPath:t,descriptor:n});return this.emitProgressIfActive(r,this.buildProgressPayload(e,`post-install`,100,t,{kind:n.kind,...o??{}})),o??void 0}async runVersionVerification(e,t,n,r){this.emitProgressIfActive(r,this.buildProgressPayload(e,`verifying`,null,t,{kind:`version-command`}))&&(this.#e||await Pe(this.strategyDeps.exec,t,n,e.version))}resolvePostInstallHandler(e){let t=this.config.postInstallHandlers?.get(e.kind);if(t===void 0)throw Error(`No post-install handler registered for kind "${e.kind}"`);return t}buildProgressPayload(e,t,n,r,i){return{jobId:e.jobId,clientId:e.clientId,version:e.version,strategy:e.strategy,stage:t,progress:n,installPath:r,activeAfterCompletion:e.makeActive,...i===void 0?{}:{metadata:i}}}resolveTargetDir(e,n){let r=t.resolve(this.resolvedBasePath,e,n);if(!k(this.resolvedBasePath,r))throw Error(`Invalid install target path for client "${e}" and version "${n}"`);return r}},j=class{definitions=new Map;constructor(e=[]){for(let t of e)this.registerUnique(t)}getDefinition(e){return this.definitions.get(e)}listDefinitions(){return[...this.definitions.values()]}register(e){this.definitions.set(e.id,e)}registerUnique(e){if(this.definitions.has(e.id))throw Error(`ClientDefinitionRegistry: duplicate client definition id '${e.id}'`);this.definitions.set(e.id,e)}};function M(e,t,n,r,i){if(n===null){if(a(r))return;throw Error(`${e}: ${i} for client '${t}' did not report a version; requires ${r}`)}if(!o(n,r))throw Error(`${e}: ${i} ${n} for client '${t}' does not satisfy ${r}`)}var ze=class{bus;resolvedBasePath;resolvedConfigBasePath;definitionLookup;exec;constructor(e){this.bus=e.bus,this.resolvedBasePath=e.resolvedBasePath,this.resolvedConfigBasePath=e.resolvedConfigBasePath,this.definitionLookup=e.definitionLookup,this.exec=e.exec}async resolve(e){let t=this.definitionLookup.getDefinition(e);if(t===void 0)throw Error(`client.resolveBinary: no definition registered for client '${e}'`);let{state:n,versions:r}=await this.bus.request(O.getSnapshot,{clientId:e}),i=n?.activeVersion??null;return i===null?this.buildGlobalContext(e,t):this.buildManagedContext(e,i,t,r)}isInstallPathWithinBase(e){return k(this.resolvedBasePath,e)}async isExpectedInstallPath(e,n,r){if(!t.isAbsolute(e)||!this.isInstallPathWithinBase(e))return!1;let i=t.resolve(this.resolvedBasePath,n,r);if(!this.isInstallPathWithinBase(i))return!1;try{let[t,n,r]=await Promise.all([x.realpath(this.resolvedBasePath),x.realpath(i),x.realpath(e)]);return k(t,n)?r===n||k(n,r):!1}catch{return!1}}async buildManagedContext(e,n,r,i){let a=i.find(e=>e.version===n);if(a===void 0)throw Error(`client.resolveBinary: active version '${n}' is not installed for client '${e}'`);if(!await this.isExpectedInstallPath(a.installPath,e,n))throw Error(`client.resolveBinary: stored installPath "${a.installPath}" does not match the expected install directory for ${e}@${n}`);r.binary!==void 0&&M(`client.resolveBinary`,e,n,r.binary.supportedVersions,`managed binary version`);let o=N(r.versionCommand)?.[0];if(o===void 0)throw Error(`client.resolveBinary: definition for '${e}' has no versionCommand — cannot derive binary path`);let s=t.resolve(a.installPath,o),c=t.resolve(a.installPath);if(!s.startsWith(c+t.sep)&&s!==c)throw Error(`client.resolveBinary: versionCommand for '${e}' resolves outside the install directory`);let{configDir:l,env:u}=this.resolveIsolatedConfig(e,r);return{binaryPath:s,env:u,configDir:l,source:`managed`,version:n}}async buildGlobalContext(e,t){if(!t.binary?.name)throw Error(`client.resolveBinary: definition for '${e}' has no binary.name — cannot scan PATH`);let n={clientId:e,binaryName:t.binary.name,supportedVersions:t.binary.supportedVersions},{results:r}=await this.bus.request(v.scan,{targets:[n]}),i=r.find(t=>t.clientId===e);if(i===void 0||!i.found)throw new me(e);let a=i.version??null;return M(`client.resolveBinary`,e,a,t.binary.supportedVersions,`detected global binary version`),{binaryPath:null,env:{},configDir:this.resolveGlobalConfigDir(t),source:`global`,version:a}}resolveIsolatedConfig(e,n){let{configIsolation:r}=n;if(r===void 0)return{configDir:null,env:{}};let i=t.join(this.resolvedConfigBasePath,e,`config`),a=r.pathKind===`file`?t.join(i,t.basename(r.defaultPath)):i;return{configDir:i,env:{[r.envVar]:a}}}resolveGlobalConfigDir(e){let{configIsolation:n}=e;if(n===void 0)return null;let r=n.defaultPath,i=r===`~`?S.homedir():r.startsWith(`~/`)?t.join(S.homedir(),r.slice(2)):r,a=n.pathKind===`file`?t.dirname(i):i;if(!t.isAbsolute(a))throw Error(`ConfigIsolation defaultPath for '${e.id}' resolved to non-absolute path '${i}'; use an absolute or tilde-expanded path (e.g. '~/.myapp')`);return a}};function N(e){if(!(e===void 0||e.length===0))return e}var Be=class{strategyDeps;constructor(e){this.strategyDeps=e}async fetchLatestVersion(e){let t=Me(e,this.strategyDeps);if(t===void 0)throw Error(`Unsupported managed install descriptor type: ${e.type}`);return t.resolveLatestVersion()}};async function Ve(e,t,n,r,i){let{versions:a,states:o}=await e.request(O.loadSnapshot,{}),s=Map.groupBy(a,e=>e.clientId),c=new Map;for(let e of o)c.set(e.clientId,e.activeVersion);let l=new Map;for(let e of r.listDefinitions())e.managedInstall!==void 0&&l.set(e.id,e.managedInstall);let u=new Set([...l.keys(),...s.keys(),...c.keys()]);return i&&await Promise.allSettled([...u].map(async e=>{let r=l.get(e);if(r===void 0)return;let i=await t.refresh(e,r),a=t.getLatestVersionMeta(e);await n.update(e,a.latestAvailableVersion,i?`fresh`:`error`)})),[...u].map(e=>{let n=l.get(e),r=c.get(e)??null,a=(s.get(e)??[]).map(e=>({version:e.version,installPath:e.installPath,installedAt:e.installedAt,isActive:e.version===r})),o=t.getLatestVersionMeta(e),u=i&&n===void 0?{...o,latestVersionSourceStatus:`error`}:o,d=r!==null&&u.latestAvailableVersion!==null&&u.latestAvailableVersion!==r;return{clientId:e,installedVersions:a,activeVersion:r,latestAvailableVersion:u.latestAvailableVersion,latestVersionLastCheckedAt:u.latestVersionLastCheckedAt,latestVersionSourceStatus:u.latestVersionSourceStatus,updateAvailable:d}})}var He=class extends s{config;definitionLookup;feedCache;versionResolver;jobRunner;strategyDeps;resolvedBasePath;resolver;pendingClients=new Set;constructor(e=r,t,n=new j([]),i=Ce()){super(e),this.config=t,this.definitionLookup=n,this.resolvedBasePath=A(t.basePath,`ClientBinaryManager`);let a=A(t.configBasePath,`ClientBinaryManager configBasePath`);this.strategyDeps=i,this.feedCache=new Se(e);let o=new Be(i);this.versionResolver=new we(o),this.jobRunner=new Re(i,t),this.resolver=new ze({bus:e,resolvedBasePath:this.resolvedBasePath,resolvedConfigBasePath:a,definitionLookup:n,exec:i.exec})}async onInit(){await this.hydrateFromStorage(),this.registerHandler(v.list,async e=>{let t=await this.handleList(e.payload.forceRefresh??!1);e.setResult({clients:t})}),this.registerHandler(v.install,async e=>{let t=await this.handleInstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(v.update,async e=>{let t=await this.handleUpdate(e.payload.clientId);e.setResult(t)}),this.registerHandler(v.setActive,async e=>{let t=await this.handleSetActive(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(v.uninstall,async e=>{let t=await this.handleUninstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(v.resolveBinary,async e=>{let t=await this.resolver.resolve(e.payload.clientId);e.setResult(t)})}onDestroy(){this.jobRunner.cancelAll(),this.versionResolver.clear(),this.pendingClients.clear()}async handleList(e){return Ve(this.bus,this.versionResolver,this.feedCache,this.definitionLookup,e)}async handleInstall(e,t){let{definition:n,descriptor:r}=this.requireManagedDefinition(e,`client.install`);return this.withClientLock(e,async()=>{let{version:i,explicit:a}=await this.versionResolver.resolveInstallVersion(e,r,t);if(n.binary!==void 0&&M(`client.install`,e,i,n.binary.supportedVersions,t===void 0?`resolved binary version`:`requested binary version`),!a){let t=this.versionResolver.getLatestVersionMeta(e);await this.feedCache.update(e,t.latestAvailableVersion,t.latestVersionSourceStatus)}return{jobId:this.startInstallJob(e,i,r,n,!1,`install`),requestedVersion:t??null,resolvedVersion:i}})}async handleUpdate(e){let{definition:t,descriptor:n}=this.requireManagedDefinition(e,`client.update`);return this.withClientLock(e,async()=>{let r=await this.versionResolver.refresh(e,n),i=this.versionResolver.getLatestVersionMeta(e);if(await this.feedCache.update(e,i.latestAvailableVersion,r?`fresh`:`error`),!r||i.latestAvailableVersion===null)throw Error(`client.update: failed to resolve latest version for client '${e}'`);let a=i.latestAvailableVersion;return t.binary!==void 0&&M(`client.update`,e,a,t.binary.supportedVersions,`resolved binary version`),{jobId:this.startInstallJob(e,a,n,t,!0,`update`),resolvedVersion:a}})}async handleSetActive(e,t){if(this.pendingClients.has(e))throw Error(`Operation already in progress for client "${e}"`);this.pendingClients.add(e);try{let{versions:n}=await this.bus.request(O.listVersions,{clientId:e}),r=n.find(e=>e.version===t);if(r===void 0)throw Error(`client.setActive: version '${t}' is not installed for client '${e}'`);let i=this.definitionLookup.getDefinition(e);if(i===void 0)throw Error(`client.setActive: no definition registered for client '${e}'`);i.binary!==void 0&&M(`client.setActive`,e,t,i.binary.supportedVersions,`requested binary version`);let a=N(i.versionCommand);if(a===void 0)throw Error(`client.setActive: no versionCommand registered for client '${e}'`);if(!await this.resolver.isExpectedInstallPath(r.installPath,e,t))throw Error(`client.setActive: stored installPath "${r.installPath}" does not match the expected install directory for ${e}@${t}`);return await Pe(this.strategyDeps.exec,r.installPath,a,t),await this.patchActiveVersion(e,t,`set-active`),{clientId:e,activeVersion:t}}finally{this.pendingClients.delete(e)}}async handleUninstall(e,n){if(this.pendingClients.has(e))throw Error(`Operation already in progress for client "${e}"`);this.pendingClients.add(e);try{let{versions:r}=await this.bus.request(O.listVersions,{clientId:e}),i=r.find(e=>e.version===n);if(i===void 0)throw Error(`client.uninstall: version '${n}' is not installed for client '${e}'`);let{removedVersion:a,previousActiveVersion:o,activeVersion:s}=await this.bus.request(O.removeVersionAndClearActive,{clientId:e,version:n,updatedAt:Date.now()});if(a===null)throw Error(`client.uninstall: failed to delete version '${n}' for client '${e}'`);let c=i.installPath,l=typeof c==`string`&&c.length>0?t.resolve(c):null;if(typeof c!=`string`||c.length===0||l===null||!t.isAbsolute(c)||!await this.resolver.isExpectedInstallPath(l,e,n)?console.warn(`[ClientBinaryManager] Skipping removeDirectory: stored installPath "${String(c)}" does not match the expected install directory for ${e}@${n}`):await this.strategyDeps.removeDirectory(l).catch(t=>{console.warn(`[ClientBinaryManager] Failed to remove binary directory "${l}" for ${e}@${n}:`,t)}),o!==null&&s===null)try{await this.bus.emit(v.version.changed,{clientId:e,previousActiveVersion:o,activeVersion:null,reason:`uninstall`})}catch(e){console.warn(`[ClientBinaryManager] Failed to emit client.version.changed:`,e)}return{clientId:e,removedVersion:n,activeVersion:s}}finally{this.pendingClients.delete(e)}}async patchActiveVersion(e,t,n){let r=(await this.bus.request(O.setActiveVersion,{clientId:e,activeVersion:t,updatedAt:Date.now()})).previousActiveVersion;if(r!==t)try{await this.bus.emit(v.version.changed,{clientId:e,previousActiveVersion:r,activeVersion:t,reason:n})}catch(e){console.warn(`[ClientBinaryManager] Failed to emit client.version.changed:`,e)}return r}async hydrateFromStorage(){let e=await this.feedCache.hydrate();for(let t of e)t.latestAvailableVersion!==null&&t.latestVersionLastCheckedAt!==null&&this.versionResolver.seedFromStorage(t.clientId,t.latestAvailableVersion,t.latestVersionLastCheckedAt,t.latestVersionSourceStatus)}requireManagedDefinition(e,t){let n=this.definitionLookup.getDefinition(e);if(n===void 0)throw Error(`${t}: no definition registered for client '${e}'`);let r=n.managedInstall;if(r===void 0)throw Error(`${t}: client '${e}' does not declare a managed install descriptor`);return{definition:n,descriptor:r}}async withClientLock(e,t){if(this.pendingClients.has(e))throw Error(`Operation already in progress for client "${e}"`);this.pendingClients.add(e);try{return await t()}catch(t){throw this.pendingClients.delete(e),t}}startInstallJob(e,t,n,r,i,a){let o={jobId:crypto.randomUUID(),clientId:e,version:t,strategy:n.type,status:`pending`,makeActive:i,reason:a};return this.jobRunner.startJob(o,n,e=>{this.bus.emit(v.installJob.progress,e).catch(e=>{console.warn(`[ClientBinaryManager] Failed to emit client.installJob.progress:`,e)})},this.makeCompletionCallback(),async e=>{this.pendingClients.delete(e.clientId),await this.bus.emit(v.installJob.completed,e).catch(e=>{console.warn(`[ClientBinaryManager] Failed to emit client.installJob.completed:`,e)})},r.postInstall,N(r.versionCommand)),o.jobId}makeCompletionCallback(){return async({clientId:e,version:t,installPath:n,makeActive:r,reason:i})=>{let a=Date.now(),o=await this.bus.request(O.recordInstalledVersion,{versionRecord:{id:crypto.randomUUID(),clientId:e,version:t,installPath:n,installedAt:a,createdAt:a},makeActive:r,updatedAt:a});if(r&&o.previousActiveVersion!==o.activeVersion)try{await this.bus.emit(v.version.changed,{clientId:e,previousActiveVersion:o.previousActiveVersion,activeVersion:o.activeVersion,reason:i})}catch(e){console.warn(`[ClientBinaryManager] Failed to emit client.version.changed:`,e)}}}};function P(e,t){return`${e}${t}`}function F(e,t){return`${e}${t}`}var Ue=class{records=new Map;bySupervisorSessionId=new Map;byPidClientId=new Map;byAdapterSessionClientId=new Map;set(e){let t=this.records.get(e.clientRuntimeId);t&&this.removeIndexEntries(t),this.records.set(e.clientRuntimeId,e),this.addIndexEntries(e)}setFromStorage(e,t,n){this.records.set(e.clientRuntimeId,e),e.supervisorSessionId!==void 0&&this.bySupervisorSessionId.set(e.supervisorSessionId,e.clientRuntimeId),t-e.updatedAt<=n&&(e.pid!==void 0&&this.byPidClientId.set(P(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.set(F(e.adapterSessionId,e.clientId),e.clientRuntimeId))}delete(e){let t=this.records.get(e);t&&(this.removeIndexEntries(t),this.records.delete(e))}get(e){return this.records.get(e)}findByEvidence(e,t,n,r){if(e!==void 0){let t=this.bySupervisorSessionId.get(e);if(t!==void 0)return this.records.get(t)}if(t!==void 0){let e=this.byPidClientId.get(P(t,r));if(e!==void 0)return this.records.get(e)}if(n!==void 0){let e=this.byAdapterSessionClientId.get(F(n,r));if(e!==void 0)return this.records.get(e)}}values(){return this.records.values()}clear(){this.records.clear(),this.bySupervisorSessionId.clear(),this.byPidClientId.clear(),this.byAdapterSessionClientId.clear()}get size(){return this.records.size}addIndexEntries(e){e.supervisorSessionId!==void 0&&this.bySupervisorSessionId.set(e.supervisorSessionId,e.clientRuntimeId),e.pid!==void 0&&this.byPidClientId.set(P(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.set(F(e.adapterSessionId,e.clientId),e.clientRuntimeId)}removeIndexEntries(e){e.supervisorSessionId!==void 0&&this.bySupervisorSessionId.delete(e.supervisorSessionId),e.pid!==void 0&&this.byPidClientId.delete(P(e.pid,e.clientId)),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.delete(F(e.adapterSessionId,e.clientId))}};const I=[`observed`,`started`],L=e.object({clientRuntimeId:e.string(),clientId:e.string(),status:e.enum(I),supervisorSessionId:e.string().optional(),pid:e.number().int().positive().optional(),parentPid:e.number().int().positive().optional(),adapterSessionId:e.string().optional(),sessionId:e.string().optional(),cwd:e.string().optional(),argv:e.array(e.string()).optional(),metadata:e.record(e.string(),e.unknown()).optional(),observedAt:e.number().int().nonnegative(),createdAt:e.number().int().nonnegative(),updatedAt:e.number().int().nonnegative()}),R=n(`client-runtime:storage`,{upsert:{request:L,response:e.object({success:e.boolean()})},loadAll:{request:e.object({}),response:e.object({records:e.array(L)})}}),z=R.subjects;function We(e){return e.supervisorSessionId!==void 0||e.adapterSessionId!==void 0}function B(e){return{...e,argv:e.argv===void 0?void 0:[...e.argv],metadata:e.metadata===void 0?void 0:structuredClone(e.metadata)}}function Ge(e){return Math.max(Date.now(),e+1)}function Ke(e,t){let n=!1;return t.supervisorSessionId!==void 0&&e.supervisorSessionId!==t.supervisorSessionId&&(e.supervisorSessionId=t.supervisorSessionId,n=!0),t.pid!==void 0&&e.pid!==t.pid&&(e.pid=t.pid,n=!0),t.parentPid!==void 0&&e.parentPid!==t.parentPid&&(e.parentPid=t.parentPid,n=!0),t.adapterSessionId!==void 0&&e.adapterSessionId!==t.adapterSessionId&&(e.adapterSessionId=t.adapterSessionId,n=!0),t.sessionId!==void 0&&e.sessionId!==t.sessionId&&(e.sessionId=t.sessionId,n=!0),t.cwd!==void 0&&e.cwd!==t.cwd&&(e.cwd=t.cwd,n=!0),t.argv!==void 0&&JSON.stringify(e.argv)!==JSON.stringify(t.argv)&&(e.argv=[...t.argv],n=!0),t.metadata!==void 0&&JSON.stringify(e.metadata)!==JSON.stringify(t.metadata)&&(e.metadata=structuredClone(t.metadata),n=!0),n}var V=class{runtimeMap=new Ue;bus;constructor(e){this.bus=e}async loadFromStorage(){if(!this.bus)return;let e=await this.bus.requestOptional(z.loadAll,{});if(!e.handled)return;let t=Date.now();for(let n of e.data.records)this.runtimeMap.setFromStorage(B(n),t,864e5)}async upsertRuntime(e){let t=this.runtimeMap.findByEvidence(e.supervisorSessionId,e.pid,e.adapterSessionId,e.clientId);if(t){let n=t.status===`observed`,r=n&&We(e),i=Ke(t,e),a=n&&e.observedAt>t.observedAt;return r&&(t.status=`started`),(i||r||a)&&(t.updatedAt=Ge(t.updatedAt),a&&(t.observedAt=e.observedAt),this.runtimeMap.set(t),await this.persistRecord(t)),{clientRuntimeId:t.clientRuntimeId,created:!1,promoted:r,record:B(t)}}let n=Date.now(),r=b(),i=We(e)?`started`:`observed`,a={clientRuntimeId:r,clientId:e.clientId,status:i,supervisorSessionId:e.supervisorSessionId,pid:e.pid,parentPid:e.parentPid,adapterSessionId:e.adapterSessionId,sessionId:e.sessionId,cwd:e.cwd,argv:e.argv?[...e.argv]:void 0,metadata:e.metadata?structuredClone(e.metadata):void 0,observedAt:e.observedAt,createdAt:n,updatedAt:n};return this.runtimeMap.set(a),await this.persistRecord(a),{clientRuntimeId:r,created:!0,promoted:!1,record:B(a)}}getRuntime(e){let t=this.runtimeMap.get(e);return t?B(t):void 0}clear(){this.runtimeMap.clear()}get size(){return this.runtimeMap.size}async persistRecord(e){this.bus&&await this.bus.requestOptional(z.upsert,B(e))}};const qe=e.object({eventName:e.string(),receivedAt:e.number().int().finite().nonnegative().describe(`Unix epoch timestamp in milliseconds`),payload:e.record(e.string(),e.unknown()),metadata:e.record(e.string(),e.unknown()).optional()}),Je=/^[a-z0-9-]+$/;function H(e,t=`canonicalizeClientId`){let n=e.trim().toLowerCase(),r=n.startsWith(`client:`)?n.slice(7):n;if(r.length===0)throw Error(`[${t}] clientId must be a non-empty string`);if(!Je.test(r))throw Error(`[${t}] clientId must contain only lowercase letters, numbers, and hyphens after an optional client: prefix`);return r}function Ye(e){return{subject:`hook.received`,$meta:{namespace:`client:${H(e,`createRawClientHookReceivedSubject`)}`,isRequest:!1,local:!1,channel:!1}}}function Xe(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ze(e,t){return Xe(e[t])}function Qe(e){return{clientId:e.clientId,source:`adapter-derived`,observedAt:Date.now(),...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.adapterSessionId!==void 0&&{adapterSessionId:e.adapterSessionId}}}function $e(e){try{e().catch(et)}catch(e){et(e)}}function et(e){(process.env.DEBUG||process.env.MAKAIO_DEBUG)&&console.debug(`[emitBestEffort] observed-semantics emission failed`,e)}function tt(e,t){return{subject:t,$meta:{namespace:`client:${H(e,`createClientWiringSubjectDef`)}`,isRequest:!0,local:!1,channel:!1}}}function nt(e){return tt(e,`wiring.list`)}const rt=e.string().min(1).refine(t.isAbsolute,{message:`projectDir must be an absolute path`}),it=e.object({entries:e.array(y)}),at=e.object({applied:e.number().int().nonnegative(),skipped:e.number().int().nonnegative()}),ot=e.object({removed:e.number().int().nonnegative()}),st=e.object({clientId:e.string().trim().min(1),entries:e.array(y)});function ct(e){if(e!==void 0&&!t.isAbsolute(e))throw Error(`projectDir must be an absolute path, got: ${e}`)}var lt=class extends s{accountRegistry;runtimeRegistry;latestSnapshots=new Map;activeIdentities=new Map;constructor(e=r,t=new he,n=new V(e)){super(e),this.accountRegistry=t,this.runtimeRegistry=n}async onInit(){await this.runtimeRegistry.loadFromStorage(),this.registerHandler(v.account.observe,e=>this.handleAccountObserve(e)),this.registerHandler(v.usage.ingest,e=>this.handleUsageIngest(e)),this.registerHandler(v.scan,async e=>{let t=await this.scanClients(e.payload.targets);e.setResult({results:t})}),this.registerHandler(v.runtime.observe,e=>this.handleRuntimeObserve(e)),this.registerHandler(v.wiring.list,async e=>{let t=await this.listWirings(e.payload);e.setResult({results:t})}),this.registerHandler(v.account.activate,e=>{this.activeIdentities.set(e.payload.clientId,{clientAccountId:e.payload.clientAccountId,identifiers:e.payload.identifiers,displayLabel:e.payload.displayLabel}),e.setResult({accepted:!0})}),this.registerHandler(v.account.getActive,e=>{let t=this.activeIdentities.get(e.payload.clientId);e.setResult({identity:t??null})})}onDestroy(){this.latestSnapshots.clear(),this.activeIdentities.clear(),this.accountRegistry.clear(),this.runtimeRegistry.clear()}getLatestSnapshot(e){return this.latestSnapshots.get(e)}async handleAccountObserve(e){let t=this.accountRegistry.upsertAccount({clientId:e.payload.clientId,identifiers:e.payload.identifiers,displayLabel:e.payload.displayLabel}),n=this.latestSnapshots.get(t.clientAccountId),r=ft(this.consolidateMergedSnapshots(t.clientAccountId,t.mergedAccountIds)??n,t.displayLabel);r&&this.latestSnapshots.set(t.clientAccountId,r),r&&(t.mergedAccountIds.length>0||r!==n)&&await this.bus.emit(v.usage.snapshot,r),e.setResult({clientAccountId:t.clientAccountId,displayLabel:t.displayLabel})}async handleUsageIngest(e){let t=this.accountRegistry.upsertAccount({clientId:e.payload.clientId,identifiers:e.payload.account.identifiers,displayLabel:e.payload.account.displayLabel});this.consolidateMergedSnapshots(t.clientAccountId,t.mergedAccountIds);let n=ut(t.clientAccountId,e.payload,t.displayLabel),r=ft(dt(this.latestSnapshots.get(t.clientAccountId),n),t.displayLabel);this.latestSnapshots.set(t.clientAccountId,r),await this.bus.emit(v.usage.snapshot,r),e.setResult({clientAccountId:t.clientAccountId,snapshot:r})}async handleRuntimeObserve(e){let{payload:t}=e;if(t.supervisorSessionId===void 0&&t.pid===void 0&&t.adapterSessionId===void 0)throw Error(`client.runtime.observe: at least one hard-evidence field is required (supervisorSessionId, pid, or adapterSessionId)`);let{record:n,...r}=await this.runtimeRegistry.upsertRuntime(t);(r.created||r.promoted)&&await this.bus.emit(v.runtime.started,{clientRuntimeId:n.clientRuntimeId,clientId:n.clientId,status:n.status,source:t.source,observedAt:t.observedAt,supervisorSessionId:n.supervisorSessionId,pid:n.pid,parentPid:n.parentPid,adapterSessionId:n.adapterSessionId,sessionId:n.sessionId,cwd:n.cwd,argv:n.argv,metadata:n.metadata}),e.setResult({clientRuntimeId:r.clientRuntimeId,created:r.created,promoted:r.promoted})}async scanClients(e){let t=e??await this.listScannableStoredClients();if(t.length===0)return[];let n=Array.from(new Set(t.map(e=>e.binaryName))),{results:r}=await this.bus.request(ce.scan,{binaries:n}),i=new Map(r.map(e=>[e.binary,e]));return t.map(e=>{let t=i.get(e.binaryName),n=t?.found??!1,r=t?.version;return{clientId:e.clientId,found:n,version:r,warningMessage:mt(n,r,e.supportedVersions)}})}async listScannableStoredClients(){let{clients:e}=await this.bus.request(le.list,{});return e.filter(pt).map(e=>({clientId:e.id,binaryName:e.binary.name,supportedVersions:e.binary.supportedVersions}))}async listWirings(e){ct(e.projectDir);let{clients:t}=await this.bus.request(le.list,{}),n=e.clientId===void 0?void 0:H(e.clientId,`listWirings`),r=t.filter(e=>e.enabled).filter(e=>n===void 0||e.id===n),i=await Promise.allSettled(r.map(async t=>{let n=nt(t.id),r=await this.bus.requestOptional(n,{projectDir:e.projectDir,makaioCommand:e.makaioCommand});return r.handled?{clientId:t.id,entries:r.data.entries}:null}));for(let e=0;e<i.length;e++){let t=i[e];if(t.status===`rejected`){let n=t.reason instanceof Error?t.reason.message:String(t.reason);console.warn(`[ClientRuntimeService] wiring.list for ${r[e].id} failed: ${n}`)}}return i.filter(e=>e.status===`fulfilled`).map(e=>e.value).filter(e=>e!==null)}consolidateMergedSnapshots(e,t){let n=this.latestSnapshots.get(e),r=!1;for(let i of t){if(i===e)continue;let t=this.latestSnapshots.get(i);t&&(n===void 0||t.observedAt>n.observedAt)&&(n={...t,clientAccountId:e},r=!0),this.latestSnapshots.delete(i)}return n&&this.latestSnapshots.set(e,n),r?n:void 0}};function ut(e,t,n){return{clientAccountId:e,clientId:t.clientId,observedAt:t.observedAt,source:t.source,displayLabel:n,usage:{windows:t.usage.windows.map(e=>({...e}))},metadata:t.metadata?{...t.metadata}:void 0}}function dt(e,t){return e&&e.observedAt>t.observedAt?e:t}function ft(e,t){return!e||t===void 0||e.displayLabel===t?e:{...e,displayLabel:t}}function pt(e){return e.enabled&&e.binary!==void 0}function mt(e,t,n){if(e&&t!==void 0&&t!==`unknown`&&n!==void 0&&!o(t,n))return`Unsupported version: requires ${n}`}const U=re,W=e.string().trim().min(1),G=n(`client-profile:storage`,{get:{request:e.object({clientId:W,name:_}),response:e.object({record:U.nullable()})},getById:{request:e.object({id:W}),response:e.object({record:U.nullable()})},list:{request:e.object({clientId:W}),response:e.object({records:e.array(U)})},set:{request:U,response:e.object({success:e.boolean()})},delete:{request:e.object({clientId:W,name:_}),response:e.object({success:e.boolean()})},clearDefault:{request:e.object({clientId:W}),response:e.object({success:e.boolean()})},setDefault:{request:e.object({clientId:W,name:_}),response:e.object({record:U.nullable()})}}),K=G.subjects;function ht(e,n,r){let i=t.resolve(e),a=t.resolve(n),o=t.relative(i,a);if(o!==``&&!o.startsWith(`..`)&&!t.isAbsolute(o))return a;throw Error(`${r} refused to access path outside client profile root`)}var gt=class extends s{clientsBasePath;constructor(e,t){super(e),this.clientsBasePath=t}async onInit(){this.registerCreateHandler(),this.registerListHandler(),this.registerGetHandler(),this.registerUpdateHandler(),this.registerDeleteHandler(),this.registerSetDefaultHandler()}registerCreateHandler(){this.registerHandler(v.profile.create,async e=>{let n=H(e.payload.clientId,`profile.create`),{name:r,description:i}=e.payload;if((await this.bus.request(K.get,{clientId:n,name:r})).record!==null)throw Error(`Profile '${r}' already exists for client '${n}'`);let a=t.join(this.clientsBasePath,n,`profiles`),o=ht(a,t.join(a,r),`profile.create`);await x.mkdir(o,{recursive:!0});let s=Date.now(),c={id:b(),clientId:n,name:r,description:i??null,configDir:o,isDefault:!1,createdAt:s,updatedAt:s};await this.bus.request(K.set,c),e.setResult({profile:c})})}registerListHandler(){this.registerHandler(v.profile.list,async e=>{let t=H(e.payload.clientId,`profile.list`),n=await this.bus.request(K.list,{clientId:t});e.setResult({profiles:n.records})})}registerGetHandler(){this.registerHandler(v.profile.get,async e=>{let t=H(e.payload.clientId,`profile.get`),n=await this.bus.request(K.get,{clientId:t,name:e.payload.name});e.setResult({profile:n.record})})}registerUpdateHandler(){this.registerHandler(v.profile.update,async e=>{let t=H(e.payload.clientId,`profile.update`),{name:n,description:r}=e.payload,i=await this.bus.request(K.get,{clientId:t,name:n});if(i.record===null)throw Error(`Profile '${n}' not found for client '${t}'`);let a={...i.record,description:r===void 0?i.record.description:r,updatedAt:Date.now()};await this.bus.request(K.set,a),e.setResult({profile:a})})}registerDeleteHandler(){this.registerHandler(v.profile.delete,async e=>{let n=H(e.payload.clientId,`profile.delete`),{name:r}=e.payload,i=await this.bus.request(K.get,{clientId:n,name:r});i.record!==null&&(ht(t.join(this.clientsBasePath,n,`profiles`),i.record.configDir,`profile.delete`),await x.rm(i.record.configDir,{recursive:!0,force:!0}));let a=await this.bus.request(K.delete,{clientId:n,name:r});e.setResult({success:a.success})})}registerSetDefaultHandler(){this.registerHandler(v.profile.setDefault,async e=>{let t=H(e.payload.clientId,`profile.setDefault`),{name:n}=e.payload,r=await this.bus.request(K.setDefault,{clientId:t,name:n});if(r.record===null)throw Error(`Profile '${n}' not found for client '${t}'`);e.setResult({profile:r.record})})}};function _t(e){return{subject:`sessionConfig.setup`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}function vt(e){return{subject:`sessionConfig.destroy`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}const yt=()=>Date.now();function bt(){let e=S.platform();if(e===`darwin`||e===`linux`||e===`win32`)return e;throw Error(`client.sessionConfig does not support platform '${e}'`)}function xt(e,n,r){let i=se.safeParse(n);if(!i.success)throw Error(`${r} received an unsafe session ID`);let a=t.resolve(e),o=t.resolve(a,i.data),s=t.relative(a,o);if(s===``||!s.startsWith(`..`)&&!t.isAbsolute(s))return o;throw Error(`${r} refused to access path outside client sessions root`)}var St=class extends s{clientsBasePath;getNow;constructor(e,t,n=yt){super(e),this.clientsBasePath=t,this.getNow=n}async onInit(){this.registerHandler(v.sessionConfig.create,async e=>{let{clientId:t,sessionId:n,profileName:r,baseConfigDir:i,projectDir:a,configInheritance:o=`full`}=e.payload,s=H(t,`sessionConfig.create`),c=this.resolveClientSessionDir(s,n,`sessionConfig.create`);await x.mkdir(c,{recursive:!0});let l=await this.resolveBaseConfigDir(s,c,r,i),u=_t(s),d=await this.bus.requestOptional(u,{sessionDir:c,baseConfigDir:l,projectDir:a,platform:bt(),configInheritance:o}),f=d.handled?d.data.env??{}:{};e.setResult({sessionDir:c,env:f})}),this.registerHandler(v.sessionConfig.destroy,async e=>{let{clientId:t,sessionId:n}=e.payload,r=H(t,`sessionConfig.destroy`),i=this.resolveClientSessionDir(r,n,`sessionConfig.destroy`);await this.destroyClientSessionDir(r,i),e.setResult({success:!0})}),this.registerHandler(v.sessionConfig.cleanup,async e=>{let{clientId:t}=e.payload,n=t===void 0?void 0:H(t,`sessionConfig.cleanup`),r=await this.cleanupOrphanedDirs(n);e.setResult({removed:r})}),this.registerHandler(ue.closed,async e=>{await this.destroySessionDirsForSessionId(e.payload.sessionId)}),await this.cleanupOrphanedDirs()}async resolveBaseConfigDir(e,t,n,r){if(r!==void 0)return r;if(n!==void 0){let t=await this.bus.request(K.get,{clientId:e,name:n});if(t.record!==null)return t.record.configDir;throw Error(`Profile '${n}' not found for client '${e}'`)}let i=(await this.bus.request(K.list,{clientId:e})).records.find(e=>e.isDefault);return i?i.configDir:t}async cleanupOrphanedDirs(e){let n=[],r=this.getNow(),i=e===void 0?await this.listClientIds():[e];return await Promise.all(i.map(async e=>{let i=t.join(this.clientsBasePath,e,`sessions`),a=await x.readdir(i).catch(()=>[]);await Promise.all(a.map(async t=>{try{let a=xt(i,t,`sessionConfig.cleanup`),o=await x.stat(a),s=o.birthtimeMs>0?o.birthtimeMs:o.ctimeMs;o.isDirectory()&&r-s>36e5&&!await this.isActiveSession(t)&&(await this.destroyClientSessionDir(e,a),n.push(a))}catch{}}))})),n}async destroySessionDirsForSessionId(e){if(!se.safeParse(e).success)return;let t=await this.listClientIds();await Promise.all(t.map(async t=>{let n=this.resolveClientSessionDir(t,e,`session.closed`);await this.destroyClientSessionDir(t,n)}))}async destroyClientSessionDir(e,t){await x.stat(t).then(e=>e.isDirectory(),e=>{let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e})&&(await this.bus.requestOptional(vt(e),{sessionDir:t,platform:bt()}),await x.rm(t,{recursive:!0,force:!0}))}async isActiveSession(e){let t=await this.bus.requestOptional(ue.get,{sessionId:e});return t.handled&&t.data.session?.status===`active`}resolveClientSessionDir(e,n,r){return xt(t.join(this.clientsBasePath,e,`sessions`),n,r)}async listClientIds(){return(await x.readdir(this.clientsBasePath,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()).map(e=>e.name)}};function Ct(e,t){return r.registerNamespace(n(`client:${e}`,{"hook.received":qe,...t})).subjects}function wt(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||!(e in n))return!1;n=n[e]}return!0}function Tt(e,t,n){let r=Object.keys(n).filter(e=>!wt(t,e));if(r.length!==0)throw Error(`[createClientNamespace] client:${e} was already registered without required subjects: ${r.join(`, `)}`)}function Et(e,t){let n=H(e,`createClientNamespace`),r=t??{},i=Ct(n,r);return Tt(n,i,r),{namespaceDomain:`client:${n}`,subjects:i}}const q=u(`client_runtimes`,{id:d(`id`).primaryKey(),clientId:d(`client_id`).notNull(),status:d(`status`).notNull(),supervisorSessionId:d(`supervisor_session_id`),pid:l(`pid`),parentPid:l(`parent_pid`),adapterSessionId:d(`adapter_session_id`),sessionId:d(`session_id`),cwd:d(`cwd`),argv:d(`argv`,{mode:`json`}).$type(),metadata:d(`metadata`,{mode:`json`}).$type(),observedAt:l(`observed_at`).notNull(),createdAt:l(`created_at`).notNull(),updatedAt:l(`updated_at`).notNull()},e=>[c(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),c(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),c(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)]),Dt=new Set(I);function Ot(e){if(!Dt.has(e.status))throw Error(`Unknown ClientRuntimeStatus in DB: '${e.status}'`);return{clientRuntimeId:e.id,clientId:e.clientId,status:e.status,supervisorSessionId:e.supervisorSessionId??void 0,pid:e.pid??void 0,parentPid:e.parentPid??void 0,adapterSessionId:e.adapterSessionId??void 0,sessionId:e.sessionId??void 0,cwd:e.cwd??void 0,argv:e.argv??void 0,metadata:e.metadata??void 0,observedAt:e.observedAt,createdAt:e.createdAt,updatedAt:e.updatedAt}}function kt(e,t,n){let r=e.on(z.upsert,async e=>{let n=e.payload,r={clientId:n.clientId,status:n.status,supervisorSessionId:n.supervisorSessionId??null,pid:n.pid??null,parentPid:n.parentPid??null,adapterSessionId:n.adapterSessionId??null,sessionId:n.sessionId??null,cwd:n.cwd??null,argv:n.argv??null,metadata:n.metadata??null,observedAt:n.observedAt,updatedAt:n.updatedAt};await t.insert(q).values({id:n.clientRuntimeId,createdAt:n.createdAt,...r}).onConflictDoUpdate({target:q.id,set:r,setWhere:ee(te`excluded.updated_at`,q.updatedAt)}),e.setResult({success:!0})}),i=e.on(z.loadAll,async e=>{let n=await t.select().from(q);e.setResult({records:n.map(Ot)})});return()=>{r(),i()}}const J=u(`client_binary_versions`,{id:d(`id`).primaryKey(),clientId:d(`client_id`).notNull(),version:d(`version`).notNull(),installPath:d(`install_path`).notNull(),installedAt:l(`installed_at`).notNull(),createdAt:l(`created_at`).notNull()},e=>[c(`idx_client_binary_versions_client_id`).on(e.clientId),f(`uq_client_binary_versions_client_version`).on(e.clientId,e.version)]),Y=u(`client_binary_state`,{clientId:d(`client_id`).primaryKey(),activeVersion:d(`active_version`),latestAvailableVersion:d(`latest_available_version`),latestVersionLastCheckedAt:l(`latest_version_last_checked_at`),latestVersionSourceStatus:d(`latest_version_source_status`,{enum:[`fresh`,`cached`,`error`]}).notNull().default(`error`),updatedAt:l(`updated_at`).notNull()});function X(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}function Z(e){return{clientId:e.clientId,activeVersion:e.activeVersion??null,latestAvailableVersion:e.latestAvailableVersion??null,latestVersionLastCheckedAt:e.latestVersionLastCheckedAt??null,latestVersionSourceStatus:e.latestVersionSourceStatus,updatedAt:e.updatedAt}}function At(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}async function jt(e,t){await e.insert(J).values(At(t)).onConflictDoNothing({target:[J.clientId,J.version]})}function Mt(e,t,n){return{clientId:e,activeVersion:t,latestAvailableVersion:null,latestVersionLastCheckedAt:null,latestVersionSourceStatus:`error`,updatedAt:n}}async function Nt(e,t,n,r){await e.insert(Y).values(Mt(t,n,r)).onConflictDoUpdate({target:Y.clientId,set:{activeVersion:n,updatedAt:r}})}async function Pt(e,t){await jt(e,t)}async function Ft(e,t,n,r){return g(e,async e=>{let[i]=await e.select().from(Y).where(h(Y.clientId,t.clientId)).limit(1),a=i?.activeVersion??null;return await jt(e,t),n?(await Nt(e,t.clientId,t.version,r),{previousActiveVersion:a,activeVersion:t.version}):{previousActiveVersion:a,activeVersion:a}})}async function It(e,t){return g(e,async e=>{let[n]=await e.select().from(Y).where(h(Y.clientId,t)).limit(1),r=await e.select().from(J).where(h(J.clientId,t));return{state:n?Z(n):null,versions:r.map(X)}})}async function Lt(e){return g(e,async e=>{let t=await e.select().from(Y),n=await e.select().from(J);return{states:t.map(Z),versions:n.map(X)}})}async function Rt(e,t){let n={clientId:t.clientId,activeVersion:t.activeVersion??null,latestAvailableVersion:t.latestAvailableVersion??null,latestVersionLastCheckedAt:t.latestVersionLastCheckedAt??null,latestVersionSourceStatus:t.latestVersionSourceStatus,updatedAt:t.updatedAt};await e.insert(Y).values(n).onConflictDoUpdate({target:Y.clientId,set:n})}async function zt(e,t,n,r,i,a){let o=r===null?{latestAvailableVersion:n,latestVersionSourceStatus:i,updatedAt:a}:{latestAvailableVersion:n,latestVersionLastCheckedAt:r,latestVersionSourceStatus:i,updatedAt:a};await e.insert(Y).values({clientId:t,activeVersion:null,latestAvailableVersion:n,latestVersionLastCheckedAt:r,latestVersionSourceStatus:i,updatedAt:a}).onConflictDoUpdate({target:Y.clientId,set:o})}async function Bt(e,t,n,r){return g(e,async e=>{let[i]=await e.select().from(Y).where(h(Y.clientId,t)).limit(1),a=i?.activeVersion??null;return await Nt(e,t,n,r),{previousActiveVersion:a,activeVersion:n}})}async function Vt(e,t,n,r){return g(e,async e=>{let[i]=await e.select().from(Y).where(h(Y.clientId,t)).limit(1),a=i?.activeVersion??null;if(!(((await e.delete(J).where(m(h(J.clientId,t),h(J.version,n)))).rowsAffected??0)>0))return{removedVersion:null,previousActiveVersion:a,activeVersion:a};await e.update(Y).set({activeVersion:null,updatedAt:r}).where(m(h(Y.clientId,t),h(Y.activeVersion,n)));let[o]=await e.select().from(Y).where(h(Y.clientId,t)).limit(1);return{removedVersion:n,previousActiveVersion:a,activeVersion:o?.activeVersion??null}})}function Ht(e,t,n){let r=[e.on(O.insertVersion,async e=>{await Pt(t,e.payload),e.setResult({success:!0})}),e.on(O.recordInstalledVersion,async e=>{let{versionRecord:n,makeActive:r,updatedAt:i}=e.payload,a=await Ft(t,n,r,i);e.setResult(a)}),e.on(O.listVersions,async e=>{let n=await t.select().from(J).where(h(J.clientId,e.payload.clientId));e.setResult({versions:n.map(X)})}),e.on(O.getSnapshot,async e=>{let{state:n,versions:r}=await It(t,e.payload.clientId);e.setResult({state:n,versions:r})}),e.on(O.loadAllVersions,async e=>{let n=await t.select().from(J);e.setResult({versions:n.map(X)})}),e.on(O.upsertState,async e=>{await Rt(t,e.payload),e.setResult({success:!0})}),e.on(O.setActiveVersion,async e=>{let{clientId:n,activeVersion:r,updatedAt:i}=e.payload,a=await Bt(t,n,r,i);e.setResult(a)}),e.on(O.getState,async e=>{let[n]=await t.select().from(Y).where(h(Y.clientId,e.payload.clientId)).limit(1);e.setResult({state:n?Z(n):null})}),e.on(O.loadAllState,async e=>{let n=await t.select().from(Y);e.setResult({states:n.map(Z)})}),e.on(O.loadSnapshot,async e=>{let{states:n,versions:r}=await Lt(t);e.setResult({states:n,versions:r})}),e.on(O.updateFeedCache,async e=>{let{clientId:n,latestAvailableVersion:r,latestVersionLastCheckedAt:i,latestVersionSourceStatus:a,updatedAt:o}=e.payload;await zt(t,n,r,i,a,o),e.setResult({success:!0})}),e.on(O.removeVersionAndClearActive,async e=>{let{clientId:n,version:r,updatedAt:i}=e.payload,a=await Vt(t,n,r,i);e.setResult(a)})];return()=>{for(let e of r)e()}}const Q=u(`client_profiles`,{id:d(`id`).primaryKey(),clientId:d(`client_id`).notNull(),name:d(`name`).notNull(),description:d(`description`),configDir:d(`config_dir`).notNull(),isDefault:l(`is_default`,{mode:`boolean`}).notNull().default(!1),createdAt:l(`created_at`).notNull(),updatedAt:l(`updated_at`).notNull()},e=>[p(`uq_client_profiles_client_name`).on(e.clientId,e.name),p(`uq_client_profiles_default`).on(e.clientId).where(te`${e.isDefault} = 1`),c(`idx_client_profiles_client_id`).on(e.clientId)]);function $(e){return{id:e.id,clientId:e.clientId,name:e.name,description:e.description??null,configDir:e.configDir,isDefault:e.isDefault,createdAt:e.createdAt,updatedAt:e.updatedAt}}async function Ut(e,t,n){let r=Date.now();return g(e,async e=>{let[i]=await e.select().from(Q).where(m(h(Q.clientId,t),h(Q.name,n))).limit(1);if(i===void 0)return null;await e.update(Q).set({isDefault:!1,updatedAt:r}).where(m(h(Q.clientId,t),h(Q.isDefault,!0))),await e.update(Q).set({isDefault:!0,updatedAt:r}).where(m(h(Q.clientId,t),h(Q.name,n)));let[a]=await e.select().from(Q).where(m(h(Q.clientId,t),h(Q.name,n))).limit(1);return a===void 0?null:$(a)})}function Wt(e,t,n){let r=[e.on(K.get,async e=>{let{clientId:n,name:r}=e.payload,[i]=await t.select().from(Q).where(m(h(Q.clientId,n),h(Q.name,r))).limit(1);e.setResult({record:i?$(i):null})}),e.on(K.getById,async e=>{let[n]=await t.select().from(Q).where(h(Q.id,e.payload.id)).limit(1);e.setResult({record:n?$(n):null})}),e.on(K.list,async e=>{let n=await t.select().from(Q).where(h(Q.clientId,e.payload.clientId));e.setResult({records:n.map($)})}),e.on(K.set,async e=>{let n=e.payload,r={id:n.id,clientId:n.clientId,name:n.name,description:n.description??null,configDir:n.configDir,isDefault:n.isDefault,createdAt:n.createdAt,updatedAt:n.updatedAt};await t.insert(Q).values(r).onConflictDoUpdate({target:Q.id,set:{name:n.name,description:n.description??null,configDir:n.configDir,isDefault:n.isDefault,updatedAt:n.updatedAt}}),e.setResult({success:!0})}),e.on(K.delete,async e=>{let{clientId:n,name:r}=e.payload,i=await t.delete(Q).where(m(h(Q.clientId,n),h(Q.name,r)));e.setResult({success:(i.rowsAffected??0)>0})}),e.on(K.clearDefault,async e=>{await t.update(Q).set({isDefault:!1,updatedAt:Date.now()}).where(m(h(Q.clientId,e.payload.clientId),h(Q.isDefault,!0))),e.setResult({success:!0})}),e.on(K.setDefault,async e=>{let{clientId:n,name:r}=e.payload,i=await Ut(t,n,r);e.setResult({record:i})})];return()=>{for(let e of r)e()}}var Gt=class{runtimeService;binaryManager;profileService;sessionConfigService;constructor(e,t,n,r){this.runtimeService=e,this.binaryManager=t,this.profileService=n,this.sessionConfigService=r}async init(){let e=(await Promise.allSettled([this.runtimeService.init(),this.binaryManager.init(),this.profileService.init(),this.sessionConfigService.init()])).filter(e=>e.status===`rejected`);if(e.length>0){for(let t=1;t<e.length;t++)console.warn(`[ClientsCoreService] Multiple init failures, secondary:`,e[t].reason);throw e[0].reason}}async destroy(){let e=(await Promise.allSettled([this.runtimeService.destroy(),this.binaryManager.destroy(),this.profileService.destroy(),this.sessionConfigService.destroy()])).filter(e=>e.status===`rejected`);for(let t of e)console.warn(`[ClientsCoreService] destroy failure:`,t.reason)}};const Kt=i(`makaio.clients-core`);function qt(e){let t=[],n=()=>{for(let e of[...t].reverse())e()};try{for(let n of e)t.push(n())}catch(e){throw n(),e}return n}function Jt(e={}){let{definitions:n=[],strategyDependencies:r,postInstallHandlers:i}=e,a=[...n];return{name:`makaio.clients-core`,displayName:`Clients Core`,version:`0.1.0`,critical:!0,namespaces:[D,R,G],storage:{registerHandlers:ne((e,t,n)=>qt([()=>kt(e,t,n),()=>Ht(e,t,n),()=>Wt(e,t,n)]))},create:e=>{let n=new j(a),o=t.join(e.makaioHome,`clients`),s=new He(e.bus,{basePath:t.join(e.makaioHome,`binaries`),configBasePath:o,postInstallHandlers:i},n,r),c=new gt(e.bus,o),l=new St(e.bus,o);return new Gt(new lt(e.bus),s,c,l)}}}async function Yt(e){let t=await r.requestOptional(v.resolveBinary,{clientId:e});return t.handled?t.data:void 0}function Xt(e,t,n){return[...n??[],e,...t].map($t).join(` `)}function Zt(e,t,n,r){return Xt(e,[...t.split(` `),n],r)}function Qt(e){return e.runtimeCapabilities.hookEvents.filter(e=>e.frameworkSubject!==void 0).map(e=>({eventName:e.name}))}function $t(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}export{rt as AbsolutePathSchema,me as BinaryNotFoundError,I as CLIENT_RUNTIME_STATUSES,he as ClientAccountRegistry,Se as ClientBinaryFeedCache,Re as ClientBinaryJobRunner,He as ClientBinaryManager,T as ClientBinaryStateRecordSchema,D as ClientBinaryStorageNamespace,O as ClientBinaryStorageSubjects,w as ClientBinaryVersionRecordSchema,we as ClientBinaryVersionResolver,j as ClientDefinitionRegistry,U as ClientProfileRecordSchema,gt as ClientProfileService,G as ClientProfileStorageNamespace,K as ClientProfileStorageSubjects,V as ClientRuntimeRegistry,lt as ClientRuntimeService,R as ClientRuntimeStorageNamespace,z as ClientRuntimeStorageSubjects,St as ClientSessionConfigService,ie as ClientSubjects,st as ClientWiringAggregatedResultSchema,at as ClientWiringApplyResponseSchema,y as ClientWiringEntrySchema,it as ClientWiringListResponseSchema,ot as ClientWiringRemoveResponseSchema,Gt as ClientsCoreService,Kt as ClientsCoreToken,qe as RawClientHookPayloadSchema,L as RuntimeRecordSchema,ct as assertAbsoluteProjectDir,de as atomicModifyFile,Xt as buildClientCommand,Qe as buildClientSessionBase,Zt as buildHookCommand,H as canonicalizeClientId,Et as createClientNamespace,nt as createClientWiringListSubjectDef,tt as createClientWiringSubjectDef,Jt as createClientsCorePackage,Ye as createRawClientHookReceivedSubject,Qt as deriveSessionEventDescriptors,$e as emitBestEffort,k as isPathWithinBase,Ze as pickNonEmptyString,Xe as pickNonEmptyStringValue,qt as registerStorageHandlersWithRollback,A as resolveAndValidateBasePath,Yt as resolveClientBinary};
1
+ import{z as e}from"zod";import*as t from"node:path";import{createBusNamespace as n}from"@makaio/framework/core";import{MakaioBus as r}from"@makaio/framework/bus";import{extensionToken as i,isUniversalRange as a,versionSatisfies as o}from"@makaio/framework/contracts";import{BaseService as s}from"@makaio/framework/service-base";import{index as c,integer as l,sqliteTable as u,text as d,unique as f,uniqueIndex as p}from"drizzle-orm/sqlite-core";import{and as m,eq as h,gt as ee,sql as te}from"drizzle-orm";import{executeTransaction as g,registerDrizzleHandlers as ne}from"@makaio/framework/storage/drizzle";import{ClientProfileNameSchema as _,ClientProfileSchema as re,ClientSubjects as ie,ClientSubjects as v,ClientWiringEntrySchema as ae,ManagedInstallDescriptorSchema as oe,SessionConfigIdSchema as se}from"@makaio/framework/contracts/client";import{randomUUID as y}from"node:crypto";import*as b from"node:fs/promises";import*as x from"node:os";import{CLIDetectionSubjects as ce}from"@makaio/framework/services/cli-detection/namespace";import{ClientStorageSubjects as le}from"@makaio/framework/services/settings/storage";import{SessionSubjects as ue}from"@makaio/framework/contracts/session";async function de(e,t,n,r,i){let a,o=(n.get(e)??Promise.resolve()).then(async()=>{let n=await i(r(await fe(e,t)));n.changed&&await pe(e,n.content),a=n.result}),s=o.then(()=>void 0,()=>void 0);n.set(e,s);try{await o}finally{n.get(e)===s&&n.delete(e)}return a}async function fe(e,t){let n;try{n=await b.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return t;throw e}return JSON.parse(n)}async function pe(e,n){let r=t.dirname(e),i=t.join(r,`${t.basename(e)}.${y()}.tmp`);await b.mkdir(r,{recursive:!0});try{await b.writeFile(i,`${JSON.stringify(n,null,2)}\n`,`utf-8`),await b.rename(i,e)}catch(e){throw await b.unlink(i).catch(()=>void 0),e}}var me=class e extends Error{code=`BINARY_NOT_FOUND`;constructor(t){super(`client.resolveBinary: no binary found for client '${t}' — install a managed version or ensure the binary is on PATH`),this.name=`BinaryNotFoundError`,Error.captureStackTrace?.(this,e)}},he=class{nextAccountSequence=1;accountIdsByIdentifier=new Map;accounts=new Map;upsertAccount(e){let t=_e(e.displayLabel),n=new Map;for(let t of e.identifiers)n.set(ge(e.clientId,t.scheme,t.value),t);let r=ve(n,this.accountIdsByIdentifier,`strong`),i=ve(n,this.accountIdsByIdentifier,`alias`),a=r[0]??(i.length===1?i[0]:i.length>1?ye(i):this.createAccount()),o=(r.length>0?xe(a,r,i):[]).flatMap(e=>this.mergeInto(a,e)),s=this.accounts.get(a);if(!s)throw Error(`Client account registry invariant violated: missing account ${a}`);for(let[e,t]of n){let n=this.accountIdsByIdentifier.get(e);r.length===0&&t.strength===`alias`&&n!==void 0&&n!==a||(s.identifiers.set(e,t),this.accountIdsByIdentifier.set(e,a))}return t!==void 0&&(s.displayLabel=t),{clientAccountId:a,displayLabel:s.displayLabel,mergedAccountIds:o}}clear(){this.accountIdsByIdentifier.clear(),this.accounts.clear(),this.nextAccountSequence=1}createAccount(){let e=`client-account-${this.nextAccountSequence}`;return this.nextAccountSequence+=1,this.accounts.set(e,{clientAccountId:e,identifiers:new Map}),e}mergeInto(e,t){if(e===t)return[];let n=this.accounts.get(e),r=this.accounts.get(t);if(!n||!r)return[];for(let[t,i]of r.identifiers)n.identifiers.set(t,i),this.accountIdsByIdentifier.set(t,e);return n.displayLabel===void 0&&r.displayLabel!==void 0&&(n.displayLabel=r.displayLabel),this.accounts.delete(t),[t]}};function ge(e,t,n){return`${e}\u0000${t}\u0000${n}`}function _e(e){return e?.trim()||void 0}function ve(e,t,n){let r=new Set;for(let[i,a]of e){if(a.strength!==n)continue;let e=t.get(i);e!==void 0&&r.add(e)}return Array.from(r).sort(S)}function ye(e){return[...e].sort(S)[0]}function S(e,t){let n=be(e),r=be(t);return n!==null&&r!==null&&n!==r?n-r:e.localeCompare(t)}function be(e){let t=e.match(/^client-account-(\d+)$/);return t?Number(t[1]):null}function xe(e,t,n){let r=new Set([...t,...n]);return r.delete(e),Array.from(r).sort(S)}function Se(e){return{subject:`config.prime`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}async function C(e,t){let n=await e.requestOptional(Se(t.clientId),t);return n.handled?n.data:{primed:!1}}function Ce(){let e=e=>async()=>{throw Error(`StrategyDependencies.${e} is not implemented`)};return{fetchText:e(`fetchText`),fetchJson:e(`fetchJson`),downloadFile:e(`downloadFile`),exec:e(`exec`),extractArchive:e(`extractArchive`),deleteFile:e(`deleteFile`),computeChecksum:e(`computeChecksum`),removeDirectory:e(`removeDirectory`)}}var we=class{resolveInstallVersion(e,t,n){let r=t.version;if(n===void 0)return{version:r,explicit:!1};let i=n.trim();if(i.length===0)throw Error(`Explicit version returned an empty version string`);if(i!==r)throw Error(`client.install: requested version ${i} for client '${e}' does not match pinned version ${r}`);return{version:i,explicit:!0}}};function Te(e){if(e!==void 0)return(t,n)=>{n!==null&&n>0?e(`downloading`,t/n*100):e(`downloading`,null)}}var Ee=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t,n){if(e!==this.#e.version)throw Error(`npm managed install requested version ${e} but descriptor pins ${this.#e.version}`);n?.(`installing`,null);let r=`${this.#e.package}@${this.#e.version}`;return await this.#t.exec(`npm`,[`install`,r,`--prefix`,t,`--no-save`,`--ignore-scripts`]),n?.(`installing`,100),{installPath:t,version:this.#e.version,strategy:`npm`}}};function De(){if(process.platform!==`linux`)return!1;try{let e=process.report?.getReport?.();if(typeof e!=`object`||!e||!(`header`in e))return!0;let{header:t}=e;return typeof t!=`object`||!t?!0:!(`glibcVersionRuntime`in t)}catch{return!1}}function Oe(e){return e.replace(/[^0-9a-fA-F]/g,``).toUpperCase()}function w(e,t,n,r){let i=e.replaceAll(`{version}`,t);return n!==void 0&&(i=i.replaceAll(`{platform}`,n)),r!==void 0&&(i=i.replaceAll(`{binary}`,r)),i}function ke(e){let t=`${e.platform}-${e.arch}`;return e.platform===`linux`&&e.isMusl?`${t}-musl`:t}function Ae(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Signed manifest must be a JSON object`);let n=e,r=n.version;if(r!==t)throw Error(`Signed manifest version ${String(r)} does not match descriptor pin ${t}`);let i=n.platforms;if(typeof i!=`object`||!i||Array.isArray(i))throw Error(`Signed manifest must contain a platforms object`);return{version:r,platforms:i}}function je(e,t){let n=e.platforms[t];if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`Signed manifest does not contain a platform entry for '${t}'`);let{binary:r,checksum:i}=n;if(typeof r!=`string`||!Me(r))throw Error(`Manifest entry for '${t}' has unsafe binary filename`);if(typeof i!=`string`||i.length===0)throw Error(`Manifest entry for '${t}' is missing a valid 'checksum' field`);return{binary:r,checksum:i}}function Me(e){return e.length>0&&e!==`.`&&e!==`..`&&!e.includes(`/`)&&!e.includes(`\\`)}var Ne=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n={platform:n?.platform??process.platform,arch:n?.arch??process.arch,isMusl:n?.isMusl??De()}}async execute(e,n,r){if(e!==this.#e.version)throw Error(`signed-binary-bucket managed install requested version ${e} but descriptor pins ${this.#e.version}`);let{config:i}=this.#e,a=ke(this.#n),o=i.platforms[a];if(o===void 0)throw Error(`signed-binary-bucket descriptor has no platform entry for '${a}'. Supported platforms: ${Object.keys(i.platforms).join(`, `)}`);await b.mkdir(n,{recursive:!0});let s=t.join(n,`.gnupg`),c=t.join(n,`signing-key.asc`),l=t.join(n,`manifest.json`),u=t.join(n,`manifest.json.sig`);r?.(`resolving`,null),await this.#r(i,e,c,l,u),r?.(`verifying`,null);let d=await this.#i(i,s,c,l,u,a);r?.(`downloading`,null);let f=w(i.binaryPathTemplate,e,o,d.binary),p=t.resolve(n,d.binary);await this.#t.downloadFile(`${i.baseUrl}/${f}`,p,Te(r)),r?.(`verifying`,null);let m=await this.#t.computeChecksum(p);if(m!==d.checksum)throw Error(`Binary checksum mismatch: expected ${d.checksum} but computed ${m}`);return r?.(`installing`,null),this.#n.platform!==`win32`&&await b.chmod(p,493),await this.#t.removeDirectory(s),await this.#t.deleteFile(c),await this.#t.deleteFile(u),r?.(`installing`,100),{installPath:n,version:this.#e.version,strategy:`signed-binary-bucket`}}async#r(e,t,n,r,i){let a=`${e.baseUrl}/${w(e.manifestPathTemplate,t)}`,o=`${e.baseUrl}/${w(e.manifestSignaturePathTemplate,t)}`,s=await this.#t.fetchText(e.publicKeyUrl);await b.writeFile(n,s,`utf-8`),await this.#t.downloadFile(a,r),await this.#t.downloadFile(o,i)}async#i(e,t,n,r,i,a){await b.mkdir(t,{recursive:!0,mode:448}),await this.#t.exec(`gpg`,[`--homedir`,t,`--import`,n]);let o=await this.#t.exec(`gpg`,[`--homedir`,t,`--with-colons`,`--fingerprint`,`--list-keys`]),s=this.#a(o);if(Oe(s)!==Oe(e.publicKeyFingerprint))throw Error(`GPG key fingerprint mismatch: expected ${e.publicKeyFingerprint} but got ${s}`);await this.#t.exec(`gpg`,[`--homedir`,t,`--verify`,i,r]).catch(e=>{throw Error(`Manifest GPG signature verification failed: ${e.message}`)});let c=await b.readFile(r,`utf-8`);return je(Ae(JSON.parse(c),this.#e.version),a)}#a(e){for(let t of e.split(`
2
+ `)){let e=t.split(`:`);if(e[0]===`fpr`&&e[9]!==void 0&&e[9].length>0)return e[9]}throw Error(`Could not extract GPG key fingerprint from output`)}};function Pe(e,t){let n=oe.safeParse(e);if(n.success)switch(n.data.type){case`npm`:return new Ee(n.data,t);case`signed-binary-bucket`:return new Ne(n.data,t)}}function Fe(e,n){let r=t.relative(e,n);return r!==``&&!r.startsWith(`..${t.sep}`)&&r!==`..`&&!t.isAbsolute(r)}function T(e,n){return!t.isAbsolute(e)||!t.isAbsolute(n)?!1:Fe(t.resolve(e),t.resolve(n))}function E(e,n){if(!e||!t.isAbsolute(e))throw Error(`${n} requires a non-empty absolute basePath`);return t.resolve(e)}async function Ie(e,n,r,i){let[a,...o]=r;if(Re(a))throw Error(`versionCommand[0] must be a relative path; received absolute path "${a}"`);if(a.split(/[/\\]/).includes(`..`))throw Error(`versionCommand[0] must not contain path traversal segments; received "${a}"`);let s=t.normalize(a),c=t.join(n,s),l=await b.realpath(n),u=await b.realpath(c);if(!Fe(l,u))throw Error(`versionCommand[0] must not escape the install directory; "${a}" resolves outside installPath`);let d;try{d=await e(u,o,{cwd:l})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Version verification failed: command "${c}" exited with an error: ${t}`,{cause:e})}let f=Le(i);if(!ze(d,f))throw Error(`Version mismatch: expected "${i}" but command output was "${d.trim()}"`)}function Le(e){return e[0]===`v`||e[0]===`V`?e.slice(1):e}function Re(e){return e.startsWith(`/`)||/^[A-Za-z]:[/\\]/.test(e)||e.startsWith(`\\`)}function ze(e,t){return(e.match(/[A-Za-z0-9][A-Za-z0-9._+-]*/g)??[]).some(e=>Le(e)===t)}var Be=class{strategyDeps;config;jobs=new Map;#e=!1;resolvedBasePath;constructor(e,t){this.strategyDeps=e,this.config=t,this.resolvedBasePath=E(t.basePath,`ClientBinaryJobRunner`)}startJob(e,t,n,r,i,a,o){let s={...e,status:`running`};return this.jobs.set(e.jobId,s),this.runJob(s,t,n,r,i,a,o),e.jobId}cancelAll(){this.#e=!0,this.jobs.clear()}safeOnProgress(e,t){try{e(t)}catch{}}emitProgressIfActive(e,t){return this.#e?!1:(this.safeOnProgress(e,t),!this.#e)}async runJob(e,t,n,r,i,a,o){try{let s=this.resolveTargetDir(e.clientId,e.version),c=Pe(t,this.strategyDeps);if(c===void 0)throw Error(`Unsupported managed install descriptor type: ${t.type}`);let l=await this.executeStrategy(e,c,s,n);if(this.#e)return;let u;try{if(u=await this.runPostInstall(e,l.installPath,a,n),this.#e)return;o!==void 0&&await this.runVersionVerification(e,l.installPath,o,n)}catch(e){throw this.#e||await this.cleanupStagedArtifact(l.installPath),e}if(this.#e)return;await this.finalizeSuccess(e,l,u,n,r,i)}catch(t){if(this.#e)return;let n=t instanceof Error?t.message:String(t),r=t instanceof Error&&`code`in t?String(t.code):void 0;try{await i({jobId:e.jobId,clientId:e.clientId,version:e.version,strategy:e.strategy,status:`error`,activeVersion:null,error:{message:n,...r===void 0?{}:{code:r}}})}catch{}}finally{this.jobs.delete(e.jobId)}}async finalizeSuccess(e,t,n,r,i,a){if(!(e.makeActive&&!this.emitProgressIfActive(r,{jobId:e.jobId,clientId:e.clientId,version:t.version,strategy:e.strategy,stage:`activating`,progress:null,installPath:t.installPath,activeAfterCompletion:!0}))&&!this.#e){try{await i({jobId:e.jobId,clientId:e.clientId,version:t.version,installPath:t.installPath,makeActive:e.makeActive,reason:e.reason})}catch(e){try{await this.strategyDeps.removeDirectory(t.installPath)}catch{}throw e}if(!this.#e)try{await a({jobId:e.jobId,clientId:e.clientId,version:t.version,strategy:e.strategy,status:`success`,installPath:t.installPath,activeVersion:e.makeActive?t.version:null,...n===void 0?{}:{metadata:{postInstall:n}}})}catch{}}}async cleanupStagedArtifact(e){try{await this.strategyDeps.removeDirectory(e)}catch{}}async executeStrategy(e,t,n,r){try{return await t.execute(e.version,n,(t,i)=>{this.emitProgressIfActive(r,{jobId:e.jobId,clientId:e.clientId,version:e.version,strategy:e.strategy,stage:t,progress:i,installPath:t===`installing`?n:void 0,activeAfterCompletion:e.makeActive})})}catch(e){throw this.#e||await this.cleanupStagedArtifact(n),e}}async runPostInstall(e,t,n,r){if(n===void 0)return;let i=this.resolvePostInstallHandler(n),a=this.buildProgressPayload(e,`post-install`,null,t,{kind:n.kind});if(!this.emitProgressIfActive(r,a))return;let o=await i({clientId:e.clientId,version:e.version,installPath:t,descriptor:n});return this.emitProgressIfActive(r,this.buildProgressPayload(e,`post-install`,100,t,{kind:n.kind,...o??{}})),o??void 0}async runVersionVerification(e,t,n,r){this.emitProgressIfActive(r,this.buildProgressPayload(e,`verifying`,null,t,{kind:`version-command`}))&&(this.#e||await Ie(this.strategyDeps.exec,t,n,e.version))}resolvePostInstallHandler(e){let t=this.config.postInstallHandlers?.get(e.kind);if(t===void 0)throw Error(`No post-install handler registered for kind "${e.kind}"`);return t}buildProgressPayload(e,t,n,r,i){return{jobId:e.jobId,clientId:e.clientId,version:e.version,strategy:e.strategy,stage:t,progress:n,installPath:r,activeAfterCompletion:e.makeActive,...i===void 0?{}:{metadata:i}}}resolveTargetDir(e,n){let r=t.resolve(this.resolvedBasePath,e,n);if(!T(this.resolvedBasePath,r))throw Error(`Invalid install target path for client "${e}" and version "${n}"`);return r}};const D=e.object({id:e.string(),clientId:e.string(),version:e.string(),installPath:e.string(),installedAt:e.number().int().nonnegative(),createdAt:e.number().int().nonnegative()}),O=e.object({clientId:e.string(),activeVersion:e.string().nullable(),updatedAt:e.number().int().nonnegative()}),k=e.object({previousActiveVersion:e.string().nullable(),activeVersion:e.string().nullable()}),A=n(`client-binary:storage`,{insertVersion:{request:D,response:e.object({success:e.boolean()})},recordInstalledVersion:{request:e.object({versionRecord:D,makeActive:e.boolean(),updatedAt:e.number().int().nonnegative()}),response:k},listVersions:{request:e.object({clientId:e.string()}),response:e.object({versions:e.array(D)})},getSnapshot:{request:e.object({clientId:e.string()}),response:e.object({state:O.nullable(),versions:e.array(D)})},loadAllVersions:{request:e.object({}),response:e.object({versions:e.array(D)})},upsertState:{request:O,response:e.object({success:e.boolean()})},setActiveVersion:{request:e.object({clientId:e.string(),activeVersion:e.string().nullable(),updatedAt:e.number().int().nonnegative()}),response:k},getState:{request:e.object({clientId:e.string()}),response:e.object({state:O.nullable()})},loadAllState:{request:e.object({}),response:e.object({states:e.array(O)})},loadSnapshot:{request:e.object({}),response:e.object({states:e.array(O),versions:e.array(D)})},removeVersionAndClearActive:{request:e.object({clientId:e.string(),version:e.string(),updatedAt:e.number().int().nonnegative()}),response:k.extend({removedVersion:e.string().nullable()})}}),j=A.subjects;var M=class{definitions=new Map;constructor(e=[]){for(let t of e)this.registerUnique(t)}getDefinition(e){return this.definitions.get(e)}listDefinitions(){return[...this.definitions.values()]}register(e){this.definitions.set(e.id,e)}registerUnique(e){if(this.definitions.has(e.id))throw Error(`ClientDefinitionRegistry: duplicate client definition id '${e.id}'`);this.definitions.set(e.id,e)}};function N(e,t,n,r,i){if(n===null){if(a(r))return;throw Error(`${e}: ${i} for client '${t}' did not report a version; requires ${r}`)}if(!o(n,r))throw Error(`${e}: ${i} ${n} for client '${t}' does not satisfy ${r}`)}var Ve=class{bus;resolvedBasePath;resolvedConfigBasePath;definitionLookup;constructor(e){this.bus=e.bus,this.resolvedBasePath=e.resolvedBasePath,this.resolvedConfigBasePath=e.resolvedConfigBasePath,this.definitionLookup=e.definitionLookup}async resolve(e){let t=this.definitionLookup.getDefinition(e);if(t===void 0)throw Error(`client.resolveBinary: no definition registered for client '${e}'`);let{state:n,versions:r}=await this.bus.request(j.getSnapshot,{clientId:e}),i=n?.activeVersion??null;return i===null?this.buildGlobalContext(e,t):this.buildManagedContext(e,i,t,r)}isInstallPathWithinBase(e){return T(this.resolvedBasePath,e)}async isExpectedInstallPath(e,n,r){if(!t.isAbsolute(e)||!this.isInstallPathWithinBase(e))return!1;let i=t.resolve(this.resolvedBasePath,n,r);if(!this.isInstallPathWithinBase(i))return!1;try{let[t,n,r]=await Promise.all([b.realpath(this.resolvedBasePath),b.realpath(i),b.realpath(e)]);return T(t,n)?r===n||T(n,r):!1}catch{return!1}}async buildManagedContext(e,n,r,i){let a=i.find(e=>e.version===n);if(a===void 0)throw Error(`client.resolveBinary: active version '${n}' is not installed for client '${e}'`);if(!await this.isExpectedInstallPath(a.installPath,e,n))throw Error(`client.resolveBinary: stored installPath "${a.installPath}" does not match the expected install directory for ${e}@${n}`);r.binary!==void 0&&N(`client.resolveBinary`,e,n,r.binary.supportedVersions,`managed binary version`);let o=P(r.versionCommand)?.[0];if(o===void 0)throw Error(`client.resolveBinary: definition for '${e}' has no versionCommand — cannot derive binary path`);let s=t.resolve(a.installPath,o),c=t.resolve(a.installPath);if(!s.startsWith(c+t.sep)&&s!==c)throw Error(`client.resolveBinary: versionCommand for '${e}' resolves outside the install directory`);let{configDir:l,env:u}=this.resolveIsolatedConfig(e,r);return{binaryPath:s,env:u,configDir:l,source:`managed`,version:n}}async buildGlobalContext(e,t){if(!t.binary?.name)throw Error(`client.resolveBinary: definition for '${e}' has no binary.name — cannot scan PATH`);let n={clientId:e,binaryName:t.binary.name,supportedVersions:t.binary.supportedVersions},{results:r}=await this.bus.request(v.scan,{targets:[n]}),i=r.find(t=>t.clientId===e);if(i===void 0||!i.found)throw new me(e);let a=i.version??null;return N(`client.resolveBinary`,e,a,t.binary.supportedVersions,`detected global binary version`),{binaryPath:null,env:{},configDir:this.resolveGlobalConfigDir(t),source:`global`,version:a}}resolveIsolatedConfig(e,n){let{configIsolation:r}=n;if(r===void 0)return{configDir:null,env:{}};let i=t.join(this.resolvedConfigBasePath,e,`config`),a=r.pathKind===`file`?t.join(i,t.basename(r.defaultPath)):i;return{configDir:i,env:{[r.envVar]:a}}}resolveGlobalConfigDir(e){let{configIsolation:n}=e;if(n===void 0)return null;let r=n.defaultPath,i=r===`~`?x.homedir():r.startsWith(`~/`)?t.join(x.homedir(),r.slice(2)):r,a=n.pathKind===`file`?t.dirname(i):i;if(!t.isAbsolute(a))throw Error(`ConfigIsolation defaultPath for '${e.id}' resolved to non-absolute path '${i}'; use an absolute or tilde-expanded path (e.g. '~/.myapp')`);return a}};function P(e){if(e===void 0)return;let{executable:t,args:n}=e,r=typeof t==`string`?t:t[process.platform]??t.default;if(typeof r!=`string`||r.trim()===``)throw Error(`client.resolveBinary: versionCommand executable is missing for this platform`);return[r,...n]}async function He(e,t){let{versions:n,states:r}=await e.request(j.loadSnapshot,{}),i=Map.groupBy(n,e=>e.clientId),a=new Map;for(let e of r)a.set(e.clientId,e.activeVersion);let o=new Map;for(let e of t.listDefinitions())e.managedInstall!==void 0&&o.set(e.id,e.managedInstall);return[...new Set(o.keys())].map(e=>{let t=o.get(e);if(t===void 0)throw Error(`assembleBinaryList: missing descriptor for client '${e}'`);let n=a.get(e)??null,r=(i.get(e)??[]).map(e=>({version:e.version,installPath:e.installPath,installedAt:e.installedAt,isActive:e.version===n})),s=t.version;return{clientId:e,installedVersions:r,activeVersion:n,pinnedVersion:s,updateAvailable:n!==null&&n!==s}})}var Ue=class extends s{config;definitionLookup;versionResolver;jobRunner;strategyDeps;resolvedBasePath;resolvedConfigBasePath;resolver;pendingClients=new Set;constructor(e=r,t,n=new M([]),i=Ce()){super(e),this.config=t,this.definitionLookup=n,this.resolvedBasePath=E(t.basePath,`ClientBinaryManager`),this.resolvedConfigBasePath=E(t.configBasePath,`ClientBinaryManager configBasePath`),this.strategyDeps=i,this.versionResolver=new we,this.jobRunner=new Be(i,t),this.resolver=new Ve({bus:e,resolvedBasePath:this.resolvedBasePath,resolvedConfigBasePath:this.resolvedConfigBasePath,definitionLookup:n})}async onInit(){this.registerHandler(v.list,async e=>{let t=await this.handleList();e.setResult({clients:t})}),this.registerHandler(v.install,async e=>{let t=await this.handleInstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(v.update,async e=>{let t=await this.handleUpdate(e.payload.clientId);e.setResult(t)}),this.registerHandler(v.setActive,async e=>{let t=await this.handleSetActive(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(v.uninstall,async e=>{let t=await this.handleUninstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(v.resolveBinary,async e=>{let t=await this.resolver.resolve(e.payload.clientId);e.setResult(t)})}onDestroy(){this.jobRunner.cancelAll(),this.pendingClients.clear()}async handleList(){return He(this.bus,this.definitionLookup)}async handleInstall(e,t){let{definition:n,descriptor:r}=this.requireManagedDefinition(e,`client.install`);return this.withClientLock(e,async()=>{let{version:i}=this.versionResolver.resolveInstallVersion(e,r,t);return n.binary!==void 0&&N(`client.install`,e,i,n.binary.supportedVersions,t===void 0?`resolved binary version`:`requested binary version`),{jobId:this.startInstallJob(e,i,r,n,!1,`install`),requestedVersion:t??null,resolvedVersion:i}})}async handleUpdate(e){let{definition:t,descriptor:n}=this.requireManagedDefinition(e,`client.update`);return this.withClientLock(e,async()=>{let{version:r}=this.versionResolver.resolveInstallVersion(e,n);return t.binary!==void 0&&N(`client.update`,e,r,t.binary.supportedVersions,`resolved binary version`),{jobId:this.startInstallJob(e,r,n,t,!0,`update`),resolvedVersion:r}})}async handleSetActive(e,t){if(this.pendingClients.has(e))throw Error(`Operation already in progress for client "${e}"`);this.pendingClients.add(e);try{let{versions:n}=await this.bus.request(j.listVersions,{clientId:e}),r=n.find(e=>e.version===t);if(r===void 0)throw Error(`client.setActive: version '${t}' is not installed for client '${e}'`);let i=this.definitionLookup.getDefinition(e);if(i===void 0)throw Error(`client.setActive: no definition registered for client '${e}'`);i.binary!==void 0&&N(`client.setActive`,e,t,i.binary.supportedVersions,`requested binary version`);let a=P(i.versionCommand);if(a===void 0)throw Error(`client.setActive: no versionCommand registered for client '${e}'`);if(!await this.resolver.isExpectedInstallPath(r.installPath,e,t))throw Error(`client.setActive: stored installPath "${r.installPath}" does not match the expected install directory for ${e}@${t}`);return await Ie(this.strategyDeps.exec,r.installPath,a,t),await this.patchActiveVersion(e,t,`set-active`),{clientId:e,activeVersion:t}}finally{this.pendingClients.delete(e)}}async handleUninstall(e,n){if(this.pendingClients.has(e))throw Error(`Operation already in progress for client "${e}"`);this.pendingClients.add(e);try{let{versions:r}=await this.bus.request(j.listVersions,{clientId:e}),i=r.find(e=>e.version===n);if(i===void 0)throw Error(`client.uninstall: version '${n}' is not installed for client '${e}'`);let{removedVersion:a,previousActiveVersion:o,activeVersion:s}=await this.bus.request(j.removeVersionAndClearActive,{clientId:e,version:n,updatedAt:Date.now()});if(a===null)throw Error(`client.uninstall: failed to delete version '${n}' for client '${e}'`);let c=i.installPath,l=typeof c==`string`&&c.length>0?t.resolve(c):null;if(typeof c!=`string`||c.length===0||l===null||!t.isAbsolute(c)||!await this.resolver.isExpectedInstallPath(l,e,n)?console.warn(`[ClientBinaryManager] Skipping removeDirectory: stored installPath "${String(c)}" does not match the expected install directory for ${e}@${n}`):await this.strategyDeps.removeDirectory(l).catch(t=>{console.warn(`[ClientBinaryManager] Failed to remove binary directory "${l}" for ${e}@${n}:`,t)}),o!==null&&s===null)try{await this.bus.emit(v.version.changed,{clientId:e,previousActiveVersion:o,activeVersion:null,reason:`uninstall`})}catch(e){console.warn(`[ClientBinaryManager] Failed to emit client.version.changed:`,e)}return{clientId:e,removedVersion:n,activeVersion:s}}finally{this.pendingClients.delete(e)}}async patchActiveVersion(e,t,n){let r=(await this.bus.request(j.setActiveVersion,{clientId:e,activeVersion:t,updatedAt:Date.now()})).previousActiveVersion;if(r!==t)try{await this.bus.emit(v.version.changed,{clientId:e,previousActiveVersion:r,activeVersion:t,reason:n})}catch(e){console.warn(`[ClientBinaryManager] Failed to emit client.version.changed:`,e)}return r}requireManagedDefinition(e,t){let n=this.definitionLookup.getDefinition(e);if(n===void 0)throw Error(`${t}: no definition registered for client '${e}'`);let r=n.managedInstall;if(r===void 0)throw Error(`${t}: client '${e}' does not declare a managed install descriptor`);return{definition:n,descriptor:r}}async withClientLock(e,t){if(this.pendingClients.has(e))throw Error(`Operation already in progress for client "${e}"`);this.pendingClients.add(e);try{return await t()}catch(t){throw this.pendingClients.delete(e),t}}startInstallJob(e,t,n,r,i,a){let o={jobId:crypto.randomUUID(),clientId:e,version:t,strategy:n.type,status:`pending`,makeActive:i,reason:a};return this.jobRunner.startJob(o,n,e=>{this.bus.emit(v.installJob.progress,e).catch(e=>{console.warn(`[ClientBinaryManager] Failed to emit client.installJob.progress:`,e)})},this.makeCompletionCallback(),async e=>{this.pendingClients.delete(e.clientId),await this.bus.emit(v.installJob.completed,e).catch(e=>{console.warn(`[ClientBinaryManager] Failed to emit client.installJob.completed:`,e)})},r.postInstall,P(r.versionCommand)),o.jobId}makeCompletionCallback(){return async({clientId:e,version:t,installPath:n,makeActive:r,reason:i})=>{let a=Date.now();await C(this.bus,{clientId:e,configDir:this.resolveManagedConfigDir(e),phase:`managed-install`,binaryVersion:t});let o=await this.bus.request(j.recordInstalledVersion,{versionRecord:{id:crypto.randomUUID(),clientId:e,version:t,installPath:n,installedAt:a,createdAt:a},makeActive:r,updatedAt:a});if(r&&o.previousActiveVersion!==o.activeVersion)try{await this.bus.emit(v.version.changed,{clientId:e,previousActiveVersion:o.previousActiveVersion,activeVersion:o.activeVersion,reason:i})}catch(e){console.warn(`[ClientBinaryManager] Failed to emit client.version.changed:`,e)}}}resolveManagedConfigDir(e){return t.join(this.resolvedConfigBasePath,e,`config`)}};function F(e,t){return`${e}${t}`}function I(e,t){return`${e}${t}`}var We=class{records=new Map;bySupervisorSessionId=new Map;byPidClientId=new Map;byAdapterSessionClientId=new Map;set(e){let t=this.records.get(e.clientRuntimeId);t&&this.removeIndexEntries(t),this.records.set(e.clientRuntimeId,e),this.addIndexEntries(e)}setFromStorage(e,t,n){this.records.set(e.clientRuntimeId,e),e.supervisorSessionId!==void 0&&this.bySupervisorSessionId.set(e.supervisorSessionId,e.clientRuntimeId),t-e.updatedAt<=n&&(e.pid!==void 0&&this.byPidClientId.set(F(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.set(I(e.adapterSessionId,e.clientId),e.clientRuntimeId))}delete(e){let t=this.records.get(e);t&&(this.removeIndexEntries(t),this.records.delete(e))}get(e){return this.records.get(e)}findByEvidence(e,t,n,r){if(e!==void 0){let t=this.bySupervisorSessionId.get(e);if(t!==void 0)return this.records.get(t)}if(t!==void 0){let e=this.byPidClientId.get(F(t,r));if(e!==void 0)return this.records.get(e)}if(n!==void 0){let e=this.byAdapterSessionClientId.get(I(n,r));if(e!==void 0)return this.records.get(e)}}values(){return this.records.values()}clear(){this.records.clear(),this.bySupervisorSessionId.clear(),this.byPidClientId.clear(),this.byAdapterSessionClientId.clear()}get size(){return this.records.size}addIndexEntries(e){e.supervisorSessionId!==void 0&&this.bySupervisorSessionId.set(e.supervisorSessionId,e.clientRuntimeId),e.pid!==void 0&&this.byPidClientId.set(F(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.set(I(e.adapterSessionId,e.clientId),e.clientRuntimeId)}removeIndexEntries(e){e.supervisorSessionId!==void 0&&this.bySupervisorSessionId.delete(e.supervisorSessionId),e.pid!==void 0&&this.byPidClientId.delete(F(e.pid,e.clientId)),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.delete(I(e.adapterSessionId,e.clientId))}};const L=[`observed`,`started`],R=e.object({clientRuntimeId:e.string(),clientId:e.string(),status:e.enum(L),supervisorSessionId:e.string().optional(),pid:e.number().int().positive().optional(),parentPid:e.number().int().positive().optional(),adapterSessionId:e.string().optional(),sessionId:e.string().optional(),cwd:e.string().optional(),argv:e.array(e.string()).optional(),metadata:e.record(e.string(),e.unknown()).optional(),observedAt:e.number().int().nonnegative(),createdAt:e.number().int().nonnegative(),updatedAt:e.number().int().nonnegative()}),z=n(`client-runtime:storage`,{upsert:{request:R,response:e.object({success:e.boolean()})},loadAll:{request:e.object({}),response:e.object({records:e.array(R)})}}),B=z.subjects;function Ge(e){return e.supervisorSessionId!==void 0||e.adapterSessionId!==void 0}function V(e){return{...e,argv:e.argv===void 0?void 0:[...e.argv],metadata:e.metadata===void 0?void 0:structuredClone(e.metadata)}}function Ke(e){return Math.max(Date.now(),e+1)}function qe(e,t){let n=!1;return t.supervisorSessionId!==void 0&&e.supervisorSessionId!==t.supervisorSessionId&&(e.supervisorSessionId=t.supervisorSessionId,n=!0),t.pid!==void 0&&e.pid!==t.pid&&(e.pid=t.pid,n=!0),t.parentPid!==void 0&&e.parentPid!==t.parentPid&&(e.parentPid=t.parentPid,n=!0),t.adapterSessionId!==void 0&&e.adapterSessionId!==t.adapterSessionId&&(e.adapterSessionId=t.adapterSessionId,n=!0),t.sessionId!==void 0&&e.sessionId!==t.sessionId&&(e.sessionId=t.sessionId,n=!0),t.cwd!==void 0&&e.cwd!==t.cwd&&(e.cwd=t.cwd,n=!0),t.argv!==void 0&&JSON.stringify(e.argv)!==JSON.stringify(t.argv)&&(e.argv=[...t.argv],n=!0),t.metadata!==void 0&&JSON.stringify(e.metadata)!==JSON.stringify(t.metadata)&&(e.metadata=structuredClone(t.metadata),n=!0),n}var Je=class{runtimeMap=new We;bus;constructor(e){this.bus=e}async loadFromStorage(){if(!this.bus)return;let e=await this.bus.requestOptional(B.loadAll,{});if(!e.handled)return;let t=Date.now();for(let n of e.data.records)this.runtimeMap.setFromStorage(V(n),t,864e5)}async upsertRuntime(e){let t=this.runtimeMap.findByEvidence(e.supervisorSessionId,e.pid,e.adapterSessionId,e.clientId);if(t){let n=t.status===`observed`,r=n&&Ge(e),i=qe(t,e),a=n&&e.observedAt>t.observedAt;return r&&(t.status=`started`),(i||r||a)&&(t.updatedAt=Ke(t.updatedAt),a&&(t.observedAt=e.observedAt),this.runtimeMap.set(t),await this.persistRecord(t)),{clientRuntimeId:t.clientRuntimeId,created:!1,promoted:r,record:V(t)}}let n=Date.now(),r=y(),i=Ge(e)?`started`:`observed`,a={clientRuntimeId:r,clientId:e.clientId,status:i,supervisorSessionId:e.supervisorSessionId,pid:e.pid,parentPid:e.parentPid,adapterSessionId:e.adapterSessionId,sessionId:e.sessionId,cwd:e.cwd,argv:e.argv?[...e.argv]:void 0,metadata:e.metadata?structuredClone(e.metadata):void 0,observedAt:e.observedAt,createdAt:n,updatedAt:n};return this.runtimeMap.set(a),await this.persistRecord(a),{clientRuntimeId:r,created:!0,promoted:!1,record:V(a)}}getRuntime(e){let t=this.runtimeMap.get(e);return t?V(t):void 0}clear(){this.runtimeMap.clear()}get size(){return this.runtimeMap.size}async persistRecord(e){this.bus&&await this.bus.requestOptional(B.upsert,V(e))}};const Ye=e.object({eventName:e.string(),receivedAt:e.number().int().finite().nonnegative().describe(`Unix epoch timestamp in milliseconds`),payload:e.record(e.string(),e.unknown()),metadata:e.record(e.string(),e.unknown()).optional()}),Xe=/^[a-z0-9-]+$/;function H(e,t=`canonicalizeClientId`){let n=e.trim().toLowerCase(),r=n.startsWith(`client:`)?n.slice(7):n;if(r.length===0)throw Error(`[${t}] clientId must be a non-empty string`);if(!Xe.test(r))throw Error(`[${t}] clientId must contain only lowercase letters, numbers, and hyphens after an optional client: prefix`);return r}function Ze(e){return{subject:`hook.received`,$meta:{namespace:`client:${H(e,`createRawClientHookReceivedSubject`)}`,isRequest:!1,local:!1,channel:!1}}}function Qe(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function $e(e,t){return Qe(e[t])}function et(e){return{clientId:e.clientId,source:`adapter-derived`,observedAt:Date.now(),...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.adapterSessionId!==void 0&&{adapterSessionId:e.adapterSessionId}}}function tt(e){try{e().catch(nt)}catch(e){nt(e)}}function nt(e){(process.env.DEBUG||process.env.MAKAIO_DEBUG)&&console.debug(`[emitBestEffort] observed-semantics emission failed`,e)}function rt(e,t){return{subject:t,$meta:{namespace:`client:${H(e,`createClientWiringSubjectDef`)}`,isRequest:!0,local:!1,channel:!1}}}function it(e){return rt(e,`wiring.list`)}const at=e.string().min(1).refine(t.isAbsolute,{message:`projectDir must be an absolute path`}),ot=e.object({entries:e.array(ae)}),st=e.object({applied:e.number().int().nonnegative(),skipped:e.number().int().nonnegative()}),ct=e.object({removed:e.number().int().nonnegative()}),lt=e.object({clientId:e.string().trim().min(1),entries:e.array(ae)});function ut(e){if(e!==void 0&&!t.isAbsolute(e))throw Error(`projectDir must be an absolute path, got: ${e}`)}var dt=class extends s{accountRegistry;runtimeRegistry;latestSnapshots=new Map;activeIdentities=new Map;constructor(e=r,t=new he,n=new Je(e)){super(e),this.accountRegistry=t,this.runtimeRegistry=n}async onInit(){await this.runtimeRegistry.loadFromStorage(),this.registerHandler(v.account.observe,e=>this.handleAccountObserve(e)),this.registerHandler(v.usage.ingest,e=>this.handleUsageIngest(e)),this.registerHandler(v.scan,async e=>{let t=await this.scanClients(e.payload.targets);e.setResult({results:t})}),this.registerHandler(v.runtime.observe,e=>this.handleRuntimeObserve(e)),this.registerHandler(v.wiring.list,async e=>{let t=await this.listWirings(e.payload);e.setResult({results:t})}),this.registerHandler(v.account.activate,e=>{this.activeIdentities.set(e.payload.clientId,{clientAccountId:e.payload.clientAccountId,identifiers:e.payload.identifiers,displayLabel:e.payload.displayLabel}),e.setResult({accepted:!0})}),this.registerHandler(v.account.getActive,e=>{let t=this.activeIdentities.get(e.payload.clientId);e.setResult({identity:t??null})})}onDestroy(){this.latestSnapshots.clear(),this.activeIdentities.clear(),this.accountRegistry.clear(),this.runtimeRegistry.clear()}getLatestSnapshot(e){return this.latestSnapshots.get(e)}async handleAccountObserve(e){let t=this.accountRegistry.upsertAccount({clientId:e.payload.clientId,identifiers:e.payload.identifiers,displayLabel:e.payload.displayLabel}),n=this.latestSnapshots.get(t.clientAccountId),r=mt(this.consolidateMergedSnapshots(t.clientAccountId,t.mergedAccountIds)??n,t.displayLabel);r&&this.latestSnapshots.set(t.clientAccountId,r),r&&(t.mergedAccountIds.length>0||r!==n)&&await this.bus.emit(v.usage.snapshot,r),e.setResult({clientAccountId:t.clientAccountId,displayLabel:t.displayLabel})}async handleUsageIngest(e){let t=this.accountRegistry.upsertAccount({clientId:e.payload.clientId,identifiers:e.payload.account.identifiers,displayLabel:e.payload.account.displayLabel});this.consolidateMergedSnapshots(t.clientAccountId,t.mergedAccountIds);let n=ft(t.clientAccountId,e.payload,t.displayLabel),r=mt(pt(this.latestSnapshots.get(t.clientAccountId),n),t.displayLabel);this.latestSnapshots.set(t.clientAccountId,r),await this.bus.emit(v.usage.snapshot,r),e.setResult({clientAccountId:t.clientAccountId,snapshot:r})}async handleRuntimeObserve(e){let{payload:t}=e;if(t.supervisorSessionId===void 0&&t.pid===void 0&&t.adapterSessionId===void 0)throw Error(`client.runtime.observe: at least one hard-evidence field is required (supervisorSessionId, pid, or adapterSessionId)`);let{record:n,...r}=await this.runtimeRegistry.upsertRuntime(t);(r.created||r.promoted)&&await this.bus.emit(v.runtime.started,{clientRuntimeId:n.clientRuntimeId,clientId:n.clientId,status:n.status,source:t.source,observedAt:t.observedAt,supervisorSessionId:n.supervisorSessionId,pid:n.pid,parentPid:n.parentPid,adapterSessionId:n.adapterSessionId,sessionId:n.sessionId,cwd:n.cwd,argv:n.argv,metadata:n.metadata}),e.setResult({clientRuntimeId:r.clientRuntimeId,created:r.created,promoted:r.promoted})}async scanClients(e){let t=e??await this.listScannableStoredClients();if(t.length===0)return[];let n=Array.from(new Set(t.map(e=>e.binaryName))),{results:r}=await this.bus.request(ce.scan,{binaries:n}),i=new Map(r.map(e=>[e.binary,e]));return t.map(e=>{let t=i.get(e.binaryName),n=t?.found??!1,r=t?.version;return{clientId:e.clientId,found:n,version:r,warningMessage:gt(n,r,e.supportedVersions)}})}async listScannableStoredClients(){let{clients:e}=await this.bus.request(le.list,{});return e.filter(ht).map(e=>({clientId:e.id,binaryName:e.binary.name,supportedVersions:e.binary.supportedVersions}))}async listWirings(e){ut(e.projectDir);let{clients:t}=await this.bus.request(le.list,{}),n=e.clientId===void 0?void 0:H(e.clientId,`listWirings`),r=t.filter(e=>e.enabled).filter(e=>n===void 0||e.id===n),i=await Promise.allSettled(r.map(async t=>{let n=it(t.id),r=await this.bus.requestOptional(n,{projectDir:e.projectDir,makaioCommand:e.makaioCommand});return r.handled?{clientId:t.id,entries:r.data.entries}:null}));for(let e=0;e<i.length;e++){let t=i[e];if(t.status===`rejected`){let n=t.reason instanceof Error?t.reason.message:String(t.reason);console.warn(`[ClientRuntimeService] wiring.list for ${r[e].id} failed: ${n}`)}}return i.filter(e=>e.status===`fulfilled`).map(e=>e.value).filter(e=>e!==null)}consolidateMergedSnapshots(e,t){let n=this.latestSnapshots.get(e),r=!1;for(let i of t){if(i===e)continue;let t=this.latestSnapshots.get(i);t&&(n===void 0||t.observedAt>n.observedAt)&&(n={...t,clientAccountId:e},r=!0),this.latestSnapshots.delete(i)}return n&&this.latestSnapshots.set(e,n),r?n:void 0}};function ft(e,t,n){return{clientAccountId:e,clientId:t.clientId,observedAt:t.observedAt,source:t.source,displayLabel:n,usage:{windows:t.usage.windows.map(e=>({...e}))},metadata:t.metadata?{...t.metadata}:void 0}}function pt(e,t){return e&&e.observedAt>t.observedAt?e:t}function mt(e,t){return!e||t===void 0||e.displayLabel===t?e:{...e,displayLabel:t}}function ht(e){return e.enabled&&e.binary!==void 0}function gt(e,t,n){if(e&&t!==void 0&&t!==`unknown`&&n!==void 0&&!o(t,n))return`Unsupported version: requires ${n}`}var _t=class extends s{constructor(e=r){super(e)}onInit(){this.registerHandler(v.config.prime,async e=>{e.setResult(await C(this.bus,e.payload))})}};const U=re,W=e.string().trim().min(1),G=n(`client-profile:storage`,{get:{request:e.object({clientId:W,name:_}),response:e.object({record:U.nullable()})},getById:{request:e.object({id:W}),response:e.object({record:U.nullable()})},list:{request:e.object({clientId:W}),response:e.object({records:e.array(U)})},set:{request:U,response:e.object({success:e.boolean()})},delete:{request:e.object({clientId:W,name:_}),response:e.object({success:e.boolean()})},clearDefault:{request:e.object({clientId:W}),response:e.object({success:e.boolean()})},setDefault:{request:e.object({clientId:W,name:_}),response:e.object({record:U.nullable()})}}),K=G.subjects;function vt(e,n,r){let i=t.resolve(e),a=t.resolve(n),o=t.relative(i,a);if(o!==``&&!o.startsWith(`..`)&&!t.isAbsolute(o))return a;throw Error(`${r} refused to access path outside client profile root`)}var yt=class extends s{clientsBasePath;constructor(e,t){super(e),this.clientsBasePath=t}async onInit(){this.registerCreateHandler(),this.registerListHandler(),this.registerGetHandler(),this.registerUpdateHandler(),this.registerDeleteHandler(),this.registerSetDefaultHandler()}registerCreateHandler(){this.registerHandler(v.profile.create,async e=>{let n=H(e.payload.clientId,`profile.create`),{name:r,description:i}=e.payload;if((await this.bus.request(K.get,{clientId:n,name:r})).record!==null)throw Error(`Profile '${r}' already exists for client '${n}'`);let a=t.join(this.clientsBasePath,n,`profiles`),o=vt(a,t.join(a,r),`profile.create`);await b.mkdir(o,{recursive:!0});try{await C(this.bus,{clientId:n,configDir:o,phase:`profile-create`});let t=Date.now(),a={id:y(),clientId:n,name:r,description:i??null,configDir:o,isDefault:!1,createdAt:t,updatedAt:t};await this.bus.request(K.set,a),e.setResult({profile:a})}catch(e){throw await b.rm(o,{recursive:!0,force:!0}),e}})}registerListHandler(){this.registerHandler(v.profile.list,async e=>{let t=H(e.payload.clientId,`profile.list`),n=await this.bus.request(K.list,{clientId:t});e.setResult({profiles:n.records})})}registerGetHandler(){this.registerHandler(v.profile.get,async e=>{let t=H(e.payload.clientId,`profile.get`),n=await this.bus.request(K.get,{clientId:t,name:e.payload.name});e.setResult({profile:n.record})})}registerUpdateHandler(){this.registerHandler(v.profile.update,async e=>{let t=H(e.payload.clientId,`profile.update`),{name:n,description:r}=e.payload,i=await this.bus.request(K.get,{clientId:t,name:n});if(i.record===null)throw Error(`Profile '${n}' not found for client '${t}'`);let a={...i.record,description:r===void 0?i.record.description:r,updatedAt:Date.now()};await this.bus.request(K.set,a),e.setResult({profile:a})})}registerDeleteHandler(){this.registerHandler(v.profile.delete,async e=>{let n=H(e.payload.clientId,`profile.delete`),{name:r}=e.payload,i=await this.bus.request(K.get,{clientId:n,name:r});i.record!==null&&(vt(t.join(this.clientsBasePath,n,`profiles`),i.record.configDir,`profile.delete`),await b.rm(i.record.configDir,{recursive:!0,force:!0}));let a=await this.bus.request(K.delete,{clientId:n,name:r});e.setResult({success:a.success})})}registerSetDefaultHandler(){this.registerHandler(v.profile.setDefault,async e=>{let t=H(e.payload.clientId,`profile.setDefault`),{name:n}=e.payload,r=await this.bus.request(K.setDefault,{clientId:t,name:n});if(r.record===null)throw Error(`Profile '${n}' not found for client '${t}'`);e.setResult({profile:r.record})})}};function bt(e){return{subject:`sessionConfig.setup`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}function xt(e){return{subject:`sessionConfig.destroy`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}const St=()=>Date.now();function Ct(){let e=x.platform();if(e===`darwin`||e===`linux`||e===`win32`)return e;throw Error(`client.sessionConfig does not support platform '${e}'`)}function wt(e,n,r){let i=se.safeParse(n);if(!i.success)throw Error(`${r} received an unsafe session ID`);let a=t.resolve(e),o=t.resolve(a,i.data),s=t.relative(a,o);if(s===``||!s.startsWith(`..`)&&!t.isAbsolute(s))return o;throw Error(`${r} refused to access path outside client sessions root`)}var Tt=class extends s{clientsBasePath;getNow;constructor(e,t,n=St){super(e),this.clientsBasePath=t,this.getNow=n}async onInit(){this.registerHandler(v.sessionConfig.create,async e=>{let{clientId:t,sessionId:n,profileName:r,baseConfigDir:i,projectDir:a,configInheritance:o=`full`}=e.payload,s=H(t,`sessionConfig.create`),c=this.resolveClientSessionDir(s,n,`sessionConfig.create`);await b.mkdir(c,{recursive:!0});try{let t=await this.resolveBaseConfigDir(s,c,r,i),n=bt(s),l=await this.bus.requestOptional(n,{sessionDir:c,baseConfigDir:t,projectDir:a,platform:Ct(),configInheritance:o}),u=l.handled?l.data.env??{}:{};await C(this.bus,{clientId:s,configDir:c,phase:`session-create`,projectDir:a}),e.setResult({sessionDir:c,env:u})}catch(e){throw await b.rm(c,{recursive:!0,force:!0}),e}}),this.registerHandler(v.sessionConfig.destroy,async e=>{let{clientId:t,sessionId:n}=e.payload,r=H(t,`sessionConfig.destroy`),i=this.resolveClientSessionDir(r,n,`sessionConfig.destroy`);await this.destroyClientSessionDir(r,i),e.setResult({success:!0})}),this.registerHandler(v.sessionConfig.cleanup,async e=>{let{clientId:t}=e.payload,n=t===void 0?void 0:H(t,`sessionConfig.cleanup`),r=await this.cleanupOrphanedDirs(n);e.setResult({removed:r})}),this.registerHandler(ue.closed,async e=>{await this.destroySessionDirsForSessionId(e.payload.sessionId)}),await this.cleanupOrphanedDirs()}async resolveBaseConfigDir(e,t,n,r){if(r!==void 0)return r;if(n!==void 0){let t=await this.bus.request(K.get,{clientId:e,name:n});if(t.record!==null)return t.record.configDir;throw Error(`Profile '${n}' not found for client '${e}'`)}let i=(await this.bus.request(K.list,{clientId:e})).records.find(e=>e.isDefault);return i?i.configDir:t}async cleanupOrphanedDirs(e){let n=[],r=this.getNow(),i=e===void 0?await this.listClientIds():[e];return await Promise.all(i.map(async e=>{let i=t.join(this.clientsBasePath,e,`sessions`),a=await b.readdir(i).catch(()=>[]);await Promise.all(a.map(async t=>{try{let a=wt(i,t,`sessionConfig.cleanup`),o=await b.stat(a),s=o.birthtimeMs>0?o.birthtimeMs:o.ctimeMs;o.isDirectory()&&r-s>36e5&&!await this.isActiveSession(t)&&(await this.destroyClientSessionDir(e,a),n.push(a))}catch{}}))})),n}async destroySessionDirsForSessionId(e){if(!se.safeParse(e).success)return;let t=await this.listClientIds();await Promise.all(t.map(async t=>{let n=this.resolveClientSessionDir(t,e,`session.closed`);await this.destroyClientSessionDir(t,n)}))}async destroyClientSessionDir(e,t){await b.stat(t).then(e=>e.isDirectory(),e=>{let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e})&&(await this.bus.requestOptional(xt(e),{sessionDir:t,platform:Ct()}),await b.rm(t,{recursive:!0,force:!0}))}async isActiveSession(e){let t=await this.bus.requestOptional(ue.get,{sessionId:e});return t.handled&&t.data.session?.status===`active`}resolveClientSessionDir(e,n,r){return wt(t.join(this.clientsBasePath,e,`sessions`),n,r)}async listClientIds(){return(await b.readdir(this.clientsBasePath,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()).map(e=>e.name)}};function Et(e,t){return r.registerNamespace(n(`client:${e}`,{"hook.received":Ye,...t})).subjects}function Dt(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||!(e in n))return!1;n=n[e]}return!0}function Ot(e,t,n){let r=Object.keys(n).filter(e=>!Dt(t,e));if(r.length!==0)throw Error(`[createClientNamespace] client:${e} was already registered without required subjects: ${r.join(`, `)}`)}function kt(e,t){let n=H(e,`createClientNamespace`),r=t??{},i=Et(n,r);return Ot(n,i,r),{namespaceDomain:`client:${n}`,subjects:i}}const q=u(`client_runtimes`,{id:d(`id`).primaryKey(),clientId:d(`client_id`).notNull(),status:d(`status`).notNull(),supervisorSessionId:d(`supervisor_session_id`),pid:l(`pid`),parentPid:l(`parent_pid`),adapterSessionId:d(`adapter_session_id`),sessionId:d(`session_id`),cwd:d(`cwd`),argv:d(`argv`,{mode:`json`}).$type(),metadata:d(`metadata`,{mode:`json`}).$type(),observedAt:l(`observed_at`).notNull(),createdAt:l(`created_at`).notNull(),updatedAt:l(`updated_at`).notNull()},e=>[c(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),c(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),c(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)]),At=new Set(L);function jt(e){if(!At.has(e.status))throw Error(`Unknown ClientRuntimeStatus in DB: '${e.status}'`);return{clientRuntimeId:e.id,clientId:e.clientId,status:e.status,supervisorSessionId:e.supervisorSessionId??void 0,pid:e.pid??void 0,parentPid:e.parentPid??void 0,adapterSessionId:e.adapterSessionId??void 0,sessionId:e.sessionId??void 0,cwd:e.cwd??void 0,argv:e.argv??void 0,metadata:e.metadata??void 0,observedAt:e.observedAt,createdAt:e.createdAt,updatedAt:e.updatedAt}}function Mt(e,t,n){let r=e.on(B.upsert,async e=>{let n=e.payload,r={clientId:n.clientId,status:n.status,supervisorSessionId:n.supervisorSessionId??null,pid:n.pid??null,parentPid:n.parentPid??null,adapterSessionId:n.adapterSessionId??null,sessionId:n.sessionId??null,cwd:n.cwd??null,argv:n.argv??null,metadata:n.metadata??null,observedAt:n.observedAt,updatedAt:n.updatedAt};await t.insert(q).values({id:n.clientRuntimeId,createdAt:n.createdAt,...r}).onConflictDoUpdate({target:q.id,set:r,setWhere:ee(te`excluded.updated_at`,q.updatedAt)}),e.setResult({success:!0})}),i=e.on(B.loadAll,async e=>{let n=await t.select().from(q);e.setResult({records:n.map(jt)})});return()=>{r(),i()}}const J=u(`client_binary_versions`,{id:d(`id`).primaryKey(),clientId:d(`client_id`).notNull(),version:d(`version`).notNull(),installPath:d(`install_path`).notNull(),installedAt:l(`installed_at`).notNull(),createdAt:l(`created_at`).notNull()},e=>[c(`idx_client_binary_versions_client_id`).on(e.clientId),f(`uq_client_binary_versions_client_version`).on(e.clientId,e.version)]),Y=u(`client_binary_state`,{clientId:d(`client_id`).primaryKey(),activeVersion:d(`active_version`),updatedAt:l(`updated_at`).notNull()});function X(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}function Z(e){return{clientId:e.clientId,activeVersion:e.activeVersion??null,updatedAt:e.updatedAt}}function Nt(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}async function Pt(e,t){await e.insert(J).values(Nt(t)).onConflictDoNothing({target:[J.clientId,J.version]})}function Ft(e,t,n){return{clientId:e,activeVersion:t,updatedAt:n}}async function It(e,t,n,r){await e.insert(Y).values(Ft(t,n,r)).onConflictDoUpdate({target:Y.clientId,set:{activeVersion:n,updatedAt:r}})}async function Lt(e,t){await Pt(e,t)}async function Rt(e,t,n,r){return g(e,async e=>{let[i]=await e.select().from(Y).where(h(Y.clientId,t.clientId)).limit(1),a=i?.activeVersion??null;return await Pt(e,t),n?(await It(e,t.clientId,t.version,r),{previousActiveVersion:a,activeVersion:t.version}):{previousActiveVersion:a,activeVersion:a}})}async function zt(e,t){return g(e,async e=>{let[n]=await e.select().from(Y).where(h(Y.clientId,t)).limit(1),r=await e.select().from(J).where(h(J.clientId,t));return{state:n?Z(n):null,versions:r.map(X)}})}async function Bt(e){return g(e,async e=>{let t=await e.select().from(Y),n=await e.select().from(J);return{states:t.map(Z),versions:n.map(X)}})}async function Vt(e,t){let n={clientId:t.clientId,activeVersion:t.activeVersion??null,updatedAt:t.updatedAt};await e.insert(Y).values(n).onConflictDoUpdate({target:Y.clientId,set:n})}async function Ht(e,t,n,r){return g(e,async e=>{let[i]=await e.select().from(Y).where(h(Y.clientId,t)).limit(1),a=i?.activeVersion??null;return await It(e,t,n,r),{previousActiveVersion:a,activeVersion:n}})}async function Ut(e,t,n,r){return g(e,async e=>{let[i]=await e.select().from(Y).where(h(Y.clientId,t)).limit(1),a=i?.activeVersion??null;if(!(((await e.delete(J).where(m(h(J.clientId,t),h(J.version,n)))).rowsAffected??0)>0))return{removedVersion:null,previousActiveVersion:a,activeVersion:a};await e.update(Y).set({activeVersion:null,updatedAt:r}).where(m(h(Y.clientId,t),h(Y.activeVersion,n)));let[o]=await e.select().from(Y).where(h(Y.clientId,t)).limit(1);return{removedVersion:n,previousActiveVersion:a,activeVersion:o?.activeVersion??null}})}function Wt(e,t,n){let r=[e.on(j.insertVersion,async e=>{await Lt(t,e.payload),e.setResult({success:!0})}),e.on(j.recordInstalledVersion,async e=>{let{versionRecord:n,makeActive:r,updatedAt:i}=e.payload,a=await Rt(t,n,r,i);e.setResult(a)}),e.on(j.listVersions,async e=>{let n=await t.select().from(J).where(h(J.clientId,e.payload.clientId));e.setResult({versions:n.map(X)})}),e.on(j.getSnapshot,async e=>{let{state:n,versions:r}=await zt(t,e.payload.clientId);e.setResult({state:n,versions:r})}),e.on(j.loadAllVersions,async e=>{let n=await t.select().from(J);e.setResult({versions:n.map(X)})}),e.on(j.upsertState,async e=>{await Vt(t,e.payload),e.setResult({success:!0})}),e.on(j.setActiveVersion,async e=>{let{clientId:n,activeVersion:r,updatedAt:i}=e.payload,a=await Ht(t,n,r,i);e.setResult(a)}),e.on(j.getState,async e=>{let[n]=await t.select().from(Y).where(h(Y.clientId,e.payload.clientId)).limit(1);e.setResult({state:n?Z(n):null})}),e.on(j.loadAllState,async e=>{let n=await t.select().from(Y);e.setResult({states:n.map(Z)})}),e.on(j.loadSnapshot,async e=>{let{states:n,versions:r}=await Bt(t);e.setResult({states:n,versions:r})}),e.on(j.removeVersionAndClearActive,async e=>{let{clientId:n,version:r,updatedAt:i}=e.payload,a=await Ut(t,n,r,i);e.setResult(a)})];return()=>{for(let e of r)e()}}const Q=u(`client_profiles`,{id:d(`id`).primaryKey(),clientId:d(`client_id`).notNull(),name:d(`name`).notNull(),description:d(`description`),configDir:d(`config_dir`).notNull(),isDefault:l(`is_default`,{mode:`boolean`}).notNull().default(!1),createdAt:l(`created_at`).notNull(),updatedAt:l(`updated_at`).notNull()},e=>[p(`uq_client_profiles_client_name`).on(e.clientId,e.name),p(`uq_client_profiles_default`).on(e.clientId).where(te`${e.isDefault} = 1`),c(`idx_client_profiles_client_id`).on(e.clientId)]);function $(e){return{id:e.id,clientId:e.clientId,name:e.name,description:e.description??null,configDir:e.configDir,isDefault:e.isDefault,createdAt:e.createdAt,updatedAt:e.updatedAt}}async function Gt(e,t,n){let r=Date.now();return g(e,async e=>{let[i]=await e.select().from(Q).where(m(h(Q.clientId,t),h(Q.name,n))).limit(1);if(i===void 0)return null;await e.update(Q).set({isDefault:!1,updatedAt:r}).where(m(h(Q.clientId,t),h(Q.isDefault,!0))),await e.update(Q).set({isDefault:!0,updatedAt:r}).where(m(h(Q.clientId,t),h(Q.name,n)));let[a]=await e.select().from(Q).where(m(h(Q.clientId,t),h(Q.name,n))).limit(1);return a===void 0?null:$(a)})}function Kt(e,t,n){let r=[e.on(K.get,async e=>{let{clientId:n,name:r}=e.payload,[i]=await t.select().from(Q).where(m(h(Q.clientId,n),h(Q.name,r))).limit(1);e.setResult({record:i?$(i):null})}),e.on(K.getById,async e=>{let[n]=await t.select().from(Q).where(h(Q.id,e.payload.id)).limit(1);e.setResult({record:n?$(n):null})}),e.on(K.list,async e=>{let n=await t.select().from(Q).where(h(Q.clientId,e.payload.clientId));e.setResult({records:n.map($)})}),e.on(K.set,async e=>{let n=e.payload,r={id:n.id,clientId:n.clientId,name:n.name,description:n.description??null,configDir:n.configDir,isDefault:n.isDefault,createdAt:n.createdAt,updatedAt:n.updatedAt};await t.insert(Q).values(r).onConflictDoUpdate({target:Q.id,set:{name:n.name,description:n.description??null,configDir:n.configDir,isDefault:n.isDefault,updatedAt:n.updatedAt}}),e.setResult({success:!0})}),e.on(K.delete,async e=>{let{clientId:n,name:r}=e.payload,i=await t.delete(Q).where(m(h(Q.clientId,n),h(Q.name,r)));e.setResult({success:(i.rowsAffected??0)>0})}),e.on(K.clearDefault,async e=>{await t.update(Q).set({isDefault:!1,updatedAt:Date.now()}).where(m(h(Q.clientId,e.payload.clientId),h(Q.isDefault,!0))),e.setResult({success:!0})}),e.on(K.setDefault,async e=>{let{clientId:n,name:r}=e.payload,i=await Gt(t,n,r);e.setResult({record:i})})];return()=>{for(let e of r)e()}}var qt=class{runtimeService;binaryManager;configPrimeService;profileService;sessionConfigService;constructor(e,t,n,r,i){this.runtimeService=e,this.binaryManager=t,this.configPrimeService=n,this.profileService=r,this.sessionConfigService=i}async init(){let e=(await Promise.allSettled([this.runtimeService.init(),this.binaryManager.init(),this.configPrimeService.init(),this.profileService.init(),this.sessionConfigService.init()])).filter(e=>e.status===`rejected`);if(e.length>0){for(let t=1;t<e.length;t++)console.warn(`[ClientsCoreService] Multiple init failures, secondary:`,e[t].reason);throw e[0].reason}}async destroy(){let e=(await Promise.allSettled([this.runtimeService.destroy(),this.binaryManager.destroy(),this.configPrimeService.destroy(),this.profileService.destroy(),this.sessionConfigService.destroy()])).filter(e=>e.status===`rejected`);for(let t of e)console.warn(`[ClientsCoreService] destroy failure:`,t.reason)}};const Jt=i(`makaio.clients-core`);function Yt(e){let t=[],n=()=>{for(let e of[...t].reverse())e()};try{for(let n of e)t.push(n())}catch(e){throw n(),e}return n}function Xt(e={}){let{definitions:n=[],strategyDependencies:r,postInstallHandlers:i}=e,a=[...n];return{name:`makaio.clients-core`,displayName:`Clients Core`,version:`0.1.0`,critical:!0,namespaces:[A,z,G],storage:{registerHandlers:ne((e,t,n)=>Yt([()=>Mt(e,t,n),()=>Wt(e,t,n),()=>Kt(e,t,n)]))},create:e=>{let n=new M(a),o=t.join(e.makaioHome,`clients`),s=new Ue(e.bus,{basePath:t.join(e.makaioHome,`binaries`),configBasePath:o,postInstallHandlers:i},n,r),c=new yt(e.bus,o),l=new Tt(e.bus,o);return new qt(new dt(e.bus),s,new _t(e.bus),c,l)}}}async function Zt(e){let t=await r.requestOptional(v.resolveBinary,{clientId:e});return t.handled?t.data:void 0}function Qt(e,t,n){return[...n??[],e,...t].map(tn).join(` `)}function $t(e,t,n,r){return Qt(e,[...t.split(` `),n],r)}function en(e){return e.runtimeCapabilities.hookEvents.filter(e=>e.frameworkSubject!==void 0).map(e=>({eventName:e.name}))}function tn(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}export{at as AbsolutePathSchema,me as BinaryNotFoundError,L as CLIENT_RUNTIME_STATUSES,he as ClientAccountRegistry,Be as ClientBinaryJobRunner,Ue as ClientBinaryManager,O as ClientBinaryStateRecordSchema,A as ClientBinaryStorageNamespace,j as ClientBinaryStorageSubjects,D as ClientBinaryVersionRecordSchema,we as ClientBinaryVersionResolver,_t as ClientConfigPrimeService,M as ClientDefinitionRegistry,U as ClientProfileRecordSchema,yt as ClientProfileService,G as ClientProfileStorageNamespace,K as ClientProfileStorageSubjects,Je as ClientRuntimeRegistry,dt as ClientRuntimeService,z as ClientRuntimeStorageNamespace,B as ClientRuntimeStorageSubjects,Tt as ClientSessionConfigService,ie as ClientSubjects,lt as ClientWiringAggregatedResultSchema,st as ClientWiringApplyResponseSchema,ae as ClientWiringEntrySchema,ot as ClientWiringListResponseSchema,ct as ClientWiringRemoveResponseSchema,qt as ClientsCoreService,Jt as ClientsCoreToken,Ye as RawClientHookPayloadSchema,R as RuntimeRecordSchema,ut as assertAbsoluteProjectDir,de as atomicModifyFile,Qt as buildClientCommand,et as buildClientSessionBase,$t as buildHookCommand,H as canonicalizeClientId,kt as createClientNamespace,it as createClientWiringListSubjectDef,rt as createClientWiringSubjectDef,Xt as createClientsCorePackage,Ze as createRawClientHookReceivedSubject,en as deriveSessionEventDescriptors,tt as emitBestEffort,T as isPathWithinBase,$e as pickNonEmptyString,Qe as pickNonEmptyStringValue,Yt as registerStorageHandlersWithRollback,E as resolveAndValidateBasePath,Zt as resolveClientBinary};
@@ -29,8 +29,8 @@ declare const ClientRecordSchema: z.ZodObject<{
29
29
  }, z.core.$strip>>>;
30
30
  }, z.core.$strip>>;
31
31
  defaultApprovalPolicy: z.ZodEnum<{
32
- reject: "reject";
33
32
  "always-ask": "always-ask";
33
+ reject: "reject";
34
34
  "full-access": "full-access";
35
35
  }>;
36
36
  logSources: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -84,8 +84,8 @@ declare const ClientStorageNamespace: _$_makaio_storage_core0.StorageNamespaceDe
84
84
  }, z.core.$strip>>>;
85
85
  }, z.core.$strip>>;
86
86
  defaultApprovalPolicy: z.ZodEnum<{
87
- reject: "reject";
88
87
  "always-ask": "always-ask";
88
+ reject: "reject";
89
89
  "full-access": "full-access";
90
90
  }>;
91
91
  logSources: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -127,8 +127,8 @@ declare const ClientStorageNamespace: _$_makaio_storage_core0.StorageNamespaceDe
127
127
  }, z.core.$strip>>>;
128
128
  }, z.core.$strip>>;
129
129
  defaultApprovalPolicy: z.ZodEnum<{
130
- reject: "reject";
131
130
  "always-ask": "always-ask";
131
+ reject: "reject";
132
132
  "full-access": "full-access";
133
133
  }>;
134
134
  logSources: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -172,8 +172,8 @@ declare const ClientStorageNamespace: _$_makaio_storage_core0.StorageNamespaceDe
172
172
  }, z.core.$strip>>>;
173
173
  }, z.core.$strip>>;
174
174
  defaultApprovalPolicy: z.ZodEnum<{
175
- reject: "reject";
176
175
  "always-ask": "always-ask";
176
+ reject: "reject";
177
177
  "full-access": "full-access";
178
178
  }>;
179
179
  logSources: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -219,8 +219,8 @@ declare const ClientStorageSubjects: _$_makaio_core0.BusSubjects<_$_makaio_core0
219
219
  }, z.core.$strip>>>;
220
220
  }, z.core.$strip>>;
221
221
  defaultApprovalPolicy: z.ZodEnum<{
222
- reject: "reject";
223
222
  "always-ask": "always-ask";
223
+ reject: "reject";
224
224
  "full-access": "full-access";
225
225
  }>;
226
226
  logSources: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -262,8 +262,8 @@ declare const ClientStorageSubjects: _$_makaio_core0.BusSubjects<_$_makaio_core0
262
262
  }, z.core.$strip>>>;
263
263
  }, z.core.$strip>>;
264
264
  defaultApprovalPolicy: z.ZodEnum<{
265
- reject: "reject";
266
265
  "always-ask": "always-ask";
266
+ reject: "reject";
267
267
  "full-access": "full-access";
268
268
  }>;
269
269
  logSources: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -307,8 +307,8 @@ declare const ClientStorageSubjects: _$_makaio_core0.BusSubjects<_$_makaio_core0
307
307
  }, z.core.$strip>>>;
308
308
  }, z.core.$strip>>;
309
309
  defaultApprovalPolicy: z.ZodEnum<{
310
- reject: "reject";
311
310
  "always-ask": "always-ask";
311
+ reject: "reject";
312
312
  "full-access": "full-access";
313
313
  }>;
314
314
  logSources: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -1,3 +1,3 @@
1
- import { C as AdapterRuntimeOptionsSchema, D as AdapterNamespace, E as AdapterSessionStatusSchema, O as AdapterSubjects, S as AdapterRuntimeOptions, T as AdapterSessionStatus, _ as RehydrateAgentResponse, a as AgentSelection, b as StartAgentResponse, c as AgentSelectionKindMap, d as SessionDiscoveredSchema, f as SessionLinked, g as RehydrateAgentRequest, h as SessionUsageSchema, i as AdapterSelectionSchema, l as AgentSelectionSchema, m as SessionUsage, n as ProviderContextSchema, o as AgentSelectionBase, p as SessionLinkedSchema, r as AdapterSelection, s as AgentSelectionBaseSchema, t as ProviderContext, u as SessionDiscovered, v as RehydrateAgentSchema, w as AdapterSchemas, x as StartAgentSchema, y as StartAgentRequest } from "../../index-T0471kWA.mjs";
2
- import { a as ROOT_SESSION_LINEAGE_KIND, c as SUBAGENT_SESSION_LINEAGE_KIND, d as SessionLineageKindSchema, f as SessionLineageSchema, i as ForkSessionLineageSchema, l as SessionLineage, n as CompressSessionLineageSchema, o as RootSessionLineageSchema, p as SubagentSessionLineageSchema, r as FORK_SESSION_LINEAGE_KIND, s as SESSION_LINEAGE_KINDS, t as COMPRESS_SESSION_LINEAGE_KIND, u as SessionLineageKind } from "../../session-lineage-Eev4uo4I.mjs";
1
+ import { C as AdapterRuntimeOptionsSchema, D as AdapterNamespace, E as AdapterSessionStatusSchema, O as AdapterSubjects, S as AdapterRuntimeOptions, T as AdapterSessionStatus, _ as RehydrateAgentResponse, a as AgentSelection, b as StartAgentResponse, c as AgentSelectionKindMap, d as SessionDiscoveredSchema, f as SessionLinked, g as RehydrateAgentRequest, h as SessionUsageSchema, i as AdapterSelectionSchema, l as AgentSelectionSchema, m as SessionUsage, n as ProviderContextSchema, o as AgentSelectionBase, p as SessionLinkedSchema, r as AdapterSelection, s as AgentSelectionBaseSchema, t as ProviderContext, u as SessionDiscovered, v as RehydrateAgentSchema, w as AdapterSchemas, x as StartAgentSchema, y as StartAgentRequest } from "../../index-DQWMu5fS.mjs";
2
+ import { a as ROOT_SESSION_LINEAGE_KIND, c as SUBAGENT_SESSION_LINEAGE_KIND, d as SessionLineageKindSchema, f as SessionLineageSchema, i as ForkSessionLineageSchema, l as SessionLineage, n as CompressSessionLineageSchema, o as RootSessionLineageSchema, p as SubagentSessionLineageSchema, r as FORK_SESSION_LINEAGE_KIND, s as SESSION_LINEAGE_KINDS, t as COMPRESS_SESSION_LINEAGE_KIND, u as SessionLineageKind } from "../../session-lineage-B0cpHfuc.mjs";
3
3
  export { AdapterNamespace, AdapterRuntimeOptions, AdapterRuntimeOptionsSchema, AdapterSchemas, AdapterSelection, AdapterSelectionSchema, AdapterSessionStatus, AdapterSessionStatusSchema, AdapterSubjects, AgentSelection, AgentSelectionBase, AgentSelectionBaseSchema, AgentSelectionKindMap, AgentSelectionSchema, COMPRESS_SESSION_LINEAGE_KIND, CompressSessionLineageSchema, FORK_SESSION_LINEAGE_KIND, ForkSessionLineageSchema, ProviderContext, ProviderContextSchema, ROOT_SESSION_LINEAGE_KIND, RehydrateAgentRequest, RehydrateAgentResponse, RehydrateAgentSchema, RootSessionLineageSchema, SESSION_LINEAGE_KINDS, SUBAGENT_SESSION_LINEAGE_KIND, SessionDiscovered, SessionDiscoveredSchema, SessionLineage, SessionLineageKind, SessionLineageKindSchema, SessionLineageSchema, SessionLinked, SessionLinkedSchema, SessionUsage, SessionUsageSchema, StartAgentRequest, StartAgentResponse, StartAgentSchema, SubagentSessionLineageSchema };
@@ -1 +1 @@
1
- import{ct as e,f as t,g as n,i as r,lt as i,n as a,r as o,st as s,ut as c,x as l,xt as u}from"../../schemas-BXstpWVp.mjs";import{COMPRESS_SESSION_LINEAGE_KIND as d,CompressSessionLineageSchema as f,FORK_SESSION_LINEAGE_KIND as p,ForkSessionLineageSchema as m,ROOT_SESSION_LINEAGE_KIND as h,RootSessionLineageSchema as g,SESSION_LINEAGE_KINDS as _,SUBAGENT_SESSION_LINEAGE_KIND as v,SessionLineageKindSchema as y,SessionLineageSchema as b,SubagentSessionLineageSchema as x}from"./schemas/session-lineage.mjs";import{n as S,r as C,t as w}from"../../adapter-CbyjCE2d.mjs";export{w as AdapterNamespace,u as AdapterRuntimeOptionsSchema,C as AdapterSchemas,e as AdapterSelectionSchema,a as AdapterSessionStatusSchema,S as AdapterSubjects,i as AgentSelectionBaseSchema,c as AgentSelectionSchema,d as COMPRESS_SESSION_LINEAGE_KIND,f as CompressSessionLineageSchema,p as FORK_SESSION_LINEAGE_KIND,m as ForkSessionLineageSchema,s as ProviderContextSchema,h as ROOT_SESSION_LINEAGE_KIND,n as RehydrateAgentSchema,g as RootSessionLineageSchema,_ as SESSION_LINEAGE_KINDS,v as SUBAGENT_SESSION_LINEAGE_KIND,r as SessionDiscoveredSchema,y as SessionLineageKindSchema,b as SessionLineageSchema,o as SessionLinkedSchema,t as SessionUsageSchema,l as StartAgentSchema,x as SubagentSessionLineageSchema};
1
+ import{ct as e,f as t,g as n,i as r,lt as i,n as a,r as o,st as s,ut as c,x as l,xt as u}from"../../schemas-Bn8aqDIE.mjs";import{COMPRESS_SESSION_LINEAGE_KIND as d,CompressSessionLineageSchema as f,FORK_SESSION_LINEAGE_KIND as p,ForkSessionLineageSchema as m,ROOT_SESSION_LINEAGE_KIND as h,RootSessionLineageSchema as g,SESSION_LINEAGE_KINDS as _,SUBAGENT_SESSION_LINEAGE_KIND as v,SessionLineageKindSchema as y,SessionLineageSchema as b,SubagentSessionLineageSchema as x}from"./schemas/session-lineage.mjs";import{n as S,r as C,t as w}from"../../adapter-CpF2aK_-.mjs";export{w as AdapterNamespace,u as AdapterRuntimeOptionsSchema,C as AdapterSchemas,e as AdapterSelectionSchema,a as AdapterSessionStatusSchema,S as AdapterSubjects,i as AgentSelectionBaseSchema,c as AgentSelectionSchema,d as COMPRESS_SESSION_LINEAGE_KIND,f as CompressSessionLineageSchema,p as FORK_SESSION_LINEAGE_KIND,m as ForkSessionLineageSchema,s as ProviderContextSchema,h as ROOT_SESSION_LINEAGE_KIND,n as RehydrateAgentSchema,g as RootSessionLineageSchema,_ as SESSION_LINEAGE_KINDS,v as SUBAGENT_SESSION_LINEAGE_KIND,r as SessionDiscoveredSchema,y as SessionLineageKindSchema,b as SessionLineageSchema,o as SessionLinkedSchema,t as SessionUsageSchema,l as StartAgentSchema,x as SubagentSessionLineageSchema};
@@ -1,2 +1,2 @@
1
- import { a as ROOT_SESSION_LINEAGE_KIND, c as SUBAGENT_SESSION_LINEAGE_KIND, d as SessionLineageKindSchema, f as SessionLineageSchema, i as ForkSessionLineageSchema, l as SessionLineage, n as CompressSessionLineageSchema, o as RootSessionLineageSchema, p as SubagentSessionLineageSchema, r as FORK_SESSION_LINEAGE_KIND, s as SESSION_LINEAGE_KINDS, t as COMPRESS_SESSION_LINEAGE_KIND, u as SessionLineageKind } from "../../../session-lineage-Eev4uo4I.mjs";
1
+ import { a as ROOT_SESSION_LINEAGE_KIND, c as SUBAGENT_SESSION_LINEAGE_KIND, d as SessionLineageKindSchema, f as SessionLineageSchema, i as ForkSessionLineageSchema, l as SessionLineage, n as CompressSessionLineageSchema, o as RootSessionLineageSchema, p as SubagentSessionLineageSchema, r as FORK_SESSION_LINEAGE_KIND, s as SESSION_LINEAGE_KINDS, t as COMPRESS_SESSION_LINEAGE_KIND, u as SessionLineageKind } from "../../../session-lineage-B0cpHfuc.mjs";
2
2
  export { COMPRESS_SESSION_LINEAGE_KIND, CompressSessionLineageSchema, FORK_SESSION_LINEAGE_KIND, ForkSessionLineageSchema, ROOT_SESSION_LINEAGE_KIND, RootSessionLineageSchema, SESSION_LINEAGE_KINDS, SUBAGENT_SESSION_LINEAGE_KIND, SessionLineage, SessionLineageKind, SessionLineageKindSchema, SessionLineageSchema, SubagentSessionLineageSchema };
@@ -1,3 +1,3 @@
1
- import { C as ManifestBucketInstallDescriptorSchema, D as PostInstallDescriptorSchema, E as PostInstallDescriptor, S as ManifestBucketInstallDescriptor, T as NpmInstallDescriptorSchema, _ as GithubReleaseInstallDescriptorSchema, a as ClientDefinitionSchema, b as ManagedInstallDescriptor, c as ClientRuntimeCapabilities, d as ClientToolCapabilityAnnotationSchema, f as ClientToolDefinition, g as GithubReleaseInstallDescriptor, h as ConfigIsolationSchema, i as ClientDefinitionInput, l as ClientRuntimeCapabilitiesSchema, m as ConfigIsolation, n as ClientBinaryCompatibilitySchema, o as ClientHookEventDeclaration, p as ClientToolDefinitionSchema, r as ClientDefinition, s as ClientHookEventDeclarationSchema, t as ClientBinaryCompatibility, u as ClientToolCapabilityAnnotation, v as LogSourceDefinition, w as NpmInstallDescriptor, x as ManagedInstallDescriptorSchema, y as LogSourceDefinitionSchema } from "../../definition-DxvZ9e22.mjs";
2
- import { $ as ClientWiringEntry, $t as ClientIdentityObservationSchema, A as SessionConfigSetupResponse, At as ClientUpdateRequest, B as ClientSessionObservedBaseSchema, Bt as InstalledVersionEntrySchema, C as SessionConfigDestroyResponse, Cn as ClientResolveBinaryResponse, Ct as ClientListSchema, D as SessionConfigInheritanceSchema, Dt as ClientUninstallRequest, E as SessionConfigInheritance, Et as ClientSetActiveSchema, F as SessionConfigTeardownResponseSchema, Ft as InstallError, G as ClientSessionToolPre, Gt as ClientAccountIdentifier, H as ClientSessionStartedSchema, Ht as LatestVersionSourceStatusSchema, I as createClientDefinition, It as InstallErrorSchema, J as ClientSessionTurnCompletedSchema, Jt as ClientAccountObserveResponse, K as ClientSessionToolPreSchema, Kt as ClientAccountIdentifierSchema, L as ClientNamespace, Lt as InstallStage, M as SessionConfigTeardownRequest, Mt as ClientUpdateSchema, N as SessionConfigTeardownRequestSchema, Nt as ClientVersionChanged, O as SessionConfigSetupRequest, Ot as ClientUninstallResponse, P as SessionConfigTeardownResponse, Pt as ClientVersionChangedSchema, Q as ClientSessionUserPromptSubmittedSchema, Qt as ClientIdentityObservation, R as ClientSubjects, Rt as InstallStageSchema, S as SessionConfigDestroyRequest, Sn as ClientResolveBinaryRequest, St as ClientListResponse, T as SessionConfigIdSchema, Tt as ClientSetActiveResponse, U as ClientSessionToolPost, Ut as ManagedInstallStrategy, V as ClientSessionStarted, Vt as LatestVersionSourceStatus, W as ClientSessionToolPostSchema, Wt as ManagedInstallStrategySchema, X as ClientSessionTurnStartedSchema, Xt as ClientIdentifierStrength, Y as ClientSessionTurnStarted, Yt as ClientAccountObserveSchema, Z as ClientSessionUserPromptSubmitted, Zt as ClientIdentifierStrengthSchema, _ as ProfileUpdateResponse, _n as ClientUsageWindows, _t as ClientInstallProgressSchema, a as ClientSessionConfigSchemas, an as ClientSessionAccountObserveRequest, at as ClientRuntimeObserveSchema, b as SessionConfigCreateRequest, bn as ClientExecutionContext, bt as ClientInstallSchema, c as ProfileDeleteRequest, cn as ClientSessionLocator, ct as ClientRuntimeSourceLayerSchema, d as ProfileGetResponse, dn as ClientUsageIngestResponse, dt as ClientRuntimeStartedSchema, en as ClientMetadataSchema, et as ClientWiringEntrySchema, f as ProfileListRequest, fn as ClientUsageIngestSchema, ft as ClientBinaryListEntry, g as ProfileUpdateRequest, gn as ClientUsageWindowSchema, gt as ClientInstallProgress, h as ProfileSetDefaultResponse, hn as ClientUsageWindow, ht as ClientInstallCompletedSchema, i as ClientProfileSchemas, in as ClientScanTargetSchema, it as ClientRuntimeObserveResponse, j as SessionConfigSetupResponseSchema, jt as ClientUpdateResponse, k as SessionConfigSetupRequestSchema, kt as ClientUninstallSchema, l as ProfileDeleteResponse, ln as ClientSessionLocatorSchema, lt as ClientRuntimeSourceSchema, m as ProfileSetDefaultRequest, mn as ClientUsageSnapshotSchema, mt as ClientInstallCompleted, n as ClientProfileNameSchema, nn as ClientScanResultSchema, nt as ClientRuntimeEvidenceBaseSchema, o as ProfileCreateRequest, on as ClientSessionAccountObserveResponse, ot as ClientRuntimeSource, p as ProfileListResponse, pn as ClientUsageSnapshot, pt as ClientBinaryListEntrySchema, q as ClientSessionTurnCompleted, qt as ClientAccountObserveRequest, r as ClientProfileSchema, rn as ClientScanTarget, rt as ClientRuntimeObserveRequest, s as ProfileCreateResponse, sn as ClientSessionAccountObserveSchema, st as ClientRuntimeSourceLayer, t as ClientProfile, tn as ClientScanResult, tt as ClientRuntimeEvidenceBase, u as ProfileGetRequest, un as ClientUsageIngestRequest, ut as ClientRuntimeStarted, v as SessionConfigCleanupRequest, vn as ClientUsageWindowsSchema, vt as ClientInstallRequest, w as SessionConfigEnvSchema, wn as ClientResolveBinarySchema, wt as ClientSetActiveRequest, x as SessionConfigCreateResponse, xn as ClientExecutionContextSchema, xt as ClientListRequest, y as SessionConfigCleanupResponse, yn as ClientSchemas, yt as ClientInstallResponse, z as ClientSessionObservedBase, zt as InstalledVersionEntry } from "../../index-C9F3Fc1A.mjs";
3
- export { ClientAccountIdentifier, ClientAccountIdentifierSchema, ClientAccountObserveRequest, ClientAccountObserveResponse, ClientAccountObserveSchema, ClientBinaryCompatibility, ClientBinaryCompatibilitySchema, ClientBinaryListEntry, ClientBinaryListEntrySchema, ClientDefinition, ClientDefinitionInput, ClientDefinitionSchema, ClientExecutionContext, ClientExecutionContextSchema, ClientHookEventDeclaration, ClientHookEventDeclarationSchema, ClientIdentifierStrength, ClientIdentifierStrengthSchema, ClientIdentityObservation, ClientIdentityObservationSchema, ClientInstallCompleted, ClientInstallCompletedSchema, ClientInstallProgress, ClientInstallProgressSchema, ClientInstallRequest, ClientInstallResponse, ClientInstallSchema, ClientListRequest, ClientListResponse, ClientListSchema, ClientMetadataSchema, ClientNamespace, ClientProfile, ClientProfileNameSchema, ClientProfileSchema, ClientProfileSchemas, ClientResolveBinaryRequest, ClientResolveBinaryResponse, ClientResolveBinarySchema, ClientRuntimeCapabilities, ClientRuntimeCapabilitiesSchema, ClientRuntimeEvidenceBase, ClientRuntimeEvidenceBaseSchema, ClientRuntimeObserveRequest, ClientRuntimeObserveResponse, ClientRuntimeObserveSchema, ClientRuntimeSource, ClientRuntimeSourceLayer, ClientRuntimeSourceLayerSchema, ClientRuntimeSourceSchema, ClientRuntimeStarted, ClientRuntimeStartedSchema, ClientScanResult, ClientScanResultSchema, ClientScanTarget, ClientScanTargetSchema, ClientSchemas, ClientSessionAccountObserveRequest, ClientSessionAccountObserveResponse, ClientSessionAccountObserveSchema, ClientSessionConfigSchemas, ClientSessionLocator, ClientSessionLocatorSchema, ClientSessionObservedBase, ClientSessionObservedBaseSchema, ClientSessionStarted, ClientSessionStartedSchema, ClientSessionToolPost, ClientSessionToolPostSchema, ClientSessionToolPre, ClientSessionToolPreSchema, ClientSessionTurnCompleted, ClientSessionTurnCompletedSchema, ClientSessionTurnStarted, ClientSessionTurnStartedSchema, ClientSessionUserPromptSubmitted, ClientSessionUserPromptSubmittedSchema, ClientSetActiveRequest, ClientSetActiveResponse, ClientSetActiveSchema, ClientSubjects, ClientToolCapabilityAnnotation, ClientToolCapabilityAnnotationSchema, ClientToolDefinition, ClientToolDefinitionSchema, ClientUninstallRequest, ClientUninstallResponse, ClientUninstallSchema, ClientUpdateRequest, ClientUpdateResponse, ClientUpdateSchema, ClientUsageIngestRequest, ClientUsageIngestResponse, ClientUsageIngestSchema, ClientUsageSnapshot, ClientUsageSnapshotSchema, ClientUsageWindow, ClientUsageWindowSchema, ClientUsageWindows, ClientUsageWindowsSchema, ClientVersionChanged, ClientVersionChangedSchema, ClientWiringEntry, ClientWiringEntrySchema, ConfigIsolation, ConfigIsolationSchema, GithubReleaseInstallDescriptor, GithubReleaseInstallDescriptorSchema, InstallError, InstallErrorSchema, InstallStage, InstallStageSchema, InstalledVersionEntry, InstalledVersionEntrySchema, LatestVersionSourceStatus, LatestVersionSourceStatusSchema, LogSourceDefinition, LogSourceDefinitionSchema, ManagedInstallDescriptor, ManagedInstallDescriptorSchema, ManagedInstallStrategy, ManagedInstallStrategySchema, ManifestBucketInstallDescriptor, ManifestBucketInstallDescriptorSchema, NpmInstallDescriptor, NpmInstallDescriptorSchema, PostInstallDescriptor, PostInstallDescriptorSchema, ProfileCreateRequest, ProfileCreateResponse, ProfileDeleteRequest, ProfileDeleteResponse, ProfileGetRequest, ProfileGetResponse, ProfileListRequest, ProfileListResponse, ProfileSetDefaultRequest, ProfileSetDefaultResponse, ProfileUpdateRequest, ProfileUpdateResponse, SessionConfigCleanupRequest, SessionConfigCleanupResponse, SessionConfigCreateRequest, SessionConfigCreateResponse, SessionConfigDestroyRequest, SessionConfigDestroyResponse, SessionConfigEnvSchema, SessionConfigIdSchema, SessionConfigInheritance, SessionConfigInheritanceSchema, SessionConfigSetupRequest, SessionConfigSetupRequestSchema, SessionConfigSetupResponse, SessionConfigSetupResponseSchema, SessionConfigTeardownRequest, SessionConfigTeardownRequestSchema, SessionConfigTeardownResponse, SessionConfigTeardownResponseSchema, createClientDefinition };
1
+ import { C as PostInstallDescriptorSchema, D as VersionCommandSchema, E as VersionCommand, S as PostInstallDescriptor, T as SignedBinaryBucketInstallDescriptorSchema, _ as LogSourceDefinitionSchema, a as ClientDefinitionSchema, b as NpmInstallDescriptor, c as ClientRuntimeCapabilities, d as ClientToolCapabilityAnnotationSchema, f as ClientToolDefinition, g as LogSourceDefinition, h as ConfigIsolationSchema, i as ClientDefinitionInput, l as ClientRuntimeCapabilitiesSchema, m as ConfigIsolation, n as ClientBinaryCompatibilitySchema, o as ClientHookEventDeclaration, p as ClientToolDefinitionSchema, r as ClientDefinition, s as ClientHookEventDeclarationSchema, t as ClientBinaryCompatibility, u as ClientToolCapabilityAnnotation, v as ManagedInstallDescriptor, w as SignedBinaryBucketInstallDescriptor, x as NpmInstallDescriptorSchema, y as ManagedInstallDescriptorSchema } from "../../definition-DB7bbFSa.mjs";
2
+ import { $ as ClientSessionTurnCompletedSchema, $t as ClientIdentifierStrength, A as SessionConfigIdSchema, At as ClientSetActiveResponse, B as SessionConfigTeardownResponseSchema, Bt as InstallError, C as SessionConfigCleanupRequest, Cn as ClientExecutionContext, Ct as ClientInstallRequest, D as SessionConfigDestroyRequest, Dn as ClientResolveBinarySchema, Dt as ClientListResponse, E as SessionConfigCreateResponse, En as ClientResolveBinaryResponse, Et as ClientListRequest, F as SessionConfigSetupResponse, Ft as ClientUpdateRequest, G as ClientSessionObservedBaseSchema, Gt as InstalledVersionEntrySchema, H as ClientNamespace, Ht as InstallStage, I as SessionConfigSetupResponseSchema, It as ClientUpdateResponse, J as ClientSessionToolPost, Jt as ClientAccountIdentifier, K as ClientSessionStarted, Kt as ManagedInstallStrategy, L as SessionConfigTeardownRequest, Lt as ClientUpdateSchema, M as SessionConfigInheritanceSchema, Mt as ClientUninstallRequest, N as SessionConfigSetupRequest, Nt as ClientUninstallResponse, O as SessionConfigDestroyResponse, Ot as ClientListSchema, P as SessionConfigSetupRequestSchema, Pt as ClientUninstallSchema, Q as ClientSessionTurnCompleted, Qt as ClientAccountObserveSchema, R as SessionConfigTeardownRequestSchema, Rt as ClientVersionChanged, S as ProfileUpdateResponse, Sn as ClientSchemas, St as ClientInstallProgressSchema, T as SessionConfigCreateRequest, Tn as ClientResolveBinaryRequest, Tt as ClientInstallSchema, U as ClientSubjects, Ut as InstallStageSchema, V as createClientDefinition, Vt as InstallErrorSchema, W as ClientSessionObservedBase, Wt as InstalledVersionEntry, X as ClientSessionToolPre, Xt as ClientAccountObserveRequest, Y as ClientSessionToolPostSchema, Yt as ClientAccountIdentifierSchema, Z as ClientSessionToolPreSchema, Zt as ClientAccountObserveResponse, _ as ProfileListRequest, _n as ClientUsageSnapshotSchema, _t as ClientBinaryListEntry, a as ClientConfigPrimeSchema, an as ClientScanResultSchema, at as ClientWiringEntrySchema, b as ProfileSetDefaultResponse, bn as ClientUsageWindows, bt as ClientInstallCompletedSchema, c as ClientProfileSchema, cn as ClientSessionAccountObserveRequest, ct as ClientRuntimeObserveRequest, d as ProfileCreateRequest, dn as ClientSessionLocator, dt as ClientRuntimeSource, en as ClientIdentifierStrengthSchema, et as ClientSessionTurnStarted, f as ProfileCreateResponse, fn as ClientSessionLocatorSchema, ft as ClientRuntimeSourceLayer, g as ProfileGetResponse, gn as ClientUsageSnapshot, gt as ClientRuntimeStartedSchema, h as ProfileGetRequest, hn as ClientUsageIngestSchema, ht as ClientRuntimeStarted, i as ClientConfigPrimeResponse, in as ClientScanResult, it as ClientWiringEntry, j as SessionConfigInheritance, jt as ClientSetActiveSchema, k as SessionConfigEnvSchema, kt as ClientSetActiveRequest, l as ClientProfileSchemas, ln as ClientSessionAccountObserveResponse, lt as ClientRuntimeObserveResponse, m as ProfileDeleteResponse, mn as ClientUsageIngestResponse, mt as ClientRuntimeSourceSchema, n as ClientConfigPrimePhaseSchema, nn as ClientIdentityObservationSchema, nt as ClientSessionUserPromptSubmitted, o as ClientProfile, on as ClientScanTarget, ot as ClientRuntimeEvidenceBase, p as ProfileDeleteRequest, pn as ClientUsageIngestRequest, pt as ClientRuntimeSourceLayerSchema, q as ClientSessionStartedSchema, qt as ManagedInstallStrategySchema, r as ClientConfigPrimeRequest, rn as ClientMetadataSchema, rt as ClientSessionUserPromptSubmittedSchema, s as ClientProfileNameSchema, sn as ClientScanTargetSchema, st as ClientRuntimeEvidenceBaseSchema, t as ClientConfigPrimePhase, tn as ClientIdentityObservation, tt as ClientSessionTurnStartedSchema, u as ClientSessionConfigSchemas, un as ClientSessionAccountObserveSchema, ut as ClientRuntimeObserveSchema, v as ProfileListResponse, vn as ClientUsageWindow, vt as ClientBinaryListEntrySchema, w as SessionConfigCleanupResponse, wn as ClientExecutionContextSchema, wt as ClientInstallResponse, x as ProfileUpdateRequest, xn as ClientUsageWindowsSchema, xt as ClientInstallProgress, y as ProfileSetDefaultRequest, yn as ClientUsageWindowSchema, yt as ClientInstallCompleted, z as SessionConfigTeardownResponse, zt as ClientVersionChangedSchema } from "../../index-DwCA1HWa.mjs";
3
+ export { ClientAccountIdentifier, ClientAccountIdentifierSchema, ClientAccountObserveRequest, ClientAccountObserveResponse, ClientAccountObserveSchema, ClientBinaryCompatibility, ClientBinaryCompatibilitySchema, ClientBinaryListEntry, ClientBinaryListEntrySchema, ClientConfigPrimePhase, ClientConfigPrimePhaseSchema, ClientConfigPrimeRequest, ClientConfigPrimeResponse, ClientConfigPrimeSchema, ClientDefinition, ClientDefinitionInput, ClientDefinitionSchema, ClientExecutionContext, ClientExecutionContextSchema, ClientHookEventDeclaration, ClientHookEventDeclarationSchema, ClientIdentifierStrength, ClientIdentifierStrengthSchema, ClientIdentityObservation, ClientIdentityObservationSchema, ClientInstallCompleted, ClientInstallCompletedSchema, ClientInstallProgress, ClientInstallProgressSchema, ClientInstallRequest, ClientInstallResponse, ClientInstallSchema, ClientListRequest, ClientListResponse, ClientListSchema, ClientMetadataSchema, ClientNamespace, ClientProfile, ClientProfileNameSchema, ClientProfileSchema, ClientProfileSchemas, ClientResolveBinaryRequest, ClientResolveBinaryResponse, ClientResolveBinarySchema, ClientRuntimeCapabilities, ClientRuntimeCapabilitiesSchema, ClientRuntimeEvidenceBase, ClientRuntimeEvidenceBaseSchema, ClientRuntimeObserveRequest, ClientRuntimeObserveResponse, ClientRuntimeObserveSchema, ClientRuntimeSource, ClientRuntimeSourceLayer, ClientRuntimeSourceLayerSchema, ClientRuntimeSourceSchema, ClientRuntimeStarted, ClientRuntimeStartedSchema, ClientScanResult, ClientScanResultSchema, ClientScanTarget, ClientScanTargetSchema, ClientSchemas, ClientSessionAccountObserveRequest, ClientSessionAccountObserveResponse, ClientSessionAccountObserveSchema, ClientSessionConfigSchemas, ClientSessionLocator, ClientSessionLocatorSchema, ClientSessionObservedBase, ClientSessionObservedBaseSchema, ClientSessionStarted, ClientSessionStartedSchema, ClientSessionToolPost, ClientSessionToolPostSchema, ClientSessionToolPre, ClientSessionToolPreSchema, ClientSessionTurnCompleted, ClientSessionTurnCompletedSchema, ClientSessionTurnStarted, ClientSessionTurnStartedSchema, ClientSessionUserPromptSubmitted, ClientSessionUserPromptSubmittedSchema, ClientSetActiveRequest, ClientSetActiveResponse, ClientSetActiveSchema, ClientSubjects, ClientToolCapabilityAnnotation, ClientToolCapabilityAnnotationSchema, ClientToolDefinition, ClientToolDefinitionSchema, ClientUninstallRequest, ClientUninstallResponse, ClientUninstallSchema, ClientUpdateRequest, ClientUpdateResponse, ClientUpdateSchema, ClientUsageIngestRequest, ClientUsageIngestResponse, ClientUsageIngestSchema, ClientUsageSnapshot, ClientUsageSnapshotSchema, ClientUsageWindow, ClientUsageWindowSchema, ClientUsageWindows, ClientUsageWindowsSchema, ClientVersionChanged, ClientVersionChangedSchema, ClientWiringEntry, ClientWiringEntrySchema, ConfigIsolation, ConfigIsolationSchema, InstallError, InstallErrorSchema, InstallStage, InstallStageSchema, InstalledVersionEntry, InstalledVersionEntrySchema, LogSourceDefinition, LogSourceDefinitionSchema, ManagedInstallDescriptor, ManagedInstallDescriptorSchema, ManagedInstallStrategy, ManagedInstallStrategySchema, NpmInstallDescriptor, NpmInstallDescriptorSchema, PostInstallDescriptor, PostInstallDescriptorSchema, ProfileCreateRequest, ProfileCreateResponse, ProfileDeleteRequest, ProfileDeleteResponse, ProfileGetRequest, ProfileGetResponse, ProfileListRequest, ProfileListResponse, ProfileSetDefaultRequest, ProfileSetDefaultResponse, ProfileUpdateRequest, ProfileUpdateResponse, SessionConfigCleanupRequest, SessionConfigCleanupResponse, SessionConfigCreateRequest, SessionConfigCreateResponse, SessionConfigDestroyRequest, SessionConfigDestroyResponse, SessionConfigEnvSchema, SessionConfigIdSchema, SessionConfigInheritance, SessionConfigInheritanceSchema, SessionConfigSetupRequest, SessionConfigSetupRequestSchema, SessionConfigSetupResponse, SessionConfigSetupResponseSchema, SessionConfigTeardownRequest, SessionConfigTeardownRequestSchema, SessionConfigTeardownResponse, SessionConfigTeardownResponseSchema, SignedBinaryBucketInstallDescriptor, SignedBinaryBucketInstallDescriptorSchema, VersionCommand, VersionCommandSchema, createClientDefinition };
@@ -1 +1 @@
1
- import{a as e,c as t,d as n,i as r,l as i,n as a,o,r as s,s as c,t as l,u}from"../../profile-4StaDQW0.mjs";import{a as d,c as f,d as p,f as m,i as h,l as g,n as _,o as v,p as y,r as b,s as x,t as S,u as C}from"../../account-identity-Ce1Bwrqi.mjs";import{A as w,B as T,C as E,D,E as O,F as k,G as A,H as j,I as M,K as N,L as P,M as F,N as I,O as L,P as R,R as z,S as B,T as V,U as H,V as U,W,_ as G,a as K,b as q,c as J,d as Y,f as X,g as Z,h as Q,i as $,j as ee,k as te,l as ne,m as re,n as ie,o as ae,p as oe,r as se,s as ce,t as le,u as ue,v as de,w as fe,x as pe,y as me,z as he}from"../../client-Dh4x4GQN.mjs";export{S as ClientAccountIdentifierSchema,_ as ClientAccountObserveSchema,R as ClientBinaryCompatibilitySchema,de as ClientBinaryListEntrySchema,k as ClientDefinitionSchema,F as ClientExecutionContextSchema,M as ClientHookEventDeclarationSchema,b as ClientIdentifierStrengthSchema,h as ClientIdentityObservationSchema,me as ClientInstallCompletedSchema,q as ClientInstallProgressSchema,pe as ClientInstallSchema,B as ClientListSchema,d as ClientMetadataSchema,ie as ClientNamespace,l as ClientProfileNameSchema,a as ClientProfileSchema,s as ClientProfileSchemas,I as ClientResolveBinarySchema,P as ClientRuntimeCapabilitiesSchema,oe as ClientRuntimeEvidenceBaseSchema,re as ClientRuntimeObserveSchema,Q as ClientRuntimeSourceLayerSchema,Z as ClientRuntimeSourceSchema,G as ClientRuntimeStartedSchema,v as ClientScanResultSchema,x as ClientScanTargetSchema,$ as ClientSchemas,f as ClientSessionAccountObserveSchema,r as ClientSessionConfigSchemas,g as ClientSessionLocatorSchema,K as ClientSessionObservedBaseSchema,ae as ClientSessionStartedSchema,ce as ClientSessionToolPostSchema,J as ClientSessionToolPreSchema,ne as ClientSessionTurnCompletedSchema,ue as ClientSessionTurnStartedSchema,Y as ClientSessionUserPromptSubmittedSchema,E as ClientSetActiveSchema,se as ClientSubjects,z as ClientToolCapabilityAnnotationSchema,he as ClientToolDefinitionSchema,fe as ClientUninstallSchema,V as ClientUpdateSchema,C as ClientUsageIngestSchema,p as ClientUsageSnapshotSchema,m as ClientUsageWindowSchema,y as ClientUsageWindowsSchema,O as ClientVersionChangedSchema,X as ClientWiringEntrySchema,T as ConfigIsolationSchema,U as GithubReleaseInstallDescriptorSchema,D as InstallErrorSchema,L as InstallStageSchema,te as InstalledVersionEntrySchema,w as LatestVersionSourceStatusSchema,j as LogSourceDefinitionSchema,H as ManagedInstallDescriptorSchema,ee as ManagedInstallStrategySchema,W as ManifestBucketInstallDescriptorSchema,A as NpmInstallDescriptorSchema,N as PostInstallDescriptorSchema,e as SessionConfigEnvSchema,o as SessionConfigIdSchema,c as SessionConfigInheritanceSchema,t as SessionConfigSetupRequestSchema,i as SessionConfigSetupResponseSchema,u as SessionConfigTeardownRequestSchema,n as SessionConfigTeardownResponseSchema,le as createClientDefinition};
1
+ import{a as e,c as t,d as n,f as r,i,l as a,n as o,o as s,p as c,r as l,s as u,t as d,u as f}from"../../profile-Cq4A7kQa.mjs";import{a as p,c as m,d as h,f as g,i as _,l as v,n as y,o as b,p as x,r as S,s as C,t as w,u as T}from"../../account-identity-Bg_vKkcs.mjs";import{A as E,B as D,C as O,D as k,E as A,F as j,G as M,H as N,I as P,L as F,M as I,N as L,O as R,P as z,R as B,S as V,T as H,U,V as W,W as G,_ as K,a as q,b as J,c as Y,d as X,f as Z,g as Q,h as $,i as ee,j as te,k as ne,l as re,m as ie,n as ae,o as oe,p as se,r as ce,s as le,t as ue,u as de,v as fe,w as pe,x as me,y as he,z as ge}from"../../client-DMWXCWhM.mjs";export{w as ClientAccountIdentifierSchema,y as ClientAccountObserveSchema,L as ClientBinaryCompatibilitySchema,fe as ClientBinaryListEntrySchema,d as ClientConfigPrimePhaseSchema,o as ClientConfigPrimeSchema,z as ClientDefinitionSchema,te as ClientExecutionContextSchema,j as ClientHookEventDeclarationSchema,S as ClientIdentifierStrengthSchema,_ as ClientIdentityObservationSchema,he as ClientInstallCompletedSchema,J as ClientInstallProgressSchema,me as ClientInstallSchema,V as ClientListSchema,p as ClientMetadataSchema,ae as ClientNamespace,l as ClientProfileNameSchema,i as ClientProfileSchema,e as ClientProfileSchemas,I as ClientResolveBinarySchema,P as ClientRuntimeCapabilitiesSchema,se as ClientRuntimeEvidenceBaseSchema,ie as ClientRuntimeObserveSchema,$ as ClientRuntimeSourceLayerSchema,Q as ClientRuntimeSourceSchema,K as ClientRuntimeStartedSchema,b as ClientScanResultSchema,C as ClientScanTargetSchema,ee as ClientSchemas,m as ClientSessionAccountObserveSchema,s as ClientSessionConfigSchemas,v as ClientSessionLocatorSchema,q as ClientSessionObservedBaseSchema,oe as ClientSessionStartedSchema,le as ClientSessionToolPostSchema,Y as ClientSessionToolPreSchema,re as ClientSessionTurnCompletedSchema,de as ClientSessionTurnStartedSchema,X as ClientSessionUserPromptSubmittedSchema,O as ClientSetActiveSchema,ce as ClientSubjects,F as ClientToolCapabilityAnnotationSchema,B as ClientToolDefinitionSchema,pe as ClientUninstallSchema,H as ClientUpdateSchema,T as ClientUsageIngestSchema,h as ClientUsageSnapshotSchema,g as ClientUsageWindowSchema,x as ClientUsageWindowsSchema,A as ClientVersionChangedSchema,Z as ClientWiringEntrySchema,ge as ConfigIsolationSchema,k as InstallErrorSchema,R as InstallStageSchema,ne as InstalledVersionEntrySchema,D as LogSourceDefinitionSchema,W as ManagedInstallDescriptorSchema,E as ManagedInstallStrategySchema,N as NpmInstallDescriptorSchema,U as PostInstallDescriptorSchema,u as SessionConfigEnvSchema,t as SessionConfigIdSchema,a as SessionConfigInheritanceSchema,f as SessionConfigSetupRequestSchema,n as SessionConfigSetupResponseSchema,r as SessionConfigTeardownRequestSchema,c as SessionConfigTeardownResponseSchema,G as SignedBinaryBucketInstallDescriptorSchema,M as VersionCommandSchema,ue as createClientDefinition};
@@ -1,2 +1,2 @@
1
- import { a as FocusContext, i as ActionIntent, n as SurfaceVisibility, r as isSurfaceVisible, t as SurfaceType } from "../../index-PdUSmPT2.mjs";
1
+ import { a as FocusContext, i as ActionIntent, n as SurfaceVisibility, r as isSurfaceVisible, t as SurfaceType } from "../../index-D2jejYlV.mjs";
2
2
  export { ActionIntent, FocusContext, SurfaceType, SurfaceVisibility, isSurfaceVisible };
@@ -1,6 +1,6 @@
1
- import { a as ConfigUpdateRequest, b as RelayConfig, i as ConfigSchemas, l as AIModelSchema, n as ConfigSubjects, o as ConfigUpdateResponse, r as ConfigGetResponse, t as ConfigNamespace, v as Config, y as ConfigSchema } from "../../config-namespace-DLSs83zr.mjs";
2
- import { t as RequiredTimeoutConfig } from "../../schemas-CGZy_rU6.mjs";
1
+ import { a as ConfigUpdateRequest, b as RelayConfig, i as ConfigSchemas, l as AIModelSchema, n as ConfigSubjects, o as ConfigUpdateResponse, r as ConfigGetResponse, t as ConfigNamespace, v as Config, y as ConfigSchema } from "../../config-namespace-ChZOpi1W.mjs";
3
2
  import { z } from "zod";
3
+ import * as _$_makaio_contracts0 from "@makaio/framework/contracts";
4
4
 
5
5
  //#region packages/contracts/src/config/credential-ref.d.ts
6
6
  /**
@@ -75,7 +75,7 @@ declare function unbrandCredentials(credentials: Record<string, CredentialRef> |
75
75
  */
76
76
  declare const ProviderDefaultsSchema: z.ZodObject<{
77
77
  model: z.ZodOptional<z.ZodString>;
78
- timeouts: z.ZodOptional<z.ZodType<Partial<RequiredTimeoutConfig>, unknown, z.core.$ZodTypeInternals<Partial<RequiredTimeoutConfig>, unknown>>>;
78
+ timeouts: z.ZodOptional<z.ZodType<Partial<_$_makaio_contracts0.RequiredTimeoutConfig>, unknown, z.core.$ZodTypeInternals<Partial<_$_makaio_contracts0.RequiredTimeoutConfig>, unknown>>>;
79
79
  cwd: z.ZodOptional<z.ZodString>;
80
80
  env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
81
81
  credentials: z.ZodOptional<z.ZodRecord<z.ZodString, z.core.$ZodBranded<z.ZodString, "CredentialRef", "out">>>;
@@ -89,7 +89,7 @@ declare const ProviderDefaultsSchema: z.ZodObject<{
89
89
  */
90
90
  declare const ProviderConfigSchema: z.ZodObject<{
91
91
  model: z.ZodOptional<z.ZodString>;
92
- timeouts: z.ZodOptional<z.ZodType<Partial<RequiredTimeoutConfig>, unknown, z.core.$ZodTypeInternals<Partial<RequiredTimeoutConfig>, unknown>>>;
92
+ timeouts: z.ZodOptional<z.ZodType<Partial<_$_makaio_contracts0.RequiredTimeoutConfig>, unknown, z.core.$ZodTypeInternals<Partial<_$_makaio_contracts0.RequiredTimeoutConfig>, unknown>>>;
93
93
  cwd: z.ZodOptional<z.ZodString>;
94
94
  env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
95
95
  credentials: z.ZodOptional<z.ZodRecord<z.ZodString, z.core.$ZodBranded<z.ZodString, "CredentialRef", "out">>>;
@@ -173,7 +173,7 @@ declare const BaseAdapterConfigSchema: z.ZodObject<{
173
173
  $schema: z.ZodLiteral<"makaio/adapter-config/v2">;
174
174
  defaults: z.ZodOptional<z.ZodObject<{
175
175
  model: z.ZodOptional<z.ZodString>;
176
- timeouts: z.ZodOptional<z.ZodType<Partial<RequiredTimeoutConfig>, unknown, z.core.$ZodTypeInternals<Partial<RequiredTimeoutConfig>, unknown>>>;
176
+ timeouts: z.ZodOptional<z.ZodType<Partial<_$_makaio_contracts0.RequiredTimeoutConfig>, unknown, z.core.$ZodTypeInternals<Partial<_$_makaio_contracts0.RequiredTimeoutConfig>, unknown>>>;
177
177
  cwd: z.ZodOptional<z.ZodString>;
178
178
  env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
179
179
  credentials: z.ZodOptional<z.ZodRecord<z.ZodString, z.core.$ZodBranded<z.ZodString, "CredentialRef", "out">>>;
@@ -181,7 +181,7 @@ declare const BaseAdapterConfigSchema: z.ZodObject<{
181
181
  }, z.core.$strip>>;
182
182
  providers: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
183
183
  model: z.ZodOptional<z.ZodString>;
184
- timeouts: z.ZodOptional<z.ZodType<Partial<RequiredTimeoutConfig>, unknown, z.core.$ZodTypeInternals<Partial<RequiredTimeoutConfig>, unknown>>>;
184
+ timeouts: z.ZodOptional<z.ZodType<Partial<_$_makaio_contracts0.RequiredTimeoutConfig>, unknown, z.core.$ZodTypeInternals<Partial<_$_makaio_contracts0.RequiredTimeoutConfig>, unknown>>>;
185
185
  cwd: z.ZodOptional<z.ZodString>;
186
186
  env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
187
187
  credentials: z.ZodOptional<z.ZodRecord<z.ZodString, z.core.$ZodBranded<z.ZodString, "CredentialRef", "out">>>;
@@ -1 +1 @@
1
- import{i as e,n as t,t as n}from"../../visibility-CZu8ooOA.mjs";import{a as r,i,n as a,o,r as s,s as c,t as l}from"../../credential-ref-DLCsoKVZ.mjs";import{p as u}from"../../shared-DxHLl9UP.mjs";import{i as d,n as f,r as p,t as m}from"../../config-namespace-MJT8P0Ud.mjs";import{z as h}from"zod";const g=h.object({initialization:h.number().optional().describe(`Time allowed for adapter/session initialization (cold starts, auth). Defaults to 30000ms.`),acknowledgement:h.number().optional().describe(`Time allowed for acknowledgement that a message was received. Defaults to 30000ms.`),completion:h.number().optional().describe(`Time allowed for completion of complex reasoning operations. Defaults to 60000ms.`),toolApproval:h.number().optional().describe(`Time allowed for tool approval responses (user is waiting). Defaults to 5000ms.`),eventWait:h.number().optional().describe(`Default time for once() calls waiting for events. Defaults to 10000ms.`)}),_=h.object({anthropic:h.string().url(),openai:h.string().url()}).partial().strict(),v=h.object({model:h.string().optional().describe(`Model identifier (adapter-specific, e.g., sonnet, opus)`),timeouts:g.optional().describe(`Timeout overrides for this provider`),cwd:h.string().optional().describe(`Working directory for agent execution`),env:h.record(h.string(),h.string()).optional().describe(`Environment variables to pass to agent execution`),credentials:h.record(h.string(),l).optional().describe(`Credential references resolved at runtime (e.g., keychain:service:account)`),providerSettings:h.record(h.string(),h.unknown()).optional().describe(`Provider-specific configuration (non-credential settings only)`)}),y=v.safeExtend({providerId:h.string().optional().describe(`FK to the providers table (stable provider ID, e.g. "anthropic")`),definitionId:h.string().optional().describe(`Provider definition identifier for schema lookup`),name:h.string().describe(`Display name for UI`),baseUrl:h.string().url().optional().describe(`Provider endpoint URL`),availableModels:h.array(e).optional().describe(`Models from this provider`),modelFilterMode:n.optional().describe(`Controls default visibility for models without explicit overrides`),modelVisibility:h.record(h.string(),t).optional().describe(`Sparse per-model visibility overrides`),isDefault:h.boolean().default(!1).describe(`Whether this is the default provider for inheritance`),enabled:h.boolean().default(!0).describe(`Whether this provider is enabled (disabled providers are not loaded)`)}),b=h.object({$schema:h.literal(`makaio/adapter-config/v2`),defaults:v.optional(),providers:h.record(h.string(),y).default(()=>({}))}),x=`makaio/provider-config/v1`,S=h.object({$schema:h.literal(x),definitionId:h.string().trim().min(1),name:h.string().trim().min(1).optional(),credentials:h.record(h.string(),l).optional(),endpointOverrides:_.optional(),modelFilterMode:n.optional(),modelVisibility:h.record(h.string(),t).optional(),isDefault:h.boolean().optional(),enabled:h.boolean().optional(),isSentinel:h.boolean().optional()}).strict(),C=`makaio/adapter-config/v1`,w=h.object({label:h.string().min(1),url:h.string().url()}).strict(),T=h.object({providerConfigId:h.string().trim().min(1),isDefault:h.boolean().optional()}).strict(),E=h.array(T).superRefine((e,t)=>{let n=new Set,r=null;for(let[i,a]of e.entries())if(n.has(a.providerConfigId)?t.addIssue({code:h.ZodIssueCode.custom,message:`Duplicate adapter binding for providerConfigId "${a.providerConfigId}".`,path:[i,`providerConfigId`]}):n.add(a.providerConfigId),a.isDefault){if(r!==null){t.addIssue({code:h.ZodIssueCode.custom,message:`Adapter config files may declare at most one default binding.`,path:[i,`isDefault`]});continue}r=i}}),D=h.object({$schema:h.literal(C),enabled:h.boolean().optional(),displayName:h.string().optional(),description:h.string().optional(),helpLinks:h.array(w).optional(),instructions:h.string().optional(),clientId:h.string().optional(),protocol:h.string().optional(),providerDefinitionIds:h.array(h.string()).optional(),settings:u.optional(),bindings:E.optional()}).strict();function O(e){return e.trim().toLowerCase().replace(/\s+/g,`-`)}function k(e){if(e.includes(`::`)||e.includes(`~`)||e.includes(`/`))return!1;let t=O(e);return t.length>0&&/^[a-z0-9][a-z0-9._-]*$/.test(t)}function A(e){let t=e.requestedName?.trim();if(t)return t;let n=e.providerName?.trim();if(n&&k(n))return n;if(k(e.definitionId))return e.definitionId}const j=h.object({name:h.string().optional(),providerId:h.string().optional(),credentials:h.record(h.string(),l).optional(),baseUrl:h.string().url().optional(),isDefault:h.boolean().optional(),enabled:h.boolean().optional(),modelFilterMode:n.optional(),modelVisibility:h.record(h.string(),t).optional()}),M=h.object({providers:h.record(h.string(),j)}),N=h.object({$schema:h.literal(`makaio/adapters-config/v1`),adapters:h.record(h.string(),M)});export{C as ADAPTER_FILE_SCHEMA_VERSION,e as AIModelSchema,D as AdapterFileSchema,M as AdaptersFileAdapterSchema,j as AdaptersFileProviderSchema,N as AdaptersFileSchema,b as BaseAdapterConfigSchema,m as ConfigNamespace,d as ConfigSchema,p as ConfigSchemas,f as ConfigSubjects,l as CredentialRefSchema,x as PROVIDER_CONFIG_SCHEMA_VERSION,S as ProviderConfigFileSchema,y as ProviderConfigSchema,v as ProviderDefaultsSchema,a as brandCredentialRecord,s as buildAccountManagerCredentialRef,i as buildStoredCredentialRef,r as isAccountManagerRef,k as isCanonicalProviderConfigName,o as parseStoredCredentialRef,A as resolveCanonicalProviderConfigName,O as slugifyProviderConfigName,c as unbrandCredentials};
1
+ import{i as e,n as t,t as n}from"../../visibility-CZu8ooOA.mjs";import{a as r,i,n as a,o,r as s,s as c,t as l}from"../../credential-ref-DLCsoKVZ.mjs";import{t as u}from"../../timeout-D33CUZ0M.mjs";import{p as d}from"../../shared-BhuSHZXH.mjs";import{i as f,n as p,r as m,t as h}from"../../config-namespace-wJ2CakDB.mjs";import{z as g}from"zod";const _=g.object({anthropic:g.string().url(),openai:g.string().url()}).partial().strict(),v=g.object({model:g.string().optional().describe(`Model identifier (adapter-specific, e.g., sonnet, opus)`),timeouts:u.optional().describe(`Timeout overrides for this provider`),cwd:g.string().optional().describe(`Working directory for agent execution`),env:g.record(g.string(),g.string()).optional().describe(`Environment variables to pass to agent execution`),credentials:g.record(g.string(),l).optional().describe(`Credential references resolved at runtime (e.g., keychain:service:account)`),providerSettings:g.record(g.string(),g.unknown()).optional().describe(`Provider-specific configuration (non-credential settings only)`)}),y=v.safeExtend({providerId:g.string().optional().describe(`FK to the providers table (stable provider ID, e.g. "anthropic")`),definitionId:g.string().optional().describe(`Provider definition identifier for schema lookup`),name:g.string().describe(`Display name for UI`),baseUrl:g.string().url().optional().describe(`Provider endpoint URL`),availableModels:g.array(e).optional().describe(`Models from this provider`),modelFilterMode:n.optional().describe(`Controls default visibility for models without explicit overrides`),modelVisibility:g.record(g.string(),t).optional().describe(`Sparse per-model visibility overrides`),isDefault:g.boolean().default(!1).describe(`Whether this is the default provider for inheritance`),enabled:g.boolean().default(!0).describe(`Whether this provider is enabled (disabled providers are not loaded)`)}),b=g.object({$schema:g.literal(`makaio/adapter-config/v2`),defaults:v.optional(),providers:g.record(g.string(),y).default(()=>({}))}),x=`makaio/provider-config/v1`,S=g.object({$schema:g.literal(x),definitionId:g.string().trim().min(1),name:g.string().trim().min(1).optional(),credentials:g.record(g.string(),l).optional(),endpointOverrides:_.optional(),modelFilterMode:n.optional(),modelVisibility:g.record(g.string(),t).optional(),isDefault:g.boolean().optional(),enabled:g.boolean().optional(),isSentinel:g.boolean().optional()}).strict(),C=`makaio/adapter-config/v1`,w=g.object({label:g.string().min(1),url:g.string().url()}).strict(),T=g.object({providerConfigId:g.string().trim().min(1),isDefault:g.boolean().optional()}).strict(),E=g.array(T).superRefine((e,t)=>{let n=new Set,r=null;for(let[i,a]of e.entries())if(n.has(a.providerConfigId)?t.addIssue({code:g.ZodIssueCode.custom,message:`Duplicate adapter binding for providerConfigId "${a.providerConfigId}".`,path:[i,`providerConfigId`]}):n.add(a.providerConfigId),a.isDefault){if(r!==null){t.addIssue({code:g.ZodIssueCode.custom,message:`Adapter config files may declare at most one default binding.`,path:[i,`isDefault`]});continue}r=i}}),D=g.object({$schema:g.literal(C),enabled:g.boolean().optional(),displayName:g.string().optional(),description:g.string().optional(),helpLinks:g.array(w).optional(),instructions:g.string().optional(),clientId:g.string().optional(),protocol:g.string().optional(),providerDefinitionIds:g.array(g.string()).optional(),settings:d.optional(),bindings:E.optional()}).strict();function O(e){return e.trim().toLowerCase().replace(/\s+/g,`-`)}function k(e){if(e.includes(`::`)||e.includes(`~`)||e.includes(`/`))return!1;let t=O(e);return t.length>0&&/^[a-z0-9][a-z0-9._-]*$/.test(t)}function A(e){let t=e.requestedName?.trim();if(t)return t;let n=e.providerName?.trim();if(n&&k(n))return n;if(k(e.definitionId))return e.definitionId}const j=g.object({name:g.string().optional(),providerId:g.string().optional(),credentials:g.record(g.string(),l).optional(),baseUrl:g.string().url().optional(),isDefault:g.boolean().optional(),enabled:g.boolean().optional(),modelFilterMode:n.optional(),modelVisibility:g.record(g.string(),t).optional()}),M=g.object({providers:g.record(g.string(),j)}),N=g.object({$schema:g.literal(`makaio/adapters-config/v1`),adapters:g.record(g.string(),M)});export{C as ADAPTER_FILE_SCHEMA_VERSION,e as AIModelSchema,D as AdapterFileSchema,M as AdaptersFileAdapterSchema,j as AdaptersFileProviderSchema,N as AdaptersFileSchema,b as BaseAdapterConfigSchema,h as ConfigNamespace,f as ConfigSchema,m as ConfigSchemas,p as ConfigSubjects,l as CredentialRefSchema,x as PROVIDER_CONFIG_SCHEMA_VERSION,S as ProviderConfigFileSchema,y as ProviderConfigSchema,v as ProviderDefaultsSchema,a as brandCredentialRecord,s as buildAccountManagerCredentialRef,i as buildStoredCredentialRef,r as isAccountManagerRef,k as isCanonicalProviderConfigName,o as parseStoredCredentialRef,A as resolveCanonicalProviderConfigName,O as slugifyProviderConfigName,c as unbrandCredentials};
@@ -1,3 +1,3 @@
1
- import { $ as ToolCallFormatterDeclaration, $n as AdapterClientRefSchema, $t as WhenContext, A as ExtensionBootstrap, An as CliManifestSchema, At as HashTriggerContext, B as ExtensionConfigComponentProps, Bn as StorageManifestSchema, Bt as EventFilter, C as BootstrapChoice, Cn as AdapterProviderDefinitionContract, Ct as UiRuntimeNavigationLevel, D as BootstrapImportContext, Dn as CliArgManifest, Dt as GatheredEntry, E as BootstrapExportResult, En as extensionToken, Et as GatheredContext, F as ExtensionToolsContribution, Fn as ExtensionManifest, Ft as ActionCategoryMap, G as MakaioWebUiComponentProps, Gn as WindowParamSpec, Gt as PickerConfig, H as LoaderContext, Hn as TrayManifestSchema, Ht as ExecuteResult, I as ExtensionTriggersContribution, In as ExtensionManifestSchema, It as ActionShortcut, J as PromisifiedActions, Jn as dep, Jt as SelectionFeedback, K as MakaioWebUiLoader, Kn as WindowParamSpecSchema, Kt as PickerOpenContext, L as ExtensionUiContribution, Ln as RuntimeRequirement, Lt as ActionShortcutModifiers, M as AdapterContribution, Mn as CliSubcommandManifestSchema, Mt as HashTriggerStage, N as ExtensionNamespaceContribution, Nn as ExtensionDependency, Nt as HashTriggerSuggestResult, O as BootstrapImportResult, On as CliArgManifestSchema, Ot as HashSuggestion, P as ExtensionSessionEventActionsContribution, Pn as ExtensionDependencySchema, Pt as ActionCategory, Q as PluginTransformedContentType, Qn as AdapterClientRef, Qt as StructuralEventFilter, R as LogImportContribution, Rn as RuntimeRequirementSchema, Rt as CreateSessionEventActionResult, S as BootstrapAssetKey, Sn as AdapterDefinitionContract, Sr as BrowserEntrypointSchema, St as UiNavigationLevelMap, T as BootstrapExportContext, Tn as ExtensionToken, Tt as UiScopeMap, U as MakaioWebUiAction, Un as WindowManifest, Ut as MessageEventFilter, V as ExtensionFieldTypeLoader, Vn as TrayManifest, Vt as ExecuteContext, W as MakaioWebUiActions, Wn as WindowManifestSchema, Wt as MessageRole, X as PluginToolCallFormatterInput, Xn as CapabilityTokenMap, Xt as SessionEventActionDeclaration, Y as PluginFormattedToolCallOutput, Yn as CapabilityToken, Yt as SessionEventActionContext, Z as PluginTransformedContent, Zn as CapabilityTokenSchema, Zt as SessionEventActionOptions, _ as ExtensionRuntimeBootContext, _n as ExtensionWarningEntrySchema, _r as TriggerManifestSchema, _t as TileRenderers, a as DetachedTransportSchema, an as ExtensionCliInteractiveContext, ar as ContributionManifestSchema, at as SlotId, b as MakaioNodeExtension, bn as ExtensionWarningSeveritySchema, br as UiSurfaceFlagsSchema, bt as UiContextValueMap, c as ExtensionDescriptorBase, cn as ExtensionContext, cr as ProtocolConfig, ct as WidgetDeclaration, d as ExtensionEntrypoints, dn as ExtensionService, dr as ProtocolRefSchema, dt as WidgetRenderers, en as ExtensionRuntimeOwnership, er as AdapterManifest, et as PageComponentProps, f as ExtensionEntrypointsSchema, fn as ExtensionServiceLifecycle, fr as ProviderManifest, ft as WidgetSize$1, g as ExtensionContributionProcessor, gn as ExtensionWarningEntry, gr as TriggerManifest, gt as TileProps, h as safeParseExtensionDescriptor, hn as ExtensionWarningActionSchema, hr as SessionEventActionManifestSchema, ht as TileIconLoader, i as DetachedTransportConfig, in as ExtensionCliHandlerContext, ir as ContributionManifest, it as SlotDeclaration, j as getBootstrapAssetKey, jn as CliSubcommandManifest, jt as HashTriggerMetadata, k as BootstrapResult, kn as CliManifest, kt as HashTrigger, l as ExtensionDescriptorParseResult, ln as NodeExtensionContext, lr as ProtocolConfigSchema, lt as WidgetDefinition, m as parseExtensionDescriptor, mn as ExtensionWarningAction, mr as SessionEventActionManifest, mt as TileDeclaration, n as parseExtensionConfig, nn as ExtensionCliBeforeRunResult, nr as ClientManifest, nt as PageMode, o as EmbeddedDescriptor, on as ExtensionCliOutputWriter, or as LogImporterManifest, ot as SlotPlacementDeclaration, p as isDetachedDescriptor, pn as ExtensionWarning, pr as ProviderManifestSchema, pt as TileCapabilities, q as MakaioWebUiRoute, qn as WindowStyle, qt as SelectionChangeContext, r as DetachedDescriptor, rn as ExtensionCliContribution, rr as ClientManifestSchema, rt as SlotContentDeclaration, s as ExtensionDescriptor, sn as ExtensionCliSubcommandEntry, sr as LogImporterManifestSchema, st as WidgetSize, t as ExtensionConfigProvider, tn as ExtensionCliBeforeRunContext, tr as AdapterManifestSchema, tt as PageDeclaration, u as ExtensionDescriptorSchema, un as ExtensionIdentity, ur as ProtocolRef, ut as WidgetProps, v as ExtensionRuntimeBootContribution, vn as ExtensionWarningSchema, vr as TriggerStage, vt as UiContextDimension, w as BootstrapDiscoverContext, wn as AdapterProviderRef, wt as UiScope, x as BootstrapAsset, xn as getExtensionWarningActionLabel, xr as BrowserEntrypoint, xt as UiNavigationLevel, y as MakaioExtension, yn as ExtensionWarningSeverity, yr as UiSurfaceFlags, yt as UiContextSnapshot, z as ExtensionConfigComponentLoader, zn as StorageManifest, zt as EntrypointConfig } from "../../index-BB419vv-.mjs";
2
- import { D as EntityUIConfig } from "../../index-BJOfdtbw.mjs";
1
+ import { $ as ToolCallFormatterDeclaration, $n as AdapterClientRefSchema, $t as WhenContext, A as ExtensionBootstrap, An as CliManifestSchema, At as HashTriggerContext, B as ExtensionConfigComponentProps, Bn as StorageManifestSchema, Bt as EventFilter, C as BootstrapChoice, Cn as AdapterProviderDefinitionContract, Ct as UiRuntimeNavigationLevel, D as BootstrapImportContext, Dn as CliArgManifest, Dt as GatheredEntry, E as BootstrapExportResult, En as extensionToken, Et as GatheredContext, F as ExtensionToolsContribution, Fn as ExtensionManifest, Ft as ActionCategoryMap, G as MakaioWebUiComponentProps, Gn as WindowParamSpec, Gt as PickerConfig, H as LoaderContext, Hn as TrayManifestSchema, Ht as ExecuteResult, I as ExtensionTriggersContribution, In as ExtensionManifestSchema, It as ActionShortcut, J as PromisifiedActions, Jn as dep, Jt as SelectionFeedback, K as MakaioWebUiLoader, Kn as WindowParamSpecSchema, Kt as PickerOpenContext, L as ExtensionUiContribution, Ln as RuntimeRequirement, Lt as ActionShortcutModifiers, M as AdapterContribution, Mn as CliSubcommandManifestSchema, Mt as HashTriggerStage, N as ExtensionNamespaceContribution, Nn as ExtensionDependency, Nt as HashTriggerSuggestResult, O as BootstrapImportResult, On as CliArgManifestSchema, Ot as HashSuggestion, P as ExtensionSessionEventActionsContribution, Pn as ExtensionDependencySchema, Pt as ActionCategory, Q as PluginTransformedContentType, Qn as AdapterClientRef, Qt as StructuralEventFilter, R as LogImportContribution, Rn as RuntimeRequirementSchema, Rt as CreateSessionEventActionResult, S as BootstrapAssetKey, Sn as AdapterDefinitionContract, Sr as BrowserEntrypointSchema, St as UiNavigationLevelMap, T as BootstrapExportContext, Tn as ExtensionToken, Tt as UiScopeMap, U as MakaioWebUiAction, Un as WindowManifest, Ut as MessageEventFilter, V as ExtensionFieldTypeLoader, Vn as TrayManifest, Vt as ExecuteContext, W as MakaioWebUiActions, Wn as WindowManifestSchema, Wt as MessageRole, X as PluginToolCallFormatterInput, Xn as CapabilityTokenMap, Xt as SessionEventActionDeclaration, Y as PluginFormattedToolCallOutput, Yn as CapabilityToken, Yt as SessionEventActionContext, Z as PluginTransformedContent, Zn as CapabilityTokenSchema, Zt as SessionEventActionOptions, _ as ExtensionRuntimeBootContext, _n as ExtensionWarningEntrySchema, _r as TriggerManifestSchema, _t as TileRenderers, a as DetachedTransportSchema, an as ExtensionCliInteractiveContext, ar as ContributionManifestSchema, at as SlotId, b as MakaioNodeExtension, bn as ExtensionWarningSeveritySchema, br as UiSurfaceFlagsSchema, bt as UiContextValueMap, c as ExtensionDescriptorBase, cn as ExtensionContext, cr as ProtocolConfig, ct as WidgetDeclaration, d as ExtensionEntrypoints, dn as ExtensionService, dr as ProtocolRefSchema, dt as WidgetRenderers, en as ExtensionRuntimeOwnership, er as AdapterManifest, et as PageComponentProps, f as ExtensionEntrypointsSchema, fn as ExtensionServiceLifecycle, fr as ProviderManifest, ft as WidgetSize$1, g as ExtensionContributionProcessor, gn as ExtensionWarningEntry, gr as TriggerManifest, gt as TileProps, h as safeParseExtensionDescriptor, hn as ExtensionWarningActionSchema, hr as SessionEventActionManifestSchema, ht as TileIconLoader, i as DetachedTransportConfig, in as ExtensionCliHandlerContext, ir as ContributionManifest, it as SlotDeclaration, j as getBootstrapAssetKey, jn as CliSubcommandManifest, jt as HashTriggerMetadata, k as BootstrapResult, kn as CliManifest, kt as HashTrigger, l as ExtensionDescriptorParseResult, ln as NodeExtensionContext, lr as ProtocolConfigSchema, lt as WidgetDefinition, m as parseExtensionDescriptor, mn as ExtensionWarningAction, mr as SessionEventActionManifest, mt as TileDeclaration, n as parseExtensionConfig, nn as ExtensionCliBeforeRunResult, nr as ClientManifest, nt as PageMode, o as EmbeddedDescriptor, on as ExtensionCliOutputWriter, or as LogImporterManifest, ot as SlotPlacementDeclaration, p as isDetachedDescriptor, pn as ExtensionWarning, pr as ProviderManifestSchema, pt as TileCapabilities, q as MakaioWebUiRoute, qn as WindowStyle, qt as SelectionChangeContext, r as DetachedDescriptor, rn as ExtensionCliContribution, rr as ClientManifestSchema, rt as SlotContentDeclaration, s as ExtensionDescriptor, sn as ExtensionCliSubcommandEntry, sr as LogImporterManifestSchema, st as WidgetSize, t as ExtensionConfigProvider, tn as ExtensionCliBeforeRunContext, tr as AdapterManifestSchema, tt as PageDeclaration, u as ExtensionDescriptorSchema, un as ExtensionIdentity, ur as ProtocolRef, ut as WidgetProps, v as ExtensionRuntimeBootContribution, vn as ExtensionWarningSchema, vr as TriggerStage, vt as UiContextDimension, w as BootstrapDiscoverContext, wn as AdapterProviderRef, wt as UiScope, x as BootstrapAsset, xn as getExtensionWarningActionLabel, xr as BrowserEntrypoint, xt as UiNavigationLevel, y as MakaioExtension, yn as ExtensionWarningSeverity, yr as UiSurfaceFlags, yt as UiContextSnapshot, z as ExtensionConfigComponentLoader, zn as StorageManifest, zt as EntrypointConfig } from "../../index-e5C62_M3.mjs";
2
+ import { D as EntityUIConfig } from "../../index-DGTFJB_8.mjs";
3
3
  export { ActionCategory, ActionCategoryMap, ActionShortcut, ActionShortcutModifiers, AdapterClientRef, AdapterClientRefSchema, AdapterContribution, AdapterDefinitionContract, AdapterManifest, AdapterManifestSchema, AdapterProviderDefinitionContract, AdapterProviderRef, BootstrapAsset, BootstrapAssetKey, BootstrapChoice, BootstrapDiscoverContext, BootstrapExportContext, BootstrapExportResult, BootstrapImportContext, BootstrapImportResult, BootstrapResult, BrowserEntrypoint, BrowserEntrypointSchema, CapabilityToken, CapabilityTokenMap, CapabilityTokenSchema, CliArgManifest, CliArgManifestSchema, CliManifest, CliManifestSchema, CliSubcommandManifest, CliSubcommandManifestSchema, ClientManifest, ClientManifestSchema, ContributionManifest, ContributionManifestSchema, CreateSessionEventActionResult, DetachedDescriptor, DetachedTransportConfig, DetachedTransportSchema, EmbeddedDescriptor, EntityUIConfig, EntrypointConfig, EventFilter, ExecuteContext, ExecuteResult, ExtensionBootstrap, ExtensionCliBeforeRunContext, ExtensionCliBeforeRunResult, ExtensionCliContribution, ExtensionCliHandlerContext, ExtensionCliInteractiveContext, ExtensionCliOutputWriter, ExtensionCliSubcommandEntry, ExtensionConfigComponentLoader, ExtensionConfigComponentProps, ExtensionConfigProvider, ExtensionContext, ExtensionContributionProcessor, ExtensionDependency, ExtensionDependencySchema, ExtensionDescriptor, ExtensionDescriptorBase, ExtensionDescriptorParseResult, ExtensionDescriptorSchema, ExtensionEntrypoints, ExtensionEntrypointsSchema, ExtensionFieldTypeLoader, ExtensionIdentity, ExtensionManifest, ExtensionManifestSchema, ExtensionNamespaceContribution, ExtensionRuntimeBootContext, ExtensionRuntimeBootContribution, ExtensionRuntimeOwnership, ExtensionService, ExtensionServiceLifecycle, ExtensionSessionEventActionsContribution, ExtensionToken, ExtensionToolsContribution, ExtensionTriggersContribution, ExtensionUiContribution, ExtensionWarning, ExtensionWarningAction, ExtensionWarningActionSchema, ExtensionWarningEntry, ExtensionWarningEntrySchema, ExtensionWarningSchema, ExtensionWarningSeverity, ExtensionWarningSeveritySchema, GatheredContext, GatheredEntry, HashSuggestion, HashTrigger, HashTriggerContext, HashTriggerMetadata, HashTriggerStage, HashTriggerSuggestResult, LoaderContext, LogImportContribution, LogImporterManifest, LogImporterManifestSchema, MakaioExtension, MakaioNodeExtension, MakaioWebUiAction, MakaioWebUiActions, MakaioWebUiComponentProps, MakaioWebUiLoader, MakaioWebUiRoute, MessageEventFilter, MessageRole, NodeExtensionContext, PageComponentProps, PageDeclaration, PageMode, WidgetSize as PageWidgetSize, PickerConfig, PickerOpenContext, PluginFormattedToolCallOutput, PluginToolCallFormatterInput, PluginTransformedContent, PluginTransformedContentType, PromisifiedActions, ProtocolConfig, ProtocolConfigSchema, ProtocolRef, ProtocolRefSchema, ProviderManifest, ProviderManifestSchema, RuntimeRequirement, RuntimeRequirementSchema, SelectionChangeContext, SelectionFeedback, SessionEventActionContext, SessionEventActionDeclaration, SessionEventActionManifest, SessionEventActionManifestSchema, SessionEventActionOptions, SlotContentDeclaration, SlotDeclaration, SlotId, SlotPlacementDeclaration, StorageManifest, StorageManifestSchema, StructuralEventFilter, TileCapabilities, TileDeclaration, TileIconLoader, TileProps, TileRenderers, ToolCallFormatterDeclaration, TrayManifest, TrayManifestSchema, TriggerManifest, TriggerManifestSchema, TriggerStage, UiContextDimension, UiContextSnapshot, UiContextValueMap, UiNavigationLevel, UiNavigationLevelMap, UiRuntimeNavigationLevel, UiScope, UiScopeMap, UiSurfaceFlags, UiSurfaceFlagsSchema, WhenContext, WidgetDeclaration, WidgetDefinition, WidgetProps, WidgetRenderers, WidgetSize$1 as WidgetSize, WindowManifest, WindowManifestSchema, WindowParamSpec, WindowParamSpecSchema, WindowStyle, dep, extensionToken, getBootstrapAssetKey, getExtensionWarningActionLabel, isDetachedDescriptor, parseExtensionConfig, parseExtensionDescriptor, safeParseExtensionDescriptor };