@makaio/framework 1.0.0-dev-1790087128488 → 1.0.0-dev-1790114433794
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.
- package/dist/.makaio-build.json +2 -2
- package/dist/adapters/claude/index.d.mts +44 -44
- package/dist/bus/index.d.mts +20 -20
- package/dist/bus/index.mjs +1 -1
- package/dist/bus-CX0d5tTa.mjs +9 -0
- package/dist/{client-DWSwtFyI.mjs → client-D1BZILNq.mjs} +1 -1
- package/dist/clients/index.d.mts +7 -2
- package/dist/clients/index.mjs +1 -1
- package/dist/contracts/adapter/index.d.mts +2 -2
- package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
- package/dist/contracts/artifact/index.d.mts +2 -2
- package/dist/contracts/automation-trigger/index.d.mts +1 -1
- package/dist/contracts/canonical-model/index.d.mts +1 -1
- package/dist/contracts/capabilities/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +3 -3
- package/dist/contracts/client/index.mjs +1 -1
- package/dist/contracts/extension/index.d.mts +5 -5
- package/dist/contracts/facet/index.d.mts +1 -1
- package/dist/contracts/harness/index.d.mts +1 -1
- package/dist/contracts/index.d.mts +156 -156
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +1 -1
- package/dist/contracts/native-session-supervisor/index.d.mts +1 -1
- package/dist/contracts/reaction/index.d.mts +1 -1
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/shared/index.d.mts +1 -1
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/contracts/worker/index.d.mts +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/{contribution-DHJJARJP.d.mts → contribution-1GL7Rjaq.d.mts} +1 -1
- package/dist/{extension-context-C2qColIL.d.mts → extension-context-pQ7Uio_s.d.mts} +3 -3
- package/dist/{hook-responses-CN5r7i3k.d.mts → hook-responses-B882RcQc.d.mts} +1 -1
- package/dist/{index-DDff0Q_Y.d.mts → index-6bsTWnnc.d.mts} +45 -45
- package/dist/{index-D7dbR7Pu2.d.mts → index-BDcK7jqJ2.d.mts} +8 -8
- package/dist/{index-f31ex0nG.d.mts → index-BtMWM80d.d.mts} +153 -26
- package/dist/{index-DNdHuoy6.d.mts → index-CmCLAMNs.d.mts} +1 -1
- package/dist/{index-BwaFXFd2.d.mts → index-ConhyAnB.d.mts} +106 -106
- package/dist/{index-DauaMtPH2.d.mts → index-D2TphOHU2.d.mts} +378 -378
- package/dist/{index-qH2Jhegj2.d.mts → index-D3peNmHN2.d.mts} +1 -1
- package/dist/{index-DvtVX-Rj.d.mts → index-D6Uq1btG.d.mts} +1 -1
- package/dist/{index-vA46dx7q.d.mts → index-DGoJayJg.d.mts} +100 -100
- package/dist/{index-DH55jJaM.d.mts → index-DJVQG6Nn.d.mts} +10 -10
- package/dist/{index-Xnn0gJhU.d.mts → index-DOD7Lmgu.d.mts} +339 -339
- package/dist/{index-DjmCOTLM.d.mts → index-Di-R1gmo.d.mts} +291 -291
- package/dist/{index-D17f9C3Y.d.mts → index-DpLjyQ-Z.d.mts} +1 -1
- package/dist/{index-D9ExWo6a2.d.mts → index-FyY9jdCQ2.d.mts} +16 -16
- package/dist/{index-Bcq3UKLQ2.d.mts → index-UjNxC0VC2.d.mts} +11 -11
- package/dist/{index-Dk_f8Cyz2.d.mts → index-aIJ7A4DC2.d.mts} +3 -3
- package/dist/{index-BMPU9fkA.d.mts → index-anIxF_eT.d.mts} +4 -4
- package/dist/kernel/extension/index.d.mts +2 -2
- package/dist/kernel/index.d.mts +2 -2
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/{namespace-BdsOXWPU.d.mts → namespace-B1CgZ0oQ.d.mts} +1 -1
- package/dist/{namespace-CHc7YF0S.d.mts → namespace-Bhx72V7S.d.mts} +2 -2
- package/dist/{namespace-x-gk5SmK.d.mts → namespace-BtOBQybk.d.mts} +18 -18
- package/dist/{namespace-B2L_hlJ0.d.mts → namespace-D5DkpaaN.d.mts} +154 -154
- package/dist/{package-Bz938q5F.d.mts → package-CwyC-Krg.d.mts} +1 -1
- package/dist/package.json +1 -1
- package/dist/{schemas-C_0aO9S1.d.mts → schemas--wiEYYQs.d.mts} +17 -17
- package/dist/{schemas-Cl7fPlRv.d.mts → schemas-B7YzDHLs.d.mts} +4 -4
- package/dist/{schemas-Dqro7M1d.d.mts → schemas-CD3Mq-jC.d.mts} +154 -154
- package/dist/{schemas-BzB6z9oX2.d.mts → schemas-DNNHiY8g2.d.mts} +7 -7
- package/dist/services/agent-runtime/index.d.mts +2 -2
- package/dist/services/agent-runtime/namespace.d.mts +1 -1
- package/dist/services/agent-runtime/schemas.d.mts +1 -1
- package/dist/services/context-rules/index.d.mts +3 -3
- package/dist/services/filesystem/namespace.d.mts +12 -12
- package/dist/services/filesystem/schemas.d.mts +6 -6
- package/dist/services/git/namespace.d.mts +2 -2
- package/dist/services/git/schemas.d.mts +2 -2
- package/dist/services/index.d.mts +103 -103
- package/dist/services/log-import/browser.d.mts +2 -2
- package/dist/services/log-import/index.d.mts +2 -2
- package/dist/services/log-import/log-import.d.mts +1 -1
- package/dist/services/log-import/namespace.d.mts +2 -2
- package/dist/services/log-import/schemas.d.mts +1 -1
- package/dist/services/preferences/index.d.mts +2 -2
- package/dist/services/preferences/schemas.d.mts +1 -1
- package/dist/services/preferences/storage-namespace.d.mts +2 -2
- package/dist/services/session/index.d.mts +2 -2
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/session/session-events/namespace.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +14 -14
- package/dist/services/subagent-template/index.d.mts +2 -2
- package/dist/services/subagent-template/namespace.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/{session-lineage-CjE3qppC.d.mts → session-lineage-BuGN3RZs.d.mts} +1 -1
- package/dist/{storage-namespace-B5r_ScUz.d.mts → storage-namespace-DaCB01dg.d.mts} +10 -10
- package/dist/{transition-BVB-sXKI.d.mts → transition-DMv8cgEd.d.mts} +1 -1
- package/dist/{types-Cues-R7O2.d.mts → types-7L3BrU9m2.d.mts} +1 -1
- package/dist/{types-CVOL6fAm.d.mts → types-Dvsn8TOX.d.mts} +338 -338
- package/dist/ui-kernel/index.d.mts +4 -4
- package/dist/ui-kernel/pages/namespace.d.mts +4 -4
- package/dist/ui-kernel/pages/schemas.d.mts +1 -1
- package/dist/{view-builder-CbZtzUZI.d.mts → view-builder-BVIbIS_J.d.mts} +2 -2
- package/dist/workflow-engine/index.d.mts +68 -68
- package/dist/workflow-engine/package.d.mts +1 -1
- package/package.json +1 -1
- package/dist/bus-ceMF9rsq.mjs +0 -9
- package/dist/{index-Cm3HuwMC2.d.mts → index-DqliLe_D2.d.mts} +6 -6
- package/dist/{schemas-CU_52YMQ.d.mts → schemas-rMUsvzeJ.d.mts} +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e,s as t}from"./definitions-Do7bP-u7.mjs";import{t as n}from"./schemas-BmoFWBdh.mjs";import{_ as r,a as i,g as a,h as o,m as s,n as ee,o as te}from"./profile-1fvMljlJ.mjs";import{n as ne,t as c}from"./version-PuU2KG3I.mjs";import{c as re,d as ie,n as ae,o as oe,s as se,t as ce,u as le}from"./account-identity-C-v4mHq3.mjs";import{z as l}from"zod";import{createBusNamespace as ue,observability as u}from"@makaio/framework/core";const d=l.object({tag:l.string(),description:l.string().optional()}),f=l.object({name:l.string(),friendlyName:l.string(),description:l.string().optional(),category:l.string().optional(),capabilities:l.array(d).default([])}),de=l.object({id:l.string(),name:l.string(),description:l.string().optional(),glob:l.string().optional()}),p=l.object({name:l.string().min(1),frameworkSubject:l.string().min(1).optional(),responseCapabilities:l.array(l.string().min(1)).readonly().default([]),minimumVersion:c.optional()}).strict();function fe(e){return e.responseCapabilities.length>0?`request`:`event`}const m=l.object({envVar:a.regex(/^[A-Za-z_][A-Za-z0-9_]*$/,{message:`envVar must be a valid environment variable name (letters, digits, underscores)`}),defaultPath:a.refine(e=>e===`~`||e.startsWith(`~/`)||r(e),{message:`defaultPath must be absolute, '~', or start with '~/'`}),pathKind:l.enum([`directory`,`file`]).default(`directory`)});function pe(e){if(!e.startsWith(`@`))return!e.includes(`@`);let t=e.indexOf(`/`);return t>1&&!e.slice(t+1).includes(`@`)}const h=l.object({type:l.literal(`npm`),package:l.string().min(1).refine(pe,{message:"package must not include an inline `@version` suffix; use the version field instead"}),version:c}),g=l.object({type:l.literal(`signed-binary-bucket`),version:c,config:l.object({baseUrl:l.string().url(),manifestPathTemplate:l.string().min(1),manifestSignaturePathTemplate:l.string().min(1),publicKeyUrl:l.string().url(),publicKeyFingerprint:l.string().min(1),binaryPathTemplate:l.string().min(1),platforms:l.record(l.string().min(1),l.string().min(1))})}),_=l.discriminatedUnion(`type`,[h,g]),v=l.object({executable:l.union([l.string().min(1),l.object({default:l.string().min(1),darwin:l.string().min(1).optional(),linux:l.string().min(1).optional(),win32:l.string().min(1).optional()}).strict()]),args:l.array(l.string()).default([])}).strict(),y=l.object({kind:l.string().min(1),payload:l.record(l.string(),l.unknown()).optional()}),b=l.object({supportsHooks:l.boolean().default(!1),supportsStatusline:l.boolean().default(!1),supportsSupervisorLaunch:l.boolean().default(!1),supportsManagedBinary:l.boolean().default(!1),hookEvents:l.array(p).default([])}).refine(e=>e.supportsHooks||e.hookEvents.length===0,{message:`hookEvents must be empty when supportsHooks is false`,path:[`hookEvents`]}),x=l.object({name:l.string().min(1),supportedVersions:ne}).strict(),S=l.object({id:l.string(),name:l.string(),version:c,description:l.string().optional(),binary:x.optional(),nativeTools:l.array(f).default([]),defaultApprovalPolicy:n,logSources:l.array(de).optional(),authMethods:e,defaultAuth:t.optional(),runtimeCapabilities:b.optional().transform(e=>b.parse(e??{})),managedInstall:_.optional(),versionCommand:v.optional(),postInstall:y.optional(),configIsolation:m.optional()}).strict().refine(e=>!e.runtimeCapabilities.supportsManagedBinary||e.managedInstall!==void 0,{message:`managedInstall is required when runtimeCapabilities.supportsManagedBinary is true`,path:[`managedInstall`]}).refine(e=>e.managedInstall===void 0||e.runtimeCapabilities.supportsManagedBinary,{message:`runtimeCapabilities.supportsManagedBinary must be true when managedInstall is provided`,path:[`runtimeCapabilities`,`supportsManagedBinary`]}).refine(e=>e.managedInstall===void 0||e.versionCommand!==void 0,{message:`versionCommand is required when managedInstall is provided`,path:[`versionCommand`]}).superRefine((e,t)=>{e.defaultAuth!==void 0&&e.authMethods.find(({id:t})=>t===e.defaultAuth?.methodId)?.mode!==`inferred`&&t.addIssue({code:l.ZodIssueCode.custom,message:`defaultAuth.methodId must reference an inferred method declared by this client.`,path:[`defaultAuth`,`methodId`]})}).superRefine((e,t)=>{if(e.managedInstall===void 0||e.versionCommand===void 0)return;let{executable:n}=e.versionCommand,r=typeof n==`string`?[{path:n,issuePath:[`versionCommand`,`executable`]}]:[{path:n.default,issuePath:[`versionCommand`,`executable`,`default`]},...n.darwin===void 0?[]:[{path:n.darwin,issuePath:[`versionCommand`,`executable`,`darwin`]}],...n.linux===void 0?[]:[{path:n.linux,issuePath:[`versionCommand`,`executable`,`linux`]}],...n.win32===void 0?[]:[{path:n.win32,issuePath:[`versionCommand`,`executable`,`win32`]}]];for(let{path:e,issuePath:n}of r){let r=e.startsWith(`/`),i=/^[A-Za-z]:/.test(e),a=e.startsWith(`\\`);if(r||i||a){t.addIssue({code:l.ZodIssueCode.custom,path:n,message:`${n.join(`.`)} must be a relative path within the install directory`});continue}e.split(/[/\\]/).some(e=>e===`..`)&&t.addIssue({code:l.ZodIssueCode.custom,path:n,message:`${n.join(`.`)} must be a relative path within the install directory`})}}),C=l.object({binaryPath:s.nullable(),env:l.record(l.string(),l.string()),configDir:s.nullable(),source:l.enum([`managed`,`global`]),version:a.nullable()}),w={request:l.object({clientId:a,sessionId:a.optional(),projectDir:s.optional(),preferSource:l.enum([`managed`,`global`]).optional(),harnessId:a.optional()}),response:C},T=l.enum([`npm`,`signed-binary-bucket`]),E=l.object({version:a,installPath:s,installedAt:o,isActive:l.boolean()}),D=l.object({clientId:a,installedVersions:l.array(E),activeVersion:a.nullable(),pinnedVersion:c,updateAvailable:l.boolean()}).strict(),O={request:l.object({forceRefresh:l.boolean().optional()}),response:l.object({clients:l.array(D)})},k={request:l.object({clientId:a,version:c.optional()}),response:l.object({jobId:a,requestedVersion:c.nullable(),resolvedVersion:c.nullable()})},A={request:l.object({clientId:a,version:a}),response:l.object({clientId:a,removedVersion:a,activeVersion:a.nullable()})},j={request:l.object({clientId:a}),response:l.object({jobId:a,resolvedVersion:c.nullable()})},M={request:l.object({clientId:a,version:a}),response:l.object({clientId:a,activeVersion:a})},N=l.enum([`resolving`,`downloading`,`verifying`,`extracting`,`installing`,`post-install`,`activating`]),P=l.object({jobId:a,clientId:a,version:a.optional(),strategy:T,stage:N,progress:l.number().min(0).max(100).nullable(),installPath:s.optional(),activeAfterCompletion:l.boolean().optional(),metadata:l.record(l.string(),l.unknown()).optional()}),F=l.object({message:l.string(),code:l.string().optional()}),I=l.object({jobId:a,clientId:a,version:a.optional(),strategy:T,status:l.enum([`success`,`error`]),installPath:s.optional(),activeVersion:a.nullable(),error:F.optional(),metadata:l.record(l.string(),l.unknown()).optional()}),L=l.object({clientId:a,previousActiveVersion:a.nullable(),activeVersion:a.nullable(),reason:l.enum([`install`,`update`,`set-active`,`uninstall`])}),R=l.enum([`supervisor`,`adapter`,`client-hook`,`statusline`,`cli-wrapper`]),z=l.object({layer:R,producer:a}),B=l.object({supervisorSessionId:a.optional(),pid:l.number().int().positive().optional(),parentPid:l.number().int().positive().optional(),adapterSessionId:a.optional(),sessionId:a.optional(),cwd:l.string().optional(),argv:l.array(l.string()).optional(),metadata:l.record(l.string(),l.unknown()).optional()}),V={request:l.object({clientId:a,source:z,observedAt:o,adapterSessionTransition:l.literal(`root-clear`).optional()}).merge(B).refine(e=>e.supervisorSessionId!==void 0||e.pid!==void 0||e.adapterSessionId!==void 0,{message:`At least one hard-evidence field is required (supervisorSessionId, pid, or adapterSessionId)`}),response:l.object({clientRuntimeId:a,created:l.boolean(),promoted:l.boolean()})},H={request:l.strictObject({clientId:a,supervisorSessionId:a}),response:l.strictObject({runtime:l.strictObject({clientId:a,supervisorSessionId:a,adapterSessionId:a.optional(),sessionId:a.optional()}).nullable()})},U=B.extend({clientRuntimeId:a,clientId:a,status:l.enum([`observed`,`started`]),source:z,observedAt:o}),W={request:l.object({adapterSessionId:a,clientId:a}),response:l.object({managed:l.boolean()})},G=l.object({clientId:u.attribute(a,`makaio.client.id`),source:u.attribute(a,`makaio.client.lifecycle.source`),observedAt:u.attribute(o,`event.observed_at`),sessionId:u.attribute(l.string(),`makaio.session.id`).optional(),adapterSessionId:u.attribute(l.string(),`makaio.adapter.session_id`).optional(),metadata:l.record(l.string(),l.unknown()).optional()}),K=[`fresh`,`fork`,`resume`,`clear`,`compact`],q=l.enum(K),J=G.extend({transcriptPath:l.string().optional(),cwd:l.string().optional(),machineId:u.attribute(l.string(),`makaio.machine.id`).optional(),startMode:u.attribute(q,`makaio.session.start_mode`).optional(),parentAdapterSessionId:u.attribute(l.string(),`makaio.session.parent_adapter_session_id`).optional()}),me=G.extend({prompt:a.optional()}),he=G.extend({}),ge=G.extend({transcriptPath:l.string().optional()}),_e=G.extend({toolName:u.attribute(a,`tool.name`).optional(),toolCallId:u.attribute(a,`tool.call_id`).optional()}),ve=G.extend({toolName:u.attribute(a,`tool.name`).optional(),toolCallId:u.attribute(a,`tool.call_id`).optional(),success:u.attribute(l.boolean(),`tool.success`).optional()}),ye=[`manual`,`auto`],be=l.enum(ye),xe=G.extend({trigger:u.attribute(be,`makaio.session.compaction_trigger`).optional(),transcriptPath:l.string().optional()}),Y=G.extend({agentId:u.attribute(a,`makaio.client.agent_id`),agentType:u.attribute(a,`makaio.client.agent_type`).optional(),turnId:u.attribute(a,`makaio.client.turn_id`).optional()}),Se=Y.extend({agentTranscriptPath:l.string().optional()}),Ce=l.object({group:a,name:a,installed:l.boolean(),command:a}),we=l.enum([`provider-reported`,`client-reported`,`estimated`]),X=l.number().finite().nonnegative(),Te=l.number().finite().min(0).max(100),Ee=l.object({clientId:u.attribute(a,`makaio.client.id`),clientAccountId:u.attribute(a,`makaio.client.account_id`).optional(),sessionId:u.attribute(a,`makaio.session.id`).optional(),adapterSessionId:u.attribute(a,`makaio.adapter.session_id`).optional(),source:u.attribute(a,`makaio.client.usage.source`),observedAt:u.attribute(o,`event.observed_at`),clientVersion:u.attribute(a,`makaio.client.version`).optional(),modelId:u.attribute(a,`llm.model`).optional(),modelDisplayName:u.attribute(a,`llm.model.display_name`).optional(),modelFamily:u.attribute(a,`llm.model.family`).optional(),latestRequestInputTokens:u.attribute(X,`llm.tokens.latest_request.input`).optional(),latestRequestOutputTokens:u.attribute(X,`llm.tokens.latest_request.output`).optional(),latestRequestCacheReadTokens:u.attribute(X,`llm.tokens.latest_request.cache_read`).optional(),latestRequestCacheWriteTokens:u.attribute(X,`llm.tokens.latest_request.cache_write`).optional(),currentContextInputTokens:u.attribute(X,`llm.context.tokens.input`).optional(),currentContextOutputTokens:u.attribute(X,`llm.context.tokens.output`).optional(),contextWindowSizeTokens:u.attribute(X,`llm.context.window_size`).optional(),contextUsedPercentage:u.attribute(Te,`llm.context.used_percentage`).optional(),contextRemainingPercentage:u.attribute(Te,`llm.context.remaining_percentage`).optional(),contextThresholdExceeded:u.attribute(l.boolean(),`llm.context.threshold_exceeded`).optional(),totalCost:u.attribute(X,`llm.cost.total`).optional(),costCurrency:u.attribute(a,`llm.cost.currency`).optional(),costProvenance:u.attribute(we,`llm.cost.provenance`).optional(),totalDurationMs:u.attribute(X,`makaio.session.duration_ms`).optional(),totalApiDurationMs:u.attribute(X,`llm.duration.total_api_ms`).optional(),totalLinesAdded:u.attribute(X,`code.lines_added`).optional(),totalLinesRemoved:u.attribute(X,`code.lines_removed`).optional(),totalEdits:u.attribute(X,`code.edits`).optional()}).strict().superRefine((e,t)=>{let n=[`totalCost`,`costCurrency`,`costProvenance`],r=n.filter(t=>e[t]!==void 0).length;if(!(r===0||r===n.length))for(let r of n)e[r]===void 0&&t.addIssue({code:l.ZodIssueCode.custom,path:[r],message:`totalCost, costCurrency, and costProvenance must be supplied together`})}),De=l.object({clientId:l.string().min(1),adapterSessionId:l.string().min(1),agentId:l.string().min(1).optional()}),Oe=De,ke=l.object({token:l.string().nullable()}),Z={"runtime.observe":V,"runtime.resolveBySupervisorSessionId":H,"runtime.started":U,"runtime.isAdapterManaged":W,scan:{request:l.object({targets:l.array(se).optional()}),response:l.object({results:l.array(oe)})},"session.account.observe":re,"account.observe":ae,"account.activate":{request:l.object({clientId:a,clientAccountId:a,identifiers:l.array(ce).min(1),displayLabel:l.string().optional()}),response:l.object({accepted:l.boolean()})},"account.getActive":{request:l.object({clientId:a}),response:l.object({identity:l.object({clientAccountId:a,identifiers:l.array(ce).min(1),displayLabel:l.string().optional()}).nullable()})},"usage.ingest":le,"usage.snapshot":ie,"session.usage.snapshot":Ee,"session.started":J,"session.userPrompt.submitted":me,"session.turn.started":he,"session.turn.completed":ge,"session.tool.pre":_e,"session.tool.post":ve,"session.compaction.pre":xe,"session.subagent.started":Y,"session.subagent.completed":Se,"session.token.get":{request:Oe,response:ke},"wiring.list":{request:l.object({clientId:a.optional(),projectDir:s.optional(),makaioCommand:a}),response:l.object({results:l.array(l.object({clientId:a,entries:l.array(Ce)}))})},list:O,install:k,uninstall:A,update:j,setActive:M,"installJob.progress":P,"installJob.completed":I,"version.changed":L,resolveBinary:w,...i,...te,"config.prime":ee},Q=ue(`client`,Z),Ae=Q.subjects;function $(e){if(Array.isArray(e)){for(let t of e)$(t);return Object.freeze(e)}if(e&&typeof e==`object`){for(let t of Object.values(e))$(t);return Object.freeze(e)}return e}function je(e){return $(S.parse(e))}const Me=Object.freeze({contextAppend:`context.append`,sessionToken:`session.token`});function Ne(e){return Object.freeze({kind:`context.append`,value:e})}function Pe(e){return Object.freeze({kind:`session.token`,value:e})}const Fe=`open`;function Ie(e){return typeof e==`string`&&e.trim().length>0}function Le(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function Re(e,t){let n=[];for(let r of e){let e=r.kind===`event-name`?r.name:r.capability;if(!t.supportedInteractions.includes(e)){n.push(`Interaction '${e}' is not a supported interaction in contract '${t.contractId}'; failurePolicy 'closed' is not permitted`);continue}let i=t.blockability.find(t=>t.interaction===e);(!i||!i.blockable)&&n.push(`Interaction '${e}' is not blockable in contract '${t.contractId}'; failurePolicy 'closed' is not permitted`)}return n}export{w as $,me as A,I as B,J as C,_e as D,ve as E,H as F,A as G,k as H,R as I,F as J,j as K,z as L,B as M,W as N,ge as O,V as P,C as Q,U as R,q as S,Y as T,O as U,P as V,M as W,E as X,N as Y,T as Z,ye as _,Ie as a,f as at,be as b,je as c,_ as ct,Z as d,g as dt,x as et,Oe as f,v as ft,Ee as g,we as h,Pe as i,d as it,Ce as j,he as k,Q as l,h as lt,De as m,Fe as n,p as nt,Le as o,m as ot,ke as p,fe as pt,L as q,Ne as r,b as rt,Re as s,de as st,Me as t,S as tt,Ae as u,y as ut,K as v,Se as w,G as x,xe as y,D as z};
|
|
1
|
+
import{o as e,s as t}from"./definitions-Do7bP-u7.mjs";import{t as n}from"./schemas-BmoFWBdh.mjs";import{_ as r,a as i,g as a,h as o,m as s,n as ee,o as te}from"./profile-1fvMljlJ.mjs";import{n as ne,t as c}from"./version-PuU2KG3I.mjs";import{c as re,d as ie,n as ae,o as oe,s as se,t as ce,u as le}from"./account-identity-C-v4mHq3.mjs";import{z as l}from"zod";import{createBusNamespace as ue,observability as u}from"@makaio/framework/core";const d=l.object({tag:l.string(),description:l.string().optional()}),f=l.object({name:l.string(),friendlyName:l.string(),description:l.string().optional(),category:l.string().optional(),capabilities:l.array(d).default([])}),de=l.object({id:l.string(),name:l.string(),description:l.string().optional(),glob:l.string().optional()}),p=l.object({name:l.string().min(1),frameworkSubject:l.string().min(1).optional(),responseCapabilities:l.array(l.string().min(1)).readonly().default([]),minimumVersion:c.optional()}).strict();function fe(e){return e.responseCapabilities.length>0?`request`:`event`}const m=l.object({envVar:a.regex(/^[A-Za-z_][A-Za-z0-9_]*$/,{message:`envVar must be a valid environment variable name (letters, digits, underscores)`}),defaultPath:a.refine(e=>e===`~`||e.startsWith(`~/`)||r(e),{message:`defaultPath must be absolute, '~', or start with '~/'`}),pathKind:l.enum([`directory`,`file`]).default(`directory`)});function pe(e){if(!e.startsWith(`@`))return!e.includes(`@`);let t=e.indexOf(`/`);return t>1&&!e.slice(t+1).includes(`@`)}const h=l.object({type:l.literal(`npm`),package:l.string().min(1).refine(pe,{message:"package must not include an inline `@version` suffix; use the version field instead"}),version:c}),g=l.object({type:l.literal(`signed-binary-bucket`),version:c,config:l.object({baseUrl:l.string().url(),manifestPathTemplate:l.string().min(1),manifestSignaturePathTemplate:l.string().min(1),publicKeyUrl:l.string().url(),publicKeyFingerprint:l.string().min(1),binaryPathTemplate:l.string().min(1),platforms:l.record(l.string().min(1),l.string().min(1))})}),_=l.discriminatedUnion(`type`,[h,g]),v=l.object({executable:l.union([l.string().min(1),l.object({default:l.string().min(1),darwin:l.string().min(1).optional(),linux:l.string().min(1).optional(),win32:l.string().min(1).optional()}).strict()]),args:l.array(l.string()).default([])}).strict(),y=l.object({kind:l.string().min(1),payload:l.record(l.string(),l.unknown()).optional()}),b=l.object({supportsHooks:l.boolean().default(!1),supportsStatusline:l.boolean().default(!1),supportsSupervisorLaunch:l.boolean().default(!1),supportsManagedBinary:l.boolean().default(!1),hookEvents:l.array(p).default([])}).refine(e=>e.supportsHooks||e.hookEvents.length===0,{message:`hookEvents must be empty when supportsHooks is false`,path:[`hookEvents`]}),x=l.object({name:l.string().min(1),supportedVersions:ne}).strict(),S=l.object({id:l.string(),name:l.string(),version:c,description:l.string().optional(),binary:x.optional(),nativeTools:l.array(f).default([]),defaultApprovalPolicy:n,logSources:l.array(de).optional(),authMethods:e,defaultAuth:t.optional(),runtimeCapabilities:b.optional().transform(e=>b.parse(e??{})),managedInstall:_.optional(),versionCommand:v.optional(),postInstall:y.optional(),configIsolation:m.optional()}).strict().refine(e=>!e.runtimeCapabilities.supportsManagedBinary||e.managedInstall!==void 0,{message:`managedInstall is required when runtimeCapabilities.supportsManagedBinary is true`,path:[`managedInstall`]}).refine(e=>e.managedInstall===void 0||e.runtimeCapabilities.supportsManagedBinary,{message:`runtimeCapabilities.supportsManagedBinary must be true when managedInstall is provided`,path:[`runtimeCapabilities`,`supportsManagedBinary`]}).refine(e=>e.managedInstall===void 0||e.versionCommand!==void 0,{message:`versionCommand is required when managedInstall is provided`,path:[`versionCommand`]}).superRefine((e,t)=>{e.defaultAuth!==void 0&&e.authMethods.find(({id:t})=>t===e.defaultAuth?.methodId)?.mode!==`inferred`&&t.addIssue({code:l.ZodIssueCode.custom,message:`defaultAuth.methodId must reference an inferred method declared by this client.`,path:[`defaultAuth`,`methodId`]})}).superRefine((e,t)=>{if(e.managedInstall===void 0||e.versionCommand===void 0)return;let{executable:n}=e.versionCommand,r=typeof n==`string`?[{path:n,issuePath:[`versionCommand`,`executable`]}]:[{path:n.default,issuePath:[`versionCommand`,`executable`,`default`]},...n.darwin===void 0?[]:[{path:n.darwin,issuePath:[`versionCommand`,`executable`,`darwin`]}],...n.linux===void 0?[]:[{path:n.linux,issuePath:[`versionCommand`,`executable`,`linux`]}],...n.win32===void 0?[]:[{path:n.win32,issuePath:[`versionCommand`,`executable`,`win32`]}]];for(let{path:e,issuePath:n}of r){let r=e.startsWith(`/`),i=/^[A-Za-z]:/.test(e),a=e.startsWith(`\\`);if(r||i||a){t.addIssue({code:l.ZodIssueCode.custom,path:n,message:`${n.join(`.`)} must be a relative path within the install directory`});continue}e.split(/[/\\]/).some(e=>e===`..`)&&t.addIssue({code:l.ZodIssueCode.custom,path:n,message:`${n.join(`.`)} must be a relative path within the install directory`})}}),C=l.object({binaryPath:s.nullable(),env:l.record(l.string(),l.string()),configDir:s.nullable(),source:l.enum([`managed`,`global`]),version:a.nullable()}),w={request:l.object({clientId:a,sessionId:a.optional(),projectDir:s.optional(),preferSource:l.enum([`managed`,`global`]).optional(),harnessId:a.optional()}),response:C},T=l.enum([`npm`,`signed-binary-bucket`]),E=l.object({version:a,installPath:s,installedAt:o,isActive:l.boolean()}),D=l.object({clientId:a,installedVersions:l.array(E),activeVersion:a.nullable(),pinnedVersion:c,updateAvailable:l.boolean()}).strict(),O={request:l.object({forceRefresh:l.boolean().optional()}),response:l.object({clients:l.array(D)})},k={request:l.object({clientId:a,version:c.optional()}),response:l.object({jobId:a,requestedVersion:c.nullable(),resolvedVersion:c.nullable()})},A={request:l.object({clientId:a,version:a}),response:l.object({clientId:a,removedVersion:a,activeVersion:a.nullable()})},j={request:l.object({clientId:a}),response:l.object({jobId:a,resolvedVersion:c.nullable()})},M={request:l.object({clientId:a,version:a}),response:l.object({clientId:a,activeVersion:a})},N=l.enum([`resolving`,`downloading`,`verifying`,`extracting`,`installing`,`post-install`,`activating`]),P=l.object({jobId:a,clientId:a,version:a.optional(),strategy:T,stage:N,progress:l.number().min(0).max(100).nullable(),installPath:s.optional(),activeAfterCompletion:l.boolean().optional(),metadata:l.record(l.string(),l.unknown()).optional()}),F=l.object({message:l.string(),code:l.string().optional()}),I=l.object({jobId:a,clientId:a,version:a.optional(),strategy:T,status:l.enum([`success`,`error`]),installPath:s.optional(),activeVersion:a.nullable(),error:F.optional(),metadata:l.record(l.string(),l.unknown()).optional()}),L=l.object({clientId:a,previousActiveVersion:a.nullable(),activeVersion:a.nullable(),reason:l.enum([`install`,`update`,`set-active`,`uninstall`])}),R=l.enum([`supervisor`,`adapter`,`client-hook`,`statusline`,`cli-wrapper`]),z=l.object({layer:R,producer:a}),B=l.object({supervisorSessionId:a.optional(),pid:l.number().int().positive().optional(),parentPid:l.number().int().positive().optional(),adapterSessionId:a.optional(),sessionId:a.optional(),cwd:l.string().optional(),argv:l.array(l.string()).optional(),metadata:l.record(l.string(),l.unknown()).optional()}),V={request:l.object({clientId:a,source:z,observedAt:o,adapterSessionTransition:l.literal(`root-clear`).optional()}).merge(B).refine(e=>e.supervisorSessionId!==void 0||e.pid!==void 0||e.adapterSessionId!==void 0,{message:`At least one hard-evidence field is required (supervisorSessionId, pid, or adapterSessionId)`}),response:l.object({clientRuntimeId:a,created:l.boolean(),promoted:l.boolean()})},H={request:l.strictObject({clientId:a,supervisorSessionId:a}),response:l.strictObject({runtime:l.strictObject({clientId:a,supervisorSessionId:a,adapterSessionId:a.optional(),sessionId:a.optional(),updatedAt:o}).nullable()})},U=B.extend({clientRuntimeId:a,clientId:a,status:l.enum([`observed`,`started`]),source:z,observedAt:o,updatedAt:o}),W=B.extend({clientRuntimeId:a,clientId:a,status:l.enum([`observed`,`started`]),source:z,observedAt:o}),G={request:l.object({adapterSessionId:a,clientId:a}),response:l.object({managed:l.boolean()})},K=l.object({clientId:u.attribute(a,`makaio.client.id`),source:u.attribute(a,`makaio.client.lifecycle.source`),observedAt:u.attribute(o,`event.observed_at`),sessionId:u.attribute(l.string(),`makaio.session.id`).optional(),adapterSessionId:u.attribute(l.string(),`makaio.adapter.session_id`).optional(),metadata:l.record(l.string(),l.unknown()).optional()}),q=[`fresh`,`fork`,`resume`,`clear`,`compact`],J=l.enum(q),me=K.extend({transcriptPath:l.string().optional(),cwd:l.string().optional(),machineId:u.attribute(l.string(),`makaio.machine.id`).optional(),startMode:u.attribute(J,`makaio.session.start_mode`).optional(),parentAdapterSessionId:u.attribute(l.string(),`makaio.session.parent_adapter_session_id`).optional()}),he=K.extend({prompt:a.optional()}),ge=K.extend({}),_e=K.extend({transcriptPath:l.string().optional()}),ve=K.extend({toolName:u.attribute(a,`tool.name`).optional(),toolCallId:u.attribute(a,`tool.call_id`).optional()}),ye=K.extend({toolName:u.attribute(a,`tool.name`).optional(),toolCallId:u.attribute(a,`tool.call_id`).optional(),success:u.attribute(l.boolean(),`tool.success`).optional()}),be=[`manual`,`auto`],xe=l.enum(be),Se=K.extend({trigger:u.attribute(xe,`makaio.session.compaction_trigger`).optional(),transcriptPath:l.string().optional()}),Y=K.extend({agentId:u.attribute(a,`makaio.client.agent_id`),agentType:u.attribute(a,`makaio.client.agent_type`).optional(),turnId:u.attribute(a,`makaio.client.turn_id`).optional()}),Ce=Y.extend({agentTranscriptPath:l.string().optional()}),we=l.object({group:a,name:a,installed:l.boolean(),command:a}),Te=l.enum([`provider-reported`,`client-reported`,`estimated`]),X=l.number().finite().nonnegative(),Z=l.number().finite().min(0).max(100),Ee=l.object({clientId:u.attribute(a,`makaio.client.id`),clientAccountId:u.attribute(a,`makaio.client.account_id`).optional(),sessionId:u.attribute(a,`makaio.session.id`).optional(),adapterSessionId:u.attribute(a,`makaio.adapter.session_id`).optional(),source:u.attribute(a,`makaio.client.usage.source`),observedAt:u.attribute(o,`event.observed_at`),clientVersion:u.attribute(a,`makaio.client.version`).optional(),modelId:u.attribute(a,`llm.model`).optional(),modelDisplayName:u.attribute(a,`llm.model.display_name`).optional(),modelFamily:u.attribute(a,`llm.model.family`).optional(),latestRequestInputTokens:u.attribute(X,`llm.tokens.latest_request.input`).optional(),latestRequestOutputTokens:u.attribute(X,`llm.tokens.latest_request.output`).optional(),latestRequestCacheReadTokens:u.attribute(X,`llm.tokens.latest_request.cache_read`).optional(),latestRequestCacheWriteTokens:u.attribute(X,`llm.tokens.latest_request.cache_write`).optional(),currentContextInputTokens:u.attribute(X,`llm.context.tokens.input`).optional(),currentContextOutputTokens:u.attribute(X,`llm.context.tokens.output`).optional(),contextWindowSizeTokens:u.attribute(X,`llm.context.window_size`).optional(),contextUsedPercentage:u.attribute(Z,`llm.context.used_percentage`).optional(),contextRemainingPercentage:u.attribute(Z,`llm.context.remaining_percentage`).optional(),contextThresholdExceeded:u.attribute(l.boolean(),`llm.context.threshold_exceeded`).optional(),totalCost:u.attribute(X,`llm.cost.total`).optional(),costCurrency:u.attribute(a,`llm.cost.currency`).optional(),costProvenance:u.attribute(Te,`llm.cost.provenance`).optional(),totalDurationMs:u.attribute(X,`makaio.session.duration_ms`).optional(),totalApiDurationMs:u.attribute(X,`llm.duration.total_api_ms`).optional(),totalLinesAdded:u.attribute(X,`code.lines_added`).optional(),totalLinesRemoved:u.attribute(X,`code.lines_removed`).optional(),totalEdits:u.attribute(X,`code.edits`).optional()}).strict().superRefine((e,t)=>{let n=[`totalCost`,`costCurrency`,`costProvenance`],r=n.filter(t=>e[t]!==void 0).length;if(!(r===0||r===n.length))for(let r of n)e[r]===void 0&&t.addIssue({code:l.ZodIssueCode.custom,path:[r],message:`totalCost, costCurrency, and costProvenance must be supplied together`})}),De=l.object({clientId:l.string().min(1),adapterSessionId:l.string().min(1),agentId:l.string().min(1).optional()}),Oe=De,ke=l.object({token:l.string().nullable()}),Ae={"runtime.observe":V,"runtime.observed":U,"runtime.resolveBySupervisorSessionId":H,"runtime.started":W,"runtime.isAdapterManaged":G,scan:{request:l.object({targets:l.array(se).optional()}),response:l.object({results:l.array(oe)})},"session.account.observe":re,"account.observe":ae,"account.activate":{request:l.object({clientId:a,clientAccountId:a,identifiers:l.array(ce).min(1),displayLabel:l.string().optional()}),response:l.object({accepted:l.boolean()})},"account.getActive":{request:l.object({clientId:a}),response:l.object({identity:l.object({clientAccountId:a,identifiers:l.array(ce).min(1),displayLabel:l.string().optional()}).nullable()})},"usage.ingest":le,"usage.snapshot":ie,"session.usage.snapshot":Ee,"session.started":me,"session.userPrompt.submitted":he,"session.turn.started":ge,"session.turn.completed":_e,"session.tool.pre":ve,"session.tool.post":ye,"session.compaction.pre":Se,"session.subagent.started":Y,"session.subagent.completed":Ce,"session.token.get":{request:Oe,response:ke},"wiring.list":{request:l.object({clientId:a.optional(),projectDir:s.optional(),makaioCommand:a}),response:l.object({results:l.array(l.object({clientId:a,entries:l.array(we)}))})},list:O,install:k,uninstall:A,update:j,setActive:M,"installJob.progress":P,"installJob.completed":I,"version.changed":L,resolveBinary:w,...i,...te,"config.prime":ee},Q=ue(`client`,Ae),je=Q.subjects;function $(e){if(Array.isArray(e)){for(let t of e)$(t);return Object.freeze(e)}if(e&&typeof e==`object`){for(let t of Object.values(e))$(t);return Object.freeze(e)}return e}function Me(e){return $(S.parse(e))}const Ne=Object.freeze({contextAppend:`context.append`,sessionToken:`session.token`});function Pe(e){return Object.freeze({kind:`context.append`,value:e})}function Fe(e){return Object.freeze({kind:`session.token`,value:e})}const Ie=`open`;function Le(e){return typeof e==`string`&&e.trim().length>0}function Re(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function ze(e,t){let n=[];for(let r of e){let e=r.kind===`event-name`?r.name:r.capability;if(!t.supportedInteractions.includes(e)){n.push(`Interaction '${e}' is not a supported interaction in contract '${t.contractId}'; failurePolicy 'closed' is not permitted`);continue}let i=t.blockability.find(t=>t.interaction===e);(!i||!i.blockable)&&n.push(`Interaction '${e}' is not blockable in contract '${t.contractId}'; failurePolicy 'closed' is not permitted`)}return n}export{C as $,he as A,D as B,me as C,ve as D,ye as E,U as F,M as G,P as H,H as I,L as J,A as K,R as L,B as M,G as N,_e as O,V as P,T as Q,z as R,J as S,Y as T,k as U,I as V,O as W,N as X,F as Y,E as Z,be as _,Le as a,d as at,xe as b,Me as c,de as ct,Ae as d,y as dt,w as et,Oe as f,g as ft,Ee as g,Te as h,Fe as i,b as it,we as j,ge as k,Q as l,_ as lt,De as m,fe as mt,Ie as n,S as nt,Re as o,f as ot,ke as p,v as pt,j as q,Pe as r,p as rt,ze as s,m as st,Ne as t,x as tt,je as u,h as ut,q as v,Ce as w,K as x,Se as y,W as z};
|
package/dist/clients/index.d.mts
CHANGED
|
@@ -943,6 +943,7 @@ interface RuntimeUpsertResult {
|
|
|
943
943
|
*/
|
|
944
944
|
declare class ClientRuntimeRegistry {
|
|
945
945
|
private readonly runtimeMap;
|
|
946
|
+
private readonly mutationLane;
|
|
946
947
|
private readonly bus;
|
|
947
948
|
private latestCreatedAt;
|
|
948
949
|
/**
|
|
@@ -958,6 +959,7 @@ declare class ClientRuntimeRegistry {
|
|
|
958
959
|
* no bus is wired in, this is a no-op.
|
|
959
960
|
*/
|
|
960
961
|
loadFromStorage(): Promise<void>;
|
|
962
|
+
private loadFromStorageInLane;
|
|
961
963
|
/**
|
|
962
964
|
* Upsert a runtime record for the provided observation evidence.
|
|
963
965
|
*
|
|
@@ -973,6 +975,7 @@ declare class ClientRuntimeRegistry {
|
|
|
973
975
|
* @returns Upsert result with the stable `clientRuntimeId` and change flags
|
|
974
976
|
*/
|
|
975
977
|
upsertRuntime(input: ClientRuntimeObserveRequest): Promise<RuntimeUpsertResult>;
|
|
978
|
+
private upsertRuntimeInLane;
|
|
976
979
|
/**
|
|
977
980
|
* Retrieve a runtime record by its stable ID.
|
|
978
981
|
*
|
|
@@ -996,6 +999,7 @@ declare class ClientRuntimeRegistry {
|
|
|
996
999
|
supervisorSessionId: string;
|
|
997
1000
|
adapterSessionId?: string;
|
|
998
1001
|
sessionId?: string;
|
|
1002
|
+
updatedAt: number;
|
|
999
1003
|
} | null;
|
|
1000
1004
|
/**
|
|
1001
1005
|
* Mark an `(adapterSessionId, clientId)` pair as adapter-owned.
|
|
@@ -1032,8 +1036,9 @@ declare class ClientRuntimeRegistry {
|
|
|
1032
1036
|
*
|
|
1033
1037
|
* Does not touch persisted records — the storage layer is authoritative
|
|
1034
1038
|
* across restarts. Call {@link loadFromStorage} to re-hydrate.
|
|
1039
|
+
* @returns Promise that resolves after already-admitted mutations drain and memory is cleared.
|
|
1035
1040
|
*/
|
|
1036
|
-
clear(): void
|
|
1041
|
+
clear(): Promise<void>;
|
|
1037
1042
|
/**
|
|
1038
1043
|
* Return the number of runtime records currently held in memory.
|
|
1039
1044
|
* @returns Number of runtime records in the in-memory map
|
|
@@ -1090,7 +1095,7 @@ declare class ClientRuntimeService extends BaseService {
|
|
|
1090
1095
|
/**
|
|
1091
1096
|
* Clear all in-memory state on destroy.
|
|
1092
1097
|
*/
|
|
1093
|
-
protected onDestroy(): void
|
|
1098
|
+
protected onDestroy(): Promise<void>;
|
|
1094
1099
|
/**
|
|
1095
1100
|
* Return the latest snapshot retained for an account, if one exists.
|
|
1096
1101
|
* @param clientAccountId - Canonical account ID
|
package/dist/clients/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"../client-binary-version-verifier-DcHCFmsI.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{VersionLiteralSchema as l,extensionToken as u,isUniversalRange as d,versionSatisfies as f}from"@makaio/framework/contracts";import{MakaioBus as p}from"@makaio/framework/bus";import{BaseService as m}from"@makaio/framework/service-base";import{index as h,unique as ee,uniqueIndex as te}from"drizzle-orm/sqlite-core";import{index as g,unique as ne,uniqueIndex as re}from"drizzle-orm/pg-core";import{defineDialectSchema as _,defineDualTable as v,didAffectRows as ie,executeTransaction as y,registerDrizzleHandlers as ae,resolveSchema as b}from"@makaio/framework/storage/drizzle";import{and as x,eq as S,gt as oe,sql as C}from"drizzle-orm";import{ClientProfileNameSchema as w,ClientProfileSchema as se,ClientSubjects as ce,ClientSubjects as T,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{SessionSubjects as ge}from"@makaio/framework/contracts/session";import*as E from"node:os";import{CLIDetectionSubjects as _e}from"@makaio/framework/services/cli-detection/namespace";import{ClientStorageSubjects as ve}from"@makaio/framework/services/settings/storage";async function ye(e,t,n,r,i){let a,o=(n.get(e)??Promise.resolve()).then(async()=>{let n=await i(r(await be(e,t)));n.changed&&await xe(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 be(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 xe(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 Se=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)}},Ce=class{nextAccountSequence=1;accountIdsByIdentifier=new Map;accounts=new Map;upsertAccount(e){let t=Te(e.displayLabel),n=new Map;for(let t of e.identifiers)n.set(we(e.clientId,t.scheme,t.value),t);let r=Ee(n,this.accountIdsByIdentifier,`strong`),i=Ee(n,this.accountIdsByIdentifier,`alias`),a=r[0]??(i.length===1?i[0]:i.length>1?De(i):this.createAccount()),o=(r.length>0?Ae(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 we(e,t,n){return`${e}\u0000${t}\u0000${n}`}function Te(e){return e?.trim()||void 0}function Ee(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(Oe)}function De(e){return[...e].sort(Oe)[0]}function Oe(e,t){let n=ke(e),r=ke(t);return n!==null&&r!==null&&n!==r?n-r:e.localeCompare(t)}function ke(e){let t=e.match(/^client-account-(\d+)$/);return t?Number(t[1]):null}function Ae(e,t,n){let r=new Set([...t,...n]);return r.delete(e),Array.from(r).sort(Oe)}function je(e){return{subject:`config.prime`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}async function D(e,t){let n=await e.requestOptional(je(t.clientId),t);return n.handled?n.data:{primed:!1}}function Me(){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 Ne=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 O(t,n){return!a.isAbsolute(t)||!a.isAbsolute(n)?!1:e(a.resolve(t),a.resolve(n))}function k(e,t){if(!e||!a.isAbsolute(e))throw Error(`${t} requires a non-empty absolute basePath`);return a.resolve(e)}var Pe=class{strategyDeps;config;jobs=new Map;#e=!1;resolvedBasePath;constructor(e,t){this.strategyDeps=e,this.config=t,this.resolvedBasePath=k(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(!O(this.resolvedBasePath,n))throw Error(`Invalid install target path for client "${e}" and version "${t}"`);return n}};const A=r.object({id:r.string(),clientId:r.string(),version:r.string(),installPath:r.string(),installedAt:r.number().int().nonnegative(),createdAt:r.number().int().nonnegative()}),j=r.object({clientId:r.string(),activeVersion:r.string().nullable(),updatedAt:r.number().int().nonnegative()}),Fe=r.object({previousActiveVersion:r.string().nullable(),activeVersion:r.string().nullable()}),M=s(`client-binary:storage`,{insertVersion:{request:A,response:r.object({success:r.boolean()})},recordInstalledVersion:{request:r.object({versionRecord:A,makeActive:r.boolean(),updatedAt:r.number().int().nonnegative()}),response:Fe},listVersions:{request:r.object({clientId:r.string()}),response:r.object({versions:r.array(A)})},getSnapshot:{request:r.object({clientId:r.string()}),response:r.object({state:j.nullable(),versions:r.array(A)})},loadAllVersions:{request:r.object({}),response:r.object({versions:r.array(A)})},upsertState:{request:j,response:r.object({success:r.boolean()})},setActiveVersion:{request:r.object({clientId:r.string(),activeVersion:r.string().nullable(),updatedAt:r.number().int().nonnegative()}),response:Fe},getState:{request:r.object({clientId:r.string()}),response:r.object({state:j.nullable()})},loadAllState:{request:r.object({}),response:r.object({states:r.array(j)})},loadSnapshot:{request:r.object({}),response:r.object({states:r.array(j),versions:r.array(A)})},removeVersionAndClearActive:{request:r.object({clientId:r.string(),version:r.string(),updatedAt:r.number().int().nonnegative()}),response:Fe.extend({removedVersion:r.string().nullable()})}}),N=M.subjects;var P=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 F(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(N.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 O(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 O(t,n)?a===n||O(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&&F(`client.resolveBinary`,e,t,n.binary.supportedVersions,`managed binary version`);let o=Re(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(T.scan,{targets:[n]}),i=r.find(t=>t.clientId===e);if(i===void 0||!i.found)throw new Se(e);let o=i.version??null;F(`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===`~`?E.homedir():n.startsWith(`~/`)?a.join(E.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 Re(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 ze(e,t){let{versions:n,states:r}=await e.request(N.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 Be=class extends m{config;definitionLookup;versionResolver;jobRunner;strategyDeps;resolvedBasePath;resolvedConfigBasePath;resolver;pendingClients=new Set;constructor(e=p,t,n=new P([]),r=Me()){super(e),this.config=t,this.definitionLookup=n,this.resolvedBasePath=k(t.basePath,`ClientBinaryManager`),this.resolvedConfigBasePath=k(t.configBasePath,`ClientBinaryManager configBasePath`),this.strategyDeps=r,this.versionResolver=new Ne,this.jobRunner=new Pe(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(T.list,async e=>{let t=await this.handleList();e.setResult({clients:t})}),this.registerHandler(T.install,async e=>{let t=await this.handleInstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(T.update,async e=>{let t=await this.handleUpdate(e.payload.clientId);e.setResult(t)}),this.registerHandler(T.setActive,async e=>{let t=await this.handleSetActive(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(T.uninstall,async e=>{let t=await this.handleUninstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(T.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 ze(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&&F(`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&&F(`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(N.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&&F(`client.setActive`,e,t,a.binary.supportedVersions,`requested binary version`);let o=Re(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(N.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(N.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(T.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(N.setActiveVersion,{clientId:e,activeVersion:t,updatedAt:Date.now()})).previousActiveVersion;if(r!==t)try{await this.bus.emit(T.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(T.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(T.installJob.completed,e).catch(e=>{console.warn(`[ClientBinaryManager] Failed to emit client.installJob.completed:`,e)})},r.postInstall,Re(r.versionCommand)),o.jobId}makeCompletionCallback(){return async({clientId:e,version:t,installPath:n,makeActive:r,reason:i})=>{let a=Date.now();await D(this.bus,{clientId:e,configDir:this.resolveManagedConfigDir(e),phase:`managed-install`,binaryVersion:t});let o=await this.bus.request(N.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(T.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 Ve(e,t){return`${e}\0${t}`}function I(e,t){return`${e}\0${t}`}var He=class{records=new Map;bySupervisorSessionId=new Map;byPidClientId=new Map;byAdapterSessionClientId=new Map;supervisorSessionCandidates=new Map;pidClientCandidates=new Map;adapterSessionClientCandidates=new Map;adapterOwnedSessions=new Set;set(e,t){let n=t??this.records.get(e.clientRuntimeId);n&&this.removeIndexEntries(n),this.records.set(e.clientRuntimeId,e),this.addIndexEntries(e,!0)}setFromStorage(e,t,n){let r=this.records.get(e.clientRuntimeId);r&&this.removeIndexEntries(r),this.records.set(e.clientRuntimeId,e);let i=t-e.updatedAt<=n;this.addIndexEntries(e,i)}delete(e){let t=this.records.get(e);t&&(this.removeIndexEntries(t),t.adapterSessionId!==void 0&&this.adapterOwnedSessions.delete(I(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 n=this.byPidClientId.get(Ve(t,r));if(n!==void 0){let t=this.records.get(n);if(t!==void 0)return this.canMatchFallbackEvidence(t,e)?t:void 0}}if(n!==void 0){let t=this.byAdapterSessionClientId.get(I(n,r));if(t!==void 0){let n=this.records.get(t);if(n!==void 0)return this.canMatchFallbackEvidence(n,e)?n:void 0}}}values(){return this.records.values()}clear(){this.records.clear(),this.bySupervisorSessionId.clear(),this.byPidClientId.clear(),this.byAdapterSessionClientId.clear(),this.supervisorSessionCandidates.clear(),this.pidClientCandidates.clear(),this.adapterSessionClientCandidates.clear(),this.adapterOwnedSessions.clear()}markAdapterOwned(e,t){this.adapterOwnedSessions.add(I(e,t))}hasAdapterSession(e,t){return this.adapterOwnedSessions.has(I(e,t))}get size(){return this.records.size}addIndexEntries(e,t){e.supervisorSessionId!==void 0&&this.setIndexEntry(this.bySupervisorSessionId,this.supervisorSessionCandidates,e.supervisorSessionId,e),t&&(e.pid!==void 0&&this.setIndexEntry(this.byPidClientId,this.pidClientCandidates,Ve(e.pid,e.clientId),e),e.adapterSessionId!==void 0&&this.setIndexEntry(this.byAdapterSessionClientId,this.adapterSessionClientCandidates,I(e.adapterSessionId,e.clientId),e))}removeIndexEntries(e){e.supervisorSessionId!==void 0&&this.deleteIndexEntry(this.bySupervisorSessionId,this.supervisorSessionCandidates,e.supervisorSessionId,e.clientRuntimeId),e.pid!==void 0&&this.deleteIndexEntry(this.byPidClientId,this.pidClientCandidates,Ve(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.deleteIndexEntry(this.byAdapterSessionClientId,this.adapterSessionClientCandidates,I(e.adapterSessionId,e.clientId),e.clientRuntimeId)}canMatchFallbackEvidence(e,t){return t===void 0||e.supervisorSessionId===void 0||e.supervisorSessionId===t}deleteIndexEntry(e,t,n,r){let i=t.get(n);if(i?.delete(r)&&(i.size===0&&t.delete(n),e.get(n)===r)){let t=this.findBestIndexOwner(i);t===void 0?e.delete(n):e.set(n,t.clientRuntimeId)}}setIndexEntry(e,t,n,r){let i=t.get(n);i===void 0&&(i=new Set,t.set(n,i)),i.add(r.clientRuntimeId);let a=e.get(n),o=a===void 0||!i.has(a)?void 0:this.records.get(a);(o===void 0||this.isNewerIndexOwner(r,o))&&e.set(n,r.clientRuntimeId)}findBestIndexOwner(e){let t;for(let n of e){let e=this.records.get(n);e!==void 0&&(t===void 0||this.isNewerIndexOwner(e,t))&&(t=e)}return t}isNewerIndexOwner(e,t){return e.createdAt>t.createdAt||e.createdAt===t.createdAt&&e.clientRuntimeId>t.clientRuntimeId}};const L=[`observed`,`started`],Ue=r.object({clientRuntimeId:r.string(),clientId:r.string(),status:r.enum(L),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()}),R=s(`client-runtime:storage`,{upsert:{request:Ue,response:r.object({success:r.boolean()})},loadAll:{request:r.object({}),response:r.object({records:r.array(Ue)})}}),z=R.subjects;function We(e){return e.supervisorSessionId!==void 0||e.adapterSessionId!==void 0}function B(e){return{...e,argv:e.argv===void 0?void 0:[...e.argv],metadata:e.metadata===void 0?void 0:structuredClone(e.metadata)}}function Ge(e){return Math.max(Date.now(),e+1)}function Ke(e,t){if(t.supervisorSessionId!==void 0&&t.supervisorSessionId===e.supervisorSessionId&&t.adapterSessionId!==void 0&&e.adapterSessionId!==void 0&&t.adapterSessionId!==e.adapterSessionId){if(qe(e,t))return;throw Error(`client.runtime.observe: adapterSessionId '${t.adapterSessionId}' conflicts with the existing adapterSessionId '${e.adapterSessionId}' for supervisorSessionId '${t.supervisorSessionId}'`)}}function qe(e,t){return t.adapterSessionTransition===`root-clear`&&t.clientId===`codex`&&t.source.layer===`client-hook`&&t.source.producer===`codex-client-session-service`&&t.supervisorSessionId!==void 0&&t.supervisorSessionId===e.supervisorSessionId&&t.adapterSessionId!==void 0&&t.adapterSessionId!==e.adapterSessionId}function Je(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}function Ye(e,t){e.adapterSessionId=t.adapterSessionId,e.sessionId=void 0}var Xe=class{runtimeMap=new He;bus;latestCreatedAt=0;constructor(e){this.bus=e}async loadFromStorage(){if(!this.bus)return;let e=await this.bus.requestOptional(z.loadAll,{});if(!e.handled)return;let t=Date.now();for(let n of e.data.records)this.runtimeMap.setFromStorage(B(n),t,864e5),this.latestCreatedAt=Math.max(this.latestCreatedAt,n.createdAt)}async upsertRuntime(e){let t=this.runtimeMap.findByEvidence(e.supervisorSessionId,e.pid,e.adapterSessionId,e.clientId);if(t){let n=B(t);Ke(t,e);let r=qe(t,e);r&&Ye(t,e);let i=t.status===`observed`,a=i&&We(e),o=Je(t,e),s=i&&e.observedAt>t.observedAt;return a&&(t.status=`started`),(r||o||a||s)&&(t.updatedAt=Ge(t.updatedAt),s&&(t.observedAt=e.observedAt),this.runtimeMap.set(t,n),await this.persistRecord(t)),{clientRuntimeId:t.clientRuntimeId,created:!1,promoted:a,record:B(t)}}let n=this.nextCreatedAt(),r=o(),i=We(e)?`started`:`observed`,a={clientRuntimeId:r,clientId:e.clientId,status:i,supervisorSessionId:e.supervisorSessionId,pid:e.pid,parentPid:e.parentPid,adapterSessionId:e.adapterSessionId,sessionId:e.sessionId,cwd:e.cwd,argv:e.argv?[...e.argv]:void 0,metadata:e.metadata?structuredClone(e.metadata):void 0,observedAt:e.observedAt,createdAt:n,updatedAt:n};return this.runtimeMap.set(a),await this.persistRecord(a),{clientRuntimeId:r,created:!0,promoted:!1,record:B(a)}}getRuntime(e){let t=this.runtimeMap.get(e);return t?B(t):void 0}resolveBySupervisorSessionId(e,t){let n=this.runtimeMap.findByEvidence(t,void 0,void 0,e);return n===void 0||n.clientId!==e||n.supervisorSessionId!==t?null:{clientId:n.clientId,supervisorSessionId:n.supervisorSessionId,...n.adapterSessionId!==void 0&&{adapterSessionId:n.adapterSessionId},...n.sessionId!==void 0&&{sessionId:n.sessionId}}}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}nextCreatedAt(){return this.latestCreatedAt=Math.max(Date.now(),this.latestCreatedAt+1),this.latestCreatedAt}async persistRecord(e){this.bus&&await this.bus.requestOptional(z.upsert,B(e))}};const V=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()}),Ze=/^[a-z0-9-]+$/;function H(e,t=`canonicalizeClientId`){let n=e.trim().toLowerCase(),r=n.startsWith(`client:`)?n.slice(7):n;if(r.length===0)throw Error(`[${t}] clientId must be a non-empty string`);if(!Ze.test(r))throw Error(`[${t}] clientId must contain only lowercase letters, numbers, and hyphens after an optional client: prefix`);return r}function Qe(e){return{subject:`hook.received`,$meta:{namespace:`client:${H(e,`createRawClientHookReceivedSubject`)}`,isRequest:!1,local:!1,channel:!1}}}const $e=5e3,et=r.object({exitCode:r.number().int().min(0).max(255).default(0),stdout:r.string().default(``),stderr:r.string().default(``)}),tt=Object.freeze({exitCode:0,stdout:``,stderr:``});function nt(e){return{subject:`hook.handle`,$meta:{namespace:`client:${H(e,`createRawClientHookHandleSubject`)}`,isRequest:!0,local:!1,channel:!1,hostLocalRequest:!0}}}function rt(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function it(e,t){return rt(e[t])}function at(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 ot(e){try{e().catch(st)}catch(e){st(e)}}function st(e){(process.env.DEBUG||process.env.MAKAIO_DEBUG)&&console.debug(`[emitBestEffort] observed-semantics emission failed`,e)}function ct(e,t){return{subject:t,$meta:{namespace:`client:${H(e,`createClientWiringSubjectDef`)}`,isRequest:!0,local:!1,channel:!1}}}function lt(e){return ct(e,`wiring.list`)}const ut=r.string().min(1).refine(a.isAbsolute,{message:`projectDir must be an absolute path`}),dt=r.object({entries:r.array(le)}),ft=r.object({applied:r.number().int().nonnegative(),skipped:r.number().int().nonnegative()}),pt=r.object({removed:r.number().int().nonnegative()}),mt=r.object({clientId:r.string().trim().min(1),entries:r.array(le)});function ht(e){if(e!==void 0&&!a.isAbsolute(e))throw Error(`projectDir must be an absolute path, got: ${e}`)}var gt=class extends m{accountRegistry;runtimeRegistry;latestSnapshots=new Map;activeIdentities=new Map;constructor(e=p,t=new Ce,n=new Xe(e)){super(e),this.accountRegistry=t,this.runtimeRegistry=n}async onInit(){await this.runtimeRegistry.loadFromStorage(),this.registerHandler(T.account.observe,e=>this.handleAccountObserve(e)),this.registerHandler(T.usage.ingest,e=>this.handleUsageIngest(e)),this.registerHandler(T.scan,async e=>{let t=await this.scanClients(e.payload.targets);e.setResult({results:t})}),this.registerHandler(T.runtime.observe,e=>this.handleRuntimeObserve(e)),this.registerHandler(T.runtime.resolveBySupervisorSessionId,e=>{e.setResult({runtime:this.runtimeRegistry.resolveBySupervisorSessionId(e.payload.clientId,e.payload.supervisorSessionId)})}),this.registerHandler(T.runtime.isAdapterManaged,e=>{let{adapterSessionId:t,clientId:n}=e.payload;e.setResult({managed:this.runtimeRegistry.hasAdapterSession(t,n)})}),this.registerHandler(T.wiring.list,async e=>{let t=await this.listWirings(e.payload);e.setResult({results:t})}),this.registerHandler(T.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(T.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=yt(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(T.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=_t(t.clientAccountId,e.payload,t.displayLabel),r=yt(vt(this.latestSnapshots.get(t.clientAccountId),n),t.displayLabel);this.latestSnapshots.set(t.clientAccountId,r),await this.bus.emit(T.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(T.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:xt(n,r,e.supportedVersions)}})}async listScannableStoredClients(){let{clients:e}=await this.bus.request(ve.list,{});return e.filter(bt).map(e=>({clientId:e.id,binaryName:e.binary.name,supportedVersions:e.binary.supportedVersions}))}async listWirings(e){ht(e.projectDir);let{clients:t}=await this.bus.request(ve.list,{}),n=e.clientId===void 0?void 0:H(e.clientId,`listWirings`),r=t.filter(e=>e.enabled).filter(e=>n===void 0||e.id===n),i=await Promise.allSettled(r.map(async t=>{let n=lt(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 _t(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 vt(e,t){return e&&e.observedAt>t.observedAt?e:t}function yt(e,t){return!e||t===void 0||e.displayLabel===t?e:{...e,displayLabel:t}}function bt(e){return e.enabled&&e.binary!==void 0}function xt(e,t,n){if(e&&t!==void 0&&t!==`unknown`&&n!==void 0&&!f(t,n))return`Unsupported version: requires ${n}`}var St=class extends m{constructor(e=p){super(e)}onInit(){this.registerHandler(T.config.prime,async e=>{e.setResult(await D(this.bus,e.payload))})}};const U=se,W=r.string().trim().min(1),G=s(`client-profile:storage`,{get:{request:r.object({clientId:W,name:w}),response:r.object({record:U.nullable()})},getById:{request:r.object({id:W}),response:r.object({record:U.nullable()})},list:{request:r.object({clientId:W}),response:r.object({records:r.array(U)})},set:{request:U,response:r.object({success:r.boolean()})},delete:{request:r.object({clientId:W,name:w}),response:r.object({success:r.boolean()})},clearDefault:{request:r.object({clientId:W}),response:r.object({success:r.boolean()})},setDefault:{request:r.object({clientId:W,name:w}),response:r.object({record:U.nullable()})}}),K=G.subjects;function Ct(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 wt=class extends m{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(T.profile.create,async e=>{let t=H(e.payload.clientId,`profile.create`),{name:n,description:r}=e.payload;if((await this.bus.request(K.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=Ct(s,a.join(s,n),`profile.create`);await i.mkdir(c,{recursive:!0});try{await D(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(K.set,a),e.setResult({profile:a})}catch(e){throw await i.rm(c,{recursive:!0,force:!0}),e}})}registerListHandler(){this.registerHandler(T.profile.list,async e=>{let t=H(e.payload.clientId,`profile.list`),n=await this.bus.request(K.list,{clientId:t});e.setResult({profiles:n.records})})}registerGetHandler(){this.registerHandler(T.profile.get,async e=>{let t=H(e.payload.clientId,`profile.get`),n=await this.bus.request(K.get,{clientId:t,name:e.payload.name});e.setResult({profile:n.record})})}registerUpdateHandler(){this.registerHandler(T.profile.update,async e=>{let t=H(e.payload.clientId,`profile.update`),{name:n,description:r}=e.payload,i=await this.bus.request(K.get,{clientId:t,name:n});if(i.record===null)throw Error(`Profile '${n}' not found for client '${t}'`);let a={...i.record,description:r===void 0?i.record.description:r,updatedAt:Date.now()};await this.bus.request(K.set,a),e.setResult({profile:a})})}registerDeleteHandler(){this.registerHandler(T.profile.delete,async e=>{let t=H(e.payload.clientId,`profile.delete`),{name:n}=e.payload,r=await this.bus.request(K.get,{clientId:t,name:n});r.record!==null&&(Ct(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(K.delete,{clientId:t,name:n});e.setResult({success:o.success})})}registerSetDefaultHandler(){this.registerHandler(T.profile.setDefault,async e=>{let t=H(e.payload.clientId,`profile.setDefault`),{name:n}=e.payload,r=await this.bus.request(K.setDefault,{clientId:t,name:n});if(r.record===null)throw Error(`Profile '${n}' not found for client '${t}'`);e.setResult({profile:r.record})})}};function Tt(e){return{subject:`sessionConfig.setup`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}function Et(e){return{subject:`sessionConfig.destroy`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}const Dt=()=>Date.now();function Ot(){let e=E.platform();if(e===`darwin`||e===`linux`||e===`win32`)return e;throw Error(`client.sessionConfig does not support platform '${e}'`)}function kt(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 At=class extends m{clientsBasePath;getNow;liveLeasesByClient=new Map;liveLeasesByOwner=new Map;constructor(e,t,n=Dt){super(e),this.clientsBasePath=t,this.getNow=n}async onInit(){this.registerCreateHandler(),this.registerHandler(T.sessionConfig.destroy,async e=>{let{clientId:t,leaseId:n}=e.payload,r=H(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(T.sessionConfig.cleanup,async e=>{let{clientId:t}=e.payload,n=t===void 0?void 0:H(t,`sessionConfig.cleanup`),r=await this.cleanupOrphanedDirs(n);e.setResult({removed:r})}),this.registerHandler(ge.closed,async e=>{await this.destroyOwnedLeases(e.payload.sessionId)}),await this.cleanupOrphanedDirs()}registerCreateHandler(){this.registerHandler(T.sessionConfig.create,async e=>{let{clientId:t,leaseId:n,ownerSessionId:r,profileName:a,baseConfigDir:o,projectDir:s,configInheritance:c=`full`}=e.payload,l=H(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=Tt(l),f=await this.bus.requestOptional(r,{sessionDir:u,baseConfigDir:t,projectDir:s,platform:Ot(),configInheritance:c}),p=f.handled?f.data.env??{}:{},m=f.handled?f.data.authMaterialized:!1;if(await D(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(K.get,{clientId:e,name:n});if(t.record!==null)return t.record.configDir;throw Error(`Profile '${n}' not found for client '${e}'`)}let i=(await this.bus.request(K.list,{clientId:e})).records.find(e=>e.isDefault);return i?i.configDir:t}async cleanupOrphanedDirs(e){let 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=kt(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(Et(e),{sessionDir:t,platform:Ot()})}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 kt(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)}},jt=class extends m{store=new Map;constructor(e){super(e)}record(e,t){let{clientId:n,adapterSessionId:r,agentId:i}=e,a=this.buildKey(n,r,i);if(this.store.get(a)!==void 0)this.store.delete(a);else if(this.store.size>=1e3){let e=this.store.keys().next().value;e!==void 0&&this.store.delete(e)}this.store.set(a,{token:t,lastActivity:Date.now()})}onInit(){this.registerHandler(T.session.token.get,e=>{let{clientId:t,adapterSessionId:n,agentId:r}=e.payload,i=this.buildKey(t,n,r),a=this.store.get(i);a!==void 0&&(this.store.delete(i),this.store.set(i,{token:a.token,lastActivity:Date.now()})),e.setResult({token:a?.token??null})});let e=setInterval(()=>{let e=Date.now()-864e5;for(let[t,n]of this.store)n.lastActivity<e&&this.store.delete(t)},3e5);e.unref(),this.addCleanup(()=>clearInterval(e))}onDestroy(){this.store.clear()}buildKey(e,t,n){let r=`${e}\n${t}`;return n===void 0?r:`${r}\n${n}`}};const Mt=new Set([`hook.received`,`hook.handle`]);function Nt(e,t){return p.registerNamespace(s(`client:${e}`,{"hook.received":V,"hook.handle":c({request:V,response:et}),...t})).subjects}function Pt(e,t){let n=Object.keys(t).filter(e=>Mt.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 Ft(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 It(e,t,n){let r=Object.keys(n).filter(e=>!Ft(t,e));if(r.length!==0)throw Error(`[createClientNamespace] client:${e} was already registered without required subjects: ${r.join(`, `)}`)}function Lt(e,t){let n=H(e,`createClientNamespace`),r=t??{};Pt(n,r);let i=Nt(n,r);return It(n,i,r),{namespaceDomain:`client:${n}`,subjects:i}}const q=v(`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=>[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)],postgres:e=>[g(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),g(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),g(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)]}),Rt=q.sqlite,zt=q.postgres,Bt=_({clientRuntimes:Rt},{clientRuntimes:zt}),Vt=new Set(L);function Ht(e){if(!Vt.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 Ut(e,t){let{clientRuntimes:n}=b(t,Bt),r=e.on(z.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(C`excluded.updated_at`,n.updatedAt)}),e.setResult({success:!0})}),i=e.on(z.loadAll,async e=>{let r=await t.select().from(n);e.setResult({records:r.map(Ht)})});return()=>{r(),i()}}const Wt=v(`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)]}),Gt=Wt.sqlite,Kt=v(`client_binary_state`,e=>({clientId:e.text(`client_id`).primaryKey(),activeVersion:e.text(`active_version`),updatedAt:e.epochMs(`updated_at`).notNull()})),qt=Kt.sqlite,Jt=Wt.postgres,Yt=Kt.postgres,J=_({clientBinaryVersions:Gt,clientBinaryState:qt},{clientBinaryVersions:Jt,clientBinaryState:Yt});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 Xt(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}async function Zt(e,t,n){await e.insert(n).values(Xt(t)).onConflictDoNothing({target:[n.clientId,n.version]})}function Qt(e,t,n){return{clientId:e,activeVersion:t,updatedAt:n}}async function $t(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 en(e,t){let{clientBinaryVersions:n}=b(e,J);await Zt(e,t,n)}async function tn(e,t,n,r){let{clientBinaryVersions:i,clientBinaryState:a}=b(e,J);return y(e,async e=>{let[o]=await e.select().from(a).where(S(a.clientId,t.clientId)).limit(1),s=o?.activeVersion??null;return await Zt(e,t,i),n?(await $t(e,t.clientId,t.version,r,a),{previousActiveVersion:s,activeVersion:t.version}):{previousActiveVersion:s,activeVersion:s}})}async function nn(e,t){let{clientBinaryVersions:n,clientBinaryState:r}=b(e,J);return y(e,async e=>{let[i]=await e.select().from(r).where(S(r.clientId,t)).limit(1),a=await e.select().from(n).where(S(n.clientId,t));return{state:i?X(i):null,versions:a.map(Y)}})}async function rn(e){let{clientBinaryVersions:t,clientBinaryState:n}=b(e,J);return y(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 an(e,t){let{clientBinaryState:n}=b(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 on(e,t,n,r){let{clientBinaryState:i}=b(e,J);return y(e,async e=>{let[a]=await e.select().from(i).where(S(i.clientId,t)).limit(1),o=a?.activeVersion??null;return await $t(e,t,n,r,i),{previousActiveVersion:o,activeVersion:n}})}async function sn(e,t,n,r){let{clientBinaryVersions:i,clientBinaryState:a}=b(e,J);return y(e,async e=>{let[o]=await e.select().from(a).where(S(a.clientId,t)).limit(1),s=o?.activeVersion??null;if(!ie(await e.delete(i).where(x(S(i.clientId,t),S(i.version,n)))))return{removedVersion:null,previousActiveVersion:s,activeVersion:s};await e.update(a).set({activeVersion:null,updatedAt:r}).where(x(S(a.clientId,t),S(a.activeVersion,n)));let[c]=await e.select().from(a).where(S(a.clientId,t)).limit(1);return{removedVersion:n,previousActiveVersion:s,activeVersion:c?.activeVersion??null}})}function cn(e,t){let{clientBinaryVersions:n,clientBinaryState:r}=b(t,J),i=[e.on(N.insertVersion,async e=>{await en(t,e.payload),e.setResult({success:!0})}),e.on(N.recordInstalledVersion,async e=>{let{versionRecord:n,makeActive:r,updatedAt:i}=e.payload,a=await tn(t,n,r,i);e.setResult(a)}),e.on(N.listVersions,async e=>{let r=await t.select().from(n).where(S(n.clientId,e.payload.clientId));e.setResult({versions:r.map(Y)})}),e.on(N.getSnapshot,async e=>{let{state:n,versions:r}=await nn(t,e.payload.clientId);e.setResult({state:n,versions:r})}),e.on(N.loadAllVersions,async e=>{let r=await t.select().from(n);e.setResult({versions:r.map(Y)})}),e.on(N.upsertState,async e=>{await an(t,e.payload),e.setResult({success:!0})}),e.on(N.setActiveVersion,async e=>{let{clientId:n,activeVersion:r,updatedAt:i}=e.payload,a=await on(t,n,r,i);e.setResult(a)}),e.on(N.getState,async e=>{let[n]=await t.select().from(r).where(S(r.clientId,e.payload.clientId)).limit(1);e.setResult({state:n?X(n):null})}),e.on(N.loadAllState,async e=>{let n=await t.select().from(r);e.setResult({states:n.map(X)})}),e.on(N.loadSnapshot,async e=>{let{states:n,versions:r}=await rn(t);e.setResult({states:n,versions:r})}),e.on(N.removeVersionAndClearActive,async e=>{let{clientId:n,version:r,updatedAt:i}=e.payload,a=await sn(t,n,r,i);e.setResult(a)})];return()=>{for(let e of i)e()}}const ln=v(`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(C`${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(C`${e.isDefault} = true`)]}),un=ln.sqlite,dn=ln.postgres,fn=_({clientProfiles:un},{clientProfiles:dn});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 pn(e,t,n){let{clientProfiles:r}=b(e,fn),i=Date.now();return y(e,async e=>{let[a]=await e.select().from(r).where(x(S(r.clientId,t),S(r.name,n))).limit(1);if(a===void 0)return null;await e.update(r).set({isDefault:!1,updatedAt:i}).where(x(S(r.clientId,t),S(r.isDefault,!0))),await e.update(r).set({isDefault:!0,updatedAt:i}).where(x(S(r.clientId,t),S(r.name,n)));let[o]=await e.select().from(r).where(x(S(r.clientId,t),S(r.name,n))).limit(1);return o===void 0?null:Z(o)})}function mn(e,t){let{clientProfiles:n}=b(t,fn),r=[e.on(K.get,async e=>{let{clientId:r,name:i}=e.payload,[a]=await t.select().from(n).where(x(S(n.clientId,r),S(n.name,i))).limit(1);e.setResult({record:a?Z(a):null})}),e.on(K.getById,async e=>{let[r]=await t.select().from(n).where(S(n.id,e.payload.id)).limit(1);e.setResult({record:r?Z(r):null})}),e.on(K.list,async e=>{let r=await t.select().from(n).where(S(n.clientId,e.payload.clientId));e.setResult({records:r.map(Z)})}),e.on(K.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(K.delete,async e=>{let{clientId:r,name:i}=e.payload,a=await t.delete(n).where(x(S(n.clientId,r),S(n.name,i)));e.setResult({success:ie(a)})}),e.on(K.clearDefault,async e=>{await t.update(n).set({isDefault:!1,updatedAt:Date.now()}).where(x(S(n.clientId,e.payload.clientId),S(n.isDefault,!0))),e.setResult({success:!0})}),e.on(K.setDefault,async e=>{let{clientId:n,name:r}=e.payload,i=await pn(t,n,r);e.setResult({record:i})})];return()=>{for(let e of r)e()}}function hn(e,t){return`${e}\0${t}`}function gn(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 _n=class{entries=new Map;registerProviderContract(e,t){gn(t);let n=hn(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=hn(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=hn(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 vn(e,t){return`${e}/${t}`}function yn(e,t,n){switch(e.kind){case`event-name`:return e.name===t;case`capability`:return n.includes(e.capability)}}function bn(e,t){let n=t.definition.priority-e.definition.priority;return n===0?e.ordinal-t.ordinal:n}function xn(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 Sn(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 Cn(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(!xn(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(!Sn(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 wn(e,t,n,r){let i=[],a=new Set;for(let o of t){let t=Cn(e,o);if(t){i.push(t);continue}let s=vn(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),Tn(e,o,n,i)}return i}function Tn(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}En(e,t,[a],i,r);return}En(e,t,t.clientIds?t.clientIds.flatMap(e=>n.getProviderContractsByClient(e)):n.getAllProviderContracts(),i,r)}function En(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 Dn=class{contractRegistry;contributors=new Map;extensionIndex=new Map;nextOrdinal=1;constructor(e){this.contractRegistry=e}installContributors(e,t){let n=wn(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=vn(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=>yn(e,n,r))&&i.push(a)}return i.sort(bn),Object.freeze(i)}clear(){this.contributors.clear(),this.extensionIndex.clear(),this.nextOrdinal=1}};function On(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 kn=class{runtimeService;binaryManager;configPrimeService;profileService;sessionConfigService;sessionTokenService;providerContractRegistry;hookResponseRegistry;sessionTokens;constructor(e,t,n,r,i,a,o,s){this.runtimeService=e,this.binaryManager=t,this.configPrimeService=n,this.profileService=r,this.sessionConfigService=i,this.sessionTokenService=a,this.providerContractRegistry=o,this.hookResponseRegistry=s,this.sessionTokens=a}async init(){let e=(await Promise.allSettled([this.runtimeService.init(),this.binaryManager.init(),this.configPrimeService.init(),this.profileService.init(),this.sessionConfigService.init(),this.sessionTokenService.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(),this.sessionTokenService.destroy()])).filter(e=>e.status===`rejected`);if(e.length>0)throw AggregateError(e.map(e=>e.reason),`ClientsCoreService failed to tear down cleanly`)}};const An=u(`makaio.clients-core`);function jn(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 Mn(e={}){let{definitions:t=[],strategyDependencies:n,postInstallHandlers:r,binaryResolutionPolicy:i}=e,o=[...t],s=new _n,c=new Dn(s);return{name:`makaio.clients-core`,displayName:`Clients Core`,version:`0.1.0`,critical:!0,namespaces:[M,R,G],storage:{registerHandlers:ae((e,t)=>jn([()=>Ut(e,t),()=>cn(e,t),()=>mn(e,t)]))},create:e=>{let t=new P(o),l=a.join(e.makaioHome,`clients`),u=new Be(e.bus,{basePath:a.join(e.makaioHome,`binaries`),configBasePath:l,postInstallHandlers:r,...i!==void 0&&{resolutionPolicy:i}},t,n),d=new wt(e.bus,l),f=new At(e.bus,l),p=new jt(e.bus);return new kn(new gt(e.bus),u,new St(e.bus),d,f,p,s,c)},runtimeBoot:{configure:e=>{e.registerContributionProcessor(On(c,s))}}}}async function Nn(e,t){let n=await e.requestOptional(T.resolveBinary,{clientId:t});return n.handled?n.data:void 0}function Pn(e,t,n){return[...n??[],e,...t].map(Rn).join(` `)}function Fn(e,t,n,r,i){return Pn(e,[...i??[],...t.split(` `),n],r)}function In(e){return e.runtimeCapabilities.hookEvents.map(e=>{let t={eventName:e.name,mode:fe(e)};return e.minimumVersion===void 0?t:{...t,minimumVersion:e.minimumVersion}})}function Ln(e,t){return e.minimumVersion===void 0||typeof t!=`string`||!l.safeParse(t).success?!0:f(t,`>=${e.minimumVersion}`)}function Rn(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}const zn=new Set([`context.append`,`session.token`]);function Bn(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||!zn.has(t.kind)||typeof t.value!=`string`)return`canonicalEffects must contain complete context.append or session.token effects`;if(Object.keys(t).some(e=>e!==`kind`&&e!==`value`))return`canonicalEffects must contain only kind and value`;if(t.kind===`session.token`&&t.value.length===0)return`session.token effect requires a non-empty string value`}return!0}function Vn(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 Hn(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=Vn(e.providerEnvelope,t.clientId,t.contractId);return o===!0?r.validate(e,{clientId:n,eventName:i,eventPayload:a}):o}function Un(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`?Bn(e.canonicalEffects):Hn(e,t,n,r,i,a)}const Q=Symbol(`contributor-timeout`);function Wn(e){return e.failurePolicy??ue}function Gn(e){return e.namespacedId??e.definition.id}function $(e,t){return e===`closed`?`closed-failure`:t}function Kn(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 qn(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 Jn(e){let t=[],n=[],r=`Request deadline already expired before collection started`;for(let i of e){let e=Gn(i),a=$(Wn(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 Yn(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 Xn(e,t,n,r,i,a){let{definition:o}=e,s=Gn(e),c=Date.now(),l=c+o.timeoutMs,u=n===void 0?l:Math.min(n,l),d=u-c,f=new AbortController;r&&Yn(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:qn(m,u,f).then(e=>e===Q?{tag:`timeout`}:{tag:`ok`,response:e},e=>({tag:`rejected`,error:e}))}}function Zn(e,t,n,r,i,a){let{contributorId:o,definition:s,startMs:c,abort:l}=e,u=Date.now()-c,d=Wn(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=Un(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:Kn(f)}}}function Qn(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 $n(e,t,n,r,i,a,o){if(e.length===0)return{outcomes:[],diagnostics:[]};if(n!==void 0&&n<=Date.now())return Jn(e);let s=e.map(e=>Xn(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}=Zn(s[e],c[e],t,o,i,a);l.push(n),r&&u.push(r)}return Qn(l,u)}export{ut as AbsolutePathSchema,Se as BinaryNotFoundError,L as CLIENT_RUNTIME_STATUSES,Ce as ClientAccountRegistry,Pe as ClientBinaryJobRunner,Be as ClientBinaryManager,j as ClientBinaryStateRecordSchema,M as ClientBinaryStorageNamespace,N as ClientBinaryStorageSubjects,A as ClientBinaryVersionRecordSchema,Ne as ClientBinaryVersionResolver,St as ClientConfigPrimeService,P as ClientDefinitionRegistry,et as ClientHookHandleResponseSchema,_n as ClientHookProviderContractRegistry,Dn as ClientHookResponseRegistry,U as ClientProfileRecordSchema,wt as ClientProfileService,G as ClientProfileStorageNamespace,K as ClientProfileStorageSubjects,Xe as ClientRuntimeRegistry,gt as ClientRuntimeService,R as ClientRuntimeStorageNamespace,z as ClientRuntimeStorageSubjects,At as ClientSessionConfigService,jt as ClientSessionTokenService,ce as ClientSubjects,mt as ClientWiringAggregatedResultSchema,ft as ClientWiringApplyResponseSchema,le as ClientWiringEntrySchema,dt as ClientWiringListResponseSchema,pt as ClientWiringRemoveResponseSchema,kn as ClientsCoreService,An as ClientsCoreToken,$e as DEFAULT_HOOK_HANDLE_TIMEOUT_MS,tt as NOOP_HOOK_HANDLE_RESPONSE,V as RawClientHookPayloadSchema,Ue as RuntimeRecordSchema,ht as assertAbsoluteProjectDir,ye as atomicModifyFile,Pn as buildClientCommand,at as buildClientSessionBase,Fn as buildHookCommand,H as canonicalizeClientId,q as clientRuntimesDual,$n as collectContributions,On as createClientHookResponseContributionProcessor,Lt as createClientNamespace,lt as createClientWiringListSubjectDef,ct as createClientWiringSubjectDef,Mn as createClientsCorePackage,nt as createRawClientHookHandleSubject,Qe as createRawClientHookReceivedSubject,t as createStrategy,In as deriveSessionEventDescriptors,ot as emitBestEffort,O as isPathWithinBase,Ln as isSessionEventSupported,it as pickNonEmptyString,rt as pickNonEmptyStringValue,cn as registerDrizzleClientBinaryStorage,mn as registerDrizzleProfileStorage,Ut as registerDrizzleRuntimeStorage,jn as registerStorageHandlersWithRollback,k as resolveAndValidateBasePath,Nn as resolveClientBinary,n as verifyInstalledVersion};
|
|
1
|
+
import{n as e,r as t,t as n}from"../client-binary-version-verifier-DcHCFmsI.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{SerialLane as s}from"@makaio/framework/utils";import{createBusNamespace as c,hostLocalRequest as l}from"@makaio/framework/core";import{VersionLiteralSchema as u,extensionToken as d,isUniversalRange as f,versionSatisfies as p}from"@makaio/framework/contracts";import{MakaioBus as m}from"@makaio/framework/bus";import{BaseService as h}from"@makaio/framework/service-base";import{index as g,unique as ee,uniqueIndex as te}from"drizzle-orm/sqlite-core";import{index as ne,unique as re,uniqueIndex as ie}from"drizzle-orm/pg-core";import{defineDialectSchema as _,defineDualTable as v,didAffectRows as ae,executeTransaction as y,registerDrizzleHandlers as oe,resolveSchema as b}from"@makaio/framework/storage/drizzle";import{and as x,eq as S,gt as se,sql as C}from"drizzle-orm";import{ClientProfileNameSchema as w,ClientProfileSchema as ce,ClientSubjects as le,ClientSubjects as T,ClientWiringEntrySchema as ue,DEFAULT_FAILURE_POLICY as de,SessionConfigLeaseIdSchema as fe,deriveHookEventTransportMode as pe,isValidContributorId as me,isValidTimeoutMs as he,validateClosedPolicy as ge}from"@makaio/framework/contracts/client";import{SessionSubjects as _e}from"@makaio/framework/contracts/session";import*as ve from"node:os";import{CLIDetectionSubjects as ye}from"@makaio/framework/services/cli-detection/namespace";import{ClientStorageSubjects as be}from"@makaio/framework/services/settings/storage";async function xe(e,t,n,r,i){let a,o=(n.get(e)??Promise.resolve()).then(async()=>{let n=await i(r(await Se(e,t)));n.changed&&await Ce(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 Se(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 Ce(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 we=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)}},Te=class{nextAccountSequence=1;accountIdsByIdentifier=new Map;accounts=new Map;upsertAccount(e){let t=De(e.displayLabel),n=new Map;for(let t of e.identifiers)n.set(Ee(e.clientId,t.scheme,t.value),t);let r=Oe(n,this.accountIdsByIdentifier,`strong`),i=Oe(n,this.accountIdsByIdentifier,`alias`),a=r[0]??(i.length===1?i[0]:i.length>1?ke(i):this.createAccount()),o=(r.length>0?Me(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 Ee(e,t,n){return`${e}\u0000${t}\u0000${n}`}function De(e){return e?.trim()||void 0}function Oe(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(Ae)}function ke(e){return[...e].sort(Ae)[0]}function Ae(e,t){let n=je(e),r=je(t);return n!==null&&r!==null&&n!==r?n-r:e.localeCompare(t)}function je(e){let t=e.match(/^client-account-(\d+)$/);return t?Number(t[1]):null}function Me(e,t,n){let r=new Set([...t,...n]);return r.delete(e),Array.from(r).sort(Ae)}function Ne(e){return{subject:`config.prime`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}async function E(e,t){let n=await e.requestOptional(Ne(t.clientId),t);return n.handled?n.data:{primed:!1}}function Pe(){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 Fe=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 D(t,n){return!a.isAbsolute(t)||!a.isAbsolute(n)?!1:e(a.resolve(t),a.resolve(n))}function O(e,t){if(!e||!a.isAbsolute(e))throw Error(`${t} requires a non-empty absolute basePath`);return a.resolve(e)}var Ie=class{strategyDeps;config;jobs=new Map;#e=!1;resolvedBasePath;constructor(e,t){this.strategyDeps=e,this.config=t,this.resolvedBasePath=O(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(!D(this.resolvedBasePath,n))throw Error(`Invalid install target path for client "${e}" and version "${t}"`);return n}};const k=r.object({id:r.string(),clientId:r.string(),version:r.string(),installPath:r.string(),installedAt:r.number().int().nonnegative(),createdAt:r.number().int().nonnegative()}),A=r.object({clientId:r.string(),activeVersion:r.string().nullable(),updatedAt:r.number().int().nonnegative()}),j=r.object({previousActiveVersion:r.string().nullable(),activeVersion:r.string().nullable()}),M=c(`client-binary:storage`,{insertVersion:{request:k,response:r.object({success:r.boolean()})},recordInstalledVersion:{request:r.object({versionRecord:k,makeActive:r.boolean(),updatedAt:r.number().int().nonnegative()}),response:j},listVersions:{request:r.object({clientId:r.string()}),response:r.object({versions:r.array(k)})},getSnapshot:{request:r.object({clientId:r.string()}),response:r.object({state:A.nullable(),versions:r.array(k)})},loadAllVersions:{request:r.object({}),response:r.object({versions:r.array(k)})},upsertState:{request:A,response:r.object({success:r.boolean()})},setActiveVersion:{request:r.object({clientId:r.string(),activeVersion:r.string().nullable(),updatedAt:r.number().int().nonnegative()}),response:j},getState:{request:r.object({clientId:r.string()}),response:r.object({state:A.nullable()})},loadAllState:{request:r.object({}),response:r.object({states:r.array(A)})},loadSnapshot:{request:r.object({}),response:r.object({states:r.array(A),versions:r.array(k)})},removeVersionAndClearActive:{request:r.object({clientId:r.string(),version:r.string(),updatedAt:r.number().int().nonnegative()}),response:j.extend({removedVersion:r.string().nullable()})}}),N=M.subjects;var P=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 Le=process.env.MAKAIO_SKIP_CLIENT_VERSION_CHECK===`1`;function F(e,t,n,r,i){if(n===null){if(f(r))return;if(Le){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(!p(n,r)){if(Le){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 Re=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(N.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 D(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 D(t,n)?a===n||D(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&&F(`client.resolveBinary`,e,t,n.binary.supportedVersions,`managed binary version`);let o=I(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(T.scan,{targets:[n]}),i=r.find(t=>t.clientId===e);if(i===void 0||!i.found)throw new we(e);let o=i.version??null;F(`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===`~`?ve.homedir():n.startsWith(`~/`)?a.join(ve.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 I(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 ze(e,t){let{versions:n,states:r}=await e.request(N.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 Be=class extends h{config;definitionLookup;versionResolver;jobRunner;strategyDeps;resolvedBasePath;resolvedConfigBasePath;resolver;pendingClients=new Set;constructor(e=m,t,n=new P([]),r=Pe()){super(e),this.config=t,this.definitionLookup=n,this.resolvedBasePath=O(t.basePath,`ClientBinaryManager`),this.resolvedConfigBasePath=O(t.configBasePath,`ClientBinaryManager configBasePath`),this.strategyDeps=r,this.versionResolver=new Fe,this.jobRunner=new Ie(r,t),this.resolver=new Re({bus:e,resolvedBasePath:this.resolvedBasePath,resolvedConfigBasePath:this.resolvedConfigBasePath,definitionLookup:n,...t.resolutionPolicy!==void 0&&{resolutionPolicy:t.resolutionPolicy}})}async onInit(){this.registerHandler(T.list,async e=>{let t=await this.handleList();e.setResult({clients:t})}),this.registerHandler(T.install,async e=>{let t=await this.handleInstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(T.update,async e=>{let t=await this.handleUpdate(e.payload.clientId);e.setResult(t)}),this.registerHandler(T.setActive,async e=>{let t=await this.handleSetActive(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(T.uninstall,async e=>{let t=await this.handleUninstall(e.payload.clientId,e.payload.version);e.setResult(t)}),this.registerHandler(T.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 ze(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&&F(`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&&F(`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(N.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&&F(`client.setActive`,e,t,a.binary.supportedVersions,`requested binary version`);let o=I(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(N.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(N.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(T.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(N.setActiveVersion,{clientId:e,activeVersion:t,updatedAt:Date.now()})).previousActiveVersion;if(r!==t)try{await this.bus.emit(T.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(T.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(T.installJob.completed,e).catch(e=>{console.warn(`[ClientBinaryManager] Failed to emit client.installJob.completed:`,e)})},r.postInstall,I(r.versionCommand)),o.jobId}makeCompletionCallback(){return async({clientId:e,version:t,installPath:n,makeActive:r,reason:i})=>{let a=Date.now();await E(this.bus,{clientId:e,configDir:this.resolveManagedConfigDir(e),phase:`managed-install`,binaryVersion:t});let o=await this.bus.request(N.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(T.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 L(e,t){return`${e}\0${t}`}function R(e,t){return`${e}\0${t}`}var Ve=class{records=new Map;bySupervisorSessionId=new Map;byPidClientId=new Map;byAdapterSessionClientId=new Map;supervisorSessionCandidates=new Map;pidClientCandidates=new Map;adapterSessionClientCandidates=new Map;adapterOwnedSessions=new Set;set(e,t){let n=t??this.records.get(e.clientRuntimeId);n&&this.removeIndexEntries(n),this.records.set(e.clientRuntimeId,e),this.addIndexEntries(e,!0)}setFromStorage(e,t,n){let r=this.records.get(e.clientRuntimeId);r&&this.removeIndexEntries(r),this.records.set(e.clientRuntimeId,e);let i=t-e.updatedAt<=n;this.addIndexEntries(e,i)}delete(e){let t=this.records.get(e);t&&(this.removeIndexEntries(t),t.adapterSessionId!==void 0&&this.adapterOwnedSessions.delete(R(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 n=this.byPidClientId.get(L(t,r));if(n!==void 0){let t=this.records.get(n);if(t!==void 0)return this.canMatchFallbackEvidence(t,e)?t:void 0}}if(n!==void 0){let t=this.byAdapterSessionClientId.get(R(n,r));if(t!==void 0){let n=this.records.get(t);if(n!==void 0)return this.canMatchFallbackEvidence(n,e)?n:void 0}}}values(){return this.records.values()}clear(){this.records.clear(),this.bySupervisorSessionId.clear(),this.byPidClientId.clear(),this.byAdapterSessionClientId.clear(),this.supervisorSessionCandidates.clear(),this.pidClientCandidates.clear(),this.adapterSessionClientCandidates.clear(),this.adapterOwnedSessions.clear()}markAdapterOwned(e,t){this.adapterOwnedSessions.add(R(e,t))}hasAdapterSession(e,t){return this.adapterOwnedSessions.has(R(e,t))}get size(){return this.records.size}addIndexEntries(e,t){e.supervisorSessionId!==void 0&&this.setIndexEntry(this.bySupervisorSessionId,this.supervisorSessionCandidates,e.supervisorSessionId,e),t&&(e.pid!==void 0&&this.setIndexEntry(this.byPidClientId,this.pidClientCandidates,L(e.pid,e.clientId),e),e.adapterSessionId!==void 0&&this.setIndexEntry(this.byAdapterSessionClientId,this.adapterSessionClientCandidates,R(e.adapterSessionId,e.clientId),e))}removeIndexEntries(e){e.supervisorSessionId!==void 0&&this.deleteIndexEntry(this.bySupervisorSessionId,this.supervisorSessionCandidates,e.supervisorSessionId,e.clientRuntimeId),e.pid!==void 0&&this.deleteIndexEntry(this.byPidClientId,this.pidClientCandidates,L(e.pid,e.clientId),e.clientRuntimeId),e.adapterSessionId!==void 0&&this.deleteIndexEntry(this.byAdapterSessionClientId,this.adapterSessionClientCandidates,R(e.adapterSessionId,e.clientId),e.clientRuntimeId)}canMatchFallbackEvidence(e,t){return t===void 0||e.supervisorSessionId===void 0||e.supervisorSessionId===t}deleteIndexEntry(e,t,n,r){let i=t.get(n);if(i?.delete(r)&&(i.size===0&&t.delete(n),e.get(n)===r)){let t=this.findBestIndexOwner(i);t===void 0?e.delete(n):e.set(n,t.clientRuntimeId)}}setIndexEntry(e,t,n,r){let i=t.get(n);i===void 0&&(i=new Set,t.set(n,i)),i.add(r.clientRuntimeId);let a=e.get(n),o=a===void 0||!i.has(a)?void 0:this.records.get(a);(o===void 0||this.isNewerIndexOwner(r,o))&&e.set(n,r.clientRuntimeId)}findBestIndexOwner(e){let t;for(let n of e){let e=this.records.get(n);e!==void 0&&(t===void 0||this.isNewerIndexOwner(e,t))&&(t=e)}return t}isNewerIndexOwner(e,t){return e.createdAt>t.createdAt||e.createdAt===t.createdAt&&e.clientRuntimeId>t.clientRuntimeId}};const z=[`observed`,`started`],B=r.object({clientRuntimeId:r.string(),clientId:r.string(),status:r.enum(z),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()}),He=c(`client-runtime:storage`,{upsert:{request:B,response:r.object({success:r.boolean()})},loadAll:{request:r.object({}),response:r.object({records:r.array(B)})}}),V=He.subjects;function Ue(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 We(e){return Math.max(Date.now(),e+1)}function Ge(e,t){if(t.supervisorSessionId!==void 0&&t.supervisorSessionId===e.supervisorSessionId&&t.adapterSessionId!==void 0&&e.adapterSessionId!==void 0&&t.adapterSessionId!==e.adapterSessionId){if(Ke(e,t))return;throw Error(`client.runtime.observe: adapterSessionId '${t.adapterSessionId}' conflicts with the existing adapterSessionId '${e.adapterSessionId}' for supervisorSessionId '${t.supervisorSessionId}'`)}}function Ke(e,t){return t.adapterSessionTransition===`root-clear`&&t.clientId===`codex`&&t.source.layer===`client-hook`&&t.source.producer===`codex-client-session-service`&&t.supervisorSessionId!==void 0&&t.supervisorSessionId===e.supervisorSessionId&&t.adapterSessionId!==void 0&&t.adapterSessionId!==e.adapterSessionId}function qe(e,t){let n=!1;return t.supervisorSessionId!==void 0&&e.supervisorSessionId!==t.supervisorSessionId&&(e.supervisorSessionId=t.supervisorSessionId,n=!0),t.pid!==void 0&&e.pid!==t.pid&&(e.pid=t.pid,n=!0),t.parentPid!==void 0&&e.parentPid!==t.parentPid&&(e.parentPid=t.parentPid,n=!0),t.adapterSessionId!==void 0&&e.adapterSessionId!==t.adapterSessionId&&(e.adapterSessionId=t.adapterSessionId,n=!0),t.sessionId!==void 0&&e.sessionId!==t.sessionId&&(e.sessionId=t.sessionId,n=!0),t.cwd!==void 0&&e.cwd!==t.cwd&&(e.cwd=t.cwd,n=!0),t.argv!==void 0&&JSON.stringify(e.argv)!==JSON.stringify(t.argv)&&(e.argv=[...t.argv],n=!0),t.metadata!==void 0&&JSON.stringify(e.metadata)!==JSON.stringify(t.metadata)&&(e.metadata=structuredClone(t.metadata),n=!0),n}function Je(e,t){e.adapterSessionId=t.adapterSessionId,e.sessionId=void 0}var Ye=class{runtimeMap=new Ve;mutationLane=new s;bus;latestCreatedAt=0;constructor(e){this.bus=e}async loadFromStorage(){await this.mutationLane.run(()=>this.loadFromStorageInLane())}async loadFromStorageInLane(){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),this.latestCreatedAt=Math.max(this.latestCreatedAt,n.createdAt)}async upsertRuntime(e){return this.mutationLane.run(()=>this.upsertRuntimeInLane(e))}async upsertRuntimeInLane(e){let t=this.runtimeMap.findByEvidence(e.supervisorSessionId,e.pid,e.adapterSessionId,e.clientId);if(t){let n=H(t);Ge(n,e);let r=Ke(n,e);r&&Je(n,e);let i=n.status===`observed`,a=i&&Ue(e),o=qe(n,e),s=i&&e.observedAt>n.observedAt;return a&&(n.status=`started`),(r||o||a||s)&&(n.updatedAt=We(n.updatedAt),s&&(n.observedAt=e.observedAt),await this.persistRecord(n),this.runtimeMap.set(n,t)),{clientRuntimeId:n.clientRuntimeId,created:!1,promoted:a,record:H(n)}}let n=this.nextCreatedAt(),r=o(),i=Ue(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 await this.persistRecord(a),this.runtimeMap.set(a),{clientRuntimeId:r,created:!0,promoted:!1,record:H(a)}}getRuntime(e){let t=this.runtimeMap.get(e);return t?H(t):void 0}resolveBySupervisorSessionId(e,t){let n=this.runtimeMap.findByEvidence(t,void 0,void 0,e);return n===void 0||n.clientId!==e||n.supervisorSessionId!==t?null:{clientId:n.clientId,supervisorSessionId:n.supervisorSessionId,...n.adapterSessionId!==void 0&&{adapterSessionId:n.adapterSessionId},...n.sessionId!==void 0&&{sessionId:n.sessionId},updatedAt:n.updatedAt}}markAdapterOwned(e,t){this.runtimeMap.markAdapterOwned(e,t)}hasAdapterSession(e,t){return this.runtimeMap.hasAdapterSession(e,t)}async clear(){await this.mutationLane.run(async()=>{this.runtimeMap.clear()})}get size(){return this.runtimeMap.size}nextCreatedAt(){return this.latestCreatedAt=Math.max(Date.now(),this.latestCreatedAt+1),this.latestCreatedAt}async persistRecord(e){if(!this.bus)return;let t=await this.bus.requestOptional(V.upsert,H(e));if(t.handled&&!t.data.success)throw Error(`client runtime storage rejected persistence for '${e.clientRuntimeId}'`)}};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()}),Xe=/^[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(!Xe.test(r))throw Error(`[${t}] clientId must contain only lowercase letters, numbers, and hyphens after an optional client: prefix`);return r}function Ze(e){return{subject:`hook.received`,$meta:{namespace:`client:${W(e,`createRawClientHookReceivedSubject`)}`,isRequest:!1,local:!1,channel:!1}}}const Qe=5e3,$e=r.object({exitCode:r.number().int().min(0).max(255).default(0),stdout:r.string().default(``),stderr:r.string().default(``)}),et=Object.freeze({exitCode:0,stdout:``,stderr:``});function tt(e){return{subject:`hook.handle`,$meta:{namespace:`client:${W(e,`createRawClientHookHandleSubject`)}`,isRequest:!0,local:!1,channel:!1,hostLocalRequest:!0}}}function nt(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function rt(e,t){return nt(e[t])}function it(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 at(e){try{e().catch(ot)}catch(e){ot(e)}}function ot(e){(process.env.DEBUG||process.env.MAKAIO_DEBUG)&&console.debug(`[emitBestEffort] observed-semantics emission failed`,e)}function st(e,t){return{subject:t,$meta:{namespace:`client:${W(e,`createClientWiringSubjectDef`)}`,isRequest:!0,local:!1,channel:!1}}}function ct(e){return st(e,`wiring.list`)}const lt=r.string().min(1).refine(a.isAbsolute,{message:`projectDir must be an absolute path`}),ut=r.object({entries:r.array(ue)}),dt=r.object({applied:r.number().int().nonnegative(),skipped:r.number().int().nonnegative()}),ft=r.object({removed:r.number().int().nonnegative()}),pt=r.object({clientId:r.string().trim().min(1),entries:r.array(ue)});function mt(e){if(e!==void 0&&!a.isAbsolute(e))throw Error(`projectDir must be an absolute path, got: ${e}`)}var ht=class extends h{accountRegistry;runtimeRegistry;latestSnapshots=new Map;activeIdentities=new Map;constructor(e=m,t=new Te,n=new Ye(e)){super(e),this.accountRegistry=t,this.runtimeRegistry=n}async onInit(){await this.runtimeRegistry.loadFromStorage(),this.registerHandler(T.account.observe,e=>this.handleAccountObserve(e)),this.registerHandler(T.usage.ingest,e=>this.handleUsageIngest(e)),this.registerHandler(T.scan,async e=>{let t=await this.scanClients(e.payload.targets);e.setResult({results:t})}),this.registerHandler(T.runtime.observe,e=>this.handleRuntimeObserve(e)),this.registerHandler(T.runtime.resolveBySupervisorSessionId,e=>{e.setResult({runtime:this.runtimeRegistry.resolveBySupervisorSessionId(e.payload.clientId,e.payload.supervisorSessionId)})}),this.registerHandler(T.runtime.isAdapterManaged,e=>{let{adapterSessionId:t,clientId:n}=e.payload;e.setResult({managed:this.runtimeRegistry.hasAdapterSession(t,n)})}),this.registerHandler(T.wiring.list,async e=>{let t=await this.listWirings(e.payload);e.setResult({results:t})}),this.registerHandler(T.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(T.account.getActive,e=>{let t=this.activeIdentities.get(e.payload.clientId);e.setResult({identity:t??null})})}async onDestroy(){await this.runtimeRegistry.clear(),this.latestSnapshots.clear(),this.activeIdentities.clear(),this.accountRegistry.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=vt(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(T.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=gt(t.clientAccountId,e.payload,t.displayLabel),r=vt(_t(this.latestSnapshots.get(t.clientAccountId),n),t.displayLabel);this.latestSnapshots.set(t.clientAccountId,r),await this.bus.emit(T.usage.snapshot,r),e.setResult({clientAccountId:t.clientAccountId,snapshot:r})}async handleRuntimeObserve(e){if(!this.initialized)throw Error(`client.runtime.observe: service is stopping`);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);if(!this.initialized){e.setResult({clientRuntimeId:r.clientRuntimeId,created:r.created,promoted:r.promoted});return}t.source.layer===`adapter`&&t.adapterSessionId!==void 0&&this.runtimeRegistry.markAdapterOwned(t.adapterSessionId,t.clientId),this.bus.emit(T.runtime.observed,{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,updatedAt:n.updatedAt}).catch(e=>{console.warn(`[ClientRuntimeService] Failed to emit client.runtime.observed:`,e)}),(r.created||r.promoted)&&this.initialized&&await this.bus.emit(T.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}).catch(e=>{console.warn(`[ClientRuntimeService] Failed to emit client.runtime.started:`,e)}),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(ye.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:bt(n,r,e.supportedVersions)}})}async listScannableStoredClients(){let{clients:e}=await this.bus.request(be.list,{});return e.filter(yt).map(e=>({clientId:e.id,binaryName:e.binary.name,supportedVersions:e.binary.supportedVersions}))}async listWirings(e){mt(e.projectDir);let{clients:t}=await this.bus.request(be.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=ct(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 gt(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 _t(e,t){return e&&e.observedAt>t.observedAt?e:t}function vt(e,t){return!e||t===void 0||e.displayLabel===t?e:{...e,displayLabel:t}}function yt(e){return e.enabled&&e.binary!==void 0}function bt(e,t,n){if(e&&t!==void 0&&t!==`unknown`&&n!==void 0&&!p(t,n))return`Unsupported version: requires ${n}`}var xt=class extends h{constructor(e=m){super(e)}onInit(){this.registerHandler(T.config.prime,async e=>{e.setResult(await E(this.bus,e.payload))})}};const G=ce,K=r.string().trim().min(1),St=c(`client-profile:storage`,{get:{request:r.object({clientId:K,name:w}),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:w}),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:w}),response:r.object({record:G.nullable()})}}),q=St.subjects;function Ct(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 wt=class extends h{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(T.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=Ct(s,a.join(s,n),`profile.create`);await i.mkdir(c,{recursive:!0});try{await E(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(T.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(T.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(T.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(T.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&&(Ct(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(T.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 Tt(e){return{subject:`sessionConfig.setup`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}function Et(e){return{subject:`sessionConfig.destroy`,$meta:{namespace:`client:${e}`,isRequest:!0,local:!1,channel:!1}}}const Dt=()=>Date.now();function Ot(){let e=ve.platform();if(e===`darwin`||e===`linux`||e===`win32`)return e;throw Error(`client.sessionConfig does not support platform '${e}'`)}function kt(e,t,n){let r=fe.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 At=class extends h{clientsBasePath;getNow;liveLeasesByClient=new Map;liveLeasesByOwner=new Map;constructor(e,t,n=Dt){super(e),this.clientsBasePath=t,this.getNow=n}async onInit(){this.registerCreateHandler(),this.registerHandler(T.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(T.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(_e.closed,async e=>{await this.destroyOwnedLeases(e.payload.sessionId)}),await this.cleanupOrphanedDirs()}registerCreateHandler(){this.registerHandler(T.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=Tt(l),f=await this.bus.requestOptional(r,{sessionDir:u,baseConfigDir:t,projectDir:s,platform:Ot(),configInheritance:c}),p=f.handled?f.data.env??{}:{},m=f.handled?f.data.authMaterialized:!1;if(await E(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(!fe.safeParse(a).success)return;let o=kt(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(Et(e),{sessionDir:t,platform:Ot()})}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 kt(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)}},jt=class extends h{store=new Map;constructor(e){super(e)}record(e,t){let{clientId:n,adapterSessionId:r,agentId:i}=e,a=this.buildKey(n,r,i);if(this.store.get(a)!==void 0)this.store.delete(a);else if(this.store.size>=1e3){let e=this.store.keys().next().value;e!==void 0&&this.store.delete(e)}this.store.set(a,{token:t,lastActivity:Date.now()})}onInit(){this.registerHandler(T.session.token.get,e=>{let{clientId:t,adapterSessionId:n,agentId:r}=e.payload,i=this.buildKey(t,n,r),a=this.store.get(i);a!==void 0&&(this.store.delete(i),this.store.set(i,{token:a.token,lastActivity:Date.now()})),e.setResult({token:a?.token??null})});let e=setInterval(()=>{let e=Date.now()-864e5;for(let[t,n]of this.store)n.lastActivity<e&&this.store.delete(t)},3e5);e.unref(),this.addCleanup(()=>clearInterval(e))}onDestroy(){this.store.clear()}buildKey(e,t,n){let r=`${e}\n${t}`;return n===void 0?r:`${r}\n${n}`}};const Mt=new Set([`hook.received`,`hook.handle`]);function Nt(e,t){return m.registerNamespace(c(`client:${e}`,{"hook.received":U,"hook.handle":l({request:U,response:$e}),...t})).subjects}function Pt(e,t){let n=Object.keys(t).filter(e=>Mt.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 Ft(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 It(e,t,n){let r=Object.keys(n).filter(e=>!Ft(t,e));if(r.length!==0)throw Error(`[createClientNamespace] client:${e} was already registered without required subjects: ${r.join(`, `)}`)}function Lt(e,t){let n=W(e,`createClientNamespace`),r=t??{};Pt(n,r);let i=Nt(n,r);return It(n,i,r),{namespaceDomain:`client:${n}`,subjects:i}}const Rt=v(`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=>[g(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),g(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),g(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)],postgres:e=>[ne(`idx_client_runtimes_supervisor_session_id`).on(e.supervisorSessionId),ne(`idx_client_runtimes_pid_client_id`).on(e.pid,e.clientId),ne(`idx_client_runtimes_adapter_session_id_client_id`).on(e.adapterSessionId,e.clientId)]}),zt=Rt.sqlite,Bt=Rt.postgres,Vt=_({clientRuntimes:zt},{clientRuntimes:Bt}),Ht=new Set(z);function Ut(e){if(!Ht.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 Wt(e,t){let{clientRuntimes:n}=b(t,Vt),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:se(C`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(Ut)})});return()=>{r(),i()}}const Gt=v(`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=>[re(`uq_client_binary_versions_client_version`).on(e.clientId,e.version)]}),Kt=Gt.sqlite,qt=v(`client_binary_state`,e=>({clientId:e.text(`client_id`).primaryKey(),activeVersion:e.text(`active_version`),updatedAt:e.epochMs(`updated_at`).notNull()})),Jt=qt.sqlite,Yt=Gt.postgres,Xt=qt.postgres,J=_({clientBinaryVersions:Kt,clientBinaryState:Jt},{clientBinaryVersions:Yt,clientBinaryState:Xt});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 Zt(e){return{id:e.id,clientId:e.clientId,version:e.version,installPath:e.installPath,installedAt:e.installedAt,createdAt:e.createdAt}}async function Qt(e,t,n){await e.insert(n).values(Zt(t)).onConflictDoNothing({target:[n.clientId,n.version]})}function $t(e,t,n){return{clientId:e,activeVersion:t,updatedAt:n}}async function en(e,t,n,r,i){await e.insert(i).values($t(t,n,r)).onConflictDoUpdate({target:i.clientId,set:{activeVersion:n,updatedAt:r}})}async function tn(e,t){let{clientBinaryVersions:n}=b(e,J);await Qt(e,t,n)}async function nn(e,t,n,r){let{clientBinaryVersions:i,clientBinaryState:a}=b(e,J);return y(e,async e=>{let[o]=await e.select().from(a).where(S(a.clientId,t.clientId)).limit(1),s=o?.activeVersion??null;return await Qt(e,t,i),n?(await en(e,t.clientId,t.version,r,a),{previousActiveVersion:s,activeVersion:t.version}):{previousActiveVersion:s,activeVersion:s}})}async function rn(e,t){let{clientBinaryVersions:n,clientBinaryState:r}=b(e,J);return y(e,async e=>{let[i]=await e.select().from(r).where(S(r.clientId,t)).limit(1),a=await e.select().from(n).where(S(n.clientId,t));return{state:i?X(i):null,versions:a.map(Y)}})}async function an(e){let{clientBinaryVersions:t,clientBinaryState:n}=b(e,J);return y(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 on(e,t){let{clientBinaryState:n}=b(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 sn(e,t,n,r){let{clientBinaryState:i}=b(e,J);return y(e,async e=>{let[a]=await e.select().from(i).where(S(i.clientId,t)).limit(1),o=a?.activeVersion??null;return await en(e,t,n,r,i),{previousActiveVersion:o,activeVersion:n}})}async function cn(e,t,n,r){let{clientBinaryVersions:i,clientBinaryState:a}=b(e,J);return y(e,async e=>{let[o]=await e.select().from(a).where(S(a.clientId,t)).limit(1),s=o?.activeVersion??null;if(!ae(await e.delete(i).where(x(S(i.clientId,t),S(i.version,n)))))return{removedVersion:null,previousActiveVersion:s,activeVersion:s};await e.update(a).set({activeVersion:null,updatedAt:r}).where(x(S(a.clientId,t),S(a.activeVersion,n)));let[c]=await e.select().from(a).where(S(a.clientId,t)).limit(1);return{removedVersion:n,previousActiveVersion:s,activeVersion:c?.activeVersion??null}})}function ln(e,t){let{clientBinaryVersions:n,clientBinaryState:r}=b(t,J),i=[e.on(N.insertVersion,async e=>{await tn(t,e.payload),e.setResult({success:!0})}),e.on(N.recordInstalledVersion,async e=>{let{versionRecord:n,makeActive:r,updatedAt:i}=e.payload,a=await nn(t,n,r,i);e.setResult(a)}),e.on(N.listVersions,async e=>{let r=await t.select().from(n).where(S(n.clientId,e.payload.clientId));e.setResult({versions:r.map(Y)})}),e.on(N.getSnapshot,async e=>{let{state:n,versions:r}=await rn(t,e.payload.clientId);e.setResult({state:n,versions:r})}),e.on(N.loadAllVersions,async e=>{let r=await t.select().from(n);e.setResult({versions:r.map(Y)})}),e.on(N.upsertState,async e=>{await on(t,e.payload),e.setResult({success:!0})}),e.on(N.setActiveVersion,async e=>{let{clientId:n,activeVersion:r,updatedAt:i}=e.payload,a=await sn(t,n,r,i);e.setResult(a)}),e.on(N.getState,async e=>{let[n]=await t.select().from(r).where(S(r.clientId,e.payload.clientId)).limit(1);e.setResult({state:n?X(n):null})}),e.on(N.loadAllState,async e=>{let n=await t.select().from(r);e.setResult({states:n.map(X)})}),e.on(N.loadSnapshot,async e=>{let{states:n,versions:r}=await an(t);e.setResult({states:n,versions:r})}),e.on(N.removeVersionAndClearActive,async e=>{let{clientId:n,version:r,updatedAt:i}=e.payload,a=await cn(t,n,r,i);e.setResult(a)})];return()=>{for(let e of i)e()}}const un=v(`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(C`${e.isDefault} = 1`)],postgres:e=>[ie(`uq_client_profiles_client_name`).on(e.clientId,e.name),ie(`uq_client_profiles_default`).on(e.clientId).where(C`${e.isDefault} = true`)]}),dn=un.sqlite,fn=un.postgres,pn=_({clientProfiles:dn},{clientProfiles:fn});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 mn(e,t,n){let{clientProfiles:r}=b(e,pn),i=Date.now();return y(e,async e=>{let[a]=await e.select().from(r).where(x(S(r.clientId,t),S(r.name,n))).limit(1);if(a===void 0)return null;await e.update(r).set({isDefault:!1,updatedAt:i}).where(x(S(r.clientId,t),S(r.isDefault,!0))),await e.update(r).set({isDefault:!0,updatedAt:i}).where(x(S(r.clientId,t),S(r.name,n)));let[o]=await e.select().from(r).where(x(S(r.clientId,t),S(r.name,n))).limit(1);return o===void 0?null:Z(o)})}function hn(e,t){let{clientProfiles:n}=b(t,pn),r=[e.on(q.get,async e=>{let{clientId:r,name:i}=e.payload,[a]=await t.select().from(n).where(x(S(n.clientId,r),S(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(S(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(S(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(x(S(n.clientId,r),S(n.name,i)));e.setResult({success:ae(a)})}),e.on(q.clearDefault,async e=>{await t.update(n).set({isDefault:!1,updatedAt:Date.now()}).where(x(S(n.clientId,e.payload.clientId),S(n.isDefault,!0))),e.setResult({success:!0})}),e.on(q.setDefault,async e=>{let{clientId:n,name:r}=e.payload,i=await mn(t,n,r);e.setResult({record:i})})];return()=>{for(let e of r)e()}}function gn(e,t){return`${e}\0${t}`}function _n(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 vn=class{entries=new Map;registerProviderContract(e,t){_n(t);let n=gn(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=gn(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=gn(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 yn(e,t){return`${e}/${t}`}function bn(e,t,n){switch(e.kind){case`event-name`:return e.name===t;case`capability`:return n.includes(e.capability)}}function xn(e,t){let n=t.definition.priority-e.definition.priority;return n===0?e.ordinal-t.ordinal:n}function Sn(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 Cn(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 wn(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(!Sn(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(!Cn(t))return{...n,code:`invalid-contributor-lane`,message:`Contributor '${t.id}' has an invalid lane or target identity`};if(!me(t.id))return{...n,code:`invalid-contributor-id`,message:`Contributor ID is empty or invalid`};if(!he(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 Tn(e,t,n,r){let i=[],a=new Set;for(let o of t){let t=wn(e,o);if(t){i.push(t);continue}let s=yn(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),En(e,o,n,i)}return i}function En(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}Dn(e,t,[a],i,r);return}Dn(e,t,t.clientIds?t.clientIds.flatMap(e=>n.getProviderContractsByClient(e)):n.getAllProviderContracts(),i,r)}function Dn(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 ge([a],n))i.push({code:`closed-policy-on-non-blockable`,message:r,contributorId:t.id,extensionName:e})}}}var On=class{contractRegistry;contributors=new Map;extensionIndex=new Map;nextOrdinal=1;constructor(e){this.contractRegistry=e}installContributors(e,t){let n=Tn(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=yn(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=>bn(e,n,r))&&i.push(a)}return i.sort(xn),Object.freeze(i)}clear(){this.contributors.clear(),this.extensionIndex.clear(),this.nextOrdinal=1}};function kn(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 An=class{runtimeService;binaryManager;configPrimeService;profileService;sessionConfigService;sessionTokenService;providerContractRegistry;hookResponseRegistry;sessionTokens;constructor(e,t,n,r,i,a,o,s){this.runtimeService=e,this.binaryManager=t,this.configPrimeService=n,this.profileService=r,this.sessionConfigService=i,this.sessionTokenService=a,this.providerContractRegistry=o,this.hookResponseRegistry=s,this.sessionTokens=a}async init(){let e=(await Promise.allSettled([this.runtimeService.init(),this.binaryManager.init(),this.configPrimeService.init(),this.profileService.init(),this.sessionConfigService.init(),this.sessionTokenService.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(),this.sessionTokenService.destroy()])).filter(e=>e.status===`rejected`);if(e.length>0)throw AggregateError(e.map(e=>e.reason),`ClientsCoreService failed to tear down cleanly`)}};const jn=d(`makaio.clients-core`);function Mn(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 Nn(e={}){let{definitions:t=[],strategyDependencies:n,postInstallHandlers:r,binaryResolutionPolicy:i}=e,o=[...t],s=new vn,c=new On(s);return{name:`makaio.clients-core`,displayName:`Clients Core`,version:`0.1.0`,critical:!0,namespaces:[M,He,St],storage:{registerHandlers:oe((e,t)=>Mn([()=>Wt(e,t),()=>ln(e,t),()=>hn(e,t)]))},create:e=>{let t=new P(o),l=a.join(e.makaioHome,`clients`),u=new Be(e.bus,{basePath:a.join(e.makaioHome,`binaries`),configBasePath:l,postInstallHandlers:r,...i!==void 0&&{resolutionPolicy:i}},t,n),d=new wt(e.bus,l),f=new At(e.bus,l),p=new jt(e.bus);return new An(new ht(e.bus),u,new xt(e.bus),d,f,p,s,c)},runtimeBoot:{configure:e=>{e.registerContributionProcessor(kn(c,s))}}}}async function Pn(e,t){let n=await e.requestOptional(T.resolveBinary,{clientId:t});return n.handled?n.data:void 0}function Fn(e,t,n){return[...n??[],e,...t].map(zn).join(` `)}function In(e,t,n,r,i){return Fn(e,[...i??[],...t.split(` `),n],r)}function Ln(e){return e.runtimeCapabilities.hookEvents.map(e=>{let t={eventName:e.name,mode:pe(e)};return e.minimumVersion===void 0?t:{...t,minimumVersion:e.minimumVersion}})}function Rn(e,t){return e.minimumVersion===void 0||typeof t!=`string`||!u.safeParse(t).success?!0:p(t,`>=${e.minimumVersion}`)}function zn(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}const Bn=new Set([`context.append`,`session.token`]);function Vn(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||!Bn.has(t.kind)||typeof t.value!=`string`)return`canonicalEffects must contain complete context.append or session.token effects`;if(Object.keys(t).some(e=>e!==`kind`&&e!==`value`))return`canonicalEffects must contain only kind and value`;if(t.kind===`session.token`&&t.value.length===0)return`session.token effect requires a non-empty string value`}return!0}function Hn(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 Un(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=Hn(e.providerEnvelope,t.clientId,t.contractId);return o===!0?r.validate(e,{clientId:n,eventName:i,eventPayload:a}):o}function Wn(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`?Vn(e.canonicalEffects):Un(e,t,n,r,i,a)}const Q=Symbol(`contributor-timeout`);function Gn(e){return e.failurePolicy??de}function Kn(e){return e.namespacedId??e.definition.id}function $(e,t){return e===`closed`?`closed-failure`:t}function qn(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 Jn(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 Yn(e){let t=[],n=[],r=`Request deadline already expired before collection started`;for(let i of e){let e=Kn(i),a=$(Gn(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 Xn(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 Zn(e,t,n,r,i,a){let{definition:o}=e,s=Kn(e),c=Date.now(),l=c+o.timeoutMs,u=n===void 0?l:Math.min(n,l),d=u-c,f=new AbortController;r&&Xn(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:Jn(m,u,f).then(e=>e===Q?{tag:`timeout`}:{tag:`ok`,response:e},e=>({tag:`rejected`,error:e}))}}function Qn(e,t,n,r,i,a){let{contributorId:o,definition:s,startMs:c,abort:l}=e,u=Date.now()-c,d=Gn(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=Wn(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:qn(f)}}}function $n(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 er(e,t,n,r,i,a,o){if(e.length===0)return{outcomes:[],diagnostics:[]};if(n!==void 0&&n<=Date.now())return Yn(e);let s=e.map(e=>Zn(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}=Qn(s[e],c[e],t,o,i,a);l.push(n),r&&u.push(r)}return $n(l,u)}export{lt as AbsolutePathSchema,we as BinaryNotFoundError,z as CLIENT_RUNTIME_STATUSES,Te as ClientAccountRegistry,Ie as ClientBinaryJobRunner,Be as ClientBinaryManager,A as ClientBinaryStateRecordSchema,M as ClientBinaryStorageNamespace,N as ClientBinaryStorageSubjects,k as ClientBinaryVersionRecordSchema,Fe as ClientBinaryVersionResolver,xt as ClientConfigPrimeService,P as ClientDefinitionRegistry,$e as ClientHookHandleResponseSchema,vn as ClientHookProviderContractRegistry,On as ClientHookResponseRegistry,G as ClientProfileRecordSchema,wt as ClientProfileService,St as ClientProfileStorageNamespace,q as ClientProfileStorageSubjects,Ye as ClientRuntimeRegistry,ht as ClientRuntimeService,He as ClientRuntimeStorageNamespace,V as ClientRuntimeStorageSubjects,At as ClientSessionConfigService,jt as ClientSessionTokenService,le as ClientSubjects,pt as ClientWiringAggregatedResultSchema,dt as ClientWiringApplyResponseSchema,ue as ClientWiringEntrySchema,ut as ClientWiringListResponseSchema,ft as ClientWiringRemoveResponseSchema,An as ClientsCoreService,jn as ClientsCoreToken,Qe as DEFAULT_HOOK_HANDLE_TIMEOUT_MS,et as NOOP_HOOK_HANDLE_RESPONSE,U as RawClientHookPayloadSchema,B as RuntimeRecordSchema,mt as assertAbsoluteProjectDir,xe as atomicModifyFile,Fn as buildClientCommand,it as buildClientSessionBase,In as buildHookCommand,W as canonicalizeClientId,Rt as clientRuntimesDual,er as collectContributions,kn as createClientHookResponseContributionProcessor,Lt as createClientNamespace,ct as createClientWiringListSubjectDef,st as createClientWiringSubjectDef,Nn as createClientsCorePackage,tt as createRawClientHookHandleSubject,Ze as createRawClientHookReceivedSubject,t as createStrategy,Ln as deriveSessionEventDescriptors,at as emitBestEffort,D as isPathWithinBase,Rn as isSessionEventSupported,rt as pickNonEmptyString,nt as pickNonEmptyStringValue,ln as registerDrizzleClientBinaryStorage,hn as registerDrizzleProfileStorage,Wt as registerDrizzleRuntimeStorage,Mn as registerStorageHandlersWithRollback,O as resolveAndValidateBasePath,Pn as resolveClientBinary,n as verifyInstalledVersion};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { A as RehydrateAgentRequest, B as AdapterSchemas, C as aggregateTeardownResults, D as AcknowledgeCallerSettlementSchema, E as AcknowledgeCallerSettlementResponse, F as StartAgentRequest, H as AdapterSubjects, I as StartAgentResponse, L as StartAgentSchema, M as RehydrateAgentSchema, N as AdapterStartDisposition, O as CallerSettlementAckRefusal, P as AdapterStartDispositionSchema, R as AdapterRuntimeOptions, S as aggregateTeardownEvidence, T as AcknowledgeCallerSettlementRequest, V as AdapterNamespace, _ as SessionUsageSchema, a as UnresolvedProviderContext, b as TeardownEvidence, c as AdapterSelectionSchema, d as AgentSelectionBaseSchema, f as AgentSelectionKindMap, g as SessionUsage, h as SessionDiscoveredSchema, i as ResolvedProviderContextSchema, j as RehydrateAgentResponse, k as CallerSettlementAckRefusalSchema, 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 ConnectorTeardownResult, w as teardownWasObserved, x as TeardownEvidenceSchema, y as ConnectorTeardownResultSchema, z as AdapterRuntimeOptionsSchema } from "../../index-
|
|
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-
|
|
1
|
+
import { A as RehydrateAgentRequest, B as AdapterSchemas, C as aggregateTeardownResults, D as AcknowledgeCallerSettlementSchema, E as AcknowledgeCallerSettlementResponse, F as StartAgentRequest, H as AdapterSubjects, I as StartAgentResponse, L as StartAgentSchema, M as RehydrateAgentSchema, N as AdapterStartDisposition, O as CallerSettlementAckRefusal, P as AdapterStartDispositionSchema, R as AdapterRuntimeOptions, S as aggregateTeardownEvidence, T as AcknowledgeCallerSettlementRequest, V as AdapterNamespace, _ as SessionUsageSchema, a as UnresolvedProviderContext, b as TeardownEvidence, c as AdapterSelectionSchema, d as AgentSelectionBaseSchema, f as AgentSelectionKindMap, g as SessionUsage, h as SessionDiscoveredSchema, i as ResolvedProviderContextSchema, j as RehydrateAgentResponse, k as CallerSettlementAckRefusalSchema, 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 ConnectorTeardownResult, w as teardownWasObserved, x as TeardownEvidenceSchema, y as ConnectorTeardownResultSchema, z as AdapterRuntimeOptionsSchema } from "../../index-DOD7Lmgu.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-BuGN3RZs.mjs";
|
|
3
3
|
export { AcknowledgeCallerSettlementRequest, AcknowledgeCallerSettlementResponse, AcknowledgeCallerSettlementSchema, AdapterNamespace, AdapterRuntimeOptions, AdapterRuntimeOptionsSchema, AdapterSchemas, AdapterSelection, AdapterSelectionSchema, AdapterStartDisposition, AdapterStartDispositionSchema, AdapterSubjects, AgentSelection, AgentSelectionBase, AgentSelectionBaseSchema, AgentSelectionKindMap, AgentSelectionSchema, COMPRESS_SESSION_LINEAGE_KIND, CallerSettlementAckRefusal, CallerSettlementAckRefusalSchema, CompressSessionLineageSchema, ConnectorTeardownResult, ConnectorTeardownResultSchema, 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, TeardownEvidence, TeardownEvidenceSchema, UnresolvedProviderContext, UnresolvedProviderContextSchema, aggregateTeardownEvidence, aggregateTeardownResults, teardownWasObserved };
|
|
@@ -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-
|
|
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-BuGN3RZs.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 ArtifactPartAreaSchema, A as ConfidenceMetadata, B as ARTIFACT_CATEGORY_LIFECYCLE_STATES, C as ArtifactScope, D as ConfidenceBasisSchema, E as ConfidenceBasis, F as EvidenceRefSchema, G as ArtifactEvidenceRequirementsSchema, H as ArtifactCategorySchema, I as LocalRef, J as ArtifactKindView, K as ArtifactKindRegistration, L as LocalRefSchema, M as EntityRef, N as EntityRefSchema, O as ConfidenceLevel, P as EvidenceRef, Q as ArtifactPartArea, R as RelationTypeRegistration, S as ArtifactRevisionSchema, T as ArtifactStatusPathSchema, U as ArtifactDataPathSchema, V as ArtifactCategory, W as ArtifactEvidenceRequirements, X as ArtifactLifecycleState, Y as ArtifactKindViewSchema, Z as ArtifactLifecycleStateSchema, _ as ArtifactRelationTarget, a as ArtifactCompareResponse, at as ArtifactUniquenessSelectorSchema, b as ArtifactRepresentationsSchema, c as ArtifactObservationSchema, d as ArtifactQueryScope, et as ArtifactRelationRequirement, f as ArtifactQueryScopeSchema, g as ArtifactRelationSchema, h as ArtifactRelationQueryTargetSchema, i as ArtifactCompareRequestSchema, it as ArtifactUniquenessRuleSchema, j as ConfidenceMetadataSchema, k as ConfidenceLevelSchema, l as ArtifactQueryRequest, m as ArtifactRelationQueryTarget, n as ArtifactActorSchema, nt as ArtifactSchemaVersionSchema, o as ArtifactCompareResponseSchema, ot as ArtifactRef, p as ArtifactRelation, q as ArtifactKindRegistrationSchema, r as ArtifactCompareRequest, rt as ArtifactUniquenessRule, s as ArtifactObservation, st as ArtifactRefSchema, t as ArtifactActor, tt as ArtifactRelationRequirementSchema, u as ArtifactQueryRequestSchema, v as ArtifactRelationTargetSchema, w as ArtifactScopeSchema, x as ArtifactRevision, y as ArtifactRepresentations, z as RelationTypeRegistrationSchema } from "../../schemas-
|
|
2
|
-
import { $ as ArtifactLifecycleTransitionedEntry, $n as ArtifactContextSelector, $t as isArtifactDataPathDeclared, A as ArtifactLifecycleSchemas, An as ArtifactSubjects, Ar as EvidenceResolveResponseSchema, At as ArtifactPatchSegment, B as ArtifactLifecycleIdentitySchema, Bn as UnresolvedArtifactContextNode, Bt as ARTIFACT_RESOLVE_PART_ERROR_CODES, C as ArtifactLifecycleGetResponseSchema, Cn as ArtifactResolveRequest, Cr as defineArtifactLifecycleHooks, Ct as ArtifactPatchOperator, D as ArtifactLifecycleHistoryResponseSchema, Dn as ArtifactRevisedPayload, Dr as EvidenceResolveRequest, Dt as ArtifactPatchRequestSchema, E as ArtifactLifecycleHistoryResponse, En as ArtifactReviseResponse, Er as extractEvidenceOccurrences, Et as ArtifactPatchRequest, F as ArtifactLifecycleCurrent, Fn as hydrateArtifactContextTree, Ft as artifactPatchFilterName, G as ArtifactLifecycleSituation, Gn as ResolvedArtifactContextWire, Gt as ArtifactResolvePartErrorSchema, H as ArtifactLifecycleInitializedEntrySchema, Hn as ArtifactContextRefEntrySchema, Ht as ArtifactRelationSourceIssue, I as ArtifactLifecycleCurrentSchema, In as ArtifactContextNode, It as artifactPatchInstructions, J as ArtifactLifecycleSnapshotSchema, Jn as ArtifactContextKnownRenderHint, Jt as resolveArtifactPart, K as ArtifactLifecycleSituationSchema, Kn as ResolvedArtifactContextWireSchema, Kt as checkArtifactPartIds, L as ArtifactLifecycleError, Ln as ArtifactContextRootNode, Lt as artifactPatchPathFilterNames, M as ArtifactLifecycleTransitionResponseSchema, Mn as ArtifactResolvePartRequestSchema, Mr as EVIDENCE_VALUE_TYPE, Mt as ArtifactPatchSuccessSchema, N as toArtifactLifecycleFailure, Nn as ArtifactResolvePartResponse, Nr as EvidenceValue, Nt as ArtifactPatchTarget, O as ArtifactLifecycleRejectedPayload, On as ArtifactSchemas, Or as EvidenceResolveRequestSchema, Ot as ArtifactPatchResponse, P as ARTIFACT_LIFECYCLE_REJECTED_CODE, Pn as ArtifactResolvePartResponseSchema, Pr as EvidenceValueSchema, Pt as ArtifactPatchTargetSchema, Q as ArtifactLifecycleTransitionIntentSchema, Qn as ArtifactContextRenderHintSchema, Qt as inspectArtifactDataLocation, R as ArtifactLifecycleHistoryEntry, Rn as ArtifactContextTree, Rt as artifactPatchSegment, S as ArtifactLifecycleGetResponse, Sn as ArtifactResolveContextResponse, Sr as BeforeArtifactHookRegistration, St as ArtifactPatchOperationResultSchema, T as ArtifactLifecycleHistoryRequestSchema, Tn as ArtifactReviseRequest, Tr as EvidenceOccurrenceExtractionOptions, Tt as ArtifactPatchPersistedSchema, U as ArtifactLifecycleRejection, Un as ArtifactContextUnresolvedReason, Ut as ArtifactResolvePartError, V as ArtifactLifecycleInitializedEntry, Vn as ArtifactContextRefEntry, Vt as ArtifactPartResolution, W as ArtifactLifecycleRejectionSchema, Wn as ArtifactContextUnresolvedReasonSchema, Wt as ArtifactResolvePartErrorCode, X as ArtifactLifecycleTransitionCommandSchema, Xn as ArtifactContextRelationSelectorSchema, Xt as ARTIFACT_COLLECTION_ELEMENT_SEGMENT, Y as ArtifactLifecycleTransitionCommand, Yn as ArtifactContextRelationSelector, Yt as validateArtifactPartAreas, Z as ArtifactLifecycleTransitionIntent, Zn as ArtifactContextRenderHint, Zt as ArtifactSchemaFragment, _ as ArtifactLifecycleCommittedPayloadSchema, _n as ArtifactRelationTypeListRequest, _r as ArtifactLifecycleHookDefinition, _t as ArtifactPatchIssue, a as UniquenessKeyPart, an as ArtifactEvidenceResolveResponse, ar as compileArtifactDataChecker, at as ARTIFACT_PATCH_ERROR_CODES, b as ArtifactLifecycleGetRequest, bn as ArtifactRelationTypeRegisterResponse, br as ArtifactLifecycleSemanticEvent, bt as ArtifactPatchMigrationSchema, c as assessUniquenessSupport, cn as ArtifactKindListResponse, cr as ArtifactDataOf, ct as ArtifactPatchArrayFilterSchema, d as ArtifactRelationTargetIdentity, dn as ArtifactNamespace, dr as defineArtifactKind, dt as ArtifactPatchDryRunSchema, en as readArtifactTitle, er as ArtifactContextSelectorSchema, et as ArtifactLifecycleTransitionedEntrySchema, f as ArtifactRelationTargetIdentitySchema, fn as ArtifactObservationAddedPayload, fr as AfterArtifactHookContext, ft as ArtifactPatchError, g as ArtifactLifecycleCommittedPayload, gn as ArtifactRelationAddedPayload, gr as ArtifactHookFilter, gt as ArtifactPatchInstruction, h as serializeArtifactRelationTargetIdentity, hn as ArtifactQueryResponse, hr as ArtifactDraftPatch, ht as ArtifactPatchFailureSchema, i as UniquenessKeyIssueReason, in as ArtifactEvidenceResolveRequest, ir as ArtifactDataValidator, it as isArtifactLifecycleTransitionAllowed, j as ArtifactLifecycleTransitionResponse, jn as ArtifactResolvePartRequest, jr as ARTIFACT_VALUE_TYPE_KEYWORD, jt as ArtifactPatchSuccess, k as ArtifactLifecycleRejectedPayloadSchema, kn as ArtifactStatusChangedPayload, kr as EvidenceResolveResponse, kt as ArtifactPatchResponseSchema, l as buildUniquenessKeys, ln as ArtifactKindRegisterRequest, lr as ArtifactKindDefinition, lt as ArtifactPatchDocument, m as describeArtifactRelationTargetIdentity, mn as ArtifactPatchSubjectResponse, mr as ArtifactDraft, mt as ArtifactPatchErrorSchema, n as UniquenessKey, nn as ArtifactCreateResponse, nr as ArtifactDataChecker, nt as advanceArtifactLifecycle, o as UniquenessSelectorCapability, on as ArtifactKindChangedPayload, or as compileArtifactDataSchema, ot as ARTIFACT_PATCH_OPERATORS, p as artifactRelationTargetIdentity, pn as ArtifactPatchSubjectRequest, pr as AfterArtifactHookRegistration, pt as ArtifactPatchErrorCode, q as ArtifactLifecycleSnapshot, qn as ARTIFACT_CONTEXT_RENDER_HINTS, qt as checkArtifactRelationSourceParts, r as UniquenessKeyIssue, rn as ArtifactCreatedPayload, rr as ArtifactDataIssue, rt as initialArtifactLifecycle, s as UniquenessSupportIssue, sn as ArtifactKindListRequest, sr as AnyArtifactKindDefinition, st as ArtifactPatchArrayFilter, t as BuildUniquenessKeysResult, tn as ArtifactCreateRequest, tr as ArtifactDataCheck, tt as ArtifactLifecycleVersionSchema, u as describeUniquenessKey, un as ArtifactKindRegisterResponse, ur as ArtifactOf, ut as ArtifactPatchDocumentSchema, v as ArtifactLifecycleFailure, vn as ArtifactRelationTypeListResponse, vr as ArtifactLifecycleHookEvent, vt as ArtifactPatchIssueSchema, w as ArtifactLifecycleHistoryRequest, wn as ArtifactResolveResponse, wr as EvidenceOccurrence, wt as ArtifactPatchPathSchema, x as ArtifactLifecycleGetRequestSchema, xn as ArtifactResolveContextRequest, xr as BeforeArtifactHookContext, xt as ArtifactPatchOperationResult, y as ArtifactLifecycleFailureSchema, yn as ArtifactRelationTypeRegisterRequest, yr as ArtifactLifecycleHookRegistration, yt as ArtifactPatchMigration, z as ArtifactLifecycleHistoryEntrySchema, zn as ResolvedArtifactContextNode, zt as artifactPatchSegments } from "../../index-
|
|
1
|
+
import { $ as ArtifactPartAreaSchema, A as ConfidenceMetadata, B as ARTIFACT_CATEGORY_LIFECYCLE_STATES, C as ArtifactScope, D as ConfidenceBasisSchema, E as ConfidenceBasis, F as EvidenceRefSchema, G as ArtifactEvidenceRequirementsSchema, H as ArtifactCategorySchema, I as LocalRef, J as ArtifactKindView, K as ArtifactKindRegistration, L as LocalRefSchema, M as EntityRef, N as EntityRefSchema, O as ConfidenceLevel, P as EvidenceRef, Q as ArtifactPartArea, R as RelationTypeRegistration, S as ArtifactRevisionSchema, T as ArtifactStatusPathSchema, U as ArtifactDataPathSchema, V as ArtifactCategory, W as ArtifactEvidenceRequirements, X as ArtifactLifecycleState, Y as ArtifactKindViewSchema, Z as ArtifactLifecycleStateSchema, _ as ArtifactRelationTarget, a as ArtifactCompareResponse, at as ArtifactUniquenessSelectorSchema, b as ArtifactRepresentationsSchema, c as ArtifactObservationSchema, d as ArtifactQueryScope, et as ArtifactRelationRequirement, f as ArtifactQueryScopeSchema, g as ArtifactRelationSchema, h as ArtifactRelationQueryTargetSchema, i as ArtifactCompareRequestSchema, it as ArtifactUniquenessRuleSchema, j as ConfidenceMetadataSchema, k as ConfidenceLevelSchema, l as ArtifactQueryRequest, m as ArtifactRelationQueryTarget, n as ArtifactActorSchema, nt as ArtifactSchemaVersionSchema, o as ArtifactCompareResponseSchema, ot as ArtifactRef, p as ArtifactRelation, q as ArtifactKindRegistrationSchema, r as ArtifactCompareRequest, rt as ArtifactUniquenessRule, s as ArtifactObservation, st as ArtifactRefSchema, t as ArtifactActor, tt as ArtifactRelationRequirementSchema, u as ArtifactQueryRequestSchema, v as ArtifactRelationTargetSchema, w as ArtifactScopeSchema, x as ArtifactRevision, y as ArtifactRepresentations, z as RelationTypeRegistrationSchema } from "../../schemas-rMUsvzeJ.mjs";
|
|
2
|
+
import { $ as ArtifactLifecycleTransitionedEntry, $n as ArtifactContextSelector, $t as isArtifactDataPathDeclared, A as ArtifactLifecycleSchemas, An as ArtifactSubjects, Ar as EvidenceResolveResponseSchema, At as ArtifactPatchSegment, B as ArtifactLifecycleIdentitySchema, Bn as UnresolvedArtifactContextNode, Bt as ARTIFACT_RESOLVE_PART_ERROR_CODES, C as ArtifactLifecycleGetResponseSchema, Cn as ArtifactResolveRequest, Cr as defineArtifactLifecycleHooks, Ct as ArtifactPatchOperator, D as ArtifactLifecycleHistoryResponseSchema, Dn as ArtifactRevisedPayload, Dr as EvidenceResolveRequest, Dt as ArtifactPatchRequestSchema, E as ArtifactLifecycleHistoryResponse, En as ArtifactReviseResponse, Er as extractEvidenceOccurrences, Et as ArtifactPatchRequest, F as ArtifactLifecycleCurrent, Fn as hydrateArtifactContextTree, Ft as artifactPatchFilterName, G as ArtifactLifecycleSituation, Gn as ResolvedArtifactContextWire, Gt as ArtifactResolvePartErrorSchema, H as ArtifactLifecycleInitializedEntrySchema, Hn as ArtifactContextRefEntrySchema, Ht as ArtifactRelationSourceIssue, I as ArtifactLifecycleCurrentSchema, In as ArtifactContextNode, It as artifactPatchInstructions, J as ArtifactLifecycleSnapshotSchema, Jn as ArtifactContextKnownRenderHint, Jt as resolveArtifactPart, K as ArtifactLifecycleSituationSchema, Kn as ResolvedArtifactContextWireSchema, Kt as checkArtifactPartIds, L as ArtifactLifecycleError, Ln as ArtifactContextRootNode, Lt as artifactPatchPathFilterNames, M as ArtifactLifecycleTransitionResponseSchema, Mn as ArtifactResolvePartRequestSchema, Mr as EVIDENCE_VALUE_TYPE, Mt as ArtifactPatchSuccessSchema, N as toArtifactLifecycleFailure, Nn as ArtifactResolvePartResponse, Nr as EvidenceValue, Nt as ArtifactPatchTarget, O as ArtifactLifecycleRejectedPayload, On as ArtifactSchemas, Or as EvidenceResolveRequestSchema, Ot as ArtifactPatchResponse, P as ARTIFACT_LIFECYCLE_REJECTED_CODE, Pn as ArtifactResolvePartResponseSchema, Pr as EvidenceValueSchema, Pt as ArtifactPatchTargetSchema, Q as ArtifactLifecycleTransitionIntentSchema, Qn as ArtifactContextRenderHintSchema, Qt as inspectArtifactDataLocation, R as ArtifactLifecycleHistoryEntry, Rn as ArtifactContextTree, Rt as artifactPatchSegment, S as ArtifactLifecycleGetResponse, Sn as ArtifactResolveContextResponse, Sr as BeforeArtifactHookRegistration, St as ArtifactPatchOperationResultSchema, T as ArtifactLifecycleHistoryRequestSchema, Tn as ArtifactReviseRequest, Tr as EvidenceOccurrenceExtractionOptions, Tt as ArtifactPatchPersistedSchema, U as ArtifactLifecycleRejection, Un as ArtifactContextUnresolvedReason, Ut as ArtifactResolvePartError, V as ArtifactLifecycleInitializedEntry, Vn as ArtifactContextRefEntry, Vt as ArtifactPartResolution, W as ArtifactLifecycleRejectionSchema, Wn as ArtifactContextUnresolvedReasonSchema, Wt as ArtifactResolvePartErrorCode, X as ArtifactLifecycleTransitionCommandSchema, Xn as ArtifactContextRelationSelectorSchema, Xt as ARTIFACT_COLLECTION_ELEMENT_SEGMENT, Y as ArtifactLifecycleTransitionCommand, Yn as ArtifactContextRelationSelector, Yt as validateArtifactPartAreas, Z as ArtifactLifecycleTransitionIntent, Zn as ArtifactContextRenderHint, Zt as ArtifactSchemaFragment, _ as ArtifactLifecycleCommittedPayloadSchema, _n as ArtifactRelationTypeListRequest, _r as ArtifactLifecycleHookDefinition, _t as ArtifactPatchIssue, a as UniquenessKeyPart, an as ArtifactEvidenceResolveResponse, ar as compileArtifactDataChecker, at as ARTIFACT_PATCH_ERROR_CODES, b as ArtifactLifecycleGetRequest, bn as ArtifactRelationTypeRegisterResponse, br as ArtifactLifecycleSemanticEvent, bt as ArtifactPatchMigrationSchema, c as assessUniquenessSupport, cn as ArtifactKindListResponse, cr as ArtifactDataOf, ct as ArtifactPatchArrayFilterSchema, d as ArtifactRelationTargetIdentity, dn as ArtifactNamespace, dr as defineArtifactKind, dt as ArtifactPatchDryRunSchema, en as readArtifactTitle, er as ArtifactContextSelectorSchema, et as ArtifactLifecycleTransitionedEntrySchema, f as ArtifactRelationTargetIdentitySchema, fn as ArtifactObservationAddedPayload, fr as AfterArtifactHookContext, ft as ArtifactPatchError, g as ArtifactLifecycleCommittedPayload, gn as ArtifactRelationAddedPayload, gr as ArtifactHookFilter, gt as ArtifactPatchInstruction, h as serializeArtifactRelationTargetIdentity, hn as ArtifactQueryResponse, hr as ArtifactDraftPatch, ht as ArtifactPatchFailureSchema, i as UniquenessKeyIssueReason, in as ArtifactEvidenceResolveRequest, ir as ArtifactDataValidator, it as isArtifactLifecycleTransitionAllowed, j as ArtifactLifecycleTransitionResponse, jn as ArtifactResolvePartRequest, jr as ARTIFACT_VALUE_TYPE_KEYWORD, jt as ArtifactPatchSuccess, k as ArtifactLifecycleRejectedPayloadSchema, kn as ArtifactStatusChangedPayload, kr as EvidenceResolveResponse, kt as ArtifactPatchResponseSchema, l as buildUniquenessKeys, ln as ArtifactKindRegisterRequest, lr as ArtifactKindDefinition, lt as ArtifactPatchDocument, m as describeArtifactRelationTargetIdentity, mn as ArtifactPatchSubjectResponse, mr as ArtifactDraft, mt as ArtifactPatchErrorSchema, n as UniquenessKey, nn as ArtifactCreateResponse, nr as ArtifactDataChecker, nt as advanceArtifactLifecycle, o as UniquenessSelectorCapability, on as ArtifactKindChangedPayload, or as compileArtifactDataSchema, ot as ARTIFACT_PATCH_OPERATORS, p as artifactRelationTargetIdentity, pn as ArtifactPatchSubjectRequest, pr as AfterArtifactHookRegistration, pt as ArtifactPatchErrorCode, q as ArtifactLifecycleSnapshot, qn as ARTIFACT_CONTEXT_RENDER_HINTS, qt as checkArtifactRelationSourceParts, r as UniquenessKeyIssue, rn as ArtifactCreatedPayload, rr as ArtifactDataIssue, rt as initialArtifactLifecycle, s as UniquenessSupportIssue, sn as ArtifactKindListRequest, sr as AnyArtifactKindDefinition, st as ArtifactPatchArrayFilter, t as BuildUniquenessKeysResult, tn as ArtifactCreateRequest, tr as ArtifactDataCheck, tt as ArtifactLifecycleVersionSchema, u as describeUniquenessKey, un as ArtifactKindRegisterResponse, ur as ArtifactOf, ut as ArtifactPatchDocumentSchema, v as ArtifactLifecycleFailure, vn as ArtifactRelationTypeListResponse, vr as ArtifactLifecycleHookEvent, vt as ArtifactPatchIssueSchema, w as ArtifactLifecycleHistoryRequest, wn as ArtifactResolveResponse, wr as EvidenceOccurrence, wt as ArtifactPatchPathSchema, x as ArtifactLifecycleGetRequestSchema, xn as ArtifactResolveContextRequest, xr as BeforeArtifactHookContext, xt as ArtifactPatchOperationResult, y as ArtifactLifecycleFailureSchema, yn as ArtifactRelationTypeRegisterRequest, yr as ArtifactLifecycleHookRegistration, yt as ArtifactPatchMigration, z as ArtifactLifecycleHistoryEntrySchema, zn as ResolvedArtifactContextNode, zt as artifactPatchSegments } from "../../index-Di-R1gmo.mjs";
|
|
3
3
|
export { ARTIFACT_CATEGORY_LIFECYCLE_STATES, ARTIFACT_COLLECTION_ELEMENT_SEGMENT, ARTIFACT_CONTEXT_RENDER_HINTS, ARTIFACT_LIFECYCLE_REJECTED_CODE, ARTIFACT_PATCH_ERROR_CODES, ARTIFACT_PATCH_OPERATORS, ARTIFACT_RESOLVE_PART_ERROR_CODES, ARTIFACT_VALUE_TYPE_KEYWORD, AfterArtifactHookContext, AfterArtifactHookRegistration, AnyArtifactKindDefinition, ArtifactActor, ArtifactActorSchema, ArtifactCategory, ArtifactCategorySchema, ArtifactCompareRequest, ArtifactCompareRequestSchema, ArtifactCompareResponse, ArtifactCompareResponseSchema, ArtifactContextKnownRenderHint, ArtifactContextNode, ArtifactContextRefEntry, ArtifactContextRefEntrySchema, ArtifactContextRelationSelector, ArtifactContextRelationSelectorSchema, ArtifactContextRenderHint, ArtifactContextRenderHintSchema, ArtifactContextRootNode, ArtifactContextSelector, ArtifactContextSelectorSchema, ArtifactContextTree, ArtifactContextUnresolvedReason, ArtifactContextUnresolvedReasonSchema, ArtifactCreateRequest, ArtifactCreateResponse, ArtifactCreatedPayload, ArtifactDataCheck, ArtifactDataChecker, ArtifactDataIssue, ArtifactDataOf, ArtifactDataPathSchema, ArtifactDataValidator, ArtifactDraft, ArtifactDraftPatch, ArtifactEvidenceRequirements, ArtifactEvidenceRequirementsSchema, ArtifactEvidenceResolveRequest, ArtifactEvidenceResolveResponse, ArtifactHookFilter, ArtifactKindChangedPayload, ArtifactKindDefinition, ArtifactKindListRequest, ArtifactKindListResponse, ArtifactKindRegisterRequest, ArtifactKindRegisterResponse, ArtifactKindRegistration, ArtifactKindRegistrationSchema, ArtifactKindView, ArtifactKindViewSchema, ArtifactLifecycleCommittedPayload, ArtifactLifecycleCommittedPayloadSchema, ArtifactLifecycleCurrent, ArtifactLifecycleCurrentSchema, ArtifactLifecycleError, ArtifactLifecycleFailure, ArtifactLifecycleFailureSchema, ArtifactLifecycleGetRequest, ArtifactLifecycleGetRequestSchema, ArtifactLifecycleGetResponse, ArtifactLifecycleGetResponseSchema, ArtifactLifecycleHistoryEntry, ArtifactLifecycleHistoryEntrySchema, ArtifactLifecycleHistoryRequest, ArtifactLifecycleHistoryRequestSchema, ArtifactLifecycleHistoryResponse, ArtifactLifecycleHistoryResponseSchema, ArtifactLifecycleHookDefinition, ArtifactLifecycleHookEvent, ArtifactLifecycleHookRegistration, ArtifactLifecycleIdentitySchema, ArtifactLifecycleInitializedEntry, ArtifactLifecycleInitializedEntrySchema, ArtifactLifecycleRejectedPayload, ArtifactLifecycleRejectedPayloadSchema, ArtifactLifecycleRejection, ArtifactLifecycleRejectionSchema, ArtifactLifecycleSchemas, ArtifactLifecycleSemanticEvent, ArtifactLifecycleSituation, ArtifactLifecycleSituationSchema, ArtifactLifecycleSnapshot, ArtifactLifecycleSnapshotSchema, ArtifactLifecycleState, ArtifactLifecycleStateSchema, ArtifactLifecycleTransitionCommand, ArtifactLifecycleTransitionCommandSchema, ArtifactLifecycleTransitionIntent, ArtifactLifecycleTransitionIntentSchema, ArtifactLifecycleTransitionResponse, ArtifactLifecycleTransitionResponseSchema, ArtifactLifecycleTransitionedEntry, ArtifactLifecycleTransitionedEntrySchema, ArtifactLifecycleVersionSchema, ArtifactNamespace, ArtifactObservation, ArtifactObservationAddedPayload, ArtifactObservationSchema, ArtifactOf, ArtifactPartArea, ArtifactPartAreaSchema, ArtifactPartResolution, ArtifactPatchArrayFilter, ArtifactPatchArrayFilterSchema, ArtifactPatchDocument, ArtifactPatchDocumentSchema, ArtifactPatchDryRunSchema, ArtifactPatchError, ArtifactPatchErrorCode, ArtifactPatchErrorSchema, ArtifactPatchFailureSchema, ArtifactPatchInstruction, ArtifactPatchIssue, ArtifactPatchIssueSchema, ArtifactPatchMigration, ArtifactPatchMigrationSchema, ArtifactPatchOperationResult, ArtifactPatchOperationResultSchema, ArtifactPatchOperator, ArtifactPatchPathSchema, ArtifactPatchPersistedSchema, ArtifactPatchRequest, ArtifactPatchRequestSchema, ArtifactPatchResponse, ArtifactPatchResponseSchema, ArtifactPatchSegment, ArtifactPatchSubjectRequest, ArtifactPatchSubjectResponse, ArtifactPatchSuccess, ArtifactPatchSuccessSchema, ArtifactPatchTarget, ArtifactPatchTargetSchema, ArtifactQueryRequest, ArtifactQueryRequestSchema, ArtifactQueryResponse, ArtifactQueryScope, ArtifactQueryScopeSchema, ArtifactRef, ArtifactRefSchema, ArtifactRelation, ArtifactRelationAddedPayload, ArtifactRelationQueryTarget, ArtifactRelationQueryTargetSchema, ArtifactRelationRequirement, ArtifactRelationRequirementSchema, ArtifactRelationSchema, ArtifactRelationSourceIssue, ArtifactRelationTarget, ArtifactRelationTargetIdentity, ArtifactRelationTargetIdentitySchema, ArtifactRelationTargetSchema, ArtifactRelationTypeListRequest, ArtifactRelationTypeListResponse, ArtifactRelationTypeRegisterRequest, ArtifactRelationTypeRegisterResponse, ArtifactRepresentations, ArtifactRepresentationsSchema, ArtifactResolveContextRequest, ArtifactResolveContextResponse, ArtifactResolvePartError, ArtifactResolvePartErrorCode, ArtifactResolvePartErrorSchema, ArtifactResolvePartRequest, ArtifactResolvePartRequestSchema, ArtifactResolvePartResponse, ArtifactResolvePartResponseSchema, ArtifactResolveRequest, ArtifactResolveResponse, ArtifactReviseRequest, ArtifactReviseResponse, ArtifactRevisedPayload, ArtifactRevision, ArtifactRevisionSchema, ArtifactSchemaFragment, ArtifactSchemaVersionSchema, ArtifactSchemas, ArtifactScope, ArtifactScopeSchema, ArtifactStatusChangedPayload, ArtifactStatusPathSchema, ArtifactSubjects, ArtifactUniquenessRule, ArtifactUniquenessRuleSchema, ArtifactUniquenessSelectorSchema, BeforeArtifactHookContext, BeforeArtifactHookRegistration, BuildUniquenessKeysResult, ConfidenceBasis, ConfidenceBasisSchema, ConfidenceLevel, ConfidenceLevelSchema, ConfidenceMetadata, ConfidenceMetadataSchema, EVIDENCE_VALUE_TYPE, EntityRef, EntityRefSchema, EvidenceOccurrence, EvidenceOccurrenceExtractionOptions, EvidenceRef, EvidenceRefSchema, EvidenceResolveRequest, EvidenceResolveRequestSchema, EvidenceResolveResponse, EvidenceResolveResponseSchema, EvidenceValue, EvidenceValueSchema, LocalRef, LocalRefSchema, RelationTypeRegistration, RelationTypeRegistrationSchema, ResolvedArtifactContextNode, ResolvedArtifactContextWire, ResolvedArtifactContextWireSchema, UniquenessKey, UniquenessKeyIssue, UniquenessKeyIssueReason, UniquenessKeyPart, UniquenessSelectorCapability, UniquenessSupportIssue, UnresolvedArtifactContextNode, advanceArtifactLifecycle, artifactPatchFilterName, artifactPatchInstructions, artifactPatchPathFilterNames, artifactPatchSegment, artifactPatchSegments, artifactRelationTargetIdentity, assessUniquenessSupport, buildUniquenessKeys, checkArtifactPartIds, checkArtifactRelationSourceParts, compileArtifactDataChecker, compileArtifactDataSchema, defineArtifactKind, defineArtifactLifecycleHooks, describeArtifactRelationTargetIdentity, describeUniquenessKey, extractEvidenceOccurrences, hydrateArtifactContextTree, initialArtifactLifecycle, inspectArtifactDataLocation, isArtifactDataPathDeclared, isArtifactLifecycleTransitionAllowed, readArtifactTitle, resolveArtifactPart, serializeArtifactRelationTargetIdentity, toArtifactLifecycleFailure, validateArtifactPartAreas };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { _ as AutomationTriggerKindSchema, a as AutomationTriggerListener, c as AutomationTriggerSubscription, d as createAutomationTriggerDescriptor, f as defineAutomationTrigger, g as AutomationTriggerDescriptorSchema, h as AutomationTriggerDescriptor, i as AutomationTriggerEvent, l as AutomationTriggerType, m as AutomationTriggerBindingSchema, n as AutomationTriggerBinding, o as AutomationTriggerParams, p as toAutomationTriggerType, r as AutomationTriggerCleanup, s as AutomationTriggerPayload, t as AutomationTriggerActivationContext, u as DefinedAutomationTrigger, v as AutomationTriggerLocalNameSchema } from "../../definition-DeIGoROj.mjs";
|
|
2
|
-
import { t as ExtensionAutomationTriggersContribution } from "../../contribution-
|
|
2
|
+
import { t as ExtensionAutomationTriggersContribution } from "../../contribution-1GL7Rjaq.mjs";
|
|
3
3
|
import { a as AutomationTriggerSchemas, i as AutomationTriggerNamespace, n as AutomationTriggerListRequest, o as AutomationTriggerSubjects, r as AutomationTriggerListResponse, t as AutomationTriggerChangedPayload } from "../../index-YOXWpZAS.mjs";
|
|
4
4
|
export { AutomationTriggerActivationContext, AutomationTriggerBinding, AutomationTriggerBindingSchema, AutomationTriggerChangedPayload, AutomationTriggerCleanup, AutomationTriggerDescriptor, AutomationTriggerDescriptorSchema, AutomationTriggerEvent, AutomationTriggerKindSchema, AutomationTriggerListRequest, AutomationTriggerListResponse, AutomationTriggerListener, AutomationTriggerLocalNameSchema, AutomationTriggerNamespace, AutomationTriggerParams, AutomationTriggerPayload, AutomationTriggerSchemas, AutomationTriggerSubjects, AutomationTriggerSubscription, AutomationTriggerType, DefinedAutomationTrigger, ExtensionAutomationTriggersContribution, createAutomationTriggerDescriptor, defineAutomationTrigger, toAutomationTriggerType };
|