@makaio/framework 1.0.0-dev-1784707578477 → 1.0.0-dev-1784806252593

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 (69) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/bus/index.d.mts +2 -2
  3. package/dist/clients/index.d.mts +5 -5
  4. package/dist/clients/index.mjs +1 -1
  5. package/dist/{context-resolution-DsPuX5ox.d.mts → context-resolution-B5IH2Z9v.d.mts} +5 -5
  6. package/dist/contracts/adapter/index.d.mts +2 -2
  7. package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
  8. package/dist/contracts/artifact/index.d.mts +2 -2
  9. package/dist/contracts/canonical-model/index.d.mts +1 -1
  10. package/dist/contracts/client/index.d.mts +2 -2
  11. package/dist/contracts/extension/index.d.mts +3 -3
  12. package/dist/contracts/index.d.mts +97 -97
  13. package/dist/contracts/materialization/index.d.mts +3 -3
  14. package/dist/contracts/session/index.d.mts +2 -2
  15. package/dist/contracts/variant/index.d.mts +1 -1
  16. package/dist/contracts/workflow/index.d.mts +2 -2
  17. package/dist/{hook-responses-mmqRa2Dq.d.mts → hook-responses-Dg8wDvRo.d.mts} +308 -21
  18. package/dist/{index-BLwvcw5C.d.mts → index-B6SBIKyk.d.mts} +57 -57
  19. package/dist/{index-DxDMF5CP.d.mts → index-BF-ZfYo4.d.mts} +7 -298
  20. package/dist/{index-t9fTvyq6.d.mts → index-BXgsQUhf.d.mts} +4 -4
  21. package/dist/{index-C3XXcDNg2.d.mts → index-BhXCCgJV2.d.mts} +1 -1
  22. package/dist/{index-DRTyhYK0.d.mts → index-CYfiCzb-.d.mts} +1 -1
  23. package/dist/{index-FamxGT0U.d.mts → index-Chy9aknK.d.mts} +10 -10
  24. package/dist/{index-C5vYc3m12.d.mts → index-D73PTKXG2.d.mts} +2 -2
  25. package/dist/{index-CtZODNBo.d.mts → index-D9Tk7hyM.d.mts} +30 -30
  26. package/dist/{index-DK5z1A5p.d.mts → index-DSyyWwR2.d.mts} +12 -12
  27. package/dist/{index-vTBR3OFK.d.mts → index-DeoKITib.d.mts} +73 -73
  28. package/dist/{index-B0N0tFS-.d.mts → index-Dfl1vniO.d.mts} +71 -71
  29. package/dist/{index-0Ju2i8gV.d.mts → index-g36yJDge.d.mts} +6 -6
  30. package/dist/{index-D6gaVj-T.d.mts → index-y5-qCuUL.d.mts} +6 -6
  31. package/dist/{index-DitLUuR5.d.mts → index-z9bcglqL.d.mts} +4 -4
  32. package/dist/kernel/extension/index.d.mts +1 -1
  33. package/dist/kernel/index.d.mts +2 -2
  34. package/dist/kernel/observability/index.d.mts +1 -1
  35. package/dist/{namespace-DGORv0pz.d.mts → namespace-BHliaabz.d.mts} +6 -6
  36. package/dist/{namespace-C_EIMKwg2.d.mts → namespace-DRHnU5Yi2.d.mts} +26 -26
  37. package/dist/{namespace-CwGeWIRG.d.mts → namespace-Db_PFX3v.d.mts} +9 -9
  38. package/dist/{namespace-DrPPxElg.d.mts → namespace-Dvo_7BQw.d.mts} +20 -20
  39. package/dist/package.json +1 -1
  40. package/dist/{schemas-oTIqxZN_.d.mts → schemas-1ahuxM83.d.mts} +10 -10
  41. package/dist/{schemas-Bu4ZEJAD.d.mts → schemas-B5tMYfhC.d.mts} +4 -4
  42. package/dist/{schemas-DIQ9GUVX.d.mts → schemas-SsGbBOZ-.d.mts} +20 -20
  43. package/dist/services/adapter-subsystem/index.d.mts +2 -2
  44. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  45. package/dist/services/agent-runtime/index.d.mts +2 -2
  46. package/dist/services/agent-runtime/namespace.d.mts +1 -1
  47. package/dist/services/agent-runtime/schemas.d.mts +1 -1
  48. package/dist/services/context-rules/index.d.mts +3 -3
  49. package/dist/services/execution-target/index.d.mts +1 -1
  50. package/dist/services/filesystem/namespace.d.mts +12 -12
  51. package/dist/services/filesystem/schemas.d.mts +6 -6
  52. package/dist/services/git/namespace.d.mts +2 -2
  53. package/dist/services/git/schemas.d.mts +1 -1
  54. package/dist/services/index.d.mts +33 -33
  55. package/dist/services/provider-context/index.d.mts +1 -1
  56. package/dist/services/session/index.d.mts +4 -4
  57. package/dist/services/session/messages/namespace.d.mts +1 -1
  58. package/dist/services/session/session-events/namespace.d.mts +1 -1
  59. package/dist/services/session-editor/index.d.mts +1 -1
  60. package/dist/services/settings/namespace.d.mts +10 -10
  61. package/dist/services/subagent-template/index.d.mts +1 -1
  62. package/dist/services/subagent-template/schemas.d.mts +1 -1
  63. package/dist/{session-lineage-Cte63dGx.d.mts → session-lineage-D4z26OtM.d.mts} +1 -1
  64. package/dist/{transition-DWv5Abk6.d.mts → transition-BuUKc2J1.d.mts} +1 -1
  65. package/dist/{types-CzTC6z8M.d.mts → types-D2KG8ewJ.d.mts} +39 -39
  66. package/dist/{types-BwEQ9ucW.d.mts → types-DVLq657Y.d.mts} +1 -1
  67. package/dist/{view-builder-Drp9dB59.d.mts → view-builder-BktOepKR.d.mts} +4 -4
  68. package/dist/workflow-engine/index.d.mts +8 -8
  69. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "version": 1,
3
- "fingerprint": "35fa7437cc56ab5ecfadace653450d509418a87ae8bef732a16339481fb526a1",
4
- "builtAt": "2026-07-22T08:07:32.761Z"
3
+ "fingerprint": "23f8c9e454740380fb28ccfdb87ae24873650f613799337f0731193f326b744c",
4
+ "builtAt": "2026-07-23T11:32:06.574Z"
5
5
  }
@@ -3778,9 +3778,9 @@ declare const CanonicalModelSelectionSchema: z.ZodObject<{
3778
3778
  description: z.ZodOptional<z.ZodString>;
3779
3779
  inputSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
3780
3780
  exposureMode: z.ZodEnum<{
3781
- hidden: "hidden";
3782
3781
  direct: "direct";
3783
3782
  discovery: "discovery";
3783
+ hidden: "hidden";
3784
3784
  }>;
3785
3785
  enabled: z.ZodBoolean;
3786
3786
  enabledBy: z.ZodOptional<z.ZodEnum<{
@@ -3797,9 +3797,9 @@ declare const CanonicalModelSelectionSchema: z.ZodObject<{
3797
3797
  description: z.ZodOptional<z.ZodString>;
3798
3798
  inputSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
3799
3799
  exposureMode: z.ZodEnum<{
3800
- hidden: "hidden";
3801
3800
  direct: "direct";
3802
3801
  discovery: "discovery";
3802
+ hidden: "hidden";
3803
3803
  }>;
3804
3804
  enabled: z.ZodBoolean;
3805
3805
  enabledBy: z.ZodOptional<z.ZodEnum<{
@@ -2405,8 +2405,8 @@ declare const RuntimeRecordSchema: z.ZodObject<{
2405
2405
  clientRuntimeId: z.ZodString;
2406
2406
  clientId: z.ZodString;
2407
2407
  status: z.ZodEnum<{
2408
- started: "started";
2409
2408
  observed: "observed";
2409
+ started: "started";
2410
2410
  }>;
2411
2411
  supervisorSessionId: z.ZodOptional<z.ZodString>;
2412
2412
  pid: z.ZodOptional<z.ZodNumber>;
@@ -2432,8 +2432,8 @@ declare const ClientRuntimeStorageNamespace: _$_makaio_core0.BusNamespaceDefinit
2432
2432
  clientRuntimeId: z.ZodString;
2433
2433
  clientId: z.ZodString;
2434
2434
  status: z.ZodEnum<{
2435
- started: "started";
2436
2435
  observed: "observed";
2436
+ started: "started";
2437
2437
  }>;
2438
2438
  supervisorSessionId: z.ZodOptional<z.ZodString>;
2439
2439
  pid: z.ZodOptional<z.ZodNumber>;
@@ -2458,8 +2458,8 @@ declare const ClientRuntimeStorageNamespace: _$_makaio_core0.BusNamespaceDefinit
2458
2458
  clientRuntimeId: z.ZodString;
2459
2459
  clientId: z.ZodString;
2460
2460
  status: z.ZodEnum<{
2461
- started: "started";
2462
2461
  observed: "observed";
2462
+ started: "started";
2463
2463
  }>;
2464
2464
  supervisorSessionId: z.ZodOptional<z.ZodString>;
2465
2465
  pid: z.ZodOptional<z.ZodNumber>;
@@ -2483,8 +2483,8 @@ declare const ClientRuntimeStorageSubjects: _$_makaio_core0.BusSubjects<_$_makai
2483
2483
  clientRuntimeId: z.ZodString;
2484
2484
  clientId: z.ZodString;
2485
2485
  status: z.ZodEnum<{
2486
- started: "started";
2487
2486
  observed: "observed";
2487
+ started: "started";
2488
2488
  }>;
2489
2489
  supervisorSessionId: z.ZodOptional<z.ZodString>;
2490
2490
  pid: z.ZodOptional<z.ZodNumber>;
@@ -2509,8 +2509,8 @@ declare const ClientRuntimeStorageSubjects: _$_makaio_core0.BusSubjects<_$_makai
2509
2509
  clientRuntimeId: z.ZodString;
2510
2510
  clientId: z.ZodString;
2511
2511
  status: z.ZodEnum<{
2512
- started: "started";
2513
2512
  observed: "observed";
2513
+ started: "started";
2514
2514
  }>;
2515
2515
  supervisorSessionId: z.ZodOptional<z.ZodString>;
2516
2516
  pid: z.ZodOptional<z.ZodNumber>;
@@ -1 +1 @@
1
- import{n as e,r as t,t as n}from"../client-binary-version-verifier-Dv7TGFxh.mjs";import{z as r}from"zod";import*as i from"node:fs/promises";import*as a from"node:path";import{randomUUID as o}from"node:crypto";import{createBusNamespace as s,hostLocalRequest as c}from"@makaio/framework/core";import{MakaioBus as l}from"@makaio/framework/bus";import{extensionToken as u,isUniversalRange as d,versionSatisfies as f}from"@makaio/framework/contracts";import{BaseService as p}from"@makaio/framework/service-base";import{index as m,unique as ee,uniqueIndex as te}from"drizzle-orm/sqlite-core";import{index as h,unique as ne,uniqueIndex as re}from"drizzle-orm/pg-core";import{defineDialectSchema as g,defineDualTable as _,didAffectRows as ie,executeTransaction as v,registerDrizzleHandlers as ae,resolveSchema as y}from"@makaio/framework/storage/drizzle";import{and as b,eq as x,gt as oe,sql as S}from"drizzle-orm";import{ClientProfileNameSchema as C,ClientProfileSchema as se,ClientSubjects as ce,ClientSubjects as w,ClientWiringEntrySchema as le,DEFAULT_FAILURE_POLICY as ue,SessionConfigLeaseIdSchema as de,deriveHookEventTransportMode as fe,isValidContributorId as pe,isValidTimeoutMs as me,validateClosedPolicy as he}from"@makaio/framework/contracts/client";import*as ge from"node:os";import{CLIDetectionSubjects as _e}from"@makaio/framework/services/cli-detection/namespace";import{ClientStorageSubjects as ve}from"@makaio/framework/services/settings/storage";import{SessionSubjects as ye}from"@makaio/framework/contracts/session";async function be(e,t,n,r,i){let a,o=(n.get(e)??Promise.resolve()).then(async()=>{let n=await i(r(await xe(e,t)));n.changed&&await Se(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 xe(e,t){let n;try{n=await i.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return t;throw e}return JSON.parse(n)}async function Se(e,t){let n=a.dirname(e),r=a.join(n,`${a.basename(e)}.${o()}.tmp`);await i.mkdir(n,{recursive:!0});try{await i.writeFile(r,`${JSON.stringify(t,null,2)}\n`,`utf-8`),await i.rename(r,e)}catch(e){throw await i.unlink(r).catch(()=>void 0),e}}var Ce=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)}},we=class{nextAccountSequence=1;accountIdsByIdentifier=new Map;accounts=new Map;upsertAccount(e){let t=Ee(e.displayLabel),n=new Map;for(let t of e.identifiers)n.set(Te(e.clientId,t.scheme,t.value),t);let r=De(n,this.accountIdsByIdentifier,`strong`),i=De(n,this.accountIdsByIdentifier,`alias`),a=r[0]??(i.length===1?i[0]:i.length>1?Oe(i):this.createAccount()),o=(r.length>0?je(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 Te(e,t,n){return`${e}\u0000${t}\u0000${n}`}function Ee(e){return e?.trim()||void 0}function De(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(ke)}function Oe(e){return[...e].sort(ke)[0]}function ke(e,t){let n=Ae(e),r=Ae(t);return n!==null&&r!==null&&n!==r?n-r:e.localeCompare(t)}function Ae(e){let t=e.match(/^client-account-(\d+)$/);return t?Number(t[1]):null}function je(e,t,n){let r=new Set([...t,...n]);return r.delete(e),Array.from(r).sort(ke)}function Me(e){return{subject:`config.prime`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}async function T(e,t){let n=await e.requestOptional(Me(t.clientId),t);return n.handled?n.data:{primed:!1}}function Ne(){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 Pe=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 E(t,n){return!a.isAbsolute(t)||!a.isAbsolute(n)?!1:e(a.resolve(t),a.resolve(n))}function D(e,t){if(!e||!a.isAbsolute(e))throw Error(`${t} requires a non-empty absolute basePath`);return a.resolve(e)}var Fe=class{strategyDeps;config;jobs=new Map;#e=!1;resolvedBasePath;constructor(e,t){this.strategyDeps=e,this.config=t,this.resolvedBasePath=D(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,n,r,i,a,o,s){try{let c=this.resolveTargetDir(e.clientId,e.version),l=t(n,this.strategyDeps);if(l===void 0)throw Error(`Unsupported managed install descriptor type: ${n.type}`);let u=await this.executeStrategy(e,l,c,r);if(this.#e)return;let d;try{if(d=await this.runPostInstall(e,u.installPath,o,r),this.#e)return;s!==void 0&&await this.runVersionVerification(e,u.installPath,s,r)}catch(e){throw this.#e||await this.cleanupStagedArtifact(u.installPath),e}if(this.#e)return;await this.finalizeSuccess(e,u,d,r,i,a)}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 a({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,r,i){this.emitProgressIfActive(i,this.buildProgressPayload(e,`verifying`,null,t,{kind:`version-command`}))&&(this.#e||await n(this.strategyDeps.exec,t,r,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,t){let n=a.resolve(this.resolvedBasePath,e,t);if(!E(this.resolvedBasePath,n))throw Error(`Invalid install target path for client "${e}" and version "${t}"`);return n}};const O=r.object({id:r.string(),clientId:r.string(),version:r.string(),installPath:r.string(),installedAt:r.number().int().nonnegative(),createdAt:r.number().int().nonnegative()}),k=r.object({clientId:r.string(),activeVersion:r.string().nullable(),updatedAt:r.number().int().nonnegative()}),A=r.object({previousActiveVersion:r.string().nullable(),activeVersion:r.string().nullable()}),j=s(`client-binary:storage`,{insertVersion:{request:O,response:r.object({success:r.boolean()})},recordInstalledVersion:{request:r.object({versionRecord:O,makeActive:r.boolean(),updatedAt:r.number().int().nonnegative()}),response:A},listVersions:{request:r.object({clientId:r.string()}),response:r.object({versions:r.array(O)})},getSnapshot:{request:r.object({clientId:r.string()}),response:r.object({state:k.nullable(),versions:r.array(O)})},loadAllVersions:{request:r.object({}),response:r.object({versions:r.array(O)})},upsertState:{request:k,response:r.object({success:r.boolean()})},setActiveVersion:{request:r.object({clientId:r.string(),activeVersion:r.string().nullable(),updatedAt:r.number().int().nonnegative()}),response:A},getState:{request:r.object({clientId:r.string()}),response:r.object({state:k.nullable()})},loadAllState:{request:r.object({}),response:r.object({states:r.array(k)})},loadSnapshot:{request:r.object({}),response:r.object({states:r.array(k),versions:r.array(O)})},removeVersionAndClearActive:{request:r.object({clientId:r.string(),version:r.string(),updatedAt:r.number().int().nonnegative()}),response:A.extend({removedVersion:r.string().nullable()})}}),M=j.subjects;var N=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)}};const Ie=process.env.MAKAIO_SKIP_CLIENT_VERSION_CHECK===`1`;function P(e,t,n,r,i){if(n===null){if(d(r))return;if(Ie){console.warn(`[SKIP_VERSION_CHECK] ${e}: ${i} for client '${t}' did not report a version; requires ${r}`);return}throw Error(`${e}: ${i} for client '${t}' did not report a version; requires ${r}`)}if(!f(n,r)){if(Ie){console.warn(`[SKIP_VERSION_CHECK] ${e}: ${i} ${n} for client '${t}' does not satisfy ${r} — check bypassed`);return}throw Error(`${e}: ${i} ${n} for client '${t}' does not satisfy ${r}`)}}var Le=class{bus;resolvedBasePath;resolvedConfigBasePath;definitionLookup;resolutionPolicy;constructor(e){this.bus=e.bus,this.resolvedBasePath=e.resolvedBasePath,this.resolvedConfigBasePath=e.resolvedConfigBasePath,this.definitionLookup=e.definitionLookup,this.resolutionPolicy=e.resolutionPolicy??`managed-first`}async resolve(e){let t=this.definitionLookup.getDefinition(e);if(t===void 0)throw Error(`client.resolveBinary: no definition registered for client '${e}'`);if(this.resolutionPolicy===`managed-first`){let{state:n,versions:r}=await this.bus.request(M.getSnapshot,{clientId:e}),i=n?.activeVersion??null;if(i!==null)return this.buildManagedContext(e,i,t,r)}return this.buildGlobalContext(e,t)}isInstallPathWithinBase(e){return E(this.resolvedBasePath,e)}async isExpectedInstallPath(e,t,n){if(!a.isAbsolute(e)||!this.isInstallPathWithinBase(e))return!1;let r=a.resolve(this.resolvedBasePath,t,n);if(!this.isInstallPathWithinBase(r))return!1;try{let[t,n,a]=await Promise.all([i.realpath(this.resolvedBasePath),i.realpath(r),i.realpath(e)]);return E(t,n)?a===n||E(n,a):!1}catch{return!1}}async buildManagedContext(e,t,n,r){let i=r.find(e=>e.version===t);if(i===void 0)throw Error(`client.resolveBinary: active version '${t}' is not installed for client '${e}'`);if(!await this.isExpectedInstallPath(i.installPath,e,t))throw Error(`client.resolveBinary: stored installPath "${i.installPath}" does not match the expected install directory for ${e}@${t}`);n.binary!==void 0&&P(`client.resolveBinary`,e,t,n.binary.supportedVersions,`managed binary version`);let o=F(n.versionCommand)?.[0];if(o===void 0)throw Error(`client.resolveBinary: definition for '${e}' has no versionCommand — cannot derive binary path`);let s=a.resolve(i.installPath,o),c=a.resolve(i.installPath);if(!s.startsWith(c+a.sep)&&s!==c)throw Error(`client.resolveBinary: versionCommand for '${e}' resolves outside the install directory`);let{configDir:l,env:u}=this.resolveIsolatedConfig(e,n);return{binaryPath:s,env:u,configDir:l,source:`managed`,version:t}}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(w.scan,{targets:[n]}),i=r.find(t=>t.clientId===e);if(i===void 0||!i.found)throw new Ce(e);let o=i.version??null;P(`client.resolveBinary`,e,o,t.binary.supportedVersions,`detected global binary version`);let s=this.resolveGlobalConfigDir(t),c=i.binaryPath??null;if(c!==null&&!a.isAbsolute(c))throw Error(`client.resolveBinary: detected global binary path for '${e}' is not absolute`);return{binaryPath:c,env:{},configDir:s,source:`global`,version:o}}resolveIsolatedConfig(e,t){let{configIsolation:n}=t;if(n===void 0)return{configDir:null,env:{}};let r=a.join(this.resolvedConfigBasePath,e,`config`),i=n.pathKind===`file`?a.join(r,a.basename(n.defaultPath)):r;return{configDir:r,env:{[n.envVar]:i}}}resolveGlobalConfigDir(e){let{configIsolation:t}=e;if(t===void 0)return null;let n=t.defaultPath,r=n===`~`?ge.homedir():n.startsWith(`~/`)?a.join(ge.homedir(),n.slice(2)):n,i=t.pathKind===`file`?a.dirname(r):r;if(!a.isAbsolute(i))throw Error(`ConfigIsolation defaultPath for '${e.id}' resolved to non-absolute path '${r}'; use an absolute or tilde-expanded path (e.g. '~/.myapp')`);return i}};function F(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 Re(e,t){let{versions:n,states:r}=await e.request(M.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 ze=class extends p{config;definitionLookup;versionResolver;jobRunner;strategyDeps;resolvedBasePath;resolvedConfigBasePath;resolver;pendingClients=new Set;constructor(e=l,t,n=new N([]),r=Ne()){super(e),this.config=t,this.definitionLookup=n,this.resolvedBasePath=D(t.basePath,`ClientBinaryManager`),this.resolvedConfigBasePath=D(t.configBasePath,`ClientBinaryManager configBasePath`),this.strategyDeps=r,this.versionResolver=new Pe,this.jobRunner=new Fe(r,t),this.resolver=new Le({bus:e,resolvedBasePath:this.resolvedBasePath,resolvedConfigBasePath:this.resolvedConfigBasePath,definitionLookup:n,...t.resolutionPolicy!==void 0&&{resolutionPolicy:t.resolutionPolicy}})}async onInit(){this.registerHandler(w.list,async e=>{let t=await this.handleList();e.setResult({clients:t})}),this.registerHandler(w.install,async e=>{let t=await this.handleInstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(w.update,async e=>{let t=await this.handleUpdate(e.payload.clientId);e.setResult(t)}),this.registerHandler(w.setActive,async e=>{let t=await this.handleSetActive(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(w.uninstall,async e=>{let t=await this.handleUninstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(w.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 Re(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&&P(`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&&P(`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:r}=await this.bus.request(M.listVersions,{clientId:e}),i=r.find(e=>e.version===t);if(i===void 0)throw Error(`client.setActive: version '${t}' is not installed for client '${e}'`);let a=this.definitionLookup.getDefinition(e);if(a===void 0)throw Error(`client.setActive: no definition registered for client '${e}'`);a.binary!==void 0&&P(`client.setActive`,e,t,a.binary.supportedVersions,`requested binary version`);let o=F(a.versionCommand);if(o===void 0)throw Error(`client.setActive: no versionCommand registered for client '${e}'`);if(!await this.resolver.isExpectedInstallPath(i.installPath,e,t))throw Error(`client.setActive: stored installPath "${i.installPath}" does not match the expected install directory for ${e}@${t}`);return await n(this.strategyDeps.exec,i.installPath,o,t),await this.patchActiveVersion(e,t,`set-active`),{clientId:e,activeVersion:t}}finally{this.pendingClients.delete(e)}}async handleUninstall(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(M.listVersions,{clientId:e}),r=n.find(e=>e.version===t);if(r===void 0)throw Error(`client.uninstall: version '${t}' is not installed for client '${e}'`);let{removedVersion:i,previousActiveVersion:o,activeVersion:s}=await this.bus.request(M.removeVersionAndClearActive,{clientId:e,version:t,updatedAt:Date.now()});if(i===null)throw Error(`client.uninstall: failed to delete version '${t}' for client '${e}'`);let c=r.installPath,l=typeof c==`string`&&c.length>0?a.resolve(c):null;if(typeof c!=`string`||c.length===0||l===null||!a.isAbsolute(c)||!await this.resolver.isExpectedInstallPath(l,e,t)?console.warn(`[ClientBinaryManager] Skipping removeDirectory: stored installPath "${String(c)}" does not match the expected install directory for ${e}@${t}`):await this.strategyDeps.removeDirectory(l).catch(n=>{console.warn(`[ClientBinaryManager] Failed to remove binary directory "${l}" for ${e}@${t}:`,n)}),o!==null&&s===null)try{await this.bus.emit(w.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:t,activeVersion:s}}finally{this.pendingClients.delete(e)}}async patchActiveVersion(e,t,n){let r=(await this.bus.request(M.setActiveVersion,{clientId:e,activeVersion:t,updatedAt:Date.now()})).previousActiveVersion;if(r!==t)try{await this.bus.emit(w.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(w.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(w.installJob.completed,e).catch(e=>{console.warn(`[ClientBinaryManager] Failed to emit client.installJob.completed:`,e)})},r.postInstall,F(r.versionCommand)),o.jobId}makeCompletionCallback(){return async({clientId:e,version:t,installPath:n,makeActive:r,reason:i})=>{let a=Date.now();await T(this.bus,{clientId:e,configDir:this.resolveManagedConfigDir(e),phase:`managed-install`,binaryVersion:t});let o=await this.bus.request(M.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(w.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 a.join(this.resolvedConfigBasePath,e,`config`)}};function I(e,t){return`${e}${t}`}function L(e,t){return`${e}${t}`}var Be=class{records=new Map;bySupervisorSessionId=new Map;byPidClientId=new Map;byAdapterSessionClientId=new Map;adapterOwnedSessions=new Set;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(I(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.set(L(e.adapterSessionId,e.clientId),e.clientRuntimeId))}delete(e){let t=this.records.get(e);t&&(this.removeIndexEntries(t),t.adapterSessionId!==void 0&&this.adapterOwnedSessions.delete(L(t.adapterSessionId,t.clientId)),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(I(t,r));if(e!==void 0)return this.records.get(e)}if(n!==void 0){let e=this.byAdapterSessionClientId.get(L(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(),this.adapterOwnedSessions.clear()}markAdapterOwned(e,t){this.adapterOwnedSessions.add(L(e,t))}hasAdapterSession(e,t){return this.adapterOwnedSessions.has(L(e,t))}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(I(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.set(L(e.adapterSessionId,e.clientId),e.clientRuntimeId)}removeIndexEntries(e){e.supervisorSessionId!==void 0&&this.bySupervisorSessionId.delete(e.supervisorSessionId),e.pid!==void 0&&this.byPidClientId.delete(I(e.pid,e.clientId)),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.delete(L(e.adapterSessionId,e.clientId))}};const R=[`observed`,`started`],z=r.object({clientRuntimeId:r.string(),clientId:r.string(),status:r.enum(R),supervisorSessionId:r.string().optional(),pid:r.number().int().positive().optional(),parentPid:r.number().int().positive().optional(),adapterSessionId:r.string().optional(),sessionId:r.string().optional(),cwd:r.string().optional(),argv:r.array(r.string()).optional(),metadata:r.record(r.string(),r.unknown()).optional(),observedAt:r.number().int().nonnegative(),createdAt:r.number().int().nonnegative(),updatedAt:r.number().int().nonnegative()}),B=s(`client-runtime:storage`,{upsert:{request:z,response:r.object({success:r.boolean()})},loadAll:{request:r.object({}),response:r.object({records:r.array(z)})}}),V=B.subjects;function Ve(e){return e.supervisorSessionId!==void 0||e.adapterSessionId!==void 0}function H(e){return{...e,argv:e.argv===void 0?void 0:[...e.argv],metadata:e.metadata===void 0?void 0:structuredClone(e.metadata)}}function He(e){return Math.max(Date.now(),e+1)}function Ue(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 We=class{runtimeMap=new Be;bus;constructor(e){this.bus=e}async loadFromStorage(){if(!this.bus)return;let e=await this.bus.requestOptional(V.loadAll,{});if(!e.handled)return;let t=Date.now();for(let n of e.data.records)this.runtimeMap.setFromStorage(H(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&&Ve(e),i=Ue(t,e),a=n&&e.observedAt>t.observedAt;return r&&(t.status=`started`),(i||r||a)&&(t.updatedAt=He(t.updatedAt),a&&(t.observedAt=e.observedAt),this.runtimeMap.set(t),await this.persistRecord(t)),{clientRuntimeId:t.clientRuntimeId,created:!1,promoted:r,record:H(t)}}let n=Date.now(),r=o(),i=Ve(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:H(a)}}getRuntime(e){let t=this.runtimeMap.get(e);return t?H(t):void 0}markAdapterOwned(e,t){this.runtimeMap.markAdapterOwned(e,t)}hasAdapterSession(e,t){return this.runtimeMap.hasAdapterSession(e,t)}clear(){this.runtimeMap.clear()}get size(){return this.runtimeMap.size}async persistRecord(e){this.bus&&await this.bus.requestOptional(V.upsert,H(e))}};const U=r.object({eventName:r.string(),receivedAt:r.number().int().finite().nonnegative().describe(`Unix epoch timestamp in milliseconds`),payload:r.record(r.string(),r.unknown()),metadata:r.record(r.string(),r.unknown()).optional()}),Ge=/^[a-z0-9-]+$/;function W(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(!Ge.test(r))throw Error(`[${t}] clientId must contain only lowercase letters, numbers, and hyphens after an optional client: prefix`);return r}function Ke(e){return{subject:`hook.received`,$meta:{namespace:`client:${W(e,`createRawClientHookReceivedSubject`)}`,isRequest:!1,local:!1,channel:!1}}}const qe=5e3,Je=r.object({exitCode:r.number().int().min(0).max(255).default(0),stdout:r.string().default(``),stderr:r.string().default(``)}),Ye=Object.freeze({exitCode:0,stdout:``,stderr:``});function Xe(e){return{subject:`hook.handle`,$meta:{namespace:`client:${W(e,`createRawClientHookHandleSubject`)}`,isRequest:!0,local:!1,channel:!1,hostLocalRequest:!0}}}function Ze(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Qe(e,t){return Ze(e[t])}function $e(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 et(e){try{e().catch(tt)}catch(e){tt(e)}}function tt(e){(process.env.DEBUG||process.env.MAKAIO_DEBUG)&&console.debug(`[emitBestEffort] observed-semantics emission failed`,e)}function nt(e,t){return{subject:t,$meta:{namespace:`client:${W(e,`createClientWiringSubjectDef`)}`,isRequest:!0,local:!1,channel:!1}}}function rt(e){return nt(e,`wiring.list`)}const it=r.string().min(1).refine(a.isAbsolute,{message:`projectDir must be an absolute path`}),at=r.object({entries:r.array(le)}),ot=r.object({applied:r.number().int().nonnegative(),skipped:r.number().int().nonnegative()}),st=r.object({removed:r.number().int().nonnegative()}),ct=r.object({clientId:r.string().trim().min(1),entries:r.array(le)});function lt(e){if(e!==void 0&&!a.isAbsolute(e))throw Error(`projectDir must be an absolute path, got: ${e}`)}var ut=class extends p{accountRegistry;runtimeRegistry;latestSnapshots=new Map;activeIdentities=new Map;constructor(e=l,t=new we,n=new We(e)){super(e),this.accountRegistry=t,this.runtimeRegistry=n}async onInit(){await this.runtimeRegistry.loadFromStorage(),this.registerHandler(w.account.observe,e=>this.handleAccountObserve(e)),this.registerHandler(w.usage.ingest,e=>this.handleUsageIngest(e)),this.registerHandler(w.scan,async e=>{let t=await this.scanClients(e.payload.targets);e.setResult({results:t})}),this.registerHandler(w.runtime.observe,e=>this.handleRuntimeObserve(e)),this.registerHandler(w.runtime.isAdapterManaged,e=>{let{adapterSessionId:t,clientId:n}=e.payload;e.setResult({managed:this.runtimeRegistry.hasAdapterSession(t,n)})}),this.registerHandler(w.wiring.list,async e=>{let t=await this.listWirings(e.payload);e.setResult({results:t})}),this.registerHandler(w.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(w.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=pt(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(w.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=dt(t.clientAccountId,e.payload,t.displayLabel),r=pt(ft(this.latestSnapshots.get(t.clientAccountId),n),t.displayLabel);this.latestSnapshots.set(t.clientAccountId,r),await this.bus.emit(w.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);t.source.layer===`adapter`&&t.adapterSessionId!==void 0&&this.runtimeRegistry.markAdapterOwned(t.adapterSessionId,t.clientId),(r.created||r.promoted)&&await this.bus.emit(w.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(_e.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,a=t?.path;return{clientId:e.clientId,found:n,...a!==void 0&&{binaryPath:a},version:r,warningMessage:ht(n,r,e.supportedVersions)}})}async listScannableStoredClients(){let{clients:e}=await this.bus.request(ve.list,{});return e.filter(mt).map(e=>({clientId:e.id,binaryName:e.binary.name,supportedVersions:e.binary.supportedVersions}))}async listWirings(e){lt(e.projectDir);let{clients:t}=await this.bus.request(ve.list,{}),n=e.clientId===void 0?void 0:W(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=rt(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 dt(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 ft(e,t){return e&&e.observedAt>t.observedAt?e:t}function pt(e,t){return!e||t===void 0||e.displayLabel===t?e:{...e,displayLabel:t}}function mt(e){return e.enabled&&e.binary!==void 0}function ht(e,t,n){if(e&&t!==void 0&&t!==`unknown`&&n!==void 0&&!f(t,n))return`Unsupported version: requires ${n}`}var gt=class extends p{constructor(e=l){super(e)}onInit(){this.registerHandler(w.config.prime,async e=>{e.setResult(await T(this.bus,e.payload))})}};const G=se,K=r.string().trim().min(1),_t=s(`client-profile:storage`,{get:{request:r.object({clientId:K,name:C}),response:r.object({record:G.nullable()})},getById:{request:r.object({id:K}),response:r.object({record:G.nullable()})},list:{request:r.object({clientId:K}),response:r.object({records:r.array(G)})},set:{request:G,response:r.object({success:r.boolean()})},delete:{request:r.object({clientId:K,name:C}),response:r.object({success:r.boolean()})},clearDefault:{request:r.object({clientId:K}),response:r.object({success:r.boolean()})},setDefault:{request:r.object({clientId:K,name:C}),response:r.object({record:G.nullable()})}}),q=_t.subjects;function vt(e,t,n){let r=a.resolve(e),i=a.resolve(t),o=a.relative(r,i);if(o!==``&&!o.startsWith(`..`)&&!a.isAbsolute(o))return i;throw Error(`${n} refused to access path outside client profile root`)}var yt=class extends p{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(w.profile.create,async e=>{let t=W(e.payload.clientId,`profile.create`),{name:n,description:r}=e.payload;if((await this.bus.request(q.get,{clientId:t,name:n})).record!==null)throw Error(`Profile '${n}' already exists for client '${t}'`);let s=a.join(this.clientsBasePath,t,`profiles`),c=vt(s,a.join(s,n),`profile.create`);await i.mkdir(c,{recursive:!0});try{await T(this.bus,{clientId:t,configDir:c,phase:`profile-create`});let i=Date.now(),a={id:o(),clientId:t,name:n,description:r??null,configDir:c,isDefault:!1,createdAt:i,updatedAt:i};await this.bus.request(q.set,a),e.setResult({profile:a})}catch(e){throw await i.rm(c,{recursive:!0,force:!0}),e}})}registerListHandler(){this.registerHandler(w.profile.list,async e=>{let t=W(e.payload.clientId,`profile.list`),n=await this.bus.request(q.list,{clientId:t});e.setResult({profiles:n.records})})}registerGetHandler(){this.registerHandler(w.profile.get,async e=>{let t=W(e.payload.clientId,`profile.get`),n=await this.bus.request(q.get,{clientId:t,name:e.payload.name});e.setResult({profile:n.record})})}registerUpdateHandler(){this.registerHandler(w.profile.update,async e=>{let t=W(e.payload.clientId,`profile.update`),{name:n,description:r}=e.payload,i=await this.bus.request(q.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(q.set,a),e.setResult({profile:a})})}registerDeleteHandler(){this.registerHandler(w.profile.delete,async e=>{let t=W(e.payload.clientId,`profile.delete`),{name:n}=e.payload,r=await this.bus.request(q.get,{clientId:t,name:n});r.record!==null&&(vt(a.join(this.clientsBasePath,t,`profiles`),r.record.configDir,`profile.delete`),await i.rm(r.record.configDir,{recursive:!0,force:!0}));let o=await this.bus.request(q.delete,{clientId:t,name:n});e.setResult({success:o.success})})}registerSetDefaultHandler(){this.registerHandler(w.profile.setDefault,async e=>{let t=W(e.payload.clientId,`profile.setDefault`),{name:n}=e.payload,r=await this.bus.request(q.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=ge.platform();if(e===`darwin`||e===`linux`||e===`win32`)return e;throw Error(`client.sessionConfig does not support platform '${e}'`)}function wt(e,t,n){let r=de.safeParse(t);if(!r.success)throw Error(`${n} received an unsafe lease ID`);let i=a.resolve(e),o=a.resolve(i,r.data),s=a.relative(i,o);if(s===``||!s.startsWith(`..`)&&!a.isAbsolute(s))return o;throw Error(`${n} refused to access path outside client sessions root`)}var Tt=class extends p{clientsBasePath;getNow;liveLeasesByClient=new Map;liveLeasesByOwner=new Map;constructor(e,t,n=St){super(e),this.clientsBasePath=t,this.getNow=n}async onInit(){this.registerCreateHandler(),this.registerHandler(w.sessionConfig.destroy,async e=>{let{clientId:t,leaseId:n}=e.payload,r=W(t,`sessionConfig.destroy`),i=this.resolveClientSessionDir(r,n,`sessionConfig.destroy`),a=this.getLiveLease(r,n);a===void 0?await this.destroyClientSessionDir(r,i):await this.releaseLiveLease(a),e.setResult({success:!0})}),this.registerHandler(w.sessionConfig.cleanup,async e=>{let{clientId:t}=e.payload,n=t===void 0?void 0:W(t,`sessionConfig.cleanup`),r=await this.cleanupOrphanedDirs(n);e.setResult({removed:r})}),this.registerHandler(ye.closed,async e=>{await this.destroyOwnedLeases(e.payload.sessionId)}),await this.cleanupOrphanedDirs()}registerCreateHandler(){this.registerHandler(w.sessionConfig.create,async e=>{let{clientId:t,leaseId:n,ownerSessionId:r,profileName:a,baseConfigDir:o,projectDir:s,configInheritance:c=`full`}=e.payload,l=W(t,`sessionConfig.create`),u=this.resolveClientSessionDir(l,n,`sessionConfig.create`),d=this.reserveLiveLease({clientId:l,leaseId:n,...r===void 0?{}:{ownerSessionId:r}});try{await i.mkdir(u,{recursive:!0});let t=await this.resolveBaseConfigDir(l,u,a,o),r=bt(l),f=await this.bus.requestOptional(r,{sessionDir:u,baseConfigDir:t,projectDir:s,platform:Ct(),configInheritance:c}),p=f.handled?f.data.env??{}:{},m=f.handled?f.data.authMaterialized:!1;if(await T(this.bus,{clientId:l,configDir:u,phase:`session-create`,projectDir:s}),d.releaseRequested)throw Error(`Config lease '${n}' was released while it was being created`);e.setResult({sessionDir:u,env:p,authMaterialized:m}),d.state=`ready`}catch(e){try{await this.beginLeaseCleanup(d)}catch(t){throw AggregateError([e,t],`Client session config creation and rollback both failed`)}throw e}finally{d.settleCreation(),d.state===`released`&&this.untrackLiveLease(d)}})}async resolveBaseConfigDir(e,t,n,r){if(r!==void 0)return r;if(n!==void 0){let t=await this.bus.request(q.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(q.list,{clientId:e})).records.find(e=>e.isDefault);return i?i.configDir:t}async cleanupOrphanedDirs(e){let t=[],n=this.getNow(),r=e===void 0?await this.listClientIds():[e];return await Promise.all(r.map(async e=>{let r=a.join(this.clientsBasePath,e,`sessions`),o=await i.readdir(r).catch(()=>[]);await Promise.all(o.map(async a=>{if(!de.safeParse(a).success)return;let o=wt(r,a,`sessionConfig.cleanup`),s;try{s=await i.stat(o)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let c=s.birthtimeMs>0?s.birthtimeMs:s.ctimeMs;s.isDirectory()&&n-c>36e5&&!this.isLiveLease(e,a)&&(await this.destroyClientSessionDir(e,o),t.push(o))}))})),t}async destroyOwnedLeases(e){let t=[...this.liveLeasesByOwner.get(e)??[]],n=(await Promise.allSettled(t.map(async e=>{this.getLiveLease(e.clientId,e.leaseId)===e&&await this.releaseLiveLease(e)}))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(n.length>0)throw AggregateError(n,`Failed to release config leases owned by session '${e}'`)}async destroyClientSessionDir(e,t){try{await this.bus.requestOptional(xt(e),{sessionDir:t,platform:Ct()})}finally{await i.rm(t,{recursive:!0,force:!0})}}isLiveLease(e,t){return this.getLiveLease(e,t)!==void 0}getLiveLease(e,t){return this.liveLeasesByClient.get(e)?.get(t)}resolveClientSessionDir(e,t,n){return wt(a.join(this.clientsBasePath,e,`sessions`),t,n)}reserveLiveLease(e){if(this.isLiveLease(e.clientId,e.leaseId))throw Error(`Config lease '${e.leaseId}' is already active for client '${e.clientId}'`);let t=Promise.withResolvers(),n={...e,state:`creating`,releaseRequested:!1,creationSettled:t.promise,settleCreation:()=>t.resolve()},r=this.liveLeasesByClient.get(n.clientId)??new Map;if(r.set(n.leaseId,n),this.liveLeasesByClient.set(n.clientId,r),n.ownerSessionId!==void 0){let e=this.liveLeasesByOwner.get(n.ownerSessionId)??new Set;e.add(n),this.liveLeasesByOwner.set(n.ownerSessionId,e)}return n}async releaseLiveLease(e){if(this.getLiveLease(e.clientId,e.leaseId)!==e){e.releasePromise!==void 0&&await e.releasePromise;return}if(e.releaseRequested=!0,e.state===`creating`){await e.creationSettled,e.releasePromise!==void 0&&await e.releasePromise;return}await this.beginLeaseCleanup(e)}beginLeaseCleanup(e){if(e.releasePromise!==void 0)return e.releasePromise;if(this.getLiveLease(e.clientId,e.leaseId)!==e)return Promise.resolve();let t=e.state===`creating`;e.state=`releasing`;let n=this.resolveClientSessionDir(e.clientId,e.leaseId,`sessionConfig.release`);return e.releasePromise=this.destroyClientSessionDir(e.clientId,n).finally(()=>{e.state=`released`,t||this.untrackLiveLease(e)}),e.releasePromise}untrackLiveLease(e){let t=this.liveLeasesByClient.get(e.clientId);if(t?.get(e.leaseId)===e&&(t.delete(e.leaseId),t.size===0&&this.liveLeasesByClient.delete(e.clientId),e.ownerSessionId!==void 0)){let t=this.liveLeasesByOwner.get(e.ownerSessionId);t?.delete(e),t?.size===0&&this.liveLeasesByOwner.delete(e.ownerSessionId)}}async listClientIds(){return(await i.readdir(this.clientsBasePath,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()).map(e=>e.name)}};const Et=new Set([`hook.received`,`hook.handle`]);function Dt(e,t){return l.registerNamespace(s(`client:${e}`,{"hook.received":U,"hook.handle":c({request:U,response:Je}),...t})).subjects}function Ot(e,t){let n=Object.keys(t).filter(e=>Et.has(e));if(n.length===0)return;let r=n.join(`, `);throw Error([`[createClientNamespace] additionalSchemas for client:${e}`,`cannot override reserved shared hook subjects: ${r}`].join(` `))}function kt(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 At(e,t,n){let r=Object.keys(n).filter(e=>!kt(t,e));if(r.length!==0)throw Error(`[createClientNamespace] client:${e} was already registered without required subjects: ${r.join(`, `)}`)}function jt(e,t){let n=W(e,`createClientNamespace`),r=t??{};Ot(n,r);let i=Dt(n,r);return At(n,i,r),{namespaceDomain:`client:${n}`,subjects:i}}const Mt=_(`client_runtimes`,e=>({id:e.text(`id`).primaryKey(),clientId:e.text(`client_id`).notNull(),status:e.text(`status`).notNull(),supervisorSessionId:e.text(`supervisor_session_id`),pid:e.int4(`pid`),parentPid:e.int4(`parent_pid`),adapterSessionId:e.text(`adapter_session_id`),sessionId:e.text(`session_id`),cwd:e.text(`cwd`),argv:e.jsonCol(`argv`),metadata:e.jsonCol(`metadata`),observedAt:e.epochMs(`observed_at`).notNull(),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull()}),{sqlite:e=>[m(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),m(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),m(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)],postgres:e=>[h(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),h(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),h(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)]}),Nt=Mt.sqlite,Pt=Mt.postgres,Ft=g({clientRuntimes:Nt},{clientRuntimes:Pt}),It=new Set(R);function Lt(e){if(!It.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 Rt(e,t){let{clientRuntimes:n}=y(t,Ft),r=e.on(V.upsert,async e=>{let r=e.payload,i={clientId:r.clientId,status:r.status,supervisorSessionId:r.supervisorSessionId??null,pid:r.pid??null,parentPid:r.parentPid??null,adapterSessionId:r.adapterSessionId??null,sessionId:r.sessionId??null,cwd:r.cwd??null,argv:r.argv??null,metadata:r.metadata??null,observedAt:r.observedAt,updatedAt:r.updatedAt};await t.insert(n).values({id:r.clientRuntimeId,createdAt:r.createdAt,...i}).onConflictDoUpdate({target:n.id,set:i,setWhere:oe(S`excluded.updated_at`,n.updatedAt)}),e.setResult({success:!0})}),i=e.on(V.loadAll,async e=>{let r=await t.select().from(n);e.setResult({records:r.map(Lt)})});return()=>{r(),i()}}const zt=_(`client_binary_versions`,e=>({id:e.text(`id`).primaryKey(),clientId:e.text(`client_id`).notNull(),version:e.text(`version`).notNull(),installPath:e.text(`install_path`).notNull(),installedAt:e.epochMs(`installed_at`).notNull(),createdAt:e.epochMs(`created_at`).notNull()}),{sqlite:e=>[ee(`uq_client_binary_versions_client_version`).on(e.clientId,e.version)],postgres:e=>[ne(`uq_client_binary_versions_client_version`).on(e.clientId,e.version)]}),Bt=zt.sqlite,Vt=_(`client_binary_state`,e=>({clientId:e.text(`client_id`).primaryKey(),activeVersion:e.text(`active_version`),updatedAt:e.epochMs(`updated_at`).notNull()})),Ht=Vt.sqlite,Ut=zt.postgres,Wt=Vt.postgres,J=g({clientBinaryVersions:Bt,clientBinaryState:Ht},{clientBinaryVersions:Ut,clientBinaryState:Wt});function Y(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}function X(e){return{clientId:e.clientId,activeVersion:e.activeVersion??null,updatedAt:e.updatedAt}}function Gt(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}async function Kt(e,t,n){await e.insert(n).values(Gt(t)).onConflictDoNothing({target:[n.clientId,n.version]})}function qt(e,t,n){return{clientId:e,activeVersion:t,updatedAt:n}}async function Jt(e,t,n,r,i){await e.insert(i).values(qt(t,n,r)).onConflictDoUpdate({target:i.clientId,set:{activeVersion:n,updatedAt:r}})}async function Yt(e,t){let{clientBinaryVersions:n}=y(e,J);await Kt(e,t,n)}async function Xt(e,t,n,r){let{clientBinaryVersions:i,clientBinaryState:a}=y(e,J);return v(e,async e=>{let[o]=await e.select().from(a).where(x(a.clientId,t.clientId)).limit(1),s=o?.activeVersion??null;return await Kt(e,t,i),n?(await Jt(e,t.clientId,t.version,r,a),{previousActiveVersion:s,activeVersion:t.version}):{previousActiveVersion:s,activeVersion:s}})}async function Zt(e,t){let{clientBinaryVersions:n,clientBinaryState:r}=y(e,J);return v(e,async e=>{let[i]=await e.select().from(r).where(x(r.clientId,t)).limit(1),a=await e.select().from(n).where(x(n.clientId,t));return{state:i?X(i):null,versions:a.map(Y)}})}async function Qt(e){let{clientBinaryVersions:t,clientBinaryState:n}=y(e,J);return v(e,async e=>{let r=await e.select().from(n),i=await e.select().from(t);return{states:r.map(X),versions:i.map(Y)}})}async function $t(e,t){let{clientBinaryState:n}=y(e,J),r={clientId:t.clientId,activeVersion:t.activeVersion??null,updatedAt:t.updatedAt};await e.insert(n).values(r).onConflictDoUpdate({target:n.clientId,set:r})}async function en(e,t,n,r){let{clientBinaryState:i}=y(e,J);return v(e,async e=>{let[a]=await e.select().from(i).where(x(i.clientId,t)).limit(1),o=a?.activeVersion??null;return await Jt(e,t,n,r,i),{previousActiveVersion:o,activeVersion:n}})}async function tn(e,t,n,r){let{clientBinaryVersions:i,clientBinaryState:a}=y(e,J);return v(e,async e=>{let[o]=await e.select().from(a).where(x(a.clientId,t)).limit(1),s=o?.activeVersion??null;if(!ie(await e.delete(i).where(b(x(i.clientId,t),x(i.version,n)))))return{removedVersion:null,previousActiveVersion:s,activeVersion:s};await e.update(a).set({activeVersion:null,updatedAt:r}).where(b(x(a.clientId,t),x(a.activeVersion,n)));let[c]=await e.select().from(a).where(x(a.clientId,t)).limit(1);return{removedVersion:n,previousActiveVersion:s,activeVersion:c?.activeVersion??null}})}function nn(e,t){let{clientBinaryVersions:n,clientBinaryState:r}=y(t,J),i=[e.on(M.insertVersion,async e=>{await Yt(t,e.payload),e.setResult({success:!0})}),e.on(M.recordInstalledVersion,async e=>{let{versionRecord:n,makeActive:r,updatedAt:i}=e.payload,a=await Xt(t,n,r,i);e.setResult(a)}),e.on(M.listVersions,async e=>{let r=await t.select().from(n).where(x(n.clientId,e.payload.clientId));e.setResult({versions:r.map(Y)})}),e.on(M.getSnapshot,async e=>{let{state:n,versions:r}=await Zt(t,e.payload.clientId);e.setResult({state:n,versions:r})}),e.on(M.loadAllVersions,async e=>{let r=await t.select().from(n);e.setResult({versions:r.map(Y)})}),e.on(M.upsertState,async e=>{await $t(t,e.payload),e.setResult({success:!0})}),e.on(M.setActiveVersion,async e=>{let{clientId:n,activeVersion:r,updatedAt:i}=e.payload,a=await en(t,n,r,i);e.setResult(a)}),e.on(M.getState,async e=>{let[n]=await t.select().from(r).where(x(r.clientId,e.payload.clientId)).limit(1);e.setResult({state:n?X(n):null})}),e.on(M.loadAllState,async e=>{let n=await t.select().from(r);e.setResult({states:n.map(X)})}),e.on(M.loadSnapshot,async e=>{let{states:n,versions:r}=await Qt(t);e.setResult({states:n,versions:r})}),e.on(M.removeVersionAndClearActive,async e=>{let{clientId:n,version:r,updatedAt:i}=e.payload,a=await tn(t,n,r,i);e.setResult(a)})];return()=>{for(let e of i)e()}}const rn=_(`client_profiles`,e=>({id:e.text(`id`).primaryKey(),clientId:e.text(`client_id`).notNull(),name:e.text(`name`).notNull(),description:e.text(`description`),configDir:e.text(`config_dir`).notNull(),isDefault:e.bool(`is_default`).notNull().default(!1),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull()}),{sqlite:e=>[te(`uq_client_profiles_client_name`).on(e.clientId,e.name),te(`uq_client_profiles_default`).on(e.clientId).where(S`${e.isDefault} = 1`)],postgres:e=>[re(`uq_client_profiles_client_name`).on(e.clientId,e.name),re(`uq_client_profiles_default`).on(e.clientId).where(S`${e.isDefault} = true`)]}),an=rn.sqlite,on=rn.postgres,sn=g({clientProfiles:an},{clientProfiles:on});function Z(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 cn(e,t,n){let{clientProfiles:r}=y(e,sn),i=Date.now();return v(e,async e=>{let[a]=await e.select().from(r).where(b(x(r.clientId,t),x(r.name,n))).limit(1);if(a===void 0)return null;await e.update(r).set({isDefault:!1,updatedAt:i}).where(b(x(r.clientId,t),x(r.isDefault,!0))),await e.update(r).set({isDefault:!0,updatedAt:i}).where(b(x(r.clientId,t),x(r.name,n)));let[o]=await e.select().from(r).where(b(x(r.clientId,t),x(r.name,n))).limit(1);return o===void 0?null:Z(o)})}function ln(e,t){let{clientProfiles:n}=y(t,sn),r=[e.on(q.get,async e=>{let{clientId:r,name:i}=e.payload,[a]=await t.select().from(n).where(b(x(n.clientId,r),x(n.name,i))).limit(1);e.setResult({record:a?Z(a):null})}),e.on(q.getById,async e=>{let[r]=await t.select().from(n).where(x(n.id,e.payload.id)).limit(1);e.setResult({record:r?Z(r):null})}),e.on(q.list,async e=>{let r=await t.select().from(n).where(x(n.clientId,e.payload.clientId));e.setResult({records:r.map(Z)})}),e.on(q.set,async e=>{let r=e.payload,i={id:r.id,clientId:r.clientId,name:r.name,description:r.description??null,configDir:r.configDir,isDefault:r.isDefault,createdAt:r.createdAt,updatedAt:r.updatedAt};await t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:{name:r.name,description:r.description??null,configDir:r.configDir,isDefault:r.isDefault,updatedAt:r.updatedAt}}),e.setResult({success:!0})}),e.on(q.delete,async e=>{let{clientId:r,name:i}=e.payload,a=await t.delete(n).where(b(x(n.clientId,r),x(n.name,i)));e.setResult({success:ie(a)})}),e.on(q.clearDefault,async e=>{await t.update(n).set({isDefault:!1,updatedAt:Date.now()}).where(b(x(n.clientId,e.payload.clientId),x(n.isDefault,!0))),e.setResult({success:!0})}),e.on(q.setDefault,async e=>{let{clientId:n,name:r}=e.payload,i=await cn(t,n,r);e.setResult({record:i})})];return()=>{for(let e of r)e()}}function un(e,t){return`${e}\0${t}`}function dn(e){let t=e=>typeof e==`string`&&e.trim().length>0;if(typeof e!=`object`||!e)throw Error(`Provider contract catalog must be an object`);if(!t(e.clientId)||!t(e.contractId)||!t(e.version))throw Error(`Provider contract catalog requires non-empty clientId, contractId, and version`);if(!Array.isArray(e.supportedInteractions)||e.supportedInteractions.length===0)throw Error(`Provider contract catalog requires supported interactions`);if(e.supportedInteractions.some(e=>!t(e))||new Set(e.supportedInteractions).size!==e.supportedInteractions.length)throw Error(`Provider contract catalog interactions must be non-empty and unique`);if(!Array.isArray(e.blockability)||e.blockability.length!==e.supportedInteractions.length)throw Error(`Provider contract catalog requires complete blockability metadata`);let n=new Map;for(let r of e.blockability){if(!t(r.interaction)||typeof r.blockable!=`boolean`||n.has(r.interaction))throw Error(`Provider contract catalog blockability metadata must be complete and unique`);n.set(r.interaction,r.blockable)}if(e.supportedInteractions.some(e=>!n.has(e))||typeof e.validate!=`function`)throw Error(`Provider contract catalog must provide blockability metadata and a validator for every interaction`)}var fn=class{entries=new Map;registerProviderContract(e,t){dn(t);let n=un(t.clientId,t.contractId),r=this.entries.get(n);if(r)throw Error(`Provider contract collision: contract '${t.contractId}' for client '${t.clientId}' is already registered by extension '${r.extensionId}'; extension '${e}' cannot claim it`);this.entries.set(n,{extensionId:e,catalog:t})}unregisterProviderContract(e,t,n){let r=un(t,n),i=this.entries.get(r);i&&i.extensionId===e&&this.entries.delete(r)}unregisterAllByExtension(e){for(let[t,n]of this.entries)n.extensionId===e&&this.entries.delete(t)}getProviderContract(e,t){let n=un(e,t);return this.entries.get(n)?.catalog}getProviderContractsByClient(e){let t=[];for(let n of this.entries.values())n.catalog.clientId===e&&t.push(n.catalog);return t}getAllProviderContracts(){return[...this.entries.values()].map(e=>e.catalog)}clear(){this.entries.clear()}};function pn(e,t){return`${e}/${t}`}function mn(e,t,n){switch(e.kind){case`event-name`:return e.name===t;case`capability`:return n.includes(e.capability)}}function hn(e,t){let n=t.definition.priority-e.definition.priority;return n===0?e.ordinal-t.ordinal:n}function gn(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e!=`object`||!e?!1:e.kind===`event-name`?typeof e.name==`string`&&e.name.trim().length>0:e.kind===`capability`&&typeof e.capability==`string`&&e.capability.trim().length>0)}function _n(e){return e.lane===`canonical`?e.clientIds===void 0||Array.isArray(e.clientIds)&&e.clientIds.length>0&&e.clientIds.every(e=>typeof e==`string`&&e.trim().length>0):e.lane===`provider`?typeof e.clientId==`string`&&e.clientId.trim().length>0&&typeof e.contractId==`string`&&e.contractId.trim().length>0:!1}function vn(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return{code:`invalid-contributor-lane`,message:`Contributor definition must be an object`,extensionName:e};let n={...typeof t.id==`string`&&{contributorId:t.id},extensionName:e};if(!Number.isFinite(t.priority))return{...n,code:`invalid-priority`,message:`Contributor '${t.id}' priority must be a finite number`};if(!gn(t.selectors))return{...n,code:`invalid-selectors`,message:`Contributor '${t.id}' requires non-empty valid selectors`};if(typeof t.respond!=`function`)return{...n,code:`invalid-respond`,message:`Contributor '${t.id}' respond must be a function`};if(!_n(t))return{...n,code:`invalid-contributor-lane`,message:`Contributor '${t.id}' has an invalid lane or target identity`};if(!pe(t.id))return{...n,code:`invalid-contributor-id`,message:`Contributor ID is empty or invalid`};if(!me(t.timeoutMs))return{...n,code:`invalid-timeout-ms`,message:`Contributor '${t.id}' has an invalid timeoutMs: ${String(t.timeoutMs)}; must be a positive finite number`}}function yn(e,t,n,r){let i=[],a=new Set;for(let o of t){let t=vn(e,o);if(t){i.push(t);continue}let s=pn(e,o.id);if(a.has(s)){i.push({code:`invalid-contributor-id`,message:`Duplicate contributor ID '${o.id}' within the same extension batch '${e}'`,contributorId:o.id,extensionName:e});continue}if(r.has(s)){i.push({code:`invalid-contributor-id`,message:`Contributor ID '${o.id}' is already registered by extension '${e}'`,contributorId:o.id,extensionName:e});continue}a.add(s),bn(e,o,n,i)}return i}function bn(e,t,n,r){let i=t.failurePolicy??`open`;if(t.lane===`provider`){let a=n.getProviderContract(t.clientId,t.contractId);if(!a){r.push({code:`inactive-provider-contract`,message:`Provider contributor requires active contract '${t.contractId}' for client '${t.clientId}'`,contributorId:t.id,extensionName:e});return}xn(e,t,[a],i,r);return}xn(e,t,t.clientIds?t.clientIds.flatMap(e=>n.getProviderContractsByClient(e)):n.getAllProviderContracts(),i,r)}function xn(e,t,n,r,i){for(let a of t.selectors){let o=a.kind===`capability`?a.capability:a.name,s=n.filter(e=>e.supportedInteractions.includes(o));if((t.lane===`provider`||a.kind===`capability`)&&s.length===0){i.push({code:`unsupported-interaction`,message:`Interaction '${o}' is not supported by an eligible active provider contract`,contributorId:t.id,extensionName:e});continue}if(r===`closed`){if(s.length===0){i.push({code:`closed-policy-on-non-blockable`,message:`Closed failure policy requires blockability proof for interaction '${o}', but no contract declares it for an eligible active client`,contributorId:t.id,extensionName:e});continue}for(let n of s)for(let r of he([a],n))i.push({code:`closed-policy-on-non-blockable`,message:r,contributorId:t.id,extensionName:e})}}}var Sn=class{contractRegistry;contributors=new Map;extensionIndex=new Map;nextOrdinal=1;constructor(e){this.contractRegistry=e}installContributors(e,t){let n=yn(e,t,this.contractRegistry,this.contributors);if(n.length>0)return{errors:n};let r=this.extensionIndex.get(e)??new Set;for(let n of t){let t=pn(e,n.id),i=Object.freeze({...n,selectors:Object.freeze(n.selectors.map(e=>Object.freeze({...e})))}),a=Object.freeze({namespacedId:t,extensionId:e,ordinal:this.nextOrdinal,definition:i});this.nextOrdinal+=1,this.contributors.set(t,a),r.add(t)}return this.extensionIndex.set(e,r),{errors:[]}}removeContributors(e){let t=this.extensionIndex.get(e);if(t){for(let e of t)this.contributors.delete(e);this.extensionIndex.delete(e)}}snapshot(e,t,n,r=[]){let i=[];for(let a of this.contributors.values()){let{definition:o}=a;o.lane===`provider`&&(o.clientId!==e||o.contractId!==t)||o.lane===`canonical`&&o.clientIds!==void 0&&!o.clientIds.includes(e)||a.definition.selectors.some(e=>mn(e,n,r))&&i.push(a)}return i.sort(hn),Object.freeze(i)}clear(){this.contributors.clear(),this.extensionIndex.clear(),this.nextOrdinal=1}};function Cn(e,t){return{filter:e=>!!e.clientHookResponses,async processActivated(n,r,i){let a=r.clientHookResponses;if(!a)return;let o={extensionName:n,getProviderContract:(e,n)=>t.getProviderContract(e,n)},s;try{s=await a.createContributors(o)}catch(e){throw Error(`[ClientHookResponseContributionProcessor] createContributors failed for '${n}': ${e instanceof Error?e.message:String(e)}`,{cause:e})}let c=e.installContributors(n,s);if(c.errors.length>0){let e=c.errors.map(e=>`[${e.code}] ${e.contributorId??`<unknown>`}: ${e.message}`).join(`; `);throw Error(`[ClientHookResponseContributionProcessor] Contributor validation failed for '${n}': ${e}`)}},async processStopped(t){e.removeContributors(t)}}}var wn=class{runtimeService;binaryManager;configPrimeService;profileService;sessionConfigService;providerContractRegistry;hookResponseRegistry;constructor(e,t,n,r,i,a,o){this.runtimeService=e,this.binaryManager=t,this.configPrimeService=n,this.profileService=r,this.sessionConfigService=i,this.providerContractRegistry=a,this.hookResponseRegistry=o}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 Tn=u(`makaio.clients-core`);function En(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 Dn(e={}){let{definitions:t=[],strategyDependencies:n,postInstallHandlers:r,binaryResolutionPolicy:i}=e,o=[...t],s=new fn,c=new Sn(s);return{name:`makaio.clients-core`,displayName:`Clients Core`,version:`0.1.0`,critical:!0,namespaces:[j,B,_t],storage:{registerHandlers:ae((e,t)=>En([()=>Rt(e,t),()=>nn(e,t),()=>ln(e,t)]))},create:e=>{let t=new N(o),l=a.join(e.makaioHome,`clients`),u=new ze(e.bus,{basePath:a.join(e.makaioHome,`binaries`),configBasePath:l,postInstallHandlers:r,...i!==void 0&&{resolutionPolicy:i}},t,n),d=new yt(e.bus,l),f=new Tt(e.bus,l);return new wn(new ut(e.bus),u,new gt(e.bus),d,f,s,c)},runtimeBoot:{configure:e=>{e.registerContributionProcessor(Cn(c,s))}}}}async function On(e,t){let n=await e.requestOptional(w.resolveBinary,{clientId:t});return n.handled?n.data:void 0}function kn(e,t,n){return[...n??[],e,...t].map(Mn).join(` `)}function An(e,t,n,r,i){return kn(e,[...i??[],...t.split(` `),n],r)}function jn(e){return e.runtimeCapabilities.hookEvents.map(e=>({eventName:e.name,mode:fe(e)}))}function Mn(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Nn(e){if(e===void 0)return!0;if(!Array.isArray(e))return`canonicalEffects must be an array`;for(let t of e){if(typeof t!=`object`||!t||t.kind!==`context.append`||typeof t.value!=`string`)return`canonicalEffects must contain complete context.append effects`;if(Object.keys(t).some(e=>e!==`kind`&&e!==`value`))return`canonicalEffects must contain only kind and value`}return!0}function Pn(e,t,n){return e===void 0?!0:typeof e!=`object`||!e||Array.isArray(e)||e.clientId!==t||e.contractId!==n||typeof e.effects!=`object`||e.effects===null||Array.isArray(e.effects)?`providerEnvelope must contain the exact clientId, contractId, and an effects object`:Object.keys(e).some(e=>e!==`clientId`&&e!==`contractId`&&e!==`effects`)?`providerEnvelope must contain only clientId, contractId, and effects`:!0}function Fn(e,t,n,r,i,a){if(!r)return`Provider contributor requires active contract '${t.contractId}'`;if(r.clientId!==n||r.clientId!==t.clientId)return`Provider contract client '${r.clientId}' does not match '${t.clientId}'`;if(r.contractId!==t.contractId)return`Provider contract '${r.contractId}' does not match '${t.contractId}'`;let o=Pn(e.providerEnvelope,t.clientId,t.contractId);return o===!0?r.validate(e,{clientId:n,eventName:i,eventPayload:a}):o}function In(e,t,n,r,i,a){if(e===void 0)return!0;if(typeof e!=`object`||!e||Array.isArray(e))return`Contributor response must be an object or undefined`;let o=t.lane===`canonical`?[`canonicalEffects`]:[`providerEnvelope`];return Object.keys(e).some(e=>!o.includes(e))?`Contributor response contains keys outside the ${t.lane} lane`:t.lane===`canonical`?Nn(e.canonicalEffects):Fn(e,t,n,r,i,a)}const Q=Symbol(`contributor-timeout`);function Ln(e){return e.failurePolicy??ue}function Rn(e){return e.namespacedId??e.definition.id}function $(e,t){return e===`closed`?`closed-failure`:t}function zn(e){if(!e)return;let t=[];return e.canonicalEffects&&t.push(...e.canonicalEffects),e.providerEnvelope&&t.push(e.providerEnvelope),t.length>0?t:void 0}function Bn(e,t,n){let r=t-Date.now();return r<=0||n.signal.aborted?(n.abort(Error(`Contributor deadline expired`)),Promise.resolve(Q)):new Promise((i,a)=>{let o=!1,s=e=>{o||(o=!0,clearTimeout(c),n.signal.removeEventListener(`abort`,l),i(e))},c=setTimeout(()=>{n.abort(Error(`Contributor timeout`)),s(Q)},r),l=()=>s(Q);n.signal.addEventListener(`abort`,l,{once:!0}),e.then(e=>{Date.now()>=t?(n.abort(Error(`Contributor timeout`)),s(Q)):s(e)},e=>{o||(o=!0,clearTimeout(c),n.signal.removeEventListener(`abort`,l),a(e))})})}function Vn(e){let t=[],n=[],r=`Request deadline already expired before collection started`;for(let i of e){let e=Rn(i),a=$(Ln(i.definition),`timeout`);t.push({contributorId:e,outcome:a,durationMs:0}),n.push({contributorId:e,severity:`error`,message:r})}let i=t.find(e=>e.outcome===`closed-failure`);return{outcomes:t,diagnostics:n,closedFailure:i?{contributorId:i.contributorId,detail:r}:void 0}}function Hn(e,t){if(t.aborted){e.abort(t.reason);return}let n=()=>{e.abort(t.reason)};t.addEventListener(`abort`,n,{once:!0}),e.signal.addEventListener(`abort`,()=>{t.removeEventListener(`abort`,n)},{once:!0})}function Un(e,t,n,r,i,a){let{definition:o}=e,s=Rn(e),c=Date.now(),l=c+o.timeoutMs,u=n===void 0?l:Math.min(n,l),d=u-c,f=new AbortController;r&&Hn(f,r);let p={clientId:t,deadline:u,remainingBudgetMs:d,signal:f.signal,eventName:i,eventPayload:a};if(f.signal.aborted)return{contributorId:s,definition:o,startMs:c,abort:f,settled:Promise.resolve({tag:`timeout`})};let m;try{let e=o.respond(p);m=e instanceof Promise?e:Promise.resolve(e)}catch(e){m=Promise.reject(e)}return{contributorId:s,definition:o,startMs:c,abort:f,settled:Bn(m,u,f).then(e=>e===Q?{tag:`timeout`}:{tag:`ok`,response:e},e=>({tag:`rejected`,error:e}))}}function Wn(e,t,n,r,i,a){let{contributorId:o,definition:s,startMs:c,abort:l}=e,u=Date.now()-c,d=Ln(s);if(l.signal.aborted||l.abort(Error(`Collection complete`)),t.tag===`timeout`){let e=`Contributor timed out after ${u}ms`;return{outcome:{contributorId:o,outcome:$(d,`timeout`),durationMs:u},diagnostic:{contributorId:o,severity:`error`,message:e}}}if(t.tag===`rejected`){let e=`Contributor rejected: ${t.error instanceof Error?t.error.message:String(t.error)}`;return{outcome:{contributorId:o,outcome:$(d,`rejection`),durationMs:u},diagnostic:{contributorId:o,severity:`error`,message:e,cause:t.error}}}let{response:f}=t,p=In(f,s,n,r,i,a);if(p!==!0){let e=`Validation failed: ${p}`;return{outcome:{contributorId:o,outcome:$(d,`rejection`),durationMs:u},diagnostic:{contributorId:o,severity:`error`,message:e}}}return{outcome:{contributorId:o,outcome:`success`,durationMs:u,effects:zn(f)}}}function Gn(e,t){let n=e.find(e=>e.outcome===`closed-failure`);if(!n)return{outcomes:e,diagnostics:t};let r={contributorId:n.contributorId,detail:t.find(e=>e.contributorId===n.contributorId)?.message??`Closed failure`};return{outcomes:e.map(e=>{if(e.effects){let{effects:t,...n}=e;return n}return e}),diagnostics:t,closedFailure:r}}async function Kn(e,t,n,r,i,a,o){if(e.length===0)return{outcomes:[],diagnostics:[]};if(n!==void 0&&n<=Date.now())return Vn(e);let s=e.map(e=>Un(e,t,n,r,i,a)),c=await Promise.all(s.map(e=>e.settled)),l=[],u=[];for(let e=0;e<s.length;e++){let{outcome:n,diagnostic:r}=Wn(s[e],c[e],t,o,i,a);l.push(n),r&&u.push(r)}return Gn(l,u)}export{it as AbsolutePathSchema,Ce as BinaryNotFoundError,R as CLIENT_RUNTIME_STATUSES,we as ClientAccountRegistry,Fe as ClientBinaryJobRunner,ze as ClientBinaryManager,k as ClientBinaryStateRecordSchema,j as ClientBinaryStorageNamespace,M as ClientBinaryStorageSubjects,O as ClientBinaryVersionRecordSchema,Pe as ClientBinaryVersionResolver,gt as ClientConfigPrimeService,N as ClientDefinitionRegistry,Je as ClientHookHandleResponseSchema,fn as ClientHookProviderContractRegistry,Sn as ClientHookResponseRegistry,G as ClientProfileRecordSchema,yt as ClientProfileService,_t as ClientProfileStorageNamespace,q as ClientProfileStorageSubjects,We as ClientRuntimeRegistry,ut as ClientRuntimeService,B as ClientRuntimeStorageNamespace,V as ClientRuntimeStorageSubjects,Tt as ClientSessionConfigService,ce as ClientSubjects,ct as ClientWiringAggregatedResultSchema,ot as ClientWiringApplyResponseSchema,le as ClientWiringEntrySchema,at as ClientWiringListResponseSchema,st as ClientWiringRemoveResponseSchema,wn as ClientsCoreService,Tn as ClientsCoreToken,qe as DEFAULT_HOOK_HANDLE_TIMEOUT_MS,Ye as NOOP_HOOK_HANDLE_RESPONSE,U as RawClientHookPayloadSchema,z as RuntimeRecordSchema,lt as assertAbsoluteProjectDir,be as atomicModifyFile,kn as buildClientCommand,$e as buildClientSessionBase,An as buildHookCommand,W as canonicalizeClientId,Mt as clientRuntimesDual,Kn as collectContributions,Cn as createClientHookResponseContributionProcessor,jt as createClientNamespace,rt as createClientWiringListSubjectDef,nt as createClientWiringSubjectDef,Dn as createClientsCorePackage,Xe as createRawClientHookHandleSubject,Ke as createRawClientHookReceivedSubject,t as createStrategy,jn as deriveSessionEventDescriptors,et as emitBestEffort,E as isPathWithinBase,Qe as pickNonEmptyString,Ze as pickNonEmptyStringValue,nn as registerDrizzleClientBinaryStorage,ln as registerDrizzleProfileStorage,Rt as registerDrizzleRuntimeStorage,En as registerStorageHandlersWithRollback,D as resolveAndValidateBasePath,On as resolveClientBinary,n as verifyInstalledVersion};
1
+ import{n as e,r as t,t as n}from"../client-binary-version-verifier-Dv7TGFxh.mjs";import{z as r}from"zod";import*as i from"node:fs/promises";import*as a from"node:path";import{randomUUID as o}from"node:crypto";import{createBusNamespace as s,hostLocalRequest as c}from"@makaio/framework/core";import{MakaioBus as l}from"@makaio/framework/bus";import{extensionToken as u,isUniversalRange as d,versionSatisfies as f}from"@makaio/framework/contracts";import{BaseService as p}from"@makaio/framework/service-base";import{index as m,unique as ee,uniqueIndex as te}from"drizzle-orm/sqlite-core";import{index as h,unique as ne,uniqueIndex as re}from"drizzle-orm/pg-core";import{defineDialectSchema as g,defineDualTable as _,didAffectRows as ie,executeTransaction as v,registerDrizzleHandlers as ae,resolveSchema as y}from"@makaio/framework/storage/drizzle";import{and as b,eq as x,gt as oe,sql as S}from"drizzle-orm";import{ClientProfileNameSchema as C,ClientProfileSchema as se,ClientSubjects as ce,ClientSubjects as w,ClientWiringEntrySchema as le,DEFAULT_FAILURE_POLICY as ue,SessionConfigLeaseIdSchema as de,deriveHookEventTransportMode as fe,isValidContributorId as pe,isValidTimeoutMs as me,validateClosedPolicy as he}from"@makaio/framework/contracts/client";import*as ge from"node:os";import{CLIDetectionSubjects as _e}from"@makaio/framework/services/cli-detection/namespace";import{ClientStorageSubjects as ve}from"@makaio/framework/services/settings/storage";import{SessionSubjects as ye}from"@makaio/framework/contracts/session";async function be(e,t,n,r,i){let a,o=(n.get(e)??Promise.resolve()).then(async()=>{let n=await i(r(await xe(e,t)));n.changed&&await Se(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 xe(e,t){let n;try{n=await i.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return t;throw e}return JSON.parse(n)}async function Se(e,t){let n=a.dirname(e),r=a.join(n,`${a.basename(e)}.${o()}.tmp`);await i.mkdir(n,{recursive:!0});try{await i.writeFile(r,`${JSON.stringify(t,null,2)}\n`,`utf-8`),await i.rename(r,e)}catch(e){throw await i.unlink(r).catch(()=>void 0),e}}var Ce=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)}},we=class{nextAccountSequence=1;accountIdsByIdentifier=new Map;accounts=new Map;upsertAccount(e){let t=Ee(e.displayLabel),n=new Map;for(let t of e.identifiers)n.set(Te(e.clientId,t.scheme,t.value),t);let r=De(n,this.accountIdsByIdentifier,`strong`),i=De(n,this.accountIdsByIdentifier,`alias`),a=r[0]??(i.length===1?i[0]:i.length>1?Oe(i):this.createAccount()),o=(r.length>0?je(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 Te(e,t,n){return`${e}\u0000${t}\u0000${n}`}function Ee(e){return e?.trim()||void 0}function De(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(ke)}function Oe(e){return[...e].sort(ke)[0]}function ke(e,t){let n=Ae(e),r=Ae(t);return n!==null&&r!==null&&n!==r?n-r:e.localeCompare(t)}function Ae(e){let t=e.match(/^client-account-(\d+)$/);return t?Number(t[1]):null}function je(e,t,n){let r=new Set([...t,...n]);return r.delete(e),Array.from(r).sort(ke)}function Me(e){return{subject:`config.prime`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}async function T(e,t){let n=await e.requestOptional(Me(t.clientId),t);return n.handled?n.data:{primed:!1}}function Ne(){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 Pe=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 E(t,n){return!a.isAbsolute(t)||!a.isAbsolute(n)?!1:e(a.resolve(t),a.resolve(n))}function D(e,t){if(!e||!a.isAbsolute(e))throw Error(`${t} requires a non-empty absolute basePath`);return a.resolve(e)}var Fe=class{strategyDeps;config;jobs=new Map;#e=!1;resolvedBasePath;constructor(e,t){this.strategyDeps=e,this.config=t,this.resolvedBasePath=D(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,n,r,i,a,o,s){try{let c=this.resolveTargetDir(e.clientId,e.version),l=t(n,this.strategyDeps);if(l===void 0)throw Error(`Unsupported managed install descriptor type: ${n.type}`);let u=await this.executeStrategy(e,l,c,r);if(this.#e)return;let d;try{if(d=await this.runPostInstall(e,u.installPath,o,r),this.#e)return;s!==void 0&&await this.runVersionVerification(e,u.installPath,s,r)}catch(e){throw this.#e||await this.cleanupStagedArtifact(u.installPath),e}if(this.#e)return;await this.finalizeSuccess(e,u,d,r,i,a)}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 a({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,r,i){this.emitProgressIfActive(i,this.buildProgressPayload(e,`verifying`,null,t,{kind:`version-command`}))&&(this.#e||await n(this.strategyDeps.exec,t,r,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,t){let n=a.resolve(this.resolvedBasePath,e,t);if(!E(this.resolvedBasePath,n))throw Error(`Invalid install target path for client "${e}" and version "${t}"`);return n}};const O=r.object({id:r.string(),clientId:r.string(),version:r.string(),installPath:r.string(),installedAt:r.number().int().nonnegative(),createdAt:r.number().int().nonnegative()}),k=r.object({clientId:r.string(),activeVersion:r.string().nullable(),updatedAt:r.number().int().nonnegative()}),A=r.object({previousActiveVersion:r.string().nullable(),activeVersion:r.string().nullable()}),j=s(`client-binary:storage`,{insertVersion:{request:O,response:r.object({success:r.boolean()})},recordInstalledVersion:{request:r.object({versionRecord:O,makeActive:r.boolean(),updatedAt:r.number().int().nonnegative()}),response:A},listVersions:{request:r.object({clientId:r.string()}),response:r.object({versions:r.array(O)})},getSnapshot:{request:r.object({clientId:r.string()}),response:r.object({state:k.nullable(),versions:r.array(O)})},loadAllVersions:{request:r.object({}),response:r.object({versions:r.array(O)})},upsertState:{request:k,response:r.object({success:r.boolean()})},setActiveVersion:{request:r.object({clientId:r.string(),activeVersion:r.string().nullable(),updatedAt:r.number().int().nonnegative()}),response:A},getState:{request:r.object({clientId:r.string()}),response:r.object({state:k.nullable()})},loadAllState:{request:r.object({}),response:r.object({states:r.array(k)})},loadSnapshot:{request:r.object({}),response:r.object({states:r.array(k),versions:r.array(O)})},removeVersionAndClearActive:{request:r.object({clientId:r.string(),version:r.string(),updatedAt:r.number().int().nonnegative()}),response:A.extend({removedVersion:r.string().nullable()})}}),M=j.subjects;var N=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)}};const Ie=process.env.MAKAIO_SKIP_CLIENT_VERSION_CHECK===`1`;function P(e,t,n,r,i){if(n===null){if(d(r))return;if(Ie){console.warn(`[SKIP_VERSION_CHECK] ${e}: ${i} for client '${t}' did not report a version; requires ${r}`);return}throw Error(`${e}: ${i} for client '${t}' did not report a version; requires ${r}`)}if(!f(n,r)){if(Ie){console.warn(`[SKIP_VERSION_CHECK] ${e}: ${i} ${n} for client '${t}' does not satisfy ${r} — check bypassed`);return}throw Error(`${e}: ${i} ${n} for client '${t}' does not satisfy ${r}`)}}var Le=class{bus;resolvedBasePath;resolvedConfigBasePath;definitionLookup;resolutionPolicy;constructor(e){this.bus=e.bus,this.resolvedBasePath=e.resolvedBasePath,this.resolvedConfigBasePath=e.resolvedConfigBasePath,this.definitionLookup=e.definitionLookup,this.resolutionPolicy=e.resolutionPolicy??`managed-first`}async resolve(e){let t=this.definitionLookup.getDefinition(e);if(t===void 0)throw Error(`client.resolveBinary: no definition registered for client '${e}'`);if(this.resolutionPolicy===`managed-first`){let{state:n,versions:r}=await this.bus.request(M.getSnapshot,{clientId:e}),i=n?.activeVersion??null;if(i!==null)return this.buildManagedContext(e,i,t,r)}return this.buildGlobalContext(e,t)}isInstallPathWithinBase(e){return E(this.resolvedBasePath,e)}async isExpectedInstallPath(e,t,n){if(!a.isAbsolute(e)||!this.isInstallPathWithinBase(e))return!1;let r=a.resolve(this.resolvedBasePath,t,n);if(!this.isInstallPathWithinBase(r))return!1;try{let[t,n,a]=await Promise.all([i.realpath(this.resolvedBasePath),i.realpath(r),i.realpath(e)]);return E(t,n)?a===n||E(n,a):!1}catch{return!1}}async buildManagedContext(e,t,n,r){let i=r.find(e=>e.version===t);if(i===void 0)throw Error(`client.resolveBinary: active version '${t}' is not installed for client '${e}'`);if(!await this.isExpectedInstallPath(i.installPath,e,t))throw Error(`client.resolveBinary: stored installPath "${i.installPath}" does not match the expected install directory for ${e}@${t}`);n.binary!==void 0&&P(`client.resolveBinary`,e,t,n.binary.supportedVersions,`managed binary version`);let o=F(n.versionCommand)?.[0];if(o===void 0)throw Error(`client.resolveBinary: definition for '${e}' has no versionCommand — cannot derive binary path`);let s=a.resolve(i.installPath,o),c=a.resolve(i.installPath);if(!s.startsWith(c+a.sep)&&s!==c)throw Error(`client.resolveBinary: versionCommand for '${e}' resolves outside the install directory`);let{configDir:l,env:u}=this.resolveIsolatedConfig(e,n);return{binaryPath:s,env:u,configDir:l,source:`managed`,version:t}}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(w.scan,{targets:[n]}),i=r.find(t=>t.clientId===e);if(i===void 0||!i.found)throw new Ce(e);let o=i.version??null;P(`client.resolveBinary`,e,o,t.binary.supportedVersions,`detected global binary version`);let s=this.resolveGlobalConfigDir(t),c=i.binaryPath??null;if(c!==null&&!a.isAbsolute(c))throw Error(`client.resolveBinary: detected global binary path for '${e}' is not absolute`);return{binaryPath:c,env:{},configDir:s,source:`global`,version:o}}resolveIsolatedConfig(e,t){let{configIsolation:n}=t;if(n===void 0)return{configDir:null,env:{}};let r=a.join(this.resolvedConfigBasePath,e,`config`),i=n.pathKind===`file`?a.join(r,a.basename(n.defaultPath)):r;return{configDir:r,env:{[n.envVar]:i}}}resolveGlobalConfigDir(e){let{configIsolation:t}=e;if(t===void 0)return null;let n=t.defaultPath,r=n===`~`?ge.homedir():n.startsWith(`~/`)?a.join(ge.homedir(),n.slice(2)):n,i=t.pathKind===`file`?a.dirname(r):r;if(!a.isAbsolute(i))throw Error(`ConfigIsolation defaultPath for '${e.id}' resolved to non-absolute path '${r}'; use an absolute or tilde-expanded path (e.g. '~/.myapp')`);return i}};function F(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 Re(e,t){let{versions:n,states:r}=await e.request(M.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 ze=class extends p{config;definitionLookup;versionResolver;jobRunner;strategyDeps;resolvedBasePath;resolvedConfigBasePath;resolver;pendingClients=new Set;constructor(e=l,t,n=new N([]),r=Ne()){super(e),this.config=t,this.definitionLookup=n,this.resolvedBasePath=D(t.basePath,`ClientBinaryManager`),this.resolvedConfigBasePath=D(t.configBasePath,`ClientBinaryManager configBasePath`),this.strategyDeps=r,this.versionResolver=new Pe,this.jobRunner=new Fe(r,t),this.resolver=new Le({bus:e,resolvedBasePath:this.resolvedBasePath,resolvedConfigBasePath:this.resolvedConfigBasePath,definitionLookup:n,...t.resolutionPolicy!==void 0&&{resolutionPolicy:t.resolutionPolicy}})}async onInit(){this.registerHandler(w.list,async e=>{let t=await this.handleList();e.setResult({clients:t})}),this.registerHandler(w.install,async e=>{let t=await this.handleInstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(w.update,async e=>{let t=await this.handleUpdate(e.payload.clientId);e.setResult(t)}),this.registerHandler(w.setActive,async e=>{let t=await this.handleSetActive(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(w.uninstall,async e=>{let t=await this.handleUninstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(w.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 Re(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&&P(`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&&P(`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:r}=await this.bus.request(M.listVersions,{clientId:e}),i=r.find(e=>e.version===t);if(i===void 0)throw Error(`client.setActive: version '${t}' is not installed for client '${e}'`);let a=this.definitionLookup.getDefinition(e);if(a===void 0)throw Error(`client.setActive: no definition registered for client '${e}'`);a.binary!==void 0&&P(`client.setActive`,e,t,a.binary.supportedVersions,`requested binary version`);let o=F(a.versionCommand);if(o===void 0)throw Error(`client.setActive: no versionCommand registered for client '${e}'`);if(!await this.resolver.isExpectedInstallPath(i.installPath,e,t))throw Error(`client.setActive: stored installPath "${i.installPath}" does not match the expected install directory for ${e}@${t}`);return await n(this.strategyDeps.exec,i.installPath,o,t),await this.patchActiveVersion(e,t,`set-active`),{clientId:e,activeVersion:t}}finally{this.pendingClients.delete(e)}}async handleUninstall(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(M.listVersions,{clientId:e}),r=n.find(e=>e.version===t);if(r===void 0)throw Error(`client.uninstall: version '${t}' is not installed for client '${e}'`);let{removedVersion:i,previousActiveVersion:o,activeVersion:s}=await this.bus.request(M.removeVersionAndClearActive,{clientId:e,version:t,updatedAt:Date.now()});if(i===null)throw Error(`client.uninstall: failed to delete version '${t}' for client '${e}'`);let c=r.installPath,l=typeof c==`string`&&c.length>0?a.resolve(c):null;if(typeof c!=`string`||c.length===0||l===null||!a.isAbsolute(c)||!await this.resolver.isExpectedInstallPath(l,e,t)?console.warn(`[ClientBinaryManager] Skipping removeDirectory: stored installPath "${String(c)}" does not match the expected install directory for ${e}@${t}`):await this.strategyDeps.removeDirectory(l).catch(n=>{console.warn(`[ClientBinaryManager] Failed to remove binary directory "${l}" for ${e}@${t}:`,n)}),o!==null&&s===null)try{await this.bus.emit(w.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:t,activeVersion:s}}finally{this.pendingClients.delete(e)}}async patchActiveVersion(e,t,n){let r=(await this.bus.request(M.setActiveVersion,{clientId:e,activeVersion:t,updatedAt:Date.now()})).previousActiveVersion;if(r!==t)try{await this.bus.emit(w.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(w.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(w.installJob.completed,e).catch(e=>{console.warn(`[ClientBinaryManager] Failed to emit client.installJob.completed:`,e)})},r.postInstall,F(r.versionCommand)),o.jobId}makeCompletionCallback(){return async({clientId:e,version:t,installPath:n,makeActive:r,reason:i})=>{let a=Date.now();await T(this.bus,{clientId:e,configDir:this.resolveManagedConfigDir(e),phase:`managed-install`,binaryVersion:t});let o=await this.bus.request(M.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(w.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 a.join(this.resolvedConfigBasePath,e,`config`)}};function I(e,t){return`${e}${t}`}function L(e,t){return`${e}${t}`}var Be=class{records=new Map;bySupervisorSessionId=new Map;byPidClientId=new Map;byAdapterSessionClientId=new Map;adapterOwnedSessions=new Set;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(I(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.set(L(e.adapterSessionId,e.clientId),e.clientRuntimeId))}delete(e){let t=this.records.get(e);t&&(this.removeIndexEntries(t),t.adapterSessionId!==void 0&&this.adapterOwnedSessions.delete(L(t.adapterSessionId,t.clientId)),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(I(t,r));if(e!==void 0)return this.records.get(e)}if(n!==void 0){let e=this.byAdapterSessionClientId.get(L(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(),this.adapterOwnedSessions.clear()}markAdapterOwned(e,t){this.adapterOwnedSessions.add(L(e,t))}hasAdapterSession(e,t){return this.adapterOwnedSessions.has(L(e,t))}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(I(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.set(L(e.adapterSessionId,e.clientId),e.clientRuntimeId)}removeIndexEntries(e){e.supervisorSessionId!==void 0&&this.bySupervisorSessionId.delete(e.supervisorSessionId),e.pid!==void 0&&this.byPidClientId.delete(I(e.pid,e.clientId)),e.adapterSessionId!==void 0&&this.byAdapterSessionClientId.delete(L(e.adapterSessionId,e.clientId))}};const R=[`observed`,`started`],z=r.object({clientRuntimeId:r.string(),clientId:r.string(),status:r.enum(R),supervisorSessionId:r.string().optional(),pid:r.number().int().positive().optional(),parentPid:r.number().int().positive().optional(),adapterSessionId:r.string().optional(),sessionId:r.string().optional(),cwd:r.string().optional(),argv:r.array(r.string()).optional(),metadata:r.record(r.string(),r.unknown()).optional(),observedAt:r.number().int().nonnegative(),createdAt:r.number().int().nonnegative(),updatedAt:r.number().int().nonnegative()}),B=s(`client-runtime:storage`,{upsert:{request:z,response:r.object({success:r.boolean()})},loadAll:{request:r.object({}),response:r.object({records:r.array(z)})}}),V=B.subjects;function Ve(e){return e.supervisorSessionId!==void 0||e.adapterSessionId!==void 0}function H(e){return{...e,argv:e.argv===void 0?void 0:[...e.argv],metadata:e.metadata===void 0?void 0:structuredClone(e.metadata)}}function He(e){return Math.max(Date.now(),e+1)}function Ue(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 We=class{runtimeMap=new Be;bus;constructor(e){this.bus=e}async loadFromStorage(){if(!this.bus)return;let e=await this.bus.requestOptional(V.loadAll,{});if(!e.handled)return;let t=Date.now();for(let n of e.data.records)this.runtimeMap.setFromStorage(H(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&&Ve(e),i=Ue(t,e),a=n&&e.observedAt>t.observedAt;return r&&(t.status=`started`),(i||r||a)&&(t.updatedAt=He(t.updatedAt),a&&(t.observedAt=e.observedAt),this.runtimeMap.set(t),await this.persistRecord(t)),{clientRuntimeId:t.clientRuntimeId,created:!1,promoted:r,record:H(t)}}let n=Date.now(),r=o(),i=Ve(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:H(a)}}getRuntime(e){let t=this.runtimeMap.get(e);return t?H(t):void 0}markAdapterOwned(e,t){this.runtimeMap.markAdapterOwned(e,t)}hasAdapterSession(e,t){return this.runtimeMap.hasAdapterSession(e,t)}clear(){this.runtimeMap.clear()}get size(){return this.runtimeMap.size}async persistRecord(e){this.bus&&await this.bus.requestOptional(V.upsert,H(e))}};const U=r.object({eventName:r.string(),receivedAt:r.number().int().finite().nonnegative().describe(`Unix epoch timestamp in milliseconds`),payload:r.record(r.string(),r.unknown()),metadata:r.record(r.string(),r.unknown()).optional()}),Ge=/^[a-z0-9-]+$/;function W(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(!Ge.test(r))throw Error(`[${t}] clientId must contain only lowercase letters, numbers, and hyphens after an optional client: prefix`);return r}function Ke(e){return{subject:`hook.received`,$meta:{namespace:`client:${W(e,`createRawClientHookReceivedSubject`)}`,isRequest:!1,local:!1,channel:!1}}}const qe=5e3,Je=r.object({exitCode:r.number().int().min(0).max(255).default(0),stdout:r.string().default(``),stderr:r.string().default(``)}),Ye=Object.freeze({exitCode:0,stdout:``,stderr:``});function Xe(e){return{subject:`hook.handle`,$meta:{namespace:`client:${W(e,`createRawClientHookHandleSubject`)}`,isRequest:!0,local:!1,channel:!1,hostLocalRequest:!0}}}function Ze(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Qe(e,t){return Ze(e[t])}function $e(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 et(e){try{e().catch(tt)}catch(e){tt(e)}}function tt(e){(process.env.DEBUG||process.env.MAKAIO_DEBUG)&&console.debug(`[emitBestEffort] observed-semantics emission failed`,e)}function nt(e,t){return{subject:t,$meta:{namespace:`client:${W(e,`createClientWiringSubjectDef`)}`,isRequest:!0,local:!1,channel:!1}}}function rt(e){return nt(e,`wiring.list`)}const it=r.string().min(1).refine(a.isAbsolute,{message:`projectDir must be an absolute path`}),at=r.object({entries:r.array(le)}),ot=r.object({applied:r.number().int().nonnegative(),skipped:r.number().int().nonnegative()}),st=r.object({removed:r.number().int().nonnegative()}),ct=r.object({clientId:r.string().trim().min(1),entries:r.array(le)});function lt(e){if(e!==void 0&&!a.isAbsolute(e))throw Error(`projectDir must be an absolute path, got: ${e}`)}var ut=class extends p{accountRegistry;runtimeRegistry;latestSnapshots=new Map;activeIdentities=new Map;constructor(e=l,t=new we,n=new We(e)){super(e),this.accountRegistry=t,this.runtimeRegistry=n}async onInit(){await this.runtimeRegistry.loadFromStorage(),this.registerHandler(w.account.observe,e=>this.handleAccountObserve(e)),this.registerHandler(w.usage.ingest,e=>this.handleUsageIngest(e)),this.registerHandler(w.scan,async e=>{let t=await this.scanClients(e.payload.targets);e.setResult({results:t})}),this.registerHandler(w.runtime.observe,e=>this.handleRuntimeObserve(e)),this.registerHandler(w.runtime.isAdapterManaged,e=>{let{adapterSessionId:t,clientId:n}=e.payload;e.setResult({managed:this.runtimeRegistry.hasAdapterSession(t,n)})}),this.registerHandler(w.wiring.list,async e=>{let t=await this.listWirings(e.payload);e.setResult({results:t})}),this.registerHandler(w.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(w.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=pt(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(w.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=dt(t.clientAccountId,e.payload,t.displayLabel),r=pt(ft(this.latestSnapshots.get(t.clientAccountId),n),t.displayLabel);this.latestSnapshots.set(t.clientAccountId,r),await this.bus.emit(w.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);t.source.layer===`adapter`&&t.adapterSessionId!==void 0&&this.runtimeRegistry.markAdapterOwned(t.adapterSessionId,t.clientId),(r.created||r.promoted)&&await this.bus.emit(w.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(_e.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,a=t?.path;return{clientId:e.clientId,found:n,...a!==void 0&&{binaryPath:a},version:r,warningMessage:ht(n,r,e.supportedVersions)}})}async listScannableStoredClients(){let{clients:e}=await this.bus.request(ve.list,{});return e.filter(mt).map(e=>({clientId:e.id,binaryName:e.binary.name,supportedVersions:e.binary.supportedVersions}))}async listWirings(e){lt(e.projectDir);let{clients:t}=await this.bus.request(ve.list,{}),n=e.clientId===void 0?void 0:W(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=rt(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 dt(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 ft(e,t){return e&&e.observedAt>t.observedAt?e:t}function pt(e,t){return!e||t===void 0||e.displayLabel===t?e:{...e,displayLabel:t}}function mt(e){return e.enabled&&e.binary!==void 0}function ht(e,t,n){if(e&&t!==void 0&&t!==`unknown`&&n!==void 0&&!f(t,n))return`Unsupported version: requires ${n}`}var gt=class extends p{constructor(e=l){super(e)}onInit(){this.registerHandler(w.config.prime,async e=>{e.setResult(await T(this.bus,e.payload))})}};const G=se,K=r.string().trim().min(1),_t=s(`client-profile:storage`,{get:{request:r.object({clientId:K,name:C}),response:r.object({record:G.nullable()})},getById:{request:r.object({id:K}),response:r.object({record:G.nullable()})},list:{request:r.object({clientId:K}),response:r.object({records:r.array(G)})},set:{request:G,response:r.object({success:r.boolean()})},delete:{request:r.object({clientId:K,name:C}),response:r.object({success:r.boolean()})},clearDefault:{request:r.object({clientId:K}),response:r.object({success:r.boolean()})},setDefault:{request:r.object({clientId:K,name:C}),response:r.object({record:G.nullable()})}}),q=_t.subjects;function vt(e,t,n){let r=a.resolve(e),i=a.resolve(t),o=a.relative(r,i);if(o!==``&&!o.startsWith(`..`)&&!a.isAbsolute(o))return i;throw Error(`${n} refused to access path outside client profile root`)}var yt=class extends p{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(w.profile.create,async e=>{let t=W(e.payload.clientId,`profile.create`),{name:n,description:r}=e.payload;if((await this.bus.request(q.get,{clientId:t,name:n})).record!==null)throw Error(`Profile '${n}' already exists for client '${t}'`);let s=a.join(this.clientsBasePath,t,`profiles`),c=vt(s,a.join(s,n),`profile.create`);await i.mkdir(c,{recursive:!0});try{await T(this.bus,{clientId:t,configDir:c,phase:`profile-create`});let i=Date.now(),a={id:o(),clientId:t,name:n,description:r??null,configDir:c,isDefault:!1,createdAt:i,updatedAt:i};await this.bus.request(q.set,a),e.setResult({profile:a})}catch(e){throw await i.rm(c,{recursive:!0,force:!0}),e}})}registerListHandler(){this.registerHandler(w.profile.list,async e=>{let t=W(e.payload.clientId,`profile.list`),n=await this.bus.request(q.list,{clientId:t});e.setResult({profiles:n.records})})}registerGetHandler(){this.registerHandler(w.profile.get,async e=>{let t=W(e.payload.clientId,`profile.get`),n=await this.bus.request(q.get,{clientId:t,name:e.payload.name});e.setResult({profile:n.record})})}registerUpdateHandler(){this.registerHandler(w.profile.update,async e=>{let t=W(e.payload.clientId,`profile.update`),{name:n,description:r}=e.payload,i=await this.bus.request(q.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(q.set,a),e.setResult({profile:a})})}registerDeleteHandler(){this.registerHandler(w.profile.delete,async e=>{let t=W(e.payload.clientId,`profile.delete`),{name:n}=e.payload,r=await this.bus.request(q.get,{clientId:t,name:n});r.record!==null&&(vt(a.join(this.clientsBasePath,t,`profiles`),r.record.configDir,`profile.delete`),await i.rm(r.record.configDir,{recursive:!0,force:!0}));let o=await this.bus.request(q.delete,{clientId:t,name:n});e.setResult({success:o.success})})}registerSetDefaultHandler(){this.registerHandler(w.profile.setDefault,async e=>{let t=W(e.payload.clientId,`profile.setDefault`),{name:n}=e.payload,r=await this.bus.request(q.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=ge.platform();if(e===`darwin`||e===`linux`||e===`win32`)return e;throw Error(`client.sessionConfig does not support platform '${e}'`)}function wt(e,t,n){let r=de.safeParse(t);if(!r.success)throw Error(`${n} received an unsafe lease ID`);let i=a.resolve(e),o=a.resolve(i,r.data),s=a.relative(i,o);if(s===``||!s.startsWith(`..`)&&!a.isAbsolute(s))return o;throw Error(`${n} refused to access path outside client sessions root`)}var Tt=class extends p{clientsBasePath;getNow;liveLeasesByClient=new Map;liveLeasesByOwner=new Map;constructor(e,t,n=St){super(e),this.clientsBasePath=t,this.getNow=n}async onInit(){this.registerCreateHandler(),this.registerHandler(w.sessionConfig.destroy,async e=>{let{clientId:t,leaseId:n}=e.payload,r=W(t,`sessionConfig.destroy`),i=this.resolveClientSessionDir(r,n,`sessionConfig.destroy`),a=this.getLiveLease(r,n);a===void 0?await this.destroyClientSessionDir(r,i):await this.releaseLiveLease(a),e.setResult({success:!0})}),this.registerHandler(w.sessionConfig.cleanup,async e=>{let{clientId:t}=e.payload,n=t===void 0?void 0:W(t,`sessionConfig.cleanup`),r=await this.cleanupOrphanedDirs(n);e.setResult({removed:r})}),this.registerHandler(ye.closed,async e=>{await this.destroyOwnedLeases(e.payload.sessionId)}),await this.cleanupOrphanedDirs()}registerCreateHandler(){this.registerHandler(w.sessionConfig.create,async e=>{let{clientId:t,leaseId:n,ownerSessionId:r,profileName:a,baseConfigDir:o,projectDir:s,configInheritance:c=`full`}=e.payload,l=W(t,`sessionConfig.create`),u=this.resolveClientSessionDir(l,n,`sessionConfig.create`),d=this.reserveLiveLease({clientId:l,leaseId:n,...r===void 0?{}:{ownerSessionId:r}});try{await i.mkdir(u,{recursive:!0});let t=await this.resolveBaseConfigDir(l,u,a,o),r=bt(l),f=await this.bus.requestOptional(r,{sessionDir:u,baseConfigDir:t,projectDir:s,platform:Ct(),configInheritance:c}),p=f.handled?f.data.env??{}:{},m=f.handled?f.data.authMaterialized:!1;if(await T(this.bus,{clientId:l,configDir:u,phase:`session-create`,projectDir:s}),d.releaseRequested)throw Error(`Config lease '${n}' was released while it was being created`);e.setResult({sessionDir:u,env:p,authMaterialized:m}),d.state=`ready`}catch(e){try{await this.beginLeaseCleanup(d)}catch(t){throw AggregateError([e,t],`Client session config creation and rollback both failed`)}throw e}finally{d.settleCreation(),d.state===`released`&&this.untrackLiveLease(d)}})}async resolveBaseConfigDir(e,t,n,r){if(r!==void 0)return r;if(n!==void 0){let t=await this.bus.request(q.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(q.list,{clientId:e})).records.find(e=>e.isDefault);return i?i.configDir:t}async cleanupOrphanedDirs(e){let t=[],n=this.getNow(),r=e===void 0?await this.listClientIds():[e];return await Promise.all(r.map(async e=>{let r=a.join(this.clientsBasePath,e,`sessions`),o=await i.readdir(r).catch(()=>[]);await Promise.all(o.map(async a=>{if(!de.safeParse(a).success)return;let o=wt(r,a,`sessionConfig.cleanup`),s;try{s=await i.stat(o)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let c=s.birthtimeMs>0?s.birthtimeMs:s.ctimeMs;s.isDirectory()&&n-c>36e5&&!this.isLiveLease(e,a)&&(await this.destroyClientSessionDir(e,o),t.push(o))}))})),t}async destroyOwnedLeases(e){let t=[...this.liveLeasesByOwner.get(e)??[]],n=(await Promise.allSettled(t.map(async e=>{this.getLiveLease(e.clientId,e.leaseId)===e&&await this.releaseLiveLease(e)}))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(n.length>0)throw AggregateError(n,`Failed to release config leases owned by session '${e}'`)}async destroyClientSessionDir(e,t){try{await this.bus.requestOptional(xt(e),{sessionDir:t,platform:Ct()})}finally{await i.rm(t,{recursive:!0,force:!0})}}isLiveLease(e,t){return this.getLiveLease(e,t)!==void 0}getLiveLease(e,t){return this.liveLeasesByClient.get(e)?.get(t)}resolveClientSessionDir(e,t,n){return wt(a.join(this.clientsBasePath,e,`sessions`),t,n)}reserveLiveLease(e){if(this.isLiveLease(e.clientId,e.leaseId))throw Error(`Config lease '${e.leaseId}' is already active for client '${e.clientId}'`);let t=Promise.withResolvers(),n={...e,state:`creating`,releaseRequested:!1,creationSettled:t.promise,settleCreation:()=>t.resolve()},r=this.liveLeasesByClient.get(n.clientId)??new Map;if(r.set(n.leaseId,n),this.liveLeasesByClient.set(n.clientId,r),n.ownerSessionId!==void 0){let e=this.liveLeasesByOwner.get(n.ownerSessionId)??new Set;e.add(n),this.liveLeasesByOwner.set(n.ownerSessionId,e)}return n}async releaseLiveLease(e){if(this.getLiveLease(e.clientId,e.leaseId)!==e){e.releasePromise!==void 0&&await e.releasePromise;return}if(e.releaseRequested=!0,e.state===`creating`){await e.creationSettled,e.releasePromise!==void 0&&await e.releasePromise;return}await this.beginLeaseCleanup(e)}beginLeaseCleanup(e){if(e.releasePromise!==void 0)return e.releasePromise;if(this.getLiveLease(e.clientId,e.leaseId)!==e)return Promise.resolve();let t=e.state===`creating`;e.state=`releasing`;let n=this.resolveClientSessionDir(e.clientId,e.leaseId,`sessionConfig.release`);return e.releasePromise=this.destroyClientSessionDir(e.clientId,n).finally(()=>{e.state=`released`,t||this.untrackLiveLease(e)}),e.releasePromise}untrackLiveLease(e){let t=this.liveLeasesByClient.get(e.clientId);if(t?.get(e.leaseId)===e&&(t.delete(e.leaseId),t.size===0&&this.liveLeasesByClient.delete(e.clientId),e.ownerSessionId!==void 0)){let t=this.liveLeasesByOwner.get(e.ownerSessionId);t?.delete(e),t?.size===0&&this.liveLeasesByOwner.delete(e.ownerSessionId)}}async listClientIds(){return(await i.readdir(this.clientsBasePath,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()).map(e=>e.name)}};const Et=new Set([`hook.received`,`hook.handle`]);function Dt(e,t){return l.registerNamespace(s(`client:${e}`,{"hook.received":U,"hook.handle":c({request:U,response:Je}),...t})).subjects}function Ot(e,t){let n=Object.keys(t).filter(e=>Et.has(e));if(n.length===0)return;let r=n.join(`, `);throw Error([`[createClientNamespace] additionalSchemas for client:${e}`,`cannot override reserved shared hook subjects: ${r}`].join(` `))}function kt(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 At(e,t,n){let r=Object.keys(n).filter(e=>!kt(t,e));if(r.length!==0)throw Error(`[createClientNamespace] client:${e} was already registered without required subjects: ${r.join(`, `)}`)}function jt(e,t){let n=W(e,`createClientNamespace`),r=t??{};Ot(n,r);let i=Dt(n,r);return At(n,i,r),{namespaceDomain:`client:${n}`,subjects:i}}const Mt=_(`client_runtimes`,e=>({id:e.text(`id`).primaryKey(),clientId:e.text(`client_id`).notNull(),status:e.text(`status`).notNull(),supervisorSessionId:e.text(`supervisor_session_id`),pid:e.int4(`pid`),parentPid:e.int4(`parent_pid`),adapterSessionId:e.text(`adapter_session_id`),sessionId:e.text(`session_id`),cwd:e.text(`cwd`),argv:e.jsonCol(`argv`),metadata:e.jsonCol(`metadata`),observedAt:e.epochMs(`observed_at`).notNull(),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull()}),{sqlite:e=>[m(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),m(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),m(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)],postgres:e=>[h(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),h(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),h(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)]}),Nt=Mt.sqlite,Pt=Mt.postgres,Ft=g({clientRuntimes:Nt},{clientRuntimes:Pt}),It=new Set(R);function Lt(e){if(!It.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 Rt(e,t){let{clientRuntimes:n}=y(t,Ft),r=e.on(V.upsert,async e=>{let r=e.payload,i={clientId:r.clientId,status:r.status,supervisorSessionId:r.supervisorSessionId??null,pid:r.pid??null,parentPid:r.parentPid??null,adapterSessionId:r.adapterSessionId??null,sessionId:r.sessionId??null,cwd:r.cwd??null,argv:r.argv??null,metadata:r.metadata??null,observedAt:r.observedAt,updatedAt:r.updatedAt};await t.insert(n).values({id:r.clientRuntimeId,createdAt:r.createdAt,...i}).onConflictDoUpdate({target:n.id,set:i,setWhere:oe(S`excluded.updated_at`,n.updatedAt)}),e.setResult({success:!0})}),i=e.on(V.loadAll,async e=>{let r=await t.select().from(n);e.setResult({records:r.map(Lt)})});return()=>{r(),i()}}const zt=_(`client_binary_versions`,e=>({id:e.text(`id`).primaryKey(),clientId:e.text(`client_id`).notNull(),version:e.text(`version`).notNull(),installPath:e.text(`install_path`).notNull(),installedAt:e.epochMs(`installed_at`).notNull(),createdAt:e.epochMs(`created_at`).notNull()}),{sqlite:e=>[ee(`uq_client_binary_versions_client_version`).on(e.clientId,e.version)],postgres:e=>[ne(`uq_client_binary_versions_client_version`).on(e.clientId,e.version)]}),Bt=zt.sqlite,Vt=_(`client_binary_state`,e=>({clientId:e.text(`client_id`).primaryKey(),activeVersion:e.text(`active_version`),updatedAt:e.epochMs(`updated_at`).notNull()})),Ht=Vt.sqlite,Ut=zt.postgres,Wt=Vt.postgres,J=g({clientBinaryVersions:Bt,clientBinaryState:Ht},{clientBinaryVersions:Ut,clientBinaryState:Wt});function Y(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}function X(e){return{clientId:e.clientId,activeVersion:e.activeVersion??null,updatedAt:e.updatedAt}}function Gt(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}async function Kt(e,t,n){await e.insert(n).values(Gt(t)).onConflictDoNothing({target:[n.clientId,n.version]})}function qt(e,t,n){return{clientId:e,activeVersion:t,updatedAt:n}}async function Jt(e,t,n,r,i){await e.insert(i).values(qt(t,n,r)).onConflictDoUpdate({target:i.clientId,set:{activeVersion:n,updatedAt:r}})}async function Yt(e,t){let{clientBinaryVersions:n}=y(e,J);await Kt(e,t,n)}async function Xt(e,t,n,r){let{clientBinaryVersions:i,clientBinaryState:a}=y(e,J);return v(e,async e=>{let[o]=await e.select().from(a).where(x(a.clientId,t.clientId)).limit(1),s=o?.activeVersion??null;return await Kt(e,t,i),n?(await Jt(e,t.clientId,t.version,r,a),{previousActiveVersion:s,activeVersion:t.version}):{previousActiveVersion:s,activeVersion:s}})}async function Zt(e,t){let{clientBinaryVersions:n,clientBinaryState:r}=y(e,J);return v(e,async e=>{let[i]=await e.select().from(r).where(x(r.clientId,t)).limit(1),a=await e.select().from(n).where(x(n.clientId,t));return{state:i?X(i):null,versions:a.map(Y)}})}async function Qt(e){let{clientBinaryVersions:t,clientBinaryState:n}=y(e,J);return v(e,async e=>{let r=await e.select().from(n),i=await e.select().from(t);return{states:r.map(X),versions:i.map(Y)}})}async function $t(e,t){let{clientBinaryState:n}=y(e,J),r={clientId:t.clientId,activeVersion:t.activeVersion??null,updatedAt:t.updatedAt};await e.insert(n).values(r).onConflictDoUpdate({target:n.clientId,set:r})}async function en(e,t,n,r){let{clientBinaryState:i}=y(e,J);return v(e,async e=>{let[a]=await e.select().from(i).where(x(i.clientId,t)).limit(1),o=a?.activeVersion??null;return await Jt(e,t,n,r,i),{previousActiveVersion:o,activeVersion:n}})}async function tn(e,t,n,r){let{clientBinaryVersions:i,clientBinaryState:a}=y(e,J);return v(e,async e=>{let[o]=await e.select().from(a).where(x(a.clientId,t)).limit(1),s=o?.activeVersion??null;if(!ie(await e.delete(i).where(b(x(i.clientId,t),x(i.version,n)))))return{removedVersion:null,previousActiveVersion:s,activeVersion:s};await e.update(a).set({activeVersion:null,updatedAt:r}).where(b(x(a.clientId,t),x(a.activeVersion,n)));let[c]=await e.select().from(a).where(x(a.clientId,t)).limit(1);return{removedVersion:n,previousActiveVersion:s,activeVersion:c?.activeVersion??null}})}function nn(e,t){let{clientBinaryVersions:n,clientBinaryState:r}=y(t,J),i=[e.on(M.insertVersion,async e=>{await Yt(t,e.payload),e.setResult({success:!0})}),e.on(M.recordInstalledVersion,async e=>{let{versionRecord:n,makeActive:r,updatedAt:i}=e.payload,a=await Xt(t,n,r,i);e.setResult(a)}),e.on(M.listVersions,async e=>{let r=await t.select().from(n).where(x(n.clientId,e.payload.clientId));e.setResult({versions:r.map(Y)})}),e.on(M.getSnapshot,async e=>{let{state:n,versions:r}=await Zt(t,e.payload.clientId);e.setResult({state:n,versions:r})}),e.on(M.loadAllVersions,async e=>{let r=await t.select().from(n);e.setResult({versions:r.map(Y)})}),e.on(M.upsertState,async e=>{await $t(t,e.payload),e.setResult({success:!0})}),e.on(M.setActiveVersion,async e=>{let{clientId:n,activeVersion:r,updatedAt:i}=e.payload,a=await en(t,n,r,i);e.setResult(a)}),e.on(M.getState,async e=>{let[n]=await t.select().from(r).where(x(r.clientId,e.payload.clientId)).limit(1);e.setResult({state:n?X(n):null})}),e.on(M.loadAllState,async e=>{let n=await t.select().from(r);e.setResult({states:n.map(X)})}),e.on(M.loadSnapshot,async e=>{let{states:n,versions:r}=await Qt(t);e.setResult({states:n,versions:r})}),e.on(M.removeVersionAndClearActive,async e=>{let{clientId:n,version:r,updatedAt:i}=e.payload,a=await tn(t,n,r,i);e.setResult(a)})];return()=>{for(let e of i)e()}}const rn=_(`client_profiles`,e=>({id:e.text(`id`).primaryKey(),clientId:e.text(`client_id`).notNull(),name:e.text(`name`).notNull(),description:e.text(`description`),configDir:e.text(`config_dir`).notNull(),isDefault:e.bool(`is_default`).notNull().default(!1),createdAt:e.epochMs(`created_at`).notNull(),updatedAt:e.epochMs(`updated_at`).notNull()}),{sqlite:e=>[te(`uq_client_profiles_client_name`).on(e.clientId,e.name),te(`uq_client_profiles_default`).on(e.clientId).where(S`${e.isDefault} = 1`)],postgres:e=>[re(`uq_client_profiles_client_name`).on(e.clientId,e.name),re(`uq_client_profiles_default`).on(e.clientId).where(S`${e.isDefault} = true`)]}),an=rn.sqlite,on=rn.postgres,sn=g({clientProfiles:an},{clientProfiles:on});function Z(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 cn(e,t,n){let{clientProfiles:r}=y(e,sn),i=Date.now();return v(e,async e=>{let[a]=await e.select().from(r).where(b(x(r.clientId,t),x(r.name,n))).limit(1);if(a===void 0)return null;await e.update(r).set({isDefault:!1,updatedAt:i}).where(b(x(r.clientId,t),x(r.isDefault,!0))),await e.update(r).set({isDefault:!0,updatedAt:i}).where(b(x(r.clientId,t),x(r.name,n)));let[o]=await e.select().from(r).where(b(x(r.clientId,t),x(r.name,n))).limit(1);return o===void 0?null:Z(o)})}function ln(e,t){let{clientProfiles:n}=y(t,sn),r=[e.on(q.get,async e=>{let{clientId:r,name:i}=e.payload,[a]=await t.select().from(n).where(b(x(n.clientId,r),x(n.name,i))).limit(1);e.setResult({record:a?Z(a):null})}),e.on(q.getById,async e=>{let[r]=await t.select().from(n).where(x(n.id,e.payload.id)).limit(1);e.setResult({record:r?Z(r):null})}),e.on(q.list,async e=>{let r=await t.select().from(n).where(x(n.clientId,e.payload.clientId));e.setResult({records:r.map(Z)})}),e.on(q.set,async e=>{let r=e.payload,i={id:r.id,clientId:r.clientId,name:r.name,description:r.description??null,configDir:r.configDir,isDefault:r.isDefault,createdAt:r.createdAt,updatedAt:r.updatedAt};await t.insert(n).values(i).onConflictDoUpdate({target:n.id,set:{name:r.name,description:r.description??null,configDir:r.configDir,isDefault:r.isDefault,updatedAt:r.updatedAt}}),e.setResult({success:!0})}),e.on(q.delete,async e=>{let{clientId:r,name:i}=e.payload,a=await t.delete(n).where(b(x(n.clientId,r),x(n.name,i)));e.setResult({success:ie(a)})}),e.on(q.clearDefault,async e=>{await t.update(n).set({isDefault:!1,updatedAt:Date.now()}).where(b(x(n.clientId,e.payload.clientId),x(n.isDefault,!0))),e.setResult({success:!0})}),e.on(q.setDefault,async e=>{let{clientId:n,name:r}=e.payload,i=await cn(t,n,r);e.setResult({record:i})})];return()=>{for(let e of r)e()}}function un(e,t){return`${e}\0${t}`}function dn(e){let t=e=>typeof e==`string`&&e.trim().length>0;if(typeof e!=`object`||!e)throw Error(`Provider contract catalog must be an object`);if(!t(e.clientId)||!t(e.contractId)||!t(e.version))throw Error(`Provider contract catalog requires non-empty clientId, contractId, and version`);if(!Array.isArray(e.supportedInteractions)||e.supportedInteractions.length===0)throw Error(`Provider contract catalog requires supported interactions`);if(e.supportedInteractions.some(e=>!t(e))||new Set(e.supportedInteractions).size!==e.supportedInteractions.length)throw Error(`Provider contract catalog interactions must be non-empty and unique`);if(!Array.isArray(e.blockability)||e.blockability.length!==e.supportedInteractions.length)throw Error(`Provider contract catalog requires complete blockability metadata`);let n=new Map;for(let r of e.blockability){if(!t(r.interaction)||typeof r.blockable!=`boolean`||n.has(r.interaction))throw Error(`Provider contract catalog blockability metadata must be complete and unique`);n.set(r.interaction,r.blockable)}if(e.supportedInteractions.some(e=>!n.has(e))||typeof e.validate!=`function`)throw Error(`Provider contract catalog must provide blockability metadata and a validator for every interaction`)}var fn=class{entries=new Map;registerProviderContract(e,t){dn(t);let n=un(t.clientId,t.contractId),r=this.entries.get(n);if(r)throw Error(`Provider contract collision: contract '${t.contractId}' for client '${t.clientId}' is already registered by extension '${r.extensionId}'; extension '${e}' cannot claim it`);this.entries.set(n,{extensionId:e,catalog:t})}unregisterProviderContract(e,t,n){let r=un(t,n),i=this.entries.get(r);i&&i.extensionId===e&&this.entries.delete(r)}unregisterAllByExtension(e){for(let[t,n]of this.entries)n.extensionId===e&&this.entries.delete(t)}getProviderContract(e,t){let n=un(e,t);return this.entries.get(n)?.catalog}getProviderContractsByClient(e){let t=[];for(let n of this.entries.values())n.catalog.clientId===e&&t.push(n.catalog);return t}getAllProviderContracts(){return[...this.entries.values()].map(e=>e.catalog)}clear(){this.entries.clear()}};function pn(e,t){return`${e}/${t}`}function mn(e,t,n){switch(e.kind){case`event-name`:return e.name===t;case`capability`:return n.includes(e.capability)}}function hn(e,t){let n=t.definition.priority-e.definition.priority;return n===0?e.ordinal-t.ordinal:n}function gn(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e!=`object`||!e?!1:e.kind===`event-name`?typeof e.name==`string`&&e.name.trim().length>0:e.kind===`capability`&&typeof e.capability==`string`&&e.capability.trim().length>0)}function _n(e){return e.lane===`canonical`?e.clientIds===void 0||Array.isArray(e.clientIds)&&e.clientIds.length>0&&e.clientIds.every(e=>typeof e==`string`&&e.trim().length>0):e.lane===`provider`?typeof e.clientId==`string`&&e.clientId.trim().length>0&&typeof e.contractId==`string`&&e.contractId.trim().length>0:!1}function vn(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return{code:`invalid-contributor-lane`,message:`Contributor definition must be an object`,extensionName:e};let n={...typeof t.id==`string`&&{contributorId:t.id},extensionName:e};if(!Number.isFinite(t.priority))return{...n,code:`invalid-priority`,message:`Contributor '${t.id}' priority must be a finite number`};if(!gn(t.selectors))return{...n,code:`invalid-selectors`,message:`Contributor '${t.id}' requires non-empty valid selectors`};if(typeof t.respond!=`function`)return{...n,code:`invalid-respond`,message:`Contributor '${t.id}' respond must be a function`};if(!_n(t))return{...n,code:`invalid-contributor-lane`,message:`Contributor '${t.id}' has an invalid lane or target identity`};if(!pe(t.id))return{...n,code:`invalid-contributor-id`,message:`Contributor ID is empty or invalid`};if(!me(t.timeoutMs))return{...n,code:`invalid-timeout-ms`,message:`Contributor '${t.id}' has an invalid timeoutMs: ${String(t.timeoutMs)}; must be a positive finite number`}}function yn(e,t,n,r){let i=[],a=new Set;for(let o of t){let t=vn(e,o);if(t){i.push(t);continue}let s=pn(e,o.id);if(a.has(s)){i.push({code:`invalid-contributor-id`,message:`Duplicate contributor ID '${o.id}' within the same extension batch '${e}'`,contributorId:o.id,extensionName:e});continue}if(r.has(s)){i.push({code:`invalid-contributor-id`,message:`Contributor ID '${o.id}' is already registered by extension '${e}'`,contributorId:o.id,extensionName:e});continue}a.add(s),bn(e,o,n,i)}return i}function bn(e,t,n,r){let i=t.failurePolicy??`open`;if(t.lane===`provider`){let a=n.getProviderContract(t.clientId,t.contractId);if(!a){r.push({code:`inactive-provider-contract`,message:`Provider contributor requires active contract '${t.contractId}' for client '${t.clientId}'`,contributorId:t.id,extensionName:e});return}xn(e,t,[a],i,r);return}xn(e,t,t.clientIds?t.clientIds.flatMap(e=>n.getProviderContractsByClient(e)):n.getAllProviderContracts(),i,r)}function xn(e,t,n,r,i){for(let a of t.selectors){let o=a.kind===`capability`?a.capability:a.name,s=n.filter(e=>e.supportedInteractions.includes(o));if((t.lane===`provider`||a.kind===`capability`)&&s.length===0){i.push({code:`unsupported-interaction`,message:`Interaction '${o}' is not supported by an eligible active provider contract`,contributorId:t.id,extensionName:e});continue}if(r===`closed`){if(s.length===0){i.push({code:`closed-policy-on-non-blockable`,message:`Closed failure policy requires blockability proof for interaction '${o}', but no contract declares it for an eligible active client`,contributorId:t.id,extensionName:e});continue}for(let n of s)for(let r of he([a],n))i.push({code:`closed-policy-on-non-blockable`,message:r,contributorId:t.id,extensionName:e})}}}var Sn=class{contractRegistry;contributors=new Map;extensionIndex=new Map;nextOrdinal=1;constructor(e){this.contractRegistry=e}installContributors(e,t){let n=yn(e,t,this.contractRegistry,this.contributors);if(n.length>0)return{errors:n};let r=this.extensionIndex.get(e)??new Set;for(let n of t){let t=pn(e,n.id),i=Object.freeze({...n,selectors:Object.freeze(n.selectors.map(e=>Object.freeze({...e})))}),a=Object.freeze({namespacedId:t,extensionId:e,ordinal:this.nextOrdinal,definition:i});this.nextOrdinal+=1,this.contributors.set(t,a),r.add(t)}return this.extensionIndex.set(e,r),{errors:[]}}removeContributors(e){let t=this.extensionIndex.get(e);if(t){for(let e of t)this.contributors.delete(e);this.extensionIndex.delete(e)}}snapshot(e,t,n,r=[]){let i=[];for(let a of this.contributors.values()){let{definition:o}=a;o.lane===`provider`&&(o.clientId!==e||o.contractId!==t)||o.lane===`canonical`&&o.clientIds!==void 0&&!o.clientIds.includes(e)||a.definition.selectors.some(e=>mn(e,n,r))&&i.push(a)}return i.sort(hn),Object.freeze(i)}clear(){this.contributors.clear(),this.extensionIndex.clear(),this.nextOrdinal=1}};function Cn(e,t){return{filter:e=>!!e.clientHookResponses,async processActivated(n,r,i){let a=r.clientHookResponses;if(!a)return;let o={extensionName:n,extensionContext:i,getProviderContract:(e,n)=>t.getProviderContract(e,n)},s;try{s=await a.createContributors(o)}catch(e){throw Error(`[ClientHookResponseContributionProcessor] createContributors failed for '${n}': ${e instanceof Error?e.message:String(e)}`,{cause:e})}let c=e.installContributors(n,s);if(c.errors.length>0){let e=c.errors.map(e=>`[${e.code}] ${e.contributorId??`<unknown>`}: ${e.message}`).join(`; `);throw Error(`[ClientHookResponseContributionProcessor] Contributor validation failed for '${n}': ${e}`)}},async processStopped(t){e.removeContributors(t)}}}var wn=class{runtimeService;binaryManager;configPrimeService;profileService;sessionConfigService;providerContractRegistry;hookResponseRegistry;constructor(e,t,n,r,i,a,o){this.runtimeService=e,this.binaryManager=t,this.configPrimeService=n,this.profileService=r,this.sessionConfigService=i,this.providerContractRegistry=a,this.hookResponseRegistry=o}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 Tn=u(`makaio.clients-core`);function En(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 Dn(e={}){let{definitions:t=[],strategyDependencies:n,postInstallHandlers:r,binaryResolutionPolicy:i}=e,o=[...t],s=new fn,c=new Sn(s);return{name:`makaio.clients-core`,displayName:`Clients Core`,version:`0.1.0`,critical:!0,namespaces:[j,B,_t],storage:{registerHandlers:ae((e,t)=>En([()=>Rt(e,t),()=>nn(e,t),()=>ln(e,t)]))},create:e=>{let t=new N(o),l=a.join(e.makaioHome,`clients`),u=new ze(e.bus,{basePath:a.join(e.makaioHome,`binaries`),configBasePath:l,postInstallHandlers:r,...i!==void 0&&{resolutionPolicy:i}},t,n),d=new yt(e.bus,l),f=new Tt(e.bus,l);return new wn(new ut(e.bus),u,new gt(e.bus),d,f,s,c)},runtimeBoot:{configure:e=>{e.registerContributionProcessor(Cn(c,s))}}}}async function On(e,t){let n=await e.requestOptional(w.resolveBinary,{clientId:t});return n.handled?n.data:void 0}function kn(e,t,n){return[...n??[],e,...t].map(Mn).join(` `)}function An(e,t,n,r,i){return kn(e,[...i??[],...t.split(` `),n],r)}function jn(e){return e.runtimeCapabilities.hookEvents.map(e=>({eventName:e.name,mode:fe(e)}))}function Mn(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Nn(e){if(e===void 0)return!0;if(!Array.isArray(e))return`canonicalEffects must be an array`;for(let t of e){if(typeof t!=`object`||!t||t.kind!==`context.append`||typeof t.value!=`string`)return`canonicalEffects must contain complete context.append effects`;if(Object.keys(t).some(e=>e!==`kind`&&e!==`value`))return`canonicalEffects must contain only kind and value`}return!0}function Pn(e,t,n){return e===void 0?!0:typeof e!=`object`||!e||Array.isArray(e)||e.clientId!==t||e.contractId!==n||typeof e.effects!=`object`||e.effects===null||Array.isArray(e.effects)?`providerEnvelope must contain the exact clientId, contractId, and an effects object`:Object.keys(e).some(e=>e!==`clientId`&&e!==`contractId`&&e!==`effects`)?`providerEnvelope must contain only clientId, contractId, and effects`:!0}function Fn(e,t,n,r,i,a){if(!r)return`Provider contributor requires active contract '${t.contractId}'`;if(r.clientId!==n||r.clientId!==t.clientId)return`Provider contract client '${r.clientId}' does not match '${t.clientId}'`;if(r.contractId!==t.contractId)return`Provider contract '${r.contractId}' does not match '${t.contractId}'`;let o=Pn(e.providerEnvelope,t.clientId,t.contractId);return o===!0?r.validate(e,{clientId:n,eventName:i,eventPayload:a}):o}function In(e,t,n,r,i,a){if(e===void 0)return!0;if(typeof e!=`object`||!e||Array.isArray(e))return`Contributor response must be an object or undefined`;let o=t.lane===`canonical`?[`canonicalEffects`]:[`providerEnvelope`];return Object.keys(e).some(e=>!o.includes(e))?`Contributor response contains keys outside the ${t.lane} lane`:t.lane===`canonical`?Nn(e.canonicalEffects):Fn(e,t,n,r,i,a)}const Q=Symbol(`contributor-timeout`);function Ln(e){return e.failurePolicy??ue}function Rn(e){return e.namespacedId??e.definition.id}function $(e,t){return e===`closed`?`closed-failure`:t}function zn(e){if(!e)return;let t=[];return e.canonicalEffects&&t.push(...e.canonicalEffects),e.providerEnvelope&&t.push(e.providerEnvelope),t.length>0?t:void 0}function Bn(e,t,n){let r=t-Date.now();return r<=0||n.signal.aborted?(n.abort(Error(`Contributor deadline expired`)),Promise.resolve(Q)):new Promise((i,a)=>{let o=!1,s=e=>{o||(o=!0,clearTimeout(c),n.signal.removeEventListener(`abort`,l),i(e))},c=setTimeout(()=>{n.abort(Error(`Contributor timeout`)),s(Q)},r),l=()=>s(Q);n.signal.addEventListener(`abort`,l,{once:!0}),e.then(e=>{Date.now()>=t?(n.abort(Error(`Contributor timeout`)),s(Q)):s(e)},e=>{o||(o=!0,clearTimeout(c),n.signal.removeEventListener(`abort`,l),a(e))})})}function Vn(e){let t=[],n=[],r=`Request deadline already expired before collection started`;for(let i of e){let e=Rn(i),a=$(Ln(i.definition),`timeout`);t.push({contributorId:e,outcome:a,durationMs:0}),n.push({contributorId:e,severity:`error`,message:r})}let i=t.find(e=>e.outcome===`closed-failure`);return{outcomes:t,diagnostics:n,closedFailure:i?{contributorId:i.contributorId,detail:r}:void 0}}function Hn(e,t){if(t.aborted){e.abort(t.reason);return}let n=()=>{e.abort(t.reason)};t.addEventListener(`abort`,n,{once:!0}),e.signal.addEventListener(`abort`,()=>{t.removeEventListener(`abort`,n)},{once:!0})}function Un(e,t,n,r,i,a){let{definition:o}=e,s=Rn(e),c=Date.now(),l=c+o.timeoutMs,u=n===void 0?l:Math.min(n,l),d=u-c,f=new AbortController;r&&Hn(f,r);let p={clientId:t,deadline:u,remainingBudgetMs:d,signal:f.signal,eventName:i,eventPayload:a};if(f.signal.aborted)return{contributorId:s,definition:o,startMs:c,abort:f,settled:Promise.resolve({tag:`timeout`})};let m;try{let e=o.respond(p);m=e instanceof Promise?e:Promise.resolve(e)}catch(e){m=Promise.reject(e)}return{contributorId:s,definition:o,startMs:c,abort:f,settled:Bn(m,u,f).then(e=>e===Q?{tag:`timeout`}:{tag:`ok`,response:e},e=>({tag:`rejected`,error:e}))}}function Wn(e,t,n,r,i,a){let{contributorId:o,definition:s,startMs:c,abort:l}=e,u=Date.now()-c,d=Ln(s);if(l.signal.aborted||l.abort(Error(`Collection complete`)),t.tag===`timeout`){let e=`Contributor timed out after ${u}ms`;return{outcome:{contributorId:o,outcome:$(d,`timeout`),durationMs:u},diagnostic:{contributorId:o,severity:`error`,message:e}}}if(t.tag===`rejected`){let e=`Contributor rejected: ${t.error instanceof Error?t.error.message:String(t.error)}`;return{outcome:{contributorId:o,outcome:$(d,`rejection`),durationMs:u},diagnostic:{contributorId:o,severity:`error`,message:e,cause:t.error}}}let{response:f}=t,p=In(f,s,n,r,i,a);if(p!==!0){let e=`Validation failed: ${p}`;return{outcome:{contributorId:o,outcome:$(d,`rejection`),durationMs:u},diagnostic:{contributorId:o,severity:`error`,message:e}}}return{outcome:{contributorId:o,outcome:`success`,durationMs:u,effects:zn(f)}}}function Gn(e,t){let n=e.find(e=>e.outcome===`closed-failure`);if(!n)return{outcomes:e,diagnostics:t};let r={contributorId:n.contributorId,detail:t.find(e=>e.contributorId===n.contributorId)?.message??`Closed failure`};return{outcomes:e.map(e=>{if(e.effects){let{effects:t,...n}=e;return n}return e}),diagnostics:t,closedFailure:r}}async function Kn(e,t,n,r,i,a,o){if(e.length===0)return{outcomes:[],diagnostics:[]};if(n!==void 0&&n<=Date.now())return Vn(e);let s=e.map(e=>Un(e,t,n,r,i,a)),c=await Promise.all(s.map(e=>e.settled)),l=[],u=[];for(let e=0;e<s.length;e++){let{outcome:n,diagnostic:r}=Wn(s[e],c[e],t,o,i,a);l.push(n),r&&u.push(r)}return Gn(l,u)}export{it as AbsolutePathSchema,Ce as BinaryNotFoundError,R as CLIENT_RUNTIME_STATUSES,we as ClientAccountRegistry,Fe as ClientBinaryJobRunner,ze as ClientBinaryManager,k as ClientBinaryStateRecordSchema,j as ClientBinaryStorageNamespace,M as ClientBinaryStorageSubjects,O as ClientBinaryVersionRecordSchema,Pe as ClientBinaryVersionResolver,gt as ClientConfigPrimeService,N as ClientDefinitionRegistry,Je as ClientHookHandleResponseSchema,fn as ClientHookProviderContractRegistry,Sn as ClientHookResponseRegistry,G as ClientProfileRecordSchema,yt as ClientProfileService,_t as ClientProfileStorageNamespace,q as ClientProfileStorageSubjects,We as ClientRuntimeRegistry,ut as ClientRuntimeService,B as ClientRuntimeStorageNamespace,V as ClientRuntimeStorageSubjects,Tt as ClientSessionConfigService,ce as ClientSubjects,ct as ClientWiringAggregatedResultSchema,ot as ClientWiringApplyResponseSchema,le as ClientWiringEntrySchema,at as ClientWiringListResponseSchema,st as ClientWiringRemoveResponseSchema,wn as ClientsCoreService,Tn as ClientsCoreToken,qe as DEFAULT_HOOK_HANDLE_TIMEOUT_MS,Ye as NOOP_HOOK_HANDLE_RESPONSE,U as RawClientHookPayloadSchema,z as RuntimeRecordSchema,lt as assertAbsoluteProjectDir,be as atomicModifyFile,kn as buildClientCommand,$e as buildClientSessionBase,An as buildHookCommand,W as canonicalizeClientId,Mt as clientRuntimesDual,Kn as collectContributions,Cn as createClientHookResponseContributionProcessor,jt as createClientNamespace,rt as createClientWiringListSubjectDef,nt as createClientWiringSubjectDef,Dn as createClientsCorePackage,Xe as createRawClientHookHandleSubject,Ke as createRawClientHookReceivedSubject,t as createStrategy,jn as deriveSessionEventDescriptors,et as emitBestEffort,E as isPathWithinBase,Qe as pickNonEmptyString,Ze as pickNonEmptyStringValue,nn as registerDrizzleClientBinaryStorage,ln as registerDrizzleProfileStorage,Rt as registerDrizzleRuntimeStorage,En as registerStorageHandlersWithRollback,D as resolveAndValidateBasePath,On as resolveClientBinary,n as verifyInstalledVersion};
@@ -492,8 +492,8 @@ declare const ArtifactKindRegistrationSchema: z.ZodObject<{
492
492
  }>>;
493
493
  fromLevel: z.ZodOptional<z.ZodEnum<{
494
494
  link: "link";
495
- summary: "summary";
496
495
  full: "full";
496
+ summary: "summary";
497
497
  }>>;
498
498
  viewRole: z.ZodOptional<z.ZodEnum<{
499
499
  title: "title";
@@ -507,8 +507,8 @@ declare const ArtifactKindRegistrationSchema: z.ZodObject<{
507
507
  hostRelation: z.ZodString;
508
508
  as: z.ZodOptional<z.ZodEnum<{
509
509
  link: "link";
510
- summary: "summary";
511
510
  full: "full";
511
+ summary: "summary";
512
512
  }>>;
513
513
  }, z.core.$strip>, z.ZodObject<{
514
514
  kind: z.ZodLiteral<"entry">;
@@ -958,8 +958,8 @@ declare const ProjectedFieldSchema: z.ZodObject<{
958
958
  }>>;
959
959
  fromLevel: z.ZodOptional<z.ZodEnum<{
960
960
  link: "link";
961
- summary: "summary";
962
961
  full: "full";
962
+ summary: "summary";
963
963
  }>>;
964
964
  viewRole: z.ZodOptional<z.ZodEnum<{
965
965
  title: "title";
@@ -1004,8 +1004,8 @@ declare const ArtifactProjectionPolicySchema: z.ZodObject<{
1004
1004
  }>>;
1005
1005
  fromLevel: z.ZodOptional<z.ZodEnum<{
1006
1006
  link: "link";
1007
- summary: "summary";
1008
1007
  full: "full";
1008
+ summary: "summary";
1009
1009
  }>>;
1010
1010
  viewRole: z.ZodOptional<z.ZodEnum<{
1011
1011
  title: "title";
@@ -1019,8 +1019,8 @@ declare const ArtifactProjectionPolicySchema: z.ZodObject<{
1019
1019
  hostRelation: z.ZodString;
1020
1020
  as: z.ZodOptional<z.ZodEnum<{
1021
1021
  link: "link";
1022
- summary: "summary";
1023
1022
  full: "full";
1023
+ summary: "summary";
1024
1024
  }>>;
1025
1025
  }, z.core.$strip>, z.ZodObject<{
1026
1026
  kind: z.ZodLiteral<"entry">;
@@ -1,3 +1,3 @@
1
- import { C as StartAgentSchema, D as AdapterNamespace, E as AdapterSchemas, O as AdapterSubjects, S as StartAgentResponse, T as AdapterRuntimeOptionsSchema, _ as SessionUsageSchema, a as UnresolvedProviderContext, b as RehydrateAgentSchema, c as AdapterSelectionSchema, d as AgentSelectionBaseSchema, f as AgentSelectionKindMap, g as SessionUsage, h as SessionDiscoveredSchema, i as ResolvedProviderContextSchema, l as AgentSelection, m as SessionDiscovered, n as ProviderContextSchema, o as UnresolvedProviderContextSchema, p as AgentSelectionSchema, r as ResolvedProviderContext, s as AdapterSelection, t as ProviderContext, u as AgentSelectionBase, v as RehydrateAgentRequest, w as AdapterRuntimeOptions, x as StartAgentRequest, y as RehydrateAgentResponse } from "../../index-BLwvcw5C.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-Cte63dGx.mjs";
1
+ import { C as StartAgentSchema, D as AdapterNamespace, E as AdapterSchemas, O as AdapterSubjects, S as StartAgentResponse, T as AdapterRuntimeOptionsSchema, _ as SessionUsageSchema, a as UnresolvedProviderContext, b as RehydrateAgentSchema, c as AdapterSelectionSchema, d as AgentSelectionBaseSchema, f as AgentSelectionKindMap, g as SessionUsage, h as SessionDiscoveredSchema, i as ResolvedProviderContextSchema, l as AgentSelection, m as SessionDiscovered, n as ProviderContextSchema, o as UnresolvedProviderContextSchema, p as AgentSelectionSchema, r as ResolvedProviderContext, s as AdapterSelection, t as ProviderContext, u as AgentSelectionBase, v as RehydrateAgentRequest, w as AdapterRuntimeOptions, x as StartAgentRequest, y as RehydrateAgentResponse } from "../../index-B6SBIKyk.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-D4z26OtM.mjs";
3
3
  export { AdapterNamespace, AdapterRuntimeOptions, AdapterRuntimeOptionsSchema, AdapterSchemas, AdapterSelection, AdapterSelectionSchema, 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, ResolvedProviderContext, ResolvedProviderContextSchema, RootSessionLineageSchema, SESSION_LINEAGE_KINDS, SUBAGENT_SESSION_LINEAGE_KIND, SessionDiscovered, SessionDiscoveredSchema, SessionLineage, SessionLineageKind, SessionLineageKindSchema, SessionLineageSchema, SessionUsage, SessionUsageSchema, StartAgentRequest, StartAgentResponse, StartAgentSchema, SubagentSessionLineageSchema, UnresolvedProviderContext, UnresolvedProviderContextSchema };
@@ -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-Cte63dGx.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-D4z26OtM.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 { $ as ConfidenceLevel, A as ArtifactKindRegistrationSchema, B as ArtifactRelationQueryTarget, C as ArtifactCompareRequest, D as ArtifactConflictPolicy, E as ArtifactCompareResponseSchema, F as ArtifactQueryScope, G as ArtifactRepresentations, H as ArtifactRelationSchema, I as ArtifactQueryScopeSchema, J as ArtifactRevisionSchema, K as ArtifactRepresentationsSchema, L as ArtifactRef, M as ArtifactObservationSchema, N as ArtifactQueryRequest, O as ArtifactConflictPolicySchema, P as ArtifactQueryRequestSchema, Q as ConfidenceBasisSchema, R as ArtifactRefSchema, S as ArtifactActorSchema, T as ArtifactCompareResponse, U as ArtifactRelationTarget, V as ArtifactRelationQueryTargetSchema, W as ArtifactRelationTargetSchema, X as ArtifactScopeSchema, Y as ArtifactScope, Z as ConfidenceBasis, a as ResolvedArtifactContextWire, at as LocalRef, ct as RelationTypeRegistrationSchema, et as ConfidenceLevelSchema, i as ArtifactContextUnresolvedReasonSchema, it as EvidenceRefSchema, j as ArtifactObservation, k as ArtifactKindRegistration, n as ArtifactContextRefEntrySchema, nt as ConfidenceMetadataSchema, o as ResolvedArtifactContextWireSchema, ot as LocalRefSchema, q as ArtifactRevision, r as ArtifactContextUnresolvedReason, rt as EvidenceRef, st as RelationTypeRegistration, t as ArtifactContextRefEntry, tt as ConfidenceMetadata, w as ArtifactCompareRequestSchema, x as ArtifactActor, z as ArtifactRelation } from "../../context-resolution-DsPuX5ox.mjs";
2
- import { $ as ArtifactContextRelationSelectorSchema, A as ArtifactContextTree, B as ArtifactHookFilter, C as ArtifactRevisedPayload, D as hydrateArtifactContextTree, E as ArtifactSubjects, F as ArtifactKindDefinition, G as ArtifactReactionHookContext, H as ArtifactLifecycleHookEvent, I as ArtifactOf, J as BeforeArtifactHookRegistration, K as ArtifactReactionHookRegistration, L as defineArtifactKind, M as UnresolvedArtifactContextNode, N as AnyArtifactKindDefinition, O as ArtifactContextNode, P as ArtifactDataOf, Q as ArtifactContextRelationSelector, R as ArtifactDraft, S as ArtifactReviseResponse, T as ArtifactStatusChangedPayload, U as ArtifactLifecycleHookRegistration, V as ArtifactLifecycleHookDefinition, W as ArtifactLifecycleSemanticEvent, X as ARTIFACT_CONTEXT_RENDER_HINTS, Y as defineArtifactLifecycleHooks, Z as ArtifactContextKnownRenderHint, _ as ArtifactResolveContextRequest, a as ArtifactKindListRequest, b as ArtifactResolveResponse, c as ArtifactKindRegisterResponse, d as ArtifactQueryResponse, et as ArtifactContextRenderHint, f as ArtifactRelationAddedPayload, g as ArtifactRelationTypeRegisterResponse, h as ArtifactRelationTypeRegisterRequest, i as ArtifactKindChangedPayload, j as ResolvedArtifactContextNode, k as ArtifactContextRootNode, l as ArtifactNamespace, m as ArtifactRelationTypeListResponse, n as ArtifactCreateResponse, nt as ArtifactContextSelector, o as ArtifactKindListResponse, p as ArtifactRelationTypeListRequest, q as BeforeArtifactHookContext, r as ArtifactCreatedPayload, rt as ArtifactContextSelectorSchema, s as ArtifactKindRegisterRequest, t as ArtifactCreateRequest, tt as ArtifactContextRenderHintSchema, u as ArtifactObservationAddedPayload, v as ArtifactResolveContextResponse, w as ArtifactSchemas, x as ArtifactReviseRequest, y as ArtifactResolveRequest, z as ArtifactDraftPatch } from "../../index-vTBR3OFK.mjs";
1
+ import { $ as ConfidenceLevel, A as ArtifactKindRegistrationSchema, B as ArtifactRelationQueryTarget, C as ArtifactCompareRequest, D as ArtifactConflictPolicy, E as ArtifactCompareResponseSchema, F as ArtifactQueryScope, G as ArtifactRepresentations, H as ArtifactRelationSchema, I as ArtifactQueryScopeSchema, J as ArtifactRevisionSchema, K as ArtifactRepresentationsSchema, L as ArtifactRef, M as ArtifactObservationSchema, N as ArtifactQueryRequest, O as ArtifactConflictPolicySchema, P as ArtifactQueryRequestSchema, Q as ConfidenceBasisSchema, R as ArtifactRefSchema, S as ArtifactActorSchema, T as ArtifactCompareResponse, U as ArtifactRelationTarget, V as ArtifactRelationQueryTargetSchema, W as ArtifactRelationTargetSchema, X as ArtifactScopeSchema, Y as ArtifactScope, Z as ConfidenceBasis, a as ResolvedArtifactContextWire, at as LocalRef, ct as RelationTypeRegistrationSchema, et as ConfidenceLevelSchema, i as ArtifactContextUnresolvedReasonSchema, it as EvidenceRefSchema, j as ArtifactObservation, k as ArtifactKindRegistration, n as ArtifactContextRefEntrySchema, nt as ConfidenceMetadataSchema, o as ResolvedArtifactContextWireSchema, ot as LocalRefSchema, q as ArtifactRevision, r as ArtifactContextUnresolvedReason, rt as EvidenceRef, st as RelationTypeRegistration, t as ArtifactContextRefEntry, tt as ConfidenceMetadata, w as ArtifactCompareRequestSchema, x as ArtifactActor, z as ArtifactRelation } from "../../context-resolution-B5IH2Z9v.mjs";
2
+ import { $ as ArtifactContextRelationSelectorSchema, A as ArtifactContextTree, B as ArtifactHookFilter, C as ArtifactRevisedPayload, D as hydrateArtifactContextTree, E as ArtifactSubjects, F as ArtifactKindDefinition, G as ArtifactReactionHookContext, H as ArtifactLifecycleHookEvent, I as ArtifactOf, J as BeforeArtifactHookRegistration, K as ArtifactReactionHookRegistration, L as defineArtifactKind, M as UnresolvedArtifactContextNode, N as AnyArtifactKindDefinition, O as ArtifactContextNode, P as ArtifactDataOf, Q as ArtifactContextRelationSelector, R as ArtifactDraft, S as ArtifactReviseResponse, T as ArtifactStatusChangedPayload, U as ArtifactLifecycleHookRegistration, V as ArtifactLifecycleHookDefinition, W as ArtifactLifecycleSemanticEvent, X as ARTIFACT_CONTEXT_RENDER_HINTS, Y as defineArtifactLifecycleHooks, Z as ArtifactContextKnownRenderHint, _ as ArtifactResolveContextRequest, a as ArtifactKindListRequest, b as ArtifactResolveResponse, c as ArtifactKindRegisterResponse, d as ArtifactQueryResponse, et as ArtifactContextRenderHint, f as ArtifactRelationAddedPayload, g as ArtifactRelationTypeRegisterResponse, h as ArtifactRelationTypeRegisterRequest, i as ArtifactKindChangedPayload, j as ResolvedArtifactContextNode, k as ArtifactContextRootNode, l as ArtifactNamespace, m as ArtifactRelationTypeListResponse, n as ArtifactCreateResponse, nt as ArtifactContextSelector, o as ArtifactKindListResponse, p as ArtifactRelationTypeListRequest, q as BeforeArtifactHookContext, r as ArtifactCreatedPayload, rt as ArtifactContextSelectorSchema, s as ArtifactKindRegisterRequest, t as ArtifactCreateRequest, tt as ArtifactContextRenderHintSchema, u as ArtifactObservationAddedPayload, v as ArtifactResolveContextResponse, w as ArtifactSchemas, x as ArtifactReviseRequest, y as ArtifactResolveRequest, z as ArtifactDraftPatch } from "../../index-DeoKITib.mjs";
3
3
  export { ARTIFACT_CONTEXT_RENDER_HINTS, AnyArtifactKindDefinition, ArtifactActor, ArtifactActorSchema, ArtifactCompareRequest, ArtifactCompareRequestSchema, ArtifactCompareResponse, ArtifactCompareResponseSchema, ArtifactConflictPolicy, ArtifactConflictPolicySchema, ArtifactContextKnownRenderHint, ArtifactContextNode, ArtifactContextRefEntry, ArtifactContextRefEntrySchema, ArtifactContextRelationSelector, ArtifactContextRelationSelectorSchema, ArtifactContextRenderHint, ArtifactContextRenderHintSchema, ArtifactContextRootNode, ArtifactContextSelector, ArtifactContextSelectorSchema, ArtifactContextTree, ArtifactContextUnresolvedReason, ArtifactContextUnresolvedReasonSchema, ArtifactCreateRequest, ArtifactCreateResponse, ArtifactCreatedPayload, ArtifactDataOf, ArtifactDraft, ArtifactDraftPatch, ArtifactHookFilter, ArtifactKindChangedPayload, ArtifactKindDefinition, ArtifactKindListRequest, ArtifactKindListResponse, ArtifactKindRegisterRequest, ArtifactKindRegisterResponse, ArtifactKindRegistration, ArtifactKindRegistrationSchema, ArtifactLifecycleHookDefinition, ArtifactLifecycleHookEvent, ArtifactLifecycleHookRegistration, ArtifactLifecycleSemanticEvent, ArtifactNamespace, ArtifactObservation, ArtifactObservationAddedPayload, ArtifactObservationSchema, ArtifactOf, ArtifactQueryRequest, ArtifactQueryRequestSchema, ArtifactQueryResponse, ArtifactQueryScope, ArtifactQueryScopeSchema, ArtifactReactionHookContext, ArtifactReactionHookRegistration, ArtifactRef, ArtifactRefSchema, ArtifactRelation, ArtifactRelationAddedPayload, ArtifactRelationQueryTarget, ArtifactRelationQueryTargetSchema, ArtifactRelationSchema, ArtifactRelationTarget, ArtifactRelationTargetSchema, ArtifactRelationTypeListRequest, ArtifactRelationTypeListResponse, ArtifactRelationTypeRegisterRequest, ArtifactRelationTypeRegisterResponse, ArtifactRepresentations, ArtifactRepresentationsSchema, ArtifactResolveContextRequest, ArtifactResolveContextResponse, ArtifactResolveRequest, ArtifactResolveResponse, ArtifactReviseRequest, ArtifactReviseResponse, ArtifactRevisedPayload, ArtifactRevision, ArtifactRevisionSchema, ArtifactSchemas, ArtifactScope, ArtifactScopeSchema, ArtifactStatusChangedPayload, ArtifactSubjects, BeforeArtifactHookContext, BeforeArtifactHookRegistration, ConfidenceBasis, ConfidenceBasisSchema, ConfidenceLevel, ConfidenceLevelSchema, ConfidenceMetadata, ConfidenceMetadataSchema, EvidenceRef, EvidenceRefSchema, LocalRef, LocalRefSchema, RelationTypeRegistration, RelationTypeRegistrationSchema, ResolvedArtifactContextNode, ResolvedArtifactContextWire, ResolvedArtifactContextWireSchema, UnresolvedArtifactContextNode, defineArtifactKind, defineArtifactLifecycleHooks, hydrateArtifactContextTree };
@@ -1,2 +1,2 @@
1
- import { C as QualifiedModelRef, D as VirtualModelRef, E as ResolvableCanonicalModelSchema, O as VirtualModelRefSchema, S as ParsedCanonicalModelSchema, T as ResolvableCanonicalModel, _ as CanonicalModelParseErrorCodeSchema, a as CanonicalModelSchemas, b as CanonicalModelParseResultSchema, c as SEGMENT_RE, d as parseCanonicalModel, f as BareModelRef, g as CanonicalModelParseErrorCode, h as CanonicalModelParseError, i as CanonicalModelResolvedSelectionSchema, l as VIRTUAL_NAME_RE, m as CANONICAL_MODEL_PARSE_ERROR_CODES, n as CanonicalModelSubjects, o as CanonicalModelSelection, p as BareModelRefSchema, r as CanonicalModelResolvedSelection, s as CanonicalModelSelectionSchema, t as CanonicalModelNamespace, u as isCanonicalModelParseError, v as CanonicalModelParseErrorSchema, w as QualifiedModelRefSchema, x as ParsedCanonicalModel, y as CanonicalModelParseResult } from "../../index-FamxGT0U.mjs";
1
+ import { C as QualifiedModelRef, D as VirtualModelRef, E as ResolvableCanonicalModelSchema, O as VirtualModelRefSchema, S as ParsedCanonicalModelSchema, T as ResolvableCanonicalModel, _ as CanonicalModelParseErrorCodeSchema, a as CanonicalModelSchemas, b as CanonicalModelParseResultSchema, c as SEGMENT_RE, d as parseCanonicalModel, f as BareModelRef, g as CanonicalModelParseErrorCode, h as CanonicalModelParseError, i as CanonicalModelResolvedSelectionSchema, l as VIRTUAL_NAME_RE, m as CANONICAL_MODEL_PARSE_ERROR_CODES, n as CanonicalModelSubjects, o as CanonicalModelSelection, p as BareModelRefSchema, r as CanonicalModelResolvedSelection, s as CanonicalModelSelectionSchema, t as CanonicalModelNamespace, u as isCanonicalModelParseError, v as CanonicalModelParseErrorSchema, w as QualifiedModelRefSchema, x as ParsedCanonicalModel, y as CanonicalModelParseResult } from "../../index-Chy9aknK.mjs";
2
2
  export { BareModelRef, BareModelRefSchema, CANONICAL_MODEL_PARSE_ERROR_CODES, CanonicalModelNamespace, CanonicalModelParseError, CanonicalModelParseErrorCode, CanonicalModelParseErrorCodeSchema, CanonicalModelParseErrorSchema, CanonicalModelParseResult, CanonicalModelParseResultSchema, CanonicalModelResolvedSelection, CanonicalModelResolvedSelectionSchema, CanonicalModelSchemas, CanonicalModelSelection, CanonicalModelSelectionSchema, CanonicalModelSubjects, ParsedCanonicalModel, ParsedCanonicalModelSchema, QualifiedModelRef, QualifiedModelRefSchema, ResolvableCanonicalModel, ResolvableCanonicalModelSchema, SEGMENT_RE, VIRTUAL_NAME_RE, VirtualModelRef, VirtualModelRefSchema, isCanonicalModelParseError, parseCanonicalModel };
@@ -1,3 +1,3 @@
1
- import { A as ClientHookEventDeclarationSchema, B as LogSourceDefinitionSchema, C as validateClosedPolicy, D as ClientDefinitionInput, E as ClientDefinition, F as ClientToolDefinition, G as PostInstallDescriptor, H as ManagedInstallDescriptorSchema, I as ClientToolDefinitionSchema, J as SignedBinaryBucketInstallDescriptorSchema, K as PostInstallDescriptorSchema, L as ConfigIsolation, M as ClientRuntimeCapabilitiesSchema, N as ClientToolCapabilityAnnotation, O as ClientDefinitionSchema, P as ClientToolCapabilityAnnotationSchema, R as ConfigIsolationSchema, S as isValidTimeoutMs, T as ClientBinaryCompatibilitySchema, U as NpmInstallDescriptor, V as ManagedInstallDescriptor, W as NpmInstallDescriptorSchema, X as VersionCommandSchema, Y as VersionCommand, Z as deriveHookEventTransportMode, _ as ProviderContributionEnvelope, a as CapabilitySelector, b as createAppendEffect, c as ContributorDefinition, d as EventNameSelector, f as ExtensionClientHookResponsesContribution, g as ProviderContractCatalogEntry, h as InteractionSelector, i as CanonicalEffect, j as ClientRuntimeCapabilities, k as ClientHookEventDeclaration, l as ContributorResponse, m as InteractionBlockability, n as ActivationValidationError, o as ContributorActivationContext, p as FailurePolicy, q as SignedBinaryBucketInstallDescriptor, r as CanonicalAppendEffect, s as ContributorCallbackContext, t as ActivationErrorCode, u as DEFAULT_FAILURE_POLICY, v as RuntimeOutcome, w as ClientBinaryCompatibility, x as isValidContributorId, y as RuntimeOutcomeCode, z as LogSourceDefinition } from "../../hook-responses-mmqRa2Dq.mjs";
2
- import { $ as ClientSessionToolPre, $t as ManagedInstallStrategySchema, A as SessionConfigInheritance, An as ClientUsageWindows, At as ClientInstallResponse, B as SessionConfigTeardownResponseSchema, Bt as ClientUninstallSchema, C as SessionConfigCleanupRequest, Cn as ClientUsageIngestRequest, Ct as ClientBinaryListEntry, D as SessionConfigDestroyRequest, Dn as ClientUsageSnapshotSchema, Dt as ClientInstallProgress, E as SessionConfigCreateResponse, En as ClientUsageSnapshot, Et as ClientInstallCompletedSchema, F as SessionConfigSetupResponse, Fn as ClientResolveBinaryRequest, Ft as ClientSetActiveRequest, G as ClientSessionObservedBase, Gt as ClientVersionChangedSchema, H as ClientNamespace, Ht as ClientUpdateResponse, I as SessionConfigSetupResponseSchema, In as ClientResolveBinaryResponse, It as ClientSetActiveResponse, J as ClientSessionStartModeSchema, Jt as InstallStage, K as ClientSessionObservedBaseSchema, Kt as InstallError, L as SessionConfigTeardownRequest, Ln as ClientResolveBinarySchema, Lt as ClientSetActiveSchema, M as SessionConfigLeaseIdSchema, Mn as ClientSchemas, Mt as ClientListRequest, N as SessionConfigSetupRequest, Nn as ClientExecutionContext, Nt as ClientListResponse, O as SessionConfigDestroyResponse, On as ClientUsageWindow, Ot as ClientInstallProgressSchema, P as SessionConfigSetupRequestSchema, Pn as ClientExecutionContextSchema, Pt as ClientListSchema, Q as ClientSessionToolPostSchema, Qt as ManagedInstallStrategy, R as SessionConfigTeardownRequestSchema, Rt as ClientUninstallRequest, S as ProfileUpdateResponse, Sn as ClientSessionLocatorSchema, St as ClientRuntimeStartedSchema, T as SessionConfigCreateRequest, Tn as ClientUsageIngestSchema, Tt as ClientInstallCompleted, U as ClientSubjects, Ut as ClientUpdateSchema, V as createClientDefinition, Vt as ClientUpdateRequest, W as CLIENT_SESSION_START_MODES, Wt as ClientVersionChanged, X as ClientSessionStartedSchema, Xt as InstalledVersionEntry, Y as ClientSessionStarted, Yt as InstallStageSchema, Z as ClientSessionToolPost, Zt as InstalledVersionEntrySchema, _ as ProfileListRequest, _n as ClientScanTargetSchema, _t as ClientRuntimeSource, a as ClientConfigPrimeSchema, an as ClientAccountIdentifierSchema, at as ClientSessionUserPromptSubmitted, b as ProfileSetDefaultResponse, bn as ClientSessionAccountObserveSchema, bt as ClientRuntimeSourceSchema, c as ClientProfileSchema, cn as ClientAccountObserveSchema, ct as ClientWiringEntrySchema, d as ProfileCreateRequest, dn as ClientIdentityObservation, dt as ClientRuntimeIsAdapterManagedRequest, en as ClientSessionUsageCostProvenance, et as ClientSessionToolPreSchema, f as ProfileCreateResponse, fn as ClientIdentityObservationSchema, ft as ClientRuntimeIsAdapterManagedResponse, g as ProfileGetResponse, gn as ClientScanTarget, gt as ClientRuntimeObserveSchema, h as ProfileGetRequest, hn as ClientScanResultSchema, ht as ClientRuntimeObserveResponse, i as ClientConfigPrimeResponse, in as ClientAccountIdentifier, it as ClientSessionTurnStartedSchema, j as SessionConfigInheritanceSchema, jn as ClientUsageWindowsSchema, jt as ClientInstallSchema, k as SessionConfigEnvSchema, kn as ClientUsageWindowSchema, kt as ClientInstallRequest, l as ClientProfileSchemas, ln as ClientIdentifierStrength, lt as ClientRuntimeEvidenceBase, m as ProfileDeleteResponse, mn as ClientScanResult, mt as ClientRuntimeObserveRequest, n as ClientConfigPrimePhaseSchema, nn as ClientSessionUsageSnapshot, nt as ClientSessionTurnCompletedSchema, o as ClientProfile, on as ClientAccountObserveRequest, ot as ClientSessionUserPromptSubmittedSchema, p as ProfileDeleteRequest, pn as ClientMetadataSchema, pt as ClientRuntimeIsAdapterManagedSchema, q as ClientSessionStartMode, qt as InstallErrorSchema, r as ClientConfigPrimeRequest, rn as ClientSessionUsageSnapshotSchema, rt as ClientSessionTurnStarted, s as ClientProfileNameSchema, sn as ClientAccountObserveResponse, st as ClientWiringEntry, t as ClientConfigPrimePhase, tn as ClientSessionUsageCostProvenanceSchema, tt as ClientSessionTurnCompleted, u as ClientSessionConfigSchemas, un as ClientIdentifierStrengthSchema, ut as ClientRuntimeEvidenceBaseSchema, v as ProfileListResponse, vn as ClientSessionAccountObserveRequest, vt as ClientRuntimeSourceLayer, w as SessionConfigCleanupResponse, wn as ClientUsageIngestResponse, wt as ClientBinaryListEntrySchema, x as ProfileUpdateRequest, xn as ClientSessionLocator, xt as ClientRuntimeStarted, y as ProfileSetDefaultRequest, yn as ClientSessionAccountObserveResponse, yt as ClientRuntimeSourceLayerSchema, z as SessionConfigTeardownResponse, zt as ClientUninstallResponse } from "../../index-CtZODNBo.mjs";
1
+ import { $ as ConfigIsolation, B as ClientBinaryCompatibility, C as validateClosedPolicy, G as ClientHookEventDeclaration, H as ClientDefinition, J as ClientRuntimeCapabilitiesSchema, K as ClientHookEventDeclarationSchema, Q as ClientToolDefinitionSchema, S as isValidTimeoutMs, U as ClientDefinitionInput, V as ClientBinaryCompatibilitySchema, W as ClientDefinitionSchema, X as ClientToolCapabilityAnnotationSchema, Y as ClientToolCapabilityAnnotation, Z as ClientToolDefinition, _ as ProviderContributionEnvelope, a as CapabilitySelector, at as NpmInstallDescriptor, b as createAppendEffect, c as ContributorDefinition, ct as PostInstallDescriptorSchema, d as EventNameSelector, dt as VersionCommand, et as ConfigIsolationSchema, f as ExtensionClientHookResponsesContribution, ft as VersionCommandSchema, g as ProviderContractCatalogEntry, h as InteractionSelector, i as CanonicalEffect, it as ManagedInstallDescriptorSchema, l as ContributorResponse, lt as SignedBinaryBucketInstallDescriptor, m as InteractionBlockability, n as ActivationValidationError, nt as LogSourceDefinitionSchema, o as ContributorActivationContext, ot as NpmInstallDescriptorSchema, p as FailurePolicy, pt as deriveHookEventTransportMode, q as ClientRuntimeCapabilities, r as CanonicalAppendEffect, rt as ManagedInstallDescriptor, s as ContributorCallbackContext, st as PostInstallDescriptor, t as ActivationErrorCode, tt as LogSourceDefinition, u as DEFAULT_FAILURE_POLICY, ut as SignedBinaryBucketInstallDescriptorSchema, v as RuntimeOutcome, x as isValidContributorId, y as RuntimeOutcomeCode } from "../../hook-responses-Dg8wDvRo.mjs";
2
+ import { $ as ClientSessionToolPre, $t as ManagedInstallStrategySchema, A as SessionConfigInheritance, An as ClientUsageWindows, At as ClientInstallResponse, B as SessionConfigTeardownResponseSchema, Bt as ClientUninstallSchema, C as SessionConfigCleanupRequest, Cn as ClientUsageIngestRequest, Ct as ClientBinaryListEntry, D as SessionConfigDestroyRequest, Dn as ClientUsageSnapshotSchema, Dt as ClientInstallProgress, E as SessionConfigCreateResponse, En as ClientUsageSnapshot, Et as ClientInstallCompletedSchema, F as SessionConfigSetupResponse, Fn as ClientResolveBinaryRequest, Ft as ClientSetActiveRequest, G as ClientSessionObservedBase, Gt as ClientVersionChangedSchema, H as ClientNamespace, Ht as ClientUpdateResponse, I as SessionConfigSetupResponseSchema, In as ClientResolveBinaryResponse, It as ClientSetActiveResponse, J as ClientSessionStartModeSchema, Jt as InstallStage, K as ClientSessionObservedBaseSchema, Kt as InstallError, L as SessionConfigTeardownRequest, Ln as ClientResolveBinarySchema, Lt as ClientSetActiveSchema, M as SessionConfigLeaseIdSchema, Mn as ClientSchemas, Mt as ClientListRequest, N as SessionConfigSetupRequest, Nn as ClientExecutionContext, Nt as ClientListResponse, O as SessionConfigDestroyResponse, On as ClientUsageWindow, Ot as ClientInstallProgressSchema, P as SessionConfigSetupRequestSchema, Pn as ClientExecutionContextSchema, Pt as ClientListSchema, Q as ClientSessionToolPostSchema, Qt as ManagedInstallStrategy, R as SessionConfigTeardownRequestSchema, Rt as ClientUninstallRequest, S as ProfileUpdateResponse, Sn as ClientSessionLocatorSchema, St as ClientRuntimeStartedSchema, T as SessionConfigCreateRequest, Tn as ClientUsageIngestSchema, Tt as ClientInstallCompleted, U as ClientSubjects, Ut as ClientUpdateSchema, V as createClientDefinition, Vt as ClientUpdateRequest, W as CLIENT_SESSION_START_MODES, Wt as ClientVersionChanged, X as ClientSessionStartedSchema, Xt as InstalledVersionEntry, Y as ClientSessionStarted, Yt as InstallStageSchema, Z as ClientSessionToolPost, Zt as InstalledVersionEntrySchema, _ as ProfileListRequest, _n as ClientScanTargetSchema, _t as ClientRuntimeSource, a as ClientConfigPrimeSchema, an as ClientAccountIdentifierSchema, at as ClientSessionUserPromptSubmitted, b as ProfileSetDefaultResponse, bn as ClientSessionAccountObserveSchema, bt as ClientRuntimeSourceSchema, c as ClientProfileSchema, cn as ClientAccountObserveSchema, ct as ClientWiringEntrySchema, d as ProfileCreateRequest, dn as ClientIdentityObservation, dt as ClientRuntimeIsAdapterManagedRequest, en as ClientSessionUsageCostProvenance, et as ClientSessionToolPreSchema, f as ProfileCreateResponse, fn as ClientIdentityObservationSchema, ft as ClientRuntimeIsAdapterManagedResponse, g as ProfileGetResponse, gn as ClientScanTarget, gt as ClientRuntimeObserveSchema, h as ProfileGetRequest, hn as ClientScanResultSchema, ht as ClientRuntimeObserveResponse, i as ClientConfigPrimeResponse, in as ClientAccountIdentifier, it as ClientSessionTurnStartedSchema, j as SessionConfigInheritanceSchema, jn as ClientUsageWindowsSchema, jt as ClientInstallSchema, k as SessionConfigEnvSchema, kn as ClientUsageWindowSchema, kt as ClientInstallRequest, l as ClientProfileSchemas, ln as ClientIdentifierStrength, lt as ClientRuntimeEvidenceBase, m as ProfileDeleteResponse, mn as ClientScanResult, mt as ClientRuntimeObserveRequest, n as ClientConfigPrimePhaseSchema, nn as ClientSessionUsageSnapshot, nt as ClientSessionTurnCompletedSchema, o as ClientProfile, on as ClientAccountObserveRequest, ot as ClientSessionUserPromptSubmittedSchema, p as ProfileDeleteRequest, pn as ClientMetadataSchema, pt as ClientRuntimeIsAdapterManagedSchema, q as ClientSessionStartMode, qt as InstallErrorSchema, r as ClientConfigPrimeRequest, rn as ClientSessionUsageSnapshotSchema, rt as ClientSessionTurnStarted, s as ClientProfileNameSchema, sn as ClientAccountObserveResponse, st as ClientWiringEntry, t as ClientConfigPrimePhase, tn as ClientSessionUsageCostProvenanceSchema, tt as ClientSessionTurnCompleted, u as ClientSessionConfigSchemas, un as ClientIdentifierStrengthSchema, ut as ClientRuntimeEvidenceBaseSchema, v as ProfileListResponse, vn as ClientSessionAccountObserveRequest, vt as ClientRuntimeSourceLayer, w as SessionConfigCleanupResponse, wn as ClientUsageIngestResponse, wt as ClientBinaryListEntrySchema, x as ProfileUpdateRequest, xn as ClientSessionLocator, xt as ClientRuntimeStarted, y as ProfileSetDefaultRequest, yn as ClientSessionAccountObserveResponse, yt as ClientRuntimeSourceLayerSchema, z as SessionConfigTeardownResponse, zt as ClientUninstallResponse } from "../../index-D9Tk7hyM.mjs";
3
3
  export { ActivationErrorCode, ActivationValidationError, CLIENT_SESSION_START_MODES, CanonicalAppendEffect, CanonicalEffect, CapabilitySelector, 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, ClientRuntimeIsAdapterManagedRequest, ClientRuntimeIsAdapterManagedResponse, ClientRuntimeIsAdapterManagedSchema, ClientRuntimeObserveRequest, ClientRuntimeObserveResponse, ClientRuntimeObserveSchema, ClientRuntimeSource, ClientRuntimeSourceLayer, ClientRuntimeSourceLayerSchema, ClientRuntimeSourceSchema, ClientRuntimeStarted, ClientRuntimeStartedSchema, ClientScanResult, ClientScanResultSchema, ClientScanTarget, ClientScanTargetSchema, ClientSchemas, ClientSessionAccountObserveRequest, ClientSessionAccountObserveResponse, ClientSessionAccountObserveSchema, ClientSessionConfigSchemas, ClientSessionLocator, ClientSessionLocatorSchema, ClientSessionObservedBase, ClientSessionObservedBaseSchema, ClientSessionStartMode, ClientSessionStartModeSchema, ClientSessionStarted, ClientSessionStartedSchema, ClientSessionToolPost, ClientSessionToolPostSchema, ClientSessionToolPre, ClientSessionToolPreSchema, ClientSessionTurnCompleted, ClientSessionTurnCompletedSchema, ClientSessionTurnStarted, ClientSessionTurnStartedSchema, ClientSessionUsageCostProvenance, ClientSessionUsageCostProvenanceSchema, ClientSessionUsageSnapshot, ClientSessionUsageSnapshotSchema, 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, ContributorActivationContext, ContributorCallbackContext, ContributorDefinition, ContributorResponse, DEFAULT_FAILURE_POLICY, EventNameSelector, ExtensionClientHookResponsesContribution, FailurePolicy, InstallError, InstallErrorSchema, InstallStage, InstallStageSchema, InstalledVersionEntry, InstalledVersionEntrySchema, InteractionBlockability, InteractionSelector, LogSourceDefinition, LogSourceDefinitionSchema, ManagedInstallDescriptor, ManagedInstallDescriptorSchema, ManagedInstallStrategy, ManagedInstallStrategySchema, NpmInstallDescriptor, NpmInstallDescriptorSchema, PostInstallDescriptor, PostInstallDescriptorSchema, ProfileCreateRequest, ProfileCreateResponse, ProfileDeleteRequest, ProfileDeleteResponse, ProfileGetRequest, ProfileGetResponse, ProfileListRequest, ProfileListResponse, ProfileSetDefaultRequest, ProfileSetDefaultResponse, ProfileUpdateRequest, ProfileUpdateResponse, ProviderContractCatalogEntry, ProviderContributionEnvelope, RuntimeOutcome, RuntimeOutcomeCode, SessionConfigCleanupRequest, SessionConfigCleanupResponse, SessionConfigCreateRequest, SessionConfigCreateResponse, SessionConfigDestroyRequest, SessionConfigDestroyResponse, SessionConfigEnvSchema, SessionConfigInheritance, SessionConfigInheritanceSchema, SessionConfigLeaseIdSchema, SessionConfigSetupRequest, SessionConfigSetupRequestSchema, SessionConfigSetupResponse, SessionConfigSetupResponseSchema, SessionConfigTeardownRequest, SessionConfigTeardownRequestSchema, SessionConfigTeardownResponse, SessionConfigTeardownResponseSchema, SignedBinaryBucketInstallDescriptor, SignedBinaryBucketInstallDescriptorSchema, VersionCommand, VersionCommandSchema, createAppendEffect, createClientDefinition, deriveHookEventTransportMode, isValidContributorId, isValidTimeoutMs, validateClosedPolicy };