@makaio/framework 1.0.0-dev-1789178369476 → 1.0.0-dev-1789178780636

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/.makaio-build.json +2 -2
  2. package/dist/adapters/claude/index.d.mts +5 -5
  3. package/dist/{artifact-DGxKwbHE.mjs → artifact-CH7yhgti.mjs} +1 -1
  4. package/dist/bus/index.d.mts +1 -1
  5. package/dist/bus/index.mjs +1 -1
  6. package/dist/bus-CPlKKH4v.mjs +9 -0
  7. package/dist/contracts/adapter/index.d.mts +1 -1
  8. package/dist/contracts/artifact/index.d.mts +1 -1
  9. package/dist/contracts/artifact/index.mjs +1 -1
  10. package/dist/contracts/capabilities/index.d.mts +1 -1
  11. package/dist/contracts/client/index.d.mts +1 -1
  12. package/dist/contracts/extension/index.d.mts +2 -2
  13. package/dist/contracts/extension/index.mjs +1 -1
  14. package/dist/contracts/index.d.mts +44 -44
  15. package/dist/contracts/index.mjs +1 -1
  16. package/dist/contracts/materialization/index.mjs +1 -1
  17. package/dist/contracts/session/index.d.mts +2 -2
  18. package/dist/contracts/skill/index.d.mts +1 -1
  19. package/dist/contracts/variant/index.d.mts +1 -1
  20. package/dist/contracts/worker/index.d.mts +1 -1
  21. package/dist/contracts/worker/index.mjs +1 -1
  22. package/dist/contracts/workflow/index.d.mts +1 -1
  23. package/dist/contracts/workflow/index.mjs +1 -1
  24. package/dist/{extension-D8uLQSDc.mjs → extension-DRwry8GA.mjs} +1 -1
  25. package/dist/{index-BqtdO-uk.d.mts → index-4GaVggnR.d.mts} +41 -41
  26. package/dist/{index-C1nSuiG0.d.mts → index-B6WkHnCQ.d.mts} +1 -1
  27. package/dist/{index-B4pPwpKk.d.mts → index-BDRfiSz8.d.mts} +1 -1
  28. package/dist/{index-U--ajOHy.d.mts → index-BI8PuDkI.d.mts} +1 -1
  29. package/dist/{index-D0xS-mYt.d.mts → index-CA3Uzki8.d.mts} +10 -10
  30. package/dist/{index-C6e9cwAl2.d.mts → index-CdWxSwhQ2.d.mts} +4 -4
  31. package/dist/{index-Du4wUv9q.d.mts → index-CsLb9M1M.d.mts} +7 -7
  32. package/dist/{index-B3fuld9X.d.mts → index-DI07GxEW.d.mts} +5 -5
  33. package/dist/{index-CdgRoaey.d.mts → index-DNgrWs5j.d.mts} +21 -21
  34. package/dist/{index-zmDRR8gv2.d.mts → index-DVocx__-2.d.mts} +11 -11
  35. package/dist/{index-a_peDAyG.d.mts → index-DhunnX8V.d.mts} +13 -7
  36. package/dist/{index-gu4mzfTr.d.mts → index-GPTSqhvy.d.mts} +1 -1
  37. package/dist/{index-DyVXhEBC2.d.mts → index-GpfGF9AO2.d.mts} +3 -3
  38. package/dist/{index-HMb0RcTG2.d.mts → index-KnN2OyWD2.d.mts} +36 -36
  39. package/dist/{index-GFf4oKBg2.d.mts → index-iVisrVdC2.d.mts} +37 -37
  40. package/dist/{index-T-aAKybB.d.mts → index-xsaaa85T.d.mts} +8 -8
  41. package/dist/kernel/extension/index.d.mts +1 -1
  42. package/dist/kernel/index.d.mts +2 -2
  43. package/dist/kernel/observability/index.d.mts +1 -1
  44. package/dist/kind-registration-WrdMzWmV.mjs +1 -0
  45. package/dist/{materialization-kP_vEXV3.mjs → materialization-C_92G2CL.mjs} +1 -1
  46. package/dist/{namespace-DM5vykb7.d.mts → namespace-BrqkCnyt.d.mts} +4 -4
  47. package/dist/{namespace-f6Kz5cwX.d.mts → namespace-CjvSQYRJ.d.mts} +12 -12
  48. package/dist/{namespace-B5IFLQc-.d.mts → namespace-DQpBf2CK.d.mts} +6 -6
  49. package/dist/{namespace-C_tttgJ8.d.mts → namespace-DlOQmhgX.d.mts} +18 -18
  50. package/dist/{namespace-CPGTaFqO.d.mts → namespace-Phxf0Lep.d.mts} +2 -2
  51. package/dist/{namespace-LSHmxtMn.d.mts → namespace-uCaKZm89.d.mts} +4 -4
  52. package/dist/package.json +1 -1
  53. package/dist/runtime-node/workflow-execution-bus-access.mjs +1 -1
  54. package/dist/{schemas-CJKDu4Kt.d.mts → schemas-2_D4iVbb.d.mts} +1 -1
  55. package/dist/{schemas-Cj6Gbqch.d.mts → schemas-BcynDWi-.d.mts} +7 -7
  56. package/dist/{schemas-CPNdGMLf.d.mts → schemas-COiUhOce.d.mts} +8 -8
  57. package/dist/{schemas-CEJe8O6P.d.mts → schemas-DlVKv9QC.d.mts} +4 -4
  58. package/dist/{schemas-rlb0IQ-G.mjs → schemas-Dl_3zv9l.mjs} +1 -1
  59. package/dist/{schemas-CeItAAQM.d.mts → schemas-uA8246K9.d.mts} +8 -8
  60. package/dist/services/adapter-runtime/index.d.mts +3 -3
  61. package/dist/services/adapter-runtime/namespace.d.mts +1 -1
  62. package/dist/services/adapter-runtime/schemas.d.mts +1 -1
  63. package/dist/services/adapter-subsystem/index.d.mts +2 -2
  64. package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
  65. package/dist/services/context-rules/index.d.mts +3 -3
  66. package/dist/services/execution-target/index.d.mts +2 -2
  67. package/dist/services/execution-target/namespace.d.mts +1 -1
  68. package/dist/services/execution-target/schemas.d.mts +1 -1
  69. package/dist/services/filesystem/namespace.d.mts +6 -6
  70. package/dist/services/filesystem/schemas.d.mts +3 -3
  71. package/dist/services/index.d.mts +36 -36
  72. package/dist/services/provider-context/index.d.mts +1 -1
  73. package/dist/services/session/handlers/index.d.mts +1 -1
  74. package/dist/services/session/index.d.mts +5 -5
  75. package/dist/services/session/messages/namespace.d.mts +1 -1
  76. package/dist/services/session/session-events/namespace.d.mts +1 -1
  77. package/dist/services/settings/namespace.d.mts +8 -8
  78. package/dist/services/subagent-template/index.d.mts +1 -1
  79. package/dist/services/subagent-template/schemas.d.mts +1 -1
  80. package/dist/services/tray-menu/index.d.mts +2 -2
  81. package/dist/services/tray-menu/namespace.d.mts +1 -1
  82. package/dist/services/tray-menu/schemas.d.mts +1 -1
  83. package/dist/{types-7QB81mzR.d.mts → types-DhbllltK.d.mts} +15 -15
  84. package/dist/{worker-DWEma08Q.mjs → worker-IIubsEFG.mjs} +1 -1
  85. package/dist/{workflow-DA2yJJK-.mjs → workflow-dVr_9gaf.mjs} +1 -1
  86. package/dist/workflow-engine/index.d.mts +39 -39
  87. package/package.json +1 -1
  88. package/dist/bus-CyrTcF8F.mjs +0 -9
  89. package/dist/kind-registration-BcNuwXPC.mjs +0 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 1,
3
- "fingerprint": "f2a96ee91ac325027bf6a08b67f35b27082e0ac0654dfe1f31a2fb3361ac5278",
4
- "builtAt": "2026-09-12T02:00:41.539Z",
3
+ "fingerprint": "076d20a269f12bd0cd45874bddbf72d8705eb09f3bb1dd8c708607f62f433719",
4
+ "builtAt": "2026-09-12T02:07:14.427Z",
5
5
  "declarations": true,
6
6
  "declarationBackend": "tsc"
7
7
  }
@@ -1172,8 +1172,8 @@ declare const SDKMessageSchema: z.ZodUnion<readonly [z.ZodUnion<readonly [z.ZodD
1172
1172
  subtype: z.ZodLiteral<"init">;
1173
1173
  agents: z.ZodOptional<z.ZodArray<z.ZodString>>;
1174
1174
  apiKeySource: z.ZodEnum<{
1175
- user: "user";
1176
1175
  none: "none";
1176
+ user: "user";
1177
1177
  project: "project";
1178
1178
  org: "org";
1179
1179
  temporary: "temporary";
@@ -2501,8 +2501,8 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
2501
2501
  subtype: z.ZodLiteral<"init">;
2502
2502
  agents: z.ZodOptional<z.ZodArray<z.ZodString>>;
2503
2503
  apiKeySource: z.ZodEnum<{
2504
- user: "user";
2505
2504
  none: "none";
2505
+ user: "user";
2506
2506
  project: "project";
2507
2507
  org: "org";
2508
2508
  temporary: "temporary";
@@ -3791,8 +3791,8 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
3791
3791
  subtype: z.ZodLiteral<"init">;
3792
3792
  agents: z.ZodOptional<z.ZodArray<z.ZodString>>;
3793
3793
  apiKeySource: z.ZodEnum<{
3794
- user: "user";
3795
3794
  none: "none";
3795
+ user: "user";
3796
3796
  project: "project";
3797
3797
  org: "org";
3798
3798
  temporary: "temporary";
@@ -5128,8 +5128,8 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
5128
5128
  subtype: z.ZodLiteral<"init">;
5129
5129
  agents: z.ZodOptional<z.ZodArray<z.ZodString>>;
5130
5130
  apiKeySource: z.ZodEnum<{
5131
- user: "user";
5132
5131
  none: "none";
5132
+ user: "user";
5133
5133
  project: "project";
5134
5134
  org: "org";
5135
5135
  temporary: "temporary";
@@ -6418,8 +6418,8 @@ declare function createClaudeConnectorNamespace<N extends string>(namespaceName:
6418
6418
  subtype: z.ZodLiteral<"init">;
6419
6419
  agents: z.ZodOptional<z.ZodArray<z.ZodString>>;
6420
6420
  apiKeySource: z.ZodEnum<{
6421
- user: "user";
6422
6421
  none: "none";
6422
+ user: "user";
6423
6423
  project: "project";
6424
6424
  org: "org";
6425
6425
  temporary: "temporary";
@@ -1 +1 @@
1
- import{o as e}from"./chunk-DTipWd-i.mjs";import{n as t,o as n,s as r}from"./json-value-DM-EjTC1.mjs";import{C as i,_ as a,a as o,b as s,c,d as l,i as ee,l as u,n as te,p as d,r as ne,t as re,u as ie,w as f,x as ae,y as oe}from"./schemas-rlb0IQ-G.mjs";import{S as se,a as p,m as ce,r as le,s as m,t as h,u as g,y as ue}from"./kind-registration-BcNuwXPC.mjs";import{t as de}from"./zod-json-schema-ZUmGtQhT.mjs";import{t as fe}from"./ajv-Cvnmw2yn.mjs";import{t as pe}from"./2020-CRfgqanb.mjs";import{t as me}from"./dist-onY7e-pd.mjs";import{z as _}from"zod";import{createBusNamespace as he}from"@makaio/framework/core";const ge=_.strictObject({evidence:i}),v=_.strictObject({kind:_.literal(`text`),text:_.string()}),[_e,ve,ye]=i.options,be=_.union([_e.pick({source:!0,location:!0}).extend({content:v}),ve.pick({source:!0,location:!0}).extend({content:v}),ye.pick({source:!0,location:!0}).extend({content:v})]);function y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function b(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function xe(e,t){if(t===`#`)return{node:e,pointer:``};if(!t.startsWith(`#/`))return;let n;try{n=decodeURIComponent(t.slice(1))}catch{return}let r=e;for(let e of n.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(Array.isArray(r)){if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=r.length)return;r=r[Number(t)]}else{let e=y(r);if(!e||!Object.hasOwn(e,t))return;r=e[t]}}let i=typeof r==`boolean`?r:y(r);return i===void 0?void 0:{node:i,pointer:n}}function x(e,t){if(t===``)return!1;let n=e;for(let e of t.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(n=Array.isArray(n)?n[Number(t)]:y(n)?.[t],typeof y(n)?.$id==`string`)return!0}return!1}function Se(e,t,n){if(e[`x-makaio-value-type`]!==`evidence/v1`)return;let r=i.safeParse(t);if(!r.success)throw Error(`Invalid schema-declared evidence at ${n}`);return{evidence:r.data,dataPath:n}}function Ce(e,t,n,r){if(typeof t.$ref!=`string`)return!1;if(r)return!0;let i=xe(e,t.$ref);return i===void 0?!0:typeof i.node!=`boolean`&&S(e,i.node,n,x(e,i.pointer))}function S(e,t,n=new WeakSet,r=!1){let i=y(t);if(!i||n.has(i))return!1;n.add(i);let a=r||i!==e&&typeof i.$id==`string`;if(i[`x-makaio-value-type`]===`evidence/v1`||typeof i.$dynamicRef==`string`||Ce(e,i,n,a)||[`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`then`,`unevaluatedItems`,`unevaluatedProperties`].some(t=>S(e,i[t],n,a))||[`allOf`,`anyOf`,`oneOf`,`prefixItems`].some(t=>Array.isArray(i[t])&&i[t].some(t=>S(e,t,n,a)))||Array.isArray(i.items)&&i.items.some(t=>S(e,t,n,a)))return!0;for(let t of[`dependentSchemas`,`dependencies`,`patternProperties`,`properties`]){let r=y(i[t]);if(r&&Object.values(r).some(t=>S(e,t,n,a)))return!0}return!1}var we=class{dataSchema;matchesSchema;occurrences=new Map;visited=new WeakMap;constructor(e,t){this.dataSchema=e,this.matchesSchema=t}extract(e){return this.visit(this.dataSchema,e,`/data`),[...this.occurrences.values()]}visit(e,t,n,r=``){let i=this.visited.get(e)??new Set;if(i.has(n))return;if(i.add(n),this.visited.set(e,i),typeof e.$dynamicRef==`string`)throw Error(`Evidence discovery does not support active $dynamicRef at ${n}`);if(typeof e.$ref==`string`){if(x(this.dataSchema,r))throw Error(`Evidence discovery does not support local $ref inside nested $id resource at ${n}`);let i=xe(this.dataSchema,e.$ref);if(i===void 0)throw Error(`Cannot resolve local schema reference ${e.$ref} at ${n}`);if(typeof i.node!=`boolean`&&this.visit(i.node,t,n,i.pointer),this.dataSchema.$schema!==`https://json-schema.org/draft/2020-12/schema`)return}let a=Se(e,t,n);if(a){this.occurrences.set(n,a);return}this.visitCombiners(e,t,n,r),this.visitConditional(e,t,n,r),this.visitDependencies(e,t,n,r),this.assertSupportedApplicators(e,n,r),Array.isArray(t)?this.visitArray(e,t,n,r):typeof t==`object`&&t&&this.visitObject(e,t,n,r)}visitCombiners(e,t,n,r){for(let i of[`allOf`,`anyOf`,`oneOf`]){let a=e[i];if(Array.isArray(a))for(let[e,o]of a.entries()){let a=y(o),s=`${r}/${i}/${e}`;a&&(i===`allOf`||this.matchesSchema(this.dataSchema,s,t))&&this.visit(a,t,n,s)}}}visitConditional(e,t,n,r){let i=typeof e.if==`boolean`?e.if:y(e.if);if(i===void 0)return;let a=`${r}/if`,o=this.matchesSchema(this.dataSchema,a,t);o&&typeof i!=`boolean`&&this.visit(i,t,n,a);let s=o?`then`:`else`,c=y(e[s]);c&&this.visit(c,t,n,`${r}/${s}`)}visitDependencies(e,t,n,r){if(!(typeof t!=`object`||!t||Array.isArray(t)))for(let i of[`dependentSchemas`,`dependencies`]){let a=y(e[i]);if(a)for(let[e,o]of Object.entries(a)){let a=y(o);Object.hasOwn(t,e)&&a&&this.visit(a,t,n,`${r}/${i}/${b(e)}`)}}}assertSupportedApplicators(e,t,n){for(let r of[`unevaluatedProperties`,`unevaluatedItems`])if(S(this.dataSchema,e[r],void 0,x(this.dataSchema,n)))throw Error(`Evidence under unsupported ${r} applicator at ${t}`)}visitArray(e,t,n,r){let i=Array.isArray(e.prefixItems),a=i?e.prefixItems:Array.isArray(e.items)?e.items:[];a.forEach((e,a)=>{let o=y(e),s=i?`prefixItems`:`items`;o&&a<t.length&&this.visit(o,t[a],`${n}/${a}`,`${r}/${s}/${a}`)});let o=Array.isArray(e.items)?y(e.additionalItems):y(e.items);if(o){let i=Array.isArray(e.items)?`additionalItems`:`items`;t.slice(a.length).forEach((e,t)=>this.visit(o,e,`${n}/${a.length+t}`,`${r}/${i}`))}this.visitContains(e,t,n,r)}visitContains(e,t,n,r){let i=y(e.contains);if(!i)return;let a=`${r}/contains`;t.forEach((e,t)=>{this.matchesSchema(this.dataSchema,a,e)&&this.visit(i,e,`${n}/${t}`,a)})}visitObject(e,t,n,r){let i=y(e.properties),a=y(e.patternProperties);for(let[o,s]of Object.entries(t)){let t=b(o),c=i!==void 0&&Object.hasOwn(i,o),l=y(i?.[o]);l&&this.visit(l,s,`${n}/${t}`,`${r}/properties/${t}`);let ee=this.visitPatterns(a,o,s,`${n}/${t}`,r),u=y(e.additionalProperties);!c&&!ee&&u&&this.visit(u,s,`${n}/${t}`,`${r}/additionalProperties`)}}visitPatterns(e,t,n,r,i){let a=!1;for(let[o,s]of Object.entries(e??{})){if(!new RegExp(o,`u`).test(t))continue;a=!0;let e=y(s);e&&this.visit(e,n,r,`${i}/patternProperties/${b(o)}`)}return a}};function Te(e,t,n){return new we(e,n.matchesSchema).extract(t)}function Ee(e){let{dataSchema:t,hooks:n,...r}=e,i={$schema:`https://json-schema.org/draft/2020-12/schema`,...de(t)};ue(i);let a=p.parse({...r,dataSchema:i});if(a.kind!==e.kind)throw Error(`Artifact kind identifiers must not contain surrounding whitespace`);let o=_.fromJSONSchema(a.dataSchema),s=_.unknown().superRefine((e,t)=>{let n=o.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})}).pipe(t).superRefine((e,t)=>{try{se(e,a.titlePath)}catch(e){t.addIssue({code:`custom`,path:a.titlePath.split(`.`),message:e instanceof Error?e.message:`Artifact title must be a nonblank string`})}});return{...structuredClone(a),kind:e.kind,schemaVersion:e.schemaVersion,dataSchema:s,...n?{hooks:n}:{},toRegistration:()=>structuredClone(a)}}var De=e(fe(),1),Oe=e(pe(),1),ke=e(me(),1);function C(e){let t={allErrors:!0,strict:!1,strictSchema:!0},n=e.dataSchema.$schema===`https://json-schema.org/draft/2020-12/schema`?new Oe.default(t):new De.default(t);return(0,ke.default)(n),n.addKeyword({keyword:ae,schemaType:`string`,valid:!0}),n.compile(e.dataSchema)}function Ae(e){return e.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function je(e){let t=e.instancePath.split(`/`).slice(1).map(Ae),n=e.keyword===`required`?e.params.missingProperty:e.params.additionalProperty;return typeof n==`string`&&(e.keyword===`required`||e.keyword===`additionalProperties`)&&t.push(n),t.join(`.`)}function Me(e){if(e.keyword!==`type`)return;let t=e.params.type;if(typeof t==`string`)return t;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t.join(` | `)}const Ne=n.array();function Pe(e){if(e.keyword!==`enum`)return;let t=Ne.safeParse(e.params.allowedValues);return t.success?t.data:void 0}function Fe(e){return(e??[]).map(e=>{let t=Me(e),n=Pe(e);return{path:je(e),reason:e.message??`violates ${e.keyword}`,...t===void 0?{}:{expectedType:t},...n===void 0?{}:{allowedValues:n}}})}function Ie(e){return C(e)}function Le(e){let t=C(e);return e=>t(e)?{valid:!0}:{valid:!1,issues:Fe(t.errors)}}function Re(e){return{hooks:[...e.hooks]}}const ze=[`inline`,`summary`,`link`,`omit`],w=_.string().min(1),T=_.object({kinds:_.array(_.string().min(1)).optional(),hint:w.optional(),depth:_.number().int().min(1).max(20).optional(),nested:_.lazy(()=>E).optional()}),E=_.record(_.string().min(1),T);function D(e){return JSON.stringify([e.kind,e.id,e.revision])}const O=_.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),Be=_.object({target:u,sourceRef:f,relationType:_.string().min(1),hint:w,status:_.enum([`resolved`,`unresolved`]),reason:O.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:_.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),k=_.object({rootRef:f,refs:_.array(Be),resolved:_.array(l)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(D));n.has(D(e.rootRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(D(e.sourceRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`sourceRef`],message:`artifact context ref sources must have a matching revision in resolved`}),!(e.status!==`resolved`||e.target.refClass!==`artifact`)&&(n.has(D(e.target))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function Ve(e){let t=k.parse(e),n=new Map(t.resolved.map(e=>[A(e),e])),r=new Map;for(let e of t.refs){let t=A(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(A(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${A(t.rootRef)}'`);let a=He(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return Ge(a,e),e}}}function He(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:We(e,r,i,new Set([A(e)]))}}function Ue(e,t,n,r,i,a,o){let s=A(e),c=new Set(o);return c.add(s),{status:`resolved`,ref:e,artifact:t,relation:n,hint:r,children:We(e,i,a,c)}}function We(e,t,n,r){return(t.get(A(e))??[]).map(e=>{if(e.status===`unresolved`)return{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:e.reason};if(e.target.refClass!==`artifact`)throw Error(`Resolved artifact context refs must target an artifact revision`);let i=A(e.target),a=n.get(i);if(!a)throw Error(`Resolved artifact context is missing target artifact '${i}'`);return r.has(i)?{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:`cycle-detected`}:Ue(e.target,a,e.relationType,e.hint,t,n,r)})}function Ge(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)Ge(n,t)}}function A(e){return JSON.stringify([e.kind,e.id,e.revision])}const j=[`$set`,`$unset`,`$push`,`$pull`],M=`[A-Za-z_$][A-Za-z0-9_$]*`,N=`[A-Za-z_$][A-Za-z0-9_$-]*`,Ke=`(?:0|[1-9][0-9]*)`,qe=`(?:${`\\$\\[${M}\\]`}|${Ke}|${N})`,Je=RegExp(`^${N}(?:\\.${qe})*$`),Ye=RegExp(`^${M}(?:\\.${N})*$`),Xe=RegExp(`^${Ke}$`),Ze=RegExp(`^\\$\\[(${M})\\]$`),P=_.string().regex(Je,`Expected a data-relative path of object properties, array positions, or $[filter] placeholders`);function Qe(e){let t=Ze.exec(e);return t?.[1]===void 0?Xe.test(e)?{kind:`index`,index:Number(e)}:{kind:`property`,name:e}:{kind:`filter`,placeholder:t[1]}}function $e(e){return e.split(`.`).map(Qe)}function et(e){return $e(e).flatMap(e=>e.kind===`filter`?[e.placeholder]:[])}const tt=r(_.record(_.string().regex(Ye,`Expected a filter key of the form name or name.field.path`),n),{prototypeKey:`an array filter cannot compare a __proto__ key, which JSON transport drops`,nonPlainObject:`an array filter must be a plain object of comparison keys`,symbolKey:`an array filter cannot carry symbol-keyed comparisons`,nonEnumerableKey:`an array filter cannot carry non-enumerable comparison keys`,extraArrayKey:`an array filter must be a plain object, not an array`});function nt(e){let t=new Set(Object.keys(e).map(e=>e.split(`.`)[0]));if(t.size!==1)return;let[n]=t;return n!==void 0&&n.length>0?n:void 0}function F(e,t){return r(_.record(P,t),{prototypeKey:`${e} cannot address __proto__, which JSON transport drops`,nonPlainObject:`${e} must be a plain object of path instructions`,symbolKey:`${e} cannot carry symbol-keyed instructions`,nonEnumerableKey:`${e} cannot carry non-enumerable instructions`,extraArrayKey:`${e} must be a plain object, not an array`})}const rt=_.literal(!0),it=_.strictObject({$set:F(`$set`,n).optional(),$unset:F(`$unset`,rt).optional(),$push:F(`$push`,n).optional(),$pull:F(`$pull`,n).optional(),arrayFilters:_.array(tt).optional()});function I(e){return j.flatMap(t=>Object.entries(e[t]??{}).map(([e,n])=>({operator:t,path:e,value:n})))}function at(e,t){let n=I(e),r=new Map;(e.arrayFilters??[]).forEach((e,n)=>{let i=nt(e);if(i===void 0){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`An array filter must bind exactly one placeholder name across all of its keys`});return}if(r.has(i)){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter placeholder ${i} is already bound by another filter`});return}r.set(i,n)});let i=new Set;for(let{operator:e,path:a}of n)for(let n of et(a))i.add(n),r.has(n)||t.addIssue({code:`custom`,path:[e,a],message:`Path uses placeholder $[${n}] without a matching entry in arrayFilters`});for(let[e,n]of r)i.has(e)||t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter binds placeholder ${e}, which no path uses`})}const ot=it.superRefine(at).superRefine((e,t)=>{I(e).length===0&&t.addIssue({code:`custom`,message:`Declare at least one of ${j.join(`, `)}`})}),st=it.superRefine(at),ct=_.strictObject({kind:f.shape.kind,id:f.shape.id}),lt=_.strictObject({ref:ct,baseRevision:f.shape.revision,patch:st,dryRun:_.boolean().optional(),schemaVersion:g.optional().describe(`Target schema version for the patched revision; defaults to the base revision's. Use it to migrate an artifact left at an older version by a kind bump.`),statusPath:d.optional(),representations:ie.strict().nullable().optional().describe(`Rendering hints (markdown, summary, plaintext) for the new revision. Omit to keep the previous revision's hints. An object replaces all of them, it does not merge: send every hint you want to keep. null clears them.`)}).superRefine((e,t)=>{e.schemaVersion===void 0&&I(e.patch).length===0&&t.addIssue({code:`custom`,path:[`patch`],message:`Declare at least one of ${j.join(`, `)}, or name a schemaVersion to migrate a payload that already fits`})}),ut=[`ARTIFACT_NOT_FOUND`,`BASE_REVISION_CONFLICT`,`KIND_NOT_REGISTERED`,`SCHEMA_VERSION_MISMATCH`,`PATH_NOT_DECLARED`,`PATH_NOT_RESOLVABLE`,`TARGET_NOT_A_COLLECTION`,`UNSUPPORTED_TARGET`,`NO_MATCH`,`SCHEMA_VALIDATION_FAILED`,`NO_CHANGE`,`STORE_REJECTED`,`HOST_FAILED`],dt=_.strictObject({path:_.string(),reason:_.string().min(1),expectedType:_.string().min(1).optional(),allowedValues:_.array(n).optional()}),ft=_.strictObject({code:_.enum(ut),message:_.string().min(1),operator:_.enum(j).optional(),path:P.optional(),currentRevision:f.shape.revision.optional(),issues:_.array(dt).optional(),repair:_.string().min(1)}).superRefine((e,t)=>{e.code===`BASE_REVISION_CONFLICT`&&e.currentRevision===void 0&&t.addIssue({code:_.ZodIssueCode.custom,message:`A BASE_REVISION_CONFLICT must name the revision the artifact carries.`,path:[`currentRevision`]})}),pt=_.strictObject({operator:_.enum(j),path:P,matched:_.number().int().positive()}),mt=_.strictObject({from:g,to:g}).refine(e=>e.to>e.from,{path:[`to`],message:`A migration moves the artifact forward to a newer schema version`}),ht=_.strictObject({ok:_.literal(!0),base:f,operations:_.array(pt),migration:mt.optional()});function gt(e,t){e.operations.length===0&&e.migration===void 0&&t.addIssue({code:`custom`,path:[`operations`],message:`A success without a migration must report at least one applied instruction`})}const _t=ht.extend({dryRun:_.literal(!0)}).superRefine(gt),vt=ht.extend({dryRun:_.literal(!1),artifact:f}).superRefine(gt),yt=_.discriminatedUnion(`dryRun`,[_t,vt]),bt=_.strictObject({ok:_.literal(!1),error:ft}),xt=_.union([yt,bt]),St=_.object({ref:oe}),Ct=_.union([_.strictObject({ok:_.literal(!0),ref:oe,areaPath:le,part:t}),_.strictObject({ok:_.literal(!1),error:ce})]),L=f.pick({kind:!0,id:!0}),R=_.number().int().positive(),z=R,B={knowledge:`valid`,commitment:`proposed`,interaction:`open`},V=_.discriminatedUnion(`category`,[_.strictObject({category:_.literal(`knowledge`),state:_.enum(h.knowledge),version:z}),_.strictObject({category:_.literal(`commitment`),state:_.enum(h.commitment),version:z}),_.strictObject({category:_.literal(`interaction`),state:_.enum(h.interaction),version:z})]).superRefine((e,t)=>{e.version===1&&e.state!==B[e.category]&&t.addIssue({code:`custom`,path:[`state`],message:`Lifecycle version 1 is reserved for the category initial state`})}),H=_.union([V,_.strictObject({category:_.literal(`record`)})]),U=_.string().trim().min(1),wt=_.strictObject({kind:U,ref:U}),W=_.discriminatedUnion(`kind`,[_.strictObject({kind:_.literal(`revision-assessment`),assessedRevision:f.shape.revision,source:wt.optional()}),_.strictObject({kind:_.literal(`handover`),source:wt})]),Tt={artifact:L,expectedVersion:z,state:m,situation:W,reason:U.optional()},G=_.strictObject(Tt),Et=_.strictObject({...Tt,actor:re}),Dt={valid:[`retired`],retired:[`valid`],proposed:[`decided`],decided:[`fulfilled`,`revoked`],fulfilled:[],revoked:[],open:[`resolved`,`closed-without-resolution`],resolved:[],"closed-without-resolution":[]};function K(e,t){return Dt[e].includes(t)}const Ot={artifact:L,lifecycle:V,actor:re,timestamp:_.number().int().nonnegative(),observedRevision:f.shape.revision},kt=_.strictObject({...Ot,operation:_.literal(`initialized`)}).superRefine((e,t)=>{(e.lifecycle.version!==1||e.lifecycle.state!==B[e.lifecycle.category])&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`Initialization requires the category initial state and version 1`})});function At(e,t){return t===`retired`||e===`retired`&&t===`valid`}const jt=`Retiring or reinstating knowledge requires a reason`,q=_.strictObject({...Ot,operation:_.literal(`transitioned`),previousState:m,situation:W,reason:G.shape.reason}).superRefine((e,t)=>{(!K(e.previousState,e.lifecycle.state)||e.lifecycle.version<=1)&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`History requires a category-compatible transition after initialization`}),At(e.previousState,e.lifecycle.state)&&!e.reason&&t.addIssue({code:`custom`,path:[`reason`],message:jt}),e.situation.kind===`revision-assessment`&&e.situation.assessedRevision!==e.observedRevision&&t.addIssue({code:`custom`,path:[`situation`],message:`An assessment cannot authorize a different observed content revision`})}),Mt=_.discriminatedUnion(`operation`,[kt,q]),J=_.discriminatedUnion(`reason`,[_.strictObject({reason:_.literal(`lifecycle-version-conflict`),expectedVersion:z,current:V,requestedState:m}),_.strictObject({reason:_.literal(`content-basis-conflict`),assessedRevision:f.shape.revision,currentRevision:f.shape.revision}),_.strictObject({reason:_.literal(`invalid-transition`),current:H,requestedState:m}),_.strictObject({reason:_.literal(`precondition-failed`),current:V,requestedState:m})]),Y=`artifact-lifecycle-rejected`;var X=class extends Error{code=Y;data;constructor(e,t){super(e),this.name=`ArtifactLifecycleError`,this.data=J.parse(t)}};function Nt(e){return e===`record`?{category:`record`}:V.parse({category:e,state:B[e],version:1})}function Pt(e){let t=H.parse(e.current),n=f.shape.revision.parse(e.currentRevision),r=Et.parse(e.command);if(t.category===`record`)throw new X(`Record artifacts do not have a lifecycle`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(r.expectedVersion!==t.version)throw new X(`Artifact lifecycle changed since the supplied baseline`,{reason:`lifecycle-version-conflict`,expectedVersion:r.expectedVersion,current:t,requestedState:r.state});if(r.situation.kind===`revision-assessment`&&r.situation.assessedRevision!==n)throw new X(`Assessed content revision is no longer current`,{reason:`content-basis-conflict`,assessedRevision:r.situation.assessedRevision,currentRevision:n});if(!K(t.state,r.state))throw new X(`Artifact lifecycle transition is not allowed`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(At(t.state,r.state)&&!r.reason)throw new X(jt,{reason:`precondition-failed`,current:t,requestedState:r.state});return V.parse({...t,state:r.state,version:t.version+1})}const Z=_.strictObject({artifact:L}),Ft=_.strictObject({lifecycle:H}),It=_.strictObject({artifact:L,afterVersion:R.optional(),limit:_.number().int().min(1).max(100).default(50)}),Lt=_.strictObject({entries:_.array(Mt).max(100),nextCursor:R.optional()}).superRefine(({entries:e,nextCursor:t},n)=>{let r=e[0],i;for(let[t,a]of e.entries()){let e=a.artifact.kind===r?.artifact.kind&&a.artifact.id===r?.artifact.id,o=i===void 0||a.lifecycle.version===i.lifecycle.version+1,s=i===void 0||a.operation===`transitioned`&&a.lifecycle.category===i.lifecycle.category&&a.previousState===i.lifecycle.state;if(!e||!o||!s){n.addIssue({code:`custom`,path:[`entries`,t],message:`History pages contain one artifact in contiguous ascending, state-linked order`});break}i=a}t!==void 0&&t!==i?.lifecycle.version&&n.addIssue({code:`custom`,path:[`nextCursor`],message:`nextCursor must equal the last returned lifecycle version`})}),Q=_.strictObject({entry:q}),Rt=Q,zt=_.strictObject({code:_.literal(Y),message:_.string().min(1),data:J});function Bt(e){return{code:e.code,message:e.message,data:e.data}}function Vt(e,t){switch(t.reason){case`content-basis-conflict`:return Wt(e,t);case`lifecycle-version-conflict`:return[...Ht(e,t),...Ut(e,t)];case`invalid-transition`:case`precondition-failed`:return[...Ht(e,t),...Gt(e,t)]}}function Ht(e,t){return t.requestedState===e.state?[]:[{path:[`requestedState`],message:`Rejection requestedState must match the rejected transition`}]}function Ut(e,t){let n=[];return t.expectedVersion!==e.expectedVersion&&n.push({path:[`expectedVersion`],message:`Version conflict baseline must match the rejected transition`}),t.current.version===e.expectedVersion&&n.push({path:[`current`,`version`],message:`Version conflict requires a current version different from the supplied baseline`}),n}function Wt(e,t){let n=[];return(e.situation.kind!==`revision-assessment`||t.assessedRevision!==e.situation.assessedRevision)&&n.push({path:[`assessedRevision`],message:`Content conflict must identify the rejected revision assessment`}),t.currentRevision===t.assessedRevision&&n.push({path:[`currentRevision`],message:`Content conflict requires a current revision different from the assessed revision`}),n}function Gt(e,t){if(t.current.category===`record`)return[];let n=[];t.current.version!==e.expectedVersion&&n.push({path:[`current`,`version`],message:`A rejection after the version check must report the supplied baseline version`});let r=K(t.current.state,t.requestedState);return t.reason===`invalid-transition`&&r&&n.push({path:[`reason`],message:`invalid-transition requires a transition the lifecycle matrix disallows`}),t.reason===`precondition-failed`&&!r&&n.push({path:[`reason`],message:`precondition-failed requires a transition the lifecycle matrix allows`}),n}const Kt=_.strictObject({transition:G,error:zt}).superRefine(({transition:e,error:t},n)=>{for(let r of Vt(e,t.data))n.addIssue({code:`custom`,path:[`error`,`data`,...r.path],message:r.message})}),qt={"lifecycle.get":{request:Z,response:Ft},"lifecycle.history":{request:It,response:Lt},"lifecycle.transition":{request:G,response:Q},"lifecycle.committed":Rt,"lifecycle.rejected":Kt},Jt={...qt,"kind.register":{request:p,response:_.object({registered:_.boolean()})},"kind.list":{request:_.object({kind:_.string().min(1).optional()}),response:_.object({kinds:_.array(p)})},"relation-type.register":{request:s,response:_.object({registered:_.boolean()})},"relation-type.list":{request:_.object({type:_.string().min(1).optional()}),response:_.object({relationTypes:_.array(s)})},create:{request:l.omit({id:!0,revision:!0,timestamp:!0}).extend({id:f.shape.id.optional()}),response:_.object({artifact:l})},revise:{request:_.object({previous:f,statusPath:d.optional(),revision:l.omit({id:!0,revision:!0,timestamp:!0})}),response:_.object({artifact:l})},patch:{request:lt,response:xt},resolve:{request:_.object({ref:f}),response:_.object({artifact:l.nullable()})},resolvePart:{request:St,response:Ct},query:{request:o,response:_.object({artifacts:_.array(l)})},compare:{request:te,response:ne},"evidence.resolve":{request:ge,response:be},resolveContext:{request:_.object({ref:f,selectors:E.optional(),maxDepth:_.number().int().min(1).max(20).default(5)}),response:_.object({context:k})},created:_.object({artifact:l}),revised:_.object({previous:f,artifact:l}),"relation.added":_.object({artifact:f,relation:c}),"observation.added":_.object({artifact:f,observation:ee}),"status.changed":_.object({artifact:f,path:_.string().min(1),previous:_.unknown().optional(),current:_.unknown().optional()}),"kind.changed":_.object({kind:_.string().min(1),schemaVersion:g})},Yt=he(`artifact`,Jt),Xt=Yt.subjects,Zt=_.discriminatedUnion(`refClass`,[f.omit({revision:!0}),a]);function Qt(e){if(e.refClass===`artifact`)return{refClass:`artifact`,kind:e.kind,id:e.id};if(e.refClass===`entity`)return{refClass:`entity`,entityType:e.entityType,id:e.id}}function $(e){return e.refClass===`artifact`?JSON.stringify([`artifact`,e.kind,e.id]):JSON.stringify([`entity`,e.entityType,e.id])}function $t(e){return e.refClass===`artifact`?`artifact:${e.kind}/${e.id}`:`entity:${e.entityType}/${e.id}`}const en=[`relation-target`];function tn(e,t){if(!e||e.length===0)return{ok:!0,rules:[]};let n=[];for(let[r,i]of e.entries()){for(let[e,a]of i.by.entries())(!en.includes(a.kind)||!t.includes(a.kind))&&n.push({ruleIndex:r,selectorIndex:e,capability:a.kind,message:`rule #${r}, selector #${e}: '${a.kind}' selectors are not supported`});i.lifecycleStates!==void 0&&!t.includes(`lifecycle-states`)&&n.push({ruleIndex:r,capability:`lifecycle-states`,message:`rule #${r}: lifecycleStates is declared but 'lifecycle-states' is not a supported capability`})}return n.length>0?{ok:!1,issues:n}:{ok:!0,rules:e}}function nn(e,t,n,r){if(e.kind===`data`)return{ruleIndex:n,selectorIndex:r,reason:`unsupported-selector`,message:`rule #${n}, selector #${r}: data-path selectors cannot be derived from relations`};let{relationType:i}=e,a=t.filter(e=>e.type===i),o=new Set,s,c;for(let e of a){let t=Qt(e.target);if(t===void 0){c=e.target.refClass;break}o.add($(t)),s=t}return c===void 0?s===void 0?{ruleIndex:n,selectorIndex:r,reason:`missing-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': no relations of this type found`}:o.size>1?{ruleIndex:n,selectorIndex:r,reason:`ambiguous-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': ${o.size} distinct targets; expected exactly one`}:{type:i,target:s}:{ruleIndex:n,selectorIndex:r,reason:`unsupported-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': found a relation with refClass '${c}'; only artifact and entity targets are supported`}}function rn(e,t){let n=[],r=[];for(let[i,a]of e.entries()){let e=a.by.map((e,n)=>nn(e,t,i,n)),o=e.filter(e=>`reason`in e);if(o.length>0){r.push(...o);continue}let s=e.filter(e=>!(`reason`in e)),c=JSON.stringify(s.map(e=>[e.type,$(e.target)]));n.push({rule:a,ruleIndex:i,parts:s,serialized:c})}return{keys:n,issues:r}}function an(e){return e.parts.map(e=>`${e.type} → ${$t(e.target)}`).join(`; `)}export{yt as $,Et as A,j as B,X as C,J as D,kt as E,Nt as F,bt as G,ot as H,K as I,pt as J,dt as K,St as L,q as M,R as N,W as O,Pt as P,xt as Q,Ct as R,H as S,L as T,_t as U,tt as V,ft as W,vt as X,P as Y,lt as Z,Kt as _,Ee as _t,Qt as a,$e as at,Bt as b,be as bt,Yt as c,O as ct,Rt as d,T as dt,ct as et,zt as f,w as ft,Lt as g,Ie as gt,It as h,Le as ht,Zt as i,Qe as it,G as j,V as k,Jt as l,k as lt,Ft as m,Re as mt,rn as n,I as nt,$t as o,Ve as ot,Z as p,E as pt,mt as q,an as r,et as rt,$ as s,Be as st,tn as t,nt as tt,Xt as u,ze as ut,qt as v,Te as vt,Mt as w,Y as x,Q as y,ge as yt,ut as z};
1
+ import{o as e}from"./chunk-DTipWd-i.mjs";import{n as t,o as n,s as r}from"./json-value-DM-EjTC1.mjs";import{C as i,_ as a,a as o,b as s,c,d as l,i as ee,l as u,n as te,p as d,r as ne,t as re,u as ie,w as f,x as ae,y as oe}from"./schemas-Dl_3zv9l.mjs";import{S as se,a as p,m as ce,r as le,s as m,t as h,u as g,y as ue}from"./kind-registration-WrdMzWmV.mjs";import{t as de}from"./zod-json-schema-ZUmGtQhT.mjs";import{t as fe}from"./ajv-Cvnmw2yn.mjs";import{t as pe}from"./2020-CRfgqanb.mjs";import{t as me}from"./dist-onY7e-pd.mjs";import{z as _}from"zod";import{createBusNamespace as he}from"@makaio/framework/core";const ge=_.strictObject({evidence:i}),v=_.strictObject({kind:_.literal(`text`),text:_.string()}),[_e,ve,ye]=i.options,be=_.union([_e.pick({source:!0,location:!0}).extend({content:v}),ve.pick({source:!0,location:!0}).extend({content:v}),ye.pick({source:!0,location:!0}).extend({content:v})]);function y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function b(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function xe(e,t){if(t===`#`)return{node:e,pointer:``};if(!t.startsWith(`#/`))return;let n;try{n=decodeURIComponent(t.slice(1))}catch{return}let r=e;for(let e of n.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(Array.isArray(r)){if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=r.length)return;r=r[Number(t)]}else{let e=y(r);if(!e||!Object.hasOwn(e,t))return;r=e[t]}}let i=typeof r==`boolean`?r:y(r);return i===void 0?void 0:{node:i,pointer:n}}function x(e,t){if(t===``)return!1;let n=e;for(let e of t.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(n=Array.isArray(n)?n[Number(t)]:y(n)?.[t],typeof y(n)?.$id==`string`)return!0}return!1}function Se(e,t,n){if(e[`x-makaio-value-type`]!==`evidence/v1`)return;let r=i.safeParse(t);if(!r.success)throw Error(`Invalid schema-declared evidence at ${n}`);return{evidence:r.data,dataPath:n}}function Ce(e,t,n,r){if(typeof t.$ref!=`string`)return!1;if(r)return!0;let i=xe(e,t.$ref);return i===void 0?!0:typeof i.node!=`boolean`&&S(e,i.node,n,x(e,i.pointer))}function S(e,t,n=new WeakSet,r=!1){let i=y(t);if(!i||n.has(i))return!1;n.add(i);let a=r||i!==e&&typeof i.$id==`string`;if(i[`x-makaio-value-type`]===`evidence/v1`||typeof i.$dynamicRef==`string`||Ce(e,i,n,a)||[`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`then`,`unevaluatedItems`,`unevaluatedProperties`].some(t=>S(e,i[t],n,a))||[`allOf`,`anyOf`,`oneOf`,`prefixItems`].some(t=>Array.isArray(i[t])&&i[t].some(t=>S(e,t,n,a)))||Array.isArray(i.items)&&i.items.some(t=>S(e,t,n,a)))return!0;for(let t of[`dependentSchemas`,`dependencies`,`patternProperties`,`properties`]){let r=y(i[t]);if(r&&Object.values(r).some(t=>S(e,t,n,a)))return!0}return!1}var we=class{dataSchema;matchesSchema;occurrences=new Map;visited=new WeakMap;constructor(e,t){this.dataSchema=e,this.matchesSchema=t}extract(e){return this.visit(this.dataSchema,e,`/data`),[...this.occurrences.values()]}visit(e,t,n,r=``){let i=this.visited.get(e)??new Set;if(i.has(n))return;if(i.add(n),this.visited.set(e,i),typeof e.$dynamicRef==`string`)throw Error(`Evidence discovery does not support active $dynamicRef at ${n}`);if(typeof e.$ref==`string`){if(x(this.dataSchema,r))throw Error(`Evidence discovery does not support local $ref inside nested $id resource at ${n}`);let i=xe(this.dataSchema,e.$ref);if(i===void 0)throw Error(`Cannot resolve local schema reference ${e.$ref} at ${n}`);if(typeof i.node!=`boolean`&&this.visit(i.node,t,n,i.pointer),this.dataSchema.$schema!==`https://json-schema.org/draft/2020-12/schema`)return}let a=Se(e,t,n);if(a){this.occurrences.set(n,a);return}this.visitCombiners(e,t,n,r),this.visitConditional(e,t,n,r),this.visitDependencies(e,t,n,r),this.assertSupportedApplicators(e,n,r),Array.isArray(t)?this.visitArray(e,t,n,r):typeof t==`object`&&t&&this.visitObject(e,t,n,r)}visitCombiners(e,t,n,r){for(let i of[`allOf`,`anyOf`,`oneOf`]){let a=e[i];if(Array.isArray(a))for(let[e,o]of a.entries()){let a=y(o),s=`${r}/${i}/${e}`;a&&(i===`allOf`||this.matchesSchema(this.dataSchema,s,t))&&this.visit(a,t,n,s)}}}visitConditional(e,t,n,r){let i=typeof e.if==`boolean`?e.if:y(e.if);if(i===void 0)return;let a=`${r}/if`,o=this.matchesSchema(this.dataSchema,a,t);o&&typeof i!=`boolean`&&this.visit(i,t,n,a);let s=o?`then`:`else`,c=y(e[s]);c&&this.visit(c,t,n,`${r}/${s}`)}visitDependencies(e,t,n,r){if(!(typeof t!=`object`||!t||Array.isArray(t)))for(let i of[`dependentSchemas`,`dependencies`]){let a=y(e[i]);if(a)for(let[e,o]of Object.entries(a)){let a=y(o);Object.hasOwn(t,e)&&a&&this.visit(a,t,n,`${r}/${i}/${b(e)}`)}}}assertSupportedApplicators(e,t,n){for(let r of[`unevaluatedProperties`,`unevaluatedItems`])if(S(this.dataSchema,e[r],void 0,x(this.dataSchema,n)))throw Error(`Evidence under unsupported ${r} applicator at ${t}`)}visitArray(e,t,n,r){let i=Array.isArray(e.prefixItems),a=i?e.prefixItems:Array.isArray(e.items)?e.items:[];a.forEach((e,a)=>{let o=y(e),s=i?`prefixItems`:`items`;o&&a<t.length&&this.visit(o,t[a],`${n}/${a}`,`${r}/${s}/${a}`)});let o=Array.isArray(e.items)?y(e.additionalItems):y(e.items);if(o){let i=Array.isArray(e.items)?`additionalItems`:`items`;t.slice(a.length).forEach((e,t)=>this.visit(o,e,`${n}/${a.length+t}`,`${r}/${i}`))}this.visitContains(e,t,n,r)}visitContains(e,t,n,r){let i=y(e.contains);if(!i)return;let a=`${r}/contains`;t.forEach((e,t)=>{this.matchesSchema(this.dataSchema,a,e)&&this.visit(i,e,`${n}/${t}`,a)})}visitObject(e,t,n,r){let i=y(e.properties),a=y(e.patternProperties);for(let[o,s]of Object.entries(t)){let t=b(o),c=i!==void 0&&Object.hasOwn(i,o),l=y(i?.[o]);l&&this.visit(l,s,`${n}/${t}`,`${r}/properties/${t}`);let ee=this.visitPatterns(a,o,s,`${n}/${t}`,r),u=y(e.additionalProperties);!c&&!ee&&u&&this.visit(u,s,`${n}/${t}`,`${r}/additionalProperties`)}}visitPatterns(e,t,n,r,i){let a=!1;for(let[o,s]of Object.entries(e??{})){if(!new RegExp(o,`u`).test(t))continue;a=!0;let e=y(s);e&&this.visit(e,n,r,`${i}/patternProperties/${b(o)}`)}return a}};function Te(e,t,n){return new we(e,n.matchesSchema).extract(t)}function Ee(e){let{dataSchema:t,hooks:n,...r}=e,i={$schema:`https://json-schema.org/draft/2020-12/schema`,...de(t)};ue(i);let a=p.parse({...r,dataSchema:i});if(a.kind!==e.kind)throw Error(`Artifact kind identifiers must not contain surrounding whitespace`);let o=_.fromJSONSchema(a.dataSchema),s=_.unknown().superRefine((e,t)=>{let n=o.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})}).pipe(t).superRefine((e,t)=>{try{se(e,a.titlePath)}catch(e){t.addIssue({code:`custom`,path:a.titlePath.split(`.`),message:e instanceof Error?e.message:`Artifact title must be a nonblank string`})}});return{...structuredClone(a),kind:e.kind,schemaVersion:e.schemaVersion,dataSchema:s,...n?{hooks:n}:{},toRegistration:()=>structuredClone(a)}}var De=e(fe(),1),Oe=e(pe(),1),ke=e(me(),1);function C(e){let t={allErrors:!0,strict:!1,strictSchema:!0},n=e.dataSchema.$schema===`https://json-schema.org/draft/2020-12/schema`?new Oe.default(t):new De.default(t);return(0,ke.default)(n),n.addKeyword({keyword:ae,schemaType:`string`,valid:!0}),n.compile(e.dataSchema)}function Ae(e){return e.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function je(e){let t=e.instancePath.split(`/`).slice(1).map(Ae),n=e.keyword===`required`?e.params.missingProperty:e.params.additionalProperty;return typeof n==`string`&&(e.keyword===`required`||e.keyword===`additionalProperties`)&&t.push(n),t.join(`.`)}function Me(e){if(e.keyword!==`type`)return;let t=e.params.type;if(typeof t==`string`)return t;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t.join(` | `)}const Ne=n.array();function Pe(e){if(e.keyword!==`enum`)return;let t=Ne.safeParse(e.params.allowedValues);return t.success?t.data:void 0}function Fe(e){return(e??[]).map(e=>{let t=Me(e),n=Pe(e);return{path:je(e),reason:e.message??`violates ${e.keyword}`,...t===void 0?{}:{expectedType:t},...n===void 0?{}:{allowedValues:n}}})}function Ie(e){return C(e)}function Le(e){let t=C(e);return e=>t(e)?{valid:!0}:{valid:!1,issues:Fe(t.errors)}}function Re(e){return{hooks:[...e.hooks]}}const ze=[`inline`,`summary`,`link`,`omit`],w=_.string().min(1),T=_.object({kinds:_.array(_.string().min(1)).optional(),hint:w.optional(),depth:_.number().int().min(1).max(20).optional(),nested:_.lazy(()=>E).optional()}),E=_.record(_.string().min(1),T);function D(e){return JSON.stringify([e.kind,e.id,e.revision])}const O=_.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),Be=_.object({target:u,sourceRef:f,relationType:_.string().min(1),hint:w,status:_.enum([`resolved`,`unresolved`]),reason:O.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:_.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:_.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),k=_.object({rootRef:f,refs:_.array(Be),resolved:_.array(l)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(D));n.has(D(e.rootRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(D(e.sourceRef))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`sourceRef`],message:`artifact context ref sources must have a matching revision in resolved`}),!(e.status!==`resolved`||e.target.refClass!==`artifact`)&&(n.has(D(e.target))||t.addIssue({code:_.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function Ve(e){let t=k.parse(e),n=new Map(t.resolved.map(e=>[A(e),e])),r=new Map;for(let e of t.refs){let t=A(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(A(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${A(t.rootRef)}'`);let a=He(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return Ge(a,e),e}}}function He(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:We(e,r,i,new Set([A(e)]))}}function Ue(e,t,n,r,i,a,o){let s=A(e),c=new Set(o);return c.add(s),{status:`resolved`,ref:e,artifact:t,relation:n,hint:r,children:We(e,i,a,c)}}function We(e,t,n,r){return(t.get(A(e))??[]).map(e=>{if(e.status===`unresolved`)return{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:e.reason};if(e.target.refClass!==`artifact`)throw Error(`Resolved artifact context refs must target an artifact revision`);let i=A(e.target),a=n.get(i);if(!a)throw Error(`Resolved artifact context is missing target artifact '${i}'`);return r.has(i)?{status:`unresolved`,target:e.target,relation:e.relationType,hint:e.hint,reason:`cycle-detected`}:Ue(e.target,a,e.relationType,e.hint,t,n,r)})}function Ge(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)Ge(n,t)}}function A(e){return JSON.stringify([e.kind,e.id,e.revision])}const j=[`$set`,`$unset`,`$push`,`$pull`],M=`[A-Za-z_$][A-Za-z0-9_$]*`,N=`[A-Za-z_$][A-Za-z0-9_$-]*`,Ke=`(?:0|[1-9][0-9]*)`,qe=`(?:${`\\$\\[${M}\\]`}|${Ke}|${N})`,Je=RegExp(`^${N}(?:\\.${qe})*$`),Ye=RegExp(`^${M}(?:\\.${N})*$`),Xe=RegExp(`^${Ke}$`),Ze=RegExp(`^\\$\\[(${M})\\]$`),P=_.string().regex(Je,`Expected a data-relative path of object properties, array positions, or $[filter] placeholders`);function Qe(e){let t=Ze.exec(e);return t?.[1]===void 0?Xe.test(e)?{kind:`index`,index:Number(e)}:{kind:`property`,name:e}:{kind:`filter`,placeholder:t[1]}}function $e(e){return e.split(`.`).map(Qe)}function et(e){return $e(e).flatMap(e=>e.kind===`filter`?[e.placeholder]:[])}const tt=r(_.record(_.string().regex(Ye,`Expected a filter key of the form name or name.field.path`),n),{prototypeKey:`an array filter cannot compare a __proto__ key, which JSON transport drops`,nonPlainObject:`an array filter must be a plain object of comparison keys`,symbolKey:`an array filter cannot carry symbol-keyed comparisons`,nonEnumerableKey:`an array filter cannot carry non-enumerable comparison keys`,extraArrayKey:`an array filter must be a plain object, not an array`});function nt(e){let t=new Set(Object.keys(e).map(e=>e.split(`.`)[0]));if(t.size!==1)return;let[n]=t;return n!==void 0&&n.length>0?n:void 0}function F(e,t){return r(_.record(P,t),{prototypeKey:`${e} cannot address __proto__, which JSON transport drops`,nonPlainObject:`${e} must be a plain object of path instructions`,symbolKey:`${e} cannot carry symbol-keyed instructions`,nonEnumerableKey:`${e} cannot carry non-enumerable instructions`,extraArrayKey:`${e} must be a plain object, not an array`})}const rt=_.literal(!0),it=_.strictObject({$set:F(`$set`,n).optional(),$unset:F(`$unset`,rt).optional(),$push:F(`$push`,n).optional(),$pull:F(`$pull`,n).optional(),arrayFilters:_.array(tt).optional()});function I(e){return j.flatMap(t=>Object.entries(e[t]??{}).map(([e,n])=>({operator:t,path:e,value:n})))}function at(e,t){let n=I(e),r=new Map;(e.arrayFilters??[]).forEach((e,n)=>{let i=nt(e);if(i===void 0){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`An array filter must bind exactly one placeholder name across all of its keys`});return}if(r.has(i)){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter placeholder ${i} is already bound by another filter`});return}r.set(i,n)});let i=new Set;for(let{operator:e,path:a}of n)for(let n of et(a))i.add(n),r.has(n)||t.addIssue({code:`custom`,path:[e,a],message:`Path uses placeholder $[${n}] without a matching entry in arrayFilters`});for(let[e,n]of r)i.has(e)||t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter binds placeholder ${e}, which no path uses`})}const ot=it.superRefine(at).superRefine((e,t)=>{I(e).length===0&&t.addIssue({code:`custom`,message:`Declare at least one of ${j.join(`, `)}`})}),st=it.superRefine(at),ct=_.strictObject({kind:f.shape.kind,id:f.shape.id}),lt=_.strictObject({ref:ct,baseRevision:f.shape.revision,patch:st,dryRun:_.boolean().optional(),schemaVersion:g.optional().describe(`Target schema version for the patched revision; defaults to the base revision's. Use it to migrate an artifact left at an older version by a kind bump.`),statusPath:d.optional(),representations:ie.strict().nullable().optional().describe(`Rendering hints (markdown, summary, plaintext) for the new revision. Omit to keep the previous revision's hints. An object replaces all of them, it does not merge: send every hint you want to keep. null clears them.`)}).superRefine((e,t)=>{e.schemaVersion===void 0&&I(e.patch).length===0&&t.addIssue({code:`custom`,path:[`patch`],message:`Declare at least one of ${j.join(`, `)}, or name a schemaVersion to migrate a payload that already fits`})}),ut=[`ARTIFACT_NOT_FOUND`,`BASE_REVISION_CONFLICT`,`KIND_NOT_REGISTERED`,`SCHEMA_VERSION_MISMATCH`,`PATH_NOT_DECLARED`,`PATH_NOT_RESOLVABLE`,`TARGET_NOT_A_COLLECTION`,`UNSUPPORTED_TARGET`,`NO_MATCH`,`SCHEMA_VALIDATION_FAILED`,`PAYLOAD_INVARIANT_FAILED`,`NO_CHANGE`,`STORE_REJECTED`,`HOST_FAILED`],dt=_.strictObject({path:_.string(),reason:_.string().min(1),expectedType:_.string().min(1).optional(),allowedValues:_.array(n).optional()}),ft=_.strictObject({code:_.enum(ut),message:_.string().min(1),operator:_.enum(j).optional(),path:P.optional(),currentRevision:f.shape.revision.optional(),issues:_.array(dt).optional(),repair:_.string().min(1)}).superRefine((e,t)=>{e.code===`BASE_REVISION_CONFLICT`&&e.currentRevision===void 0&&t.addIssue({code:_.ZodIssueCode.custom,message:`A BASE_REVISION_CONFLICT must name the revision the artifact carries.`,path:[`currentRevision`]})}),pt=_.strictObject({operator:_.enum(j),path:P,matched:_.number().int().positive()}),mt=_.strictObject({from:g,to:g}).refine(e=>e.to>e.from,{path:[`to`],message:`A migration moves the artifact forward to a newer schema version`}),ht=_.strictObject({ok:_.literal(!0),base:f,operations:_.array(pt),migration:mt.optional()});function gt(e,t){e.operations.length===0&&e.migration===void 0&&t.addIssue({code:`custom`,path:[`operations`],message:`A success without a migration must report at least one applied instruction`})}const _t=ht.extend({dryRun:_.literal(!0)}).superRefine(gt),vt=ht.extend({dryRun:_.literal(!1),artifact:f}).superRefine(gt),yt=_.discriminatedUnion(`dryRun`,[_t,vt]),bt=_.strictObject({ok:_.literal(!1),error:ft}),xt=_.union([yt,bt]),St=_.object({ref:oe}),Ct=_.union([_.strictObject({ok:_.literal(!0),ref:oe,areaPath:le,part:t}),_.strictObject({ok:_.literal(!1),error:ce})]),L=f.pick({kind:!0,id:!0}),R=_.number().int().positive(),z=R,B={knowledge:`valid`,commitment:`proposed`,interaction:`open`},V=_.discriminatedUnion(`category`,[_.strictObject({category:_.literal(`knowledge`),state:_.enum(h.knowledge),version:z}),_.strictObject({category:_.literal(`commitment`),state:_.enum(h.commitment),version:z}),_.strictObject({category:_.literal(`interaction`),state:_.enum(h.interaction),version:z})]).superRefine((e,t)=>{e.version===1&&e.state!==B[e.category]&&t.addIssue({code:`custom`,path:[`state`],message:`Lifecycle version 1 is reserved for the category initial state`})}),H=_.union([V,_.strictObject({category:_.literal(`record`)})]),U=_.string().trim().min(1),wt=_.strictObject({kind:U,ref:U}),W=_.discriminatedUnion(`kind`,[_.strictObject({kind:_.literal(`revision-assessment`),assessedRevision:f.shape.revision,source:wt.optional()}),_.strictObject({kind:_.literal(`handover`),source:wt})]),Tt={artifact:L,expectedVersion:z,state:m,situation:W,reason:U.optional()},G=_.strictObject(Tt),Et=_.strictObject({...Tt,actor:re}),Dt={valid:[`retired`],retired:[`valid`],proposed:[`decided`],decided:[`fulfilled`,`revoked`],fulfilled:[],revoked:[],open:[`resolved`,`closed-without-resolution`],resolved:[],"closed-without-resolution":[]};function K(e,t){return Dt[e].includes(t)}const Ot={artifact:L,lifecycle:V,actor:re,timestamp:_.number().int().nonnegative(),observedRevision:f.shape.revision},kt=_.strictObject({...Ot,operation:_.literal(`initialized`)}).superRefine((e,t)=>{(e.lifecycle.version!==1||e.lifecycle.state!==B[e.lifecycle.category])&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`Initialization requires the category initial state and version 1`})});function At(e,t){return t===`retired`||e===`retired`&&t===`valid`}const jt=`Retiring or reinstating knowledge requires a reason`,q=_.strictObject({...Ot,operation:_.literal(`transitioned`),previousState:m,situation:W,reason:G.shape.reason}).superRefine((e,t)=>{(!K(e.previousState,e.lifecycle.state)||e.lifecycle.version<=1)&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`History requires a category-compatible transition after initialization`}),At(e.previousState,e.lifecycle.state)&&!e.reason&&t.addIssue({code:`custom`,path:[`reason`],message:jt}),e.situation.kind===`revision-assessment`&&e.situation.assessedRevision!==e.observedRevision&&t.addIssue({code:`custom`,path:[`situation`],message:`An assessment cannot authorize a different observed content revision`})}),Mt=_.discriminatedUnion(`operation`,[kt,q]),J=_.discriminatedUnion(`reason`,[_.strictObject({reason:_.literal(`lifecycle-version-conflict`),expectedVersion:z,current:V,requestedState:m}),_.strictObject({reason:_.literal(`content-basis-conflict`),assessedRevision:f.shape.revision,currentRevision:f.shape.revision}),_.strictObject({reason:_.literal(`invalid-transition`),current:H,requestedState:m}),_.strictObject({reason:_.literal(`precondition-failed`),current:V,requestedState:m})]),Y=`artifact-lifecycle-rejected`;var X=class extends Error{code=Y;data;constructor(e,t){super(e),this.name=`ArtifactLifecycleError`,this.data=J.parse(t)}};function Nt(e){return e===`record`?{category:`record`}:V.parse({category:e,state:B[e],version:1})}function Pt(e){let t=H.parse(e.current),n=f.shape.revision.parse(e.currentRevision),r=Et.parse(e.command);if(t.category===`record`)throw new X(`Record artifacts do not have a lifecycle`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(r.expectedVersion!==t.version)throw new X(`Artifact lifecycle changed since the supplied baseline`,{reason:`lifecycle-version-conflict`,expectedVersion:r.expectedVersion,current:t,requestedState:r.state});if(r.situation.kind===`revision-assessment`&&r.situation.assessedRevision!==n)throw new X(`Assessed content revision is no longer current`,{reason:`content-basis-conflict`,assessedRevision:r.situation.assessedRevision,currentRevision:n});if(!K(t.state,r.state))throw new X(`Artifact lifecycle transition is not allowed`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(At(t.state,r.state)&&!r.reason)throw new X(jt,{reason:`precondition-failed`,current:t,requestedState:r.state});return V.parse({...t,state:r.state,version:t.version+1})}const Z=_.strictObject({artifact:L}),Ft=_.strictObject({lifecycle:H}),It=_.strictObject({artifact:L,afterVersion:R.optional(),limit:_.number().int().min(1).max(100).default(50)}),Lt=_.strictObject({entries:_.array(Mt).max(100),nextCursor:R.optional()}).superRefine(({entries:e,nextCursor:t},n)=>{let r=e[0],i;for(let[t,a]of e.entries()){let e=a.artifact.kind===r?.artifact.kind&&a.artifact.id===r?.artifact.id,o=i===void 0||a.lifecycle.version===i.lifecycle.version+1,s=i===void 0||a.operation===`transitioned`&&a.lifecycle.category===i.lifecycle.category&&a.previousState===i.lifecycle.state;if(!e||!o||!s){n.addIssue({code:`custom`,path:[`entries`,t],message:`History pages contain one artifact in contiguous ascending, state-linked order`});break}i=a}t!==void 0&&t!==i?.lifecycle.version&&n.addIssue({code:`custom`,path:[`nextCursor`],message:`nextCursor must equal the last returned lifecycle version`})}),Q=_.strictObject({entry:q}),Rt=Q,zt=_.strictObject({code:_.literal(Y),message:_.string().min(1),data:J});function Bt(e){return{code:e.code,message:e.message,data:e.data}}function Vt(e,t){switch(t.reason){case`content-basis-conflict`:return Wt(e,t);case`lifecycle-version-conflict`:return[...Ht(e,t),...Ut(e,t)];case`invalid-transition`:case`precondition-failed`:return[...Ht(e,t),...Gt(e,t)]}}function Ht(e,t){return t.requestedState===e.state?[]:[{path:[`requestedState`],message:`Rejection requestedState must match the rejected transition`}]}function Ut(e,t){let n=[];return t.expectedVersion!==e.expectedVersion&&n.push({path:[`expectedVersion`],message:`Version conflict baseline must match the rejected transition`}),t.current.version===e.expectedVersion&&n.push({path:[`current`,`version`],message:`Version conflict requires a current version different from the supplied baseline`}),n}function Wt(e,t){let n=[];return(e.situation.kind!==`revision-assessment`||t.assessedRevision!==e.situation.assessedRevision)&&n.push({path:[`assessedRevision`],message:`Content conflict must identify the rejected revision assessment`}),t.currentRevision===t.assessedRevision&&n.push({path:[`currentRevision`],message:`Content conflict requires a current revision different from the assessed revision`}),n}function Gt(e,t){if(t.current.category===`record`)return[];let n=[];t.current.version!==e.expectedVersion&&n.push({path:[`current`,`version`],message:`A rejection after the version check must report the supplied baseline version`});let r=K(t.current.state,t.requestedState);return t.reason===`invalid-transition`&&r&&n.push({path:[`reason`],message:`invalid-transition requires a transition the lifecycle matrix disallows`}),t.reason===`precondition-failed`&&!r&&n.push({path:[`reason`],message:`precondition-failed requires a transition the lifecycle matrix allows`}),n}const Kt=_.strictObject({transition:G,error:zt}).superRefine(({transition:e,error:t},n)=>{for(let r of Vt(e,t.data))n.addIssue({code:`custom`,path:[`error`,`data`,...r.path],message:r.message})}),qt={"lifecycle.get":{request:Z,response:Ft},"lifecycle.history":{request:It,response:Lt},"lifecycle.transition":{request:G,response:Q},"lifecycle.committed":Rt,"lifecycle.rejected":Kt},Jt={...qt,"kind.register":{request:p,response:_.object({registered:_.boolean()})},"kind.list":{request:_.object({kind:_.string().min(1).optional()}),response:_.object({kinds:_.array(p)})},"relation-type.register":{request:s,response:_.object({registered:_.boolean()})},"relation-type.list":{request:_.object({type:_.string().min(1).optional()}),response:_.object({relationTypes:_.array(s)})},create:{request:l.omit({id:!0,revision:!0,timestamp:!0}).extend({id:f.shape.id.optional()}),response:_.object({artifact:l})},revise:{request:_.object({previous:f,statusPath:d.optional(),revision:l.omit({id:!0,revision:!0,timestamp:!0})}),response:_.object({artifact:l})},patch:{request:lt,response:xt},resolve:{request:_.object({ref:f}),response:_.object({artifact:l.nullable()})},resolvePart:{request:St,response:Ct},query:{request:o,response:_.object({artifacts:_.array(l)})},compare:{request:te,response:ne},"evidence.resolve":{request:ge,response:be},resolveContext:{request:_.object({ref:f,selectors:E.optional(),maxDepth:_.number().int().min(1).max(20).default(5)}),response:_.object({context:k})},created:_.object({artifact:l}),revised:_.object({previous:f,artifact:l}),"relation.added":_.object({artifact:f,relation:c}),"observation.added":_.object({artifact:f,observation:ee}),"status.changed":_.object({artifact:f,path:_.string().min(1),previous:_.unknown().optional(),current:_.unknown().optional()}),"kind.changed":_.object({kind:_.string().min(1),schemaVersion:g})},Yt=he(`artifact`,Jt),Xt=Yt.subjects,Zt=_.discriminatedUnion(`refClass`,[f.omit({revision:!0}),a]);function Qt(e){if(e.refClass===`artifact`)return{refClass:`artifact`,kind:e.kind,id:e.id};if(e.refClass===`entity`)return{refClass:`entity`,entityType:e.entityType,id:e.id}}function $(e){return e.refClass===`artifact`?JSON.stringify([`artifact`,e.kind,e.id]):JSON.stringify([`entity`,e.entityType,e.id])}function $t(e){return e.refClass===`artifact`?`artifact:${e.kind}/${e.id}`:`entity:${e.entityType}/${e.id}`}const en=[`relation-target`];function tn(e,t){if(!e||e.length===0)return{ok:!0,rules:[]};let n=[];for(let[r,i]of e.entries()){for(let[e,a]of i.by.entries())(!en.includes(a.kind)||!t.includes(a.kind))&&n.push({ruleIndex:r,selectorIndex:e,capability:a.kind,message:`rule #${r}, selector #${e}: '${a.kind}' selectors are not supported`});i.lifecycleStates!==void 0&&!t.includes(`lifecycle-states`)&&n.push({ruleIndex:r,capability:`lifecycle-states`,message:`rule #${r}: lifecycleStates is declared but 'lifecycle-states' is not a supported capability`})}return n.length>0?{ok:!1,issues:n}:{ok:!0,rules:e}}function nn(e,t,n,r){if(e.kind===`data`)return{ruleIndex:n,selectorIndex:r,reason:`unsupported-selector`,message:`rule #${n}, selector #${r}: data-path selectors cannot be derived from relations`};let{relationType:i}=e,a=t.filter(e=>e.type===i),o=new Set,s,c;for(let e of a){let t=Qt(e.target);if(t===void 0){c=e.target.refClass;break}o.add($(t)),s=t}return c===void 0?s===void 0?{ruleIndex:n,selectorIndex:r,reason:`missing-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': no relations of this type found`}:o.size>1?{ruleIndex:n,selectorIndex:r,reason:`ambiguous-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': ${o.size} distinct targets; expected exactly one`}:{type:i,target:s}:{ruleIndex:n,selectorIndex:r,reason:`unsupported-target`,relationType:i,message:`rule #${n}, selector #${r}, relation '${i}': found a relation with refClass '${c}'; only artifact and entity targets are supported`}}function rn(e,t){let n=[],r=[];for(let[i,a]of e.entries()){let e=a.by.map((e,n)=>nn(e,t,i,n)),o=e.filter(e=>`reason`in e);if(o.length>0){r.push(...o);continue}let s=e.filter(e=>!(`reason`in e)),c=JSON.stringify(s.map(e=>[e.type,$(e.target)]));n.push({rule:a,ruleIndex:i,parts:s,serialized:c})}return{keys:n,issues:r}}function an(e){return e.parts.map(e=>`${e.type} → ${$t(e.target)}`).join(`; `)}export{yt as $,Et as A,j as B,X as C,J as D,kt as E,Nt as F,bt as G,ot as H,K as I,pt as J,dt as K,St as L,q as M,R as N,W as O,Pt as P,xt as Q,Ct as R,H as S,L as T,_t as U,tt as V,ft as W,vt as X,P as Y,lt as Z,Kt as _,Ee as _t,Qt as a,$e as at,Bt as b,be as bt,Yt as c,O as ct,Rt as d,T as dt,ct as et,zt as f,w as ft,Lt as g,Ie as gt,It as h,Le as ht,Zt as i,Qe as it,G as j,V as k,Jt as l,k as lt,Ft as m,Re as mt,rn as n,I as nt,$t as o,Ve as ot,Z as p,E as pt,mt as q,an as r,et as rt,$ as s,Be as st,tn as t,nt as tt,Xt as u,ze as ut,qt as v,Te as vt,Mt as w,Y as x,Q as y,ge as yt,ut as z};
@@ -3918,8 +3918,8 @@ declare module '@makaio/contracts' {
3918
3918
  //#region core/contracts/src/skill/schemas.d.ts
3919
3919
  /** Trigger that activated or reinjected a skill. */
3920
3920
  declare const SkillActivationTriggerSchema: z.ZodEnum<{
3921
- user: "user";
3922
3921
  auto: "auto";
3922
+ user: "user";
3923
3923
  model: "model";
3924
3924
  reinjection: "reinjection";
3925
3925
  }>;
@@ -1 +1 @@
1
- import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as ee,M as f,N as te,O as ne,P as re,Q as ie,R as p,S as m,T as ae,U as oe,V as h,W as g,X as se,Y as ce,Z as _,_ as le,a as ue,b as de,d as v,et as fe,f as pe,g as me,h as y,i as he,it as ge,j as b,k as x,l as S,m as C,nt as w,o as T,p as E,q as D,r as O,rt as k,s as A,t as j,tt as M,u as N,v as P,w as F,x as I,y as L,z as _e}from"../bus-CyrTcF8F.mjs";import{z as R}from"zod";const z={"channel.open":{request:R.object({endpoint:R.string(),token:R.string(),clientPubKey:R.string(),transports:R.array(R.string())}),response:R.object({channelId:R.string(),endpointPubKey:R.string()})}};function B(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array(t.length);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return btoa(n.join(``))}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function H(){return globalThis.crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`])}async function U(e){return B(await globalThis.crypto.subtle.exportKey(`raw`,e))}async function W(e){let t=V(e);return globalThis.crypto.subtle.importKey(`raw`,t,{name:`ECDH`,namedCurve:`P-256`},!1,[])}async function G(e,t){return globalThis.crypto.subtle.deriveKey({name:`ECDH`,public:t},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function K(e,t,n){let r=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.encrypt(a,e,i);return{iv:B(r),data:B(o)}}async function q(e,t,n){let r=V(t.iv),i=V(t.data),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.decrypt(a,e,i);return new TextDecoder().decode(o)}function J(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!1,payload:{},local:!1,channel:!1}}}function Y(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!0,payload:{},local:!1,channel:!1}}}var X=class{channelId;sharedKey;context;transportNames;cleanups=[];pendingRequests=new Set;closed=!1;constructor(e,t,n,r){this.channelId=e,this.sharedKey=t,this.context=n,this.transportNames=r;let i=J(e,`$close`);this.cleanups.push(this.registerEventHandler(i,t,e=>{this.handlePeerClose()}))}on(e,t,n){this.assertOpen();let r=this.requireKey(),i=e.$meta.isRequest?this.registerRequestHandler(e,r,t,n):this.registerEventHandler(e,r,t,n);return this.cleanups.push(i),()=>{i();let e=this.cleanups.indexOf(i);e!==-1&&this.cleanups.splice(e,1)}}once(e,t){this.assertOpen();let n=this.requireKey(),r=null,i=(e=>{let n=r;if(r=null,n){let e=this.cleanups.indexOf(n);e!==-1&&this.cleanups.splice(e,1)}return n?.(),t(e)});return r=e.$meta.isRequest?this.registerRequestHandler(e,n,i):this.registerEventHandler(e,n,i),this.cleanups.push(r),()=>{if(r){let e=r;r=null;let t=this.cleanups.indexOf(e);t!==-1&&this.cleanups.splice(t,1),e()}}}async emit(e,t){this.assertOpen();let n=this.requireKey(),r=J(this.channelId,e.subject),i=await K(n,JSON.stringify(t),`${this.channelId}:${e.subject}:evt`);await E(this.context,r,i,{...this.transportNames?{transports:[...this.transportNames]}:{}})}async request(e,t,n){this.assertOpen();let r=this.requireKey(),i=new AbortController;this.pendingRequests.add(i);try{let a=Y(this.channelId,e.subject),o=await K(r,JSON.stringify(t),`${this.channelId}:${e.subject}:req`),s=await q(r,await v(this.context,a,o,{signal:i.signal,...n?.timeout===void 0?{}:{timeout:n.timeout},...this.transportNames?{transports:[...this.transportNames]}:{}}),`${this.channelId}:${e.subject}:res`);return JSON.parse(s)}finally{this.pendingRequests.delete(i)}}async requestOptional(e,t,n){try{return{handled:!0,data:await this.request(e,t,n)}}catch(e){if(e instanceof o)return{handled:!1};throw e}}close(){if(this.closed)return;this.closed=!0;let e=this.sharedKey;if(e){let t=J(this.channelId,`$close`);K(e,JSON.stringify({}),`${this.channelId}:$close:evt`).then(e=>E(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new n(this.channelId)}requireKey(){return this.sharedKey}registerEventHandler(e,t,n,r){let i=J(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:evt`;return y(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r);return n({...e,payload:i})},r)}registerRequestHandler(e,t,n,r){let i=Y(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:req`,o=`${this.channelId}:${e.subject}:res`;return y(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r),s,c=e=>{s={value:e}},l=e=>{s={value:{...s?.value??{},...e}}},u=async()=>{let n=s;if(await e.next(),n!==void 0){s=n;return}let r=e.result;if(r!==void 0){let e=await q(t,r,o);s={value:JSON.parse(e)}}};if(await n({...e,payload:i,get result(){return s?.value},setResult:c,extendResult:l,next:u}),s!==void 0){let n=await K(t,JSON.stringify(s.value),o);e.setResult(n)}},r)}handlePeerClose(){this.closed||(this.closed=!0,this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null)}abortPendingRequests(){let e=new n(this.channelId);for(let t of this.pendingRequests)t.abort(e);this.pendingRequests.clear()}runCleanups(){for(let e of this.cleanups)try{e()}catch{}this.cleanups.length=0}};function Z(e){return e.namespaceRegistry.registerNamespace(_(`system`,z)).subjects.channel.open}function ve(e,t,n,r){let i=y(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new h(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),c=globalThis.crypto.randomUUID(),l=new Set(e.transportRegistry.names()),u=new X(c,s,e,(i.payload.transports??[]).filter(e=>l.has(e)));try{n(u),i.setResult({channelId:c,endpointPubKey:await U(a)})}catch(e){throw u.close(),e}});return{name:t,token:r.token,close:i}}async function ye(e,t,n){let r=Z(e),{publicKey:i,privateKey:a}=await H(),o=await U(i),s=n.transports!==void 0,c=s?[...n.transports]:[...e.transportRegistry.names()],l=s?{transports:c}:void 0,u=await v(e,r,{endpoint:t,token:n.token,clientPubKey:o,transports:c},l),d=await G(a,await W(u.endpointPubKey));return new X(u.channelId,d,e,c)}var be=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(g(n.reason));return}let a=t===0?void 0:setTimeout(()=>{let n=this.pending.get(e);n!==void 0&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(new f(e,t)))},t);if(this.pending.set(e,{resolve:r,reject:i,timeoutId:a,removeAbortListener:void 0}),n){let t=()=>{this.reject(e,g(n.reason))};n.addEventListener(`abort`,t,{once:!0});let r=()=>{n.removeEventListener(`abort`,t)},i=this.pending.get(e);i&&(i.removeAbortListener=r)}n?.aborted&&this.reject(e,g(n.reason))})}resolve(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.resolve(t))}reject(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(t))}cancel(e,t){this.reject(e,t??g(void 0))}rejectAll(e){for(let[t,n]of this.pending.entries())clearTimeout(n.timeoutId),n.removeAbortListener?.(),n.reject(e);this.pending.clear()}cleanup(){this.rejectAll(Error(`Transport disconnected`))}};const xe=_(`bus:lifecycle`,ue).subjects;function Q(e,t){let n={},r={},i={};for(let[t,a]of e)n[t]=a.priorities,r[t]=a.deliveryClass??`relayable`,a.filter!==void 0&&(i[t]=a.filter);return{type:`subscribe`,...t===void 0?{}:{ackId:t},subjects:n,deliveryClasses:r,...Object.keys(i).length>0&&{filters:i}}}function Se(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Ce(e,t){let n=e.trim();if(n.length===0||n.startsWith(`extension:`))throw Error(`Invalid extensionName: expected a non-empty extension name without the "extension:" prefix.`);let r=n;return{..._(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function we(){let e=new Map;return{register(t){let n=$(t.namespace,t.subject);return e.set(n,t),()=>{e.get(n)===t&&e.delete(n)}},get(t,n){return e.get($(t,n))}}}const Te=t.fact.$meta.namespace,Ee=t.fact.subject;function De(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function Oe(e,t,n,r,i,a){let o=C({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Te,subject:Ee,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function ke(e,t,n,r,i){return async function(a,o){if(!De(a))return!0;if(await Oe(e,a,t,n,r,i),a.type===`request`)throw Error(`Projected telemetry transport cannot satisfy request responses; exclude it from request routing.`);return a.type===`broadcast`?[]:!0}}function Ae(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:ke(t,n,r,i,a),onReceive(e){return t.onReceive(async()=>{})},connect(){return t.connect()},disconnect(){return t.disconnect()},subscribe(){return Promise.resolve()},unsubscribe(){return Promise.resolve()},get ready(){return t.ready},get onNewReadySession(){return t.onNewReadySession},set onNewReadySession(e){t.onNewReadySession=e},get onConnected(){return t.onConnected},set onConnected(e){t.onConnected=e},get onDisconnected(){return t.onDisconnected},set onDisconnected(e){t.onDisconnected=e},isReady(){return t.isReady?.()??!0},cancelRequest(e,n){t.cancelRequest?.(e,n)},onBroadcastResults(e,n,r){t.onBroadcastResults?.(e,n,r)}};return t.reconnect&&(o.reconnect=()=>t.reconnect()),o}export{c as BusAbortError,s as BusError,xe as BusLifecycle,ee as CONNECTION_LOST_ERROR_CODE,h as ChannelAuthError,n as ChannelClosedError,_e as ChannelOnlyError,p as ConnectionLostError,be as CorrelationTracker,pe as DEFAULT_REQUEST_TIMEOUT_MS,L as LOCAL_ORIGIN,l as LocalSubjectError,j as MakaioBus,re as NO_HANDLER_ERROR_CODE,o as NoHandlerError,N as OnceAbortError,de as REMOTE_ORIGIN,te as RequestError,z as SystemChannelSchemas,f as TimeoutError,b as ValidationError,le as __resetWarnedSubjects,Q as buildSubscribeMessage,Se as buildUnsubscribeMessage,k as channelSubject,e as collectorOnlySubject,O as createBusContext,he as createBusInstance,ve as createChannelEndpoint,Ce as createExtensionNamespace,S as createFilteredBus,Ae as createProjectedTelemetryTransport,we as createSubjectTelemetryProjectorRegistry,fe as defaultTransports,T as defineSubjectExtension,ae as deserializeTransportError,A as extendSubject,a as findInErrorChain,ie as getFullSubjectForSubjectDefinition,d as getPath,i as getSubjectFromBusMessage,I as handleCorrelationResponse,M as hostLocalRequest,ne as isNoHandlerErrorForSubject,oe as isRequestCancellation,ge as isRequestSchema,w as localSubject,ce as matchesAnySubscription,D as matchesFilter,se as matchesSubscription,u as mergeFilters,ye as openChannel,P as parseBusUrl,C as projectSubjectTelemetryFacts,m as serializeTransportError,r as shouldReceiveMessage,F as trackMessageCorrelation,x as transportErrorData,me as waitForSubscriptionPropagation};
1
+ import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as ee,M as f,N as te,O as ne,P as re,Q as ie,R as p,S as m,T as ae,U as oe,V as h,W as g,X as se,Y as ce,Z as _,_ as le,a as ue,b as de,d as v,et as fe,f as pe,g as me,h as y,i as he,it as ge,j as b,k as x,l as S,m as C,nt as w,o as T,p as E,q as D,r as O,rt as k,s as A,t as j,tt as M,u as N,v as P,w as F,x as I,y as L,z as _e}from"../bus-CPlKKH4v.mjs";import{z as R}from"zod";const z={"channel.open":{request:R.object({endpoint:R.string(),token:R.string(),clientPubKey:R.string(),transports:R.array(R.string())}),response:R.object({channelId:R.string(),endpointPubKey:R.string()})}};function B(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array(t.length);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return btoa(n.join(``))}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function H(){return globalThis.crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`])}async function U(e){return B(await globalThis.crypto.subtle.exportKey(`raw`,e))}async function W(e){let t=V(e);return globalThis.crypto.subtle.importKey(`raw`,t,{name:`ECDH`,namedCurve:`P-256`},!1,[])}async function G(e,t){return globalThis.crypto.subtle.deriveKey({name:`ECDH`,public:t},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function K(e,t,n){let r=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.encrypt(a,e,i);return{iv:B(r),data:B(o)}}async function q(e,t,n){let r=V(t.iv),i=V(t.data),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.decrypt(a,e,i);return new TextDecoder().decode(o)}function J(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!1,payload:{},local:!1,channel:!1}}}function Y(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!0,payload:{},local:!1,channel:!1}}}var X=class{channelId;sharedKey;context;transportNames;cleanups=[];pendingRequests=new Set;closed=!1;constructor(e,t,n,r){this.channelId=e,this.sharedKey=t,this.context=n,this.transportNames=r;let i=J(e,`$close`);this.cleanups.push(this.registerEventHandler(i,t,e=>{this.handlePeerClose()}))}on(e,t,n){this.assertOpen();let r=this.requireKey(),i=e.$meta.isRequest?this.registerRequestHandler(e,r,t,n):this.registerEventHandler(e,r,t,n);return this.cleanups.push(i),()=>{i();let e=this.cleanups.indexOf(i);e!==-1&&this.cleanups.splice(e,1)}}once(e,t){this.assertOpen();let n=this.requireKey(),r=null,i=(e=>{let n=r;if(r=null,n){let e=this.cleanups.indexOf(n);e!==-1&&this.cleanups.splice(e,1)}return n?.(),t(e)});return r=e.$meta.isRequest?this.registerRequestHandler(e,n,i):this.registerEventHandler(e,n,i),this.cleanups.push(r),()=>{if(r){let e=r;r=null;let t=this.cleanups.indexOf(e);t!==-1&&this.cleanups.splice(t,1),e()}}}async emit(e,t){this.assertOpen();let n=this.requireKey(),r=J(this.channelId,e.subject),i=await K(n,JSON.stringify(t),`${this.channelId}:${e.subject}:evt`);await E(this.context,r,i,{...this.transportNames?{transports:[...this.transportNames]}:{}})}async request(e,t,n){this.assertOpen();let r=this.requireKey(),i=new AbortController;this.pendingRequests.add(i);try{let a=Y(this.channelId,e.subject),o=await K(r,JSON.stringify(t),`${this.channelId}:${e.subject}:req`),s=await q(r,await v(this.context,a,o,{signal:i.signal,...n?.timeout===void 0?{}:{timeout:n.timeout},...this.transportNames?{transports:[...this.transportNames]}:{}}),`${this.channelId}:${e.subject}:res`);return JSON.parse(s)}finally{this.pendingRequests.delete(i)}}async requestOptional(e,t,n){try{return{handled:!0,data:await this.request(e,t,n)}}catch(e){if(e instanceof o)return{handled:!1};throw e}}close(){if(this.closed)return;this.closed=!0;let e=this.sharedKey;if(e){let t=J(this.channelId,`$close`);K(e,JSON.stringify({}),`${this.channelId}:$close:evt`).then(e=>E(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new n(this.channelId)}requireKey(){return this.sharedKey}registerEventHandler(e,t,n,r){let i=J(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:evt`;return y(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r);return n({...e,payload:i})},r)}registerRequestHandler(e,t,n,r){let i=Y(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:req`,o=`${this.channelId}:${e.subject}:res`;return y(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r),s,c=e=>{s={value:e}},l=e=>{s={value:{...s?.value??{},...e}}},u=async()=>{let n=s;if(await e.next(),n!==void 0){s=n;return}let r=e.result;if(r!==void 0){let e=await q(t,r,o);s={value:JSON.parse(e)}}};if(await n({...e,payload:i,get result(){return s?.value},setResult:c,extendResult:l,next:u}),s!==void 0){let n=await K(t,JSON.stringify(s.value),o);e.setResult(n)}},r)}handlePeerClose(){this.closed||(this.closed=!0,this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null)}abortPendingRequests(){let e=new n(this.channelId);for(let t of this.pendingRequests)t.abort(e);this.pendingRequests.clear()}runCleanups(){for(let e of this.cleanups)try{e()}catch{}this.cleanups.length=0}};function Z(e){return e.namespaceRegistry.registerNamespace(_(`system`,z)).subjects.channel.open}function ve(e,t,n,r){let i=y(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new h(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),c=globalThis.crypto.randomUUID(),l=new Set(e.transportRegistry.names()),u=new X(c,s,e,(i.payload.transports??[]).filter(e=>l.has(e)));try{n(u),i.setResult({channelId:c,endpointPubKey:await U(a)})}catch(e){throw u.close(),e}});return{name:t,token:r.token,close:i}}async function ye(e,t,n){let r=Z(e),{publicKey:i,privateKey:a}=await H(),o=await U(i),s=n.transports!==void 0,c=s?[...n.transports]:[...e.transportRegistry.names()],l=s?{transports:c}:void 0,u=await v(e,r,{endpoint:t,token:n.token,clientPubKey:o,transports:c},l),d=await G(a,await W(u.endpointPubKey));return new X(u.channelId,d,e,c)}var be=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(g(n.reason));return}let a=t===0?void 0:setTimeout(()=>{let n=this.pending.get(e);n!==void 0&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(new f(e,t)))},t);if(this.pending.set(e,{resolve:r,reject:i,timeoutId:a,removeAbortListener:void 0}),n){let t=()=>{this.reject(e,g(n.reason))};n.addEventListener(`abort`,t,{once:!0});let r=()=>{n.removeEventListener(`abort`,t)},i=this.pending.get(e);i&&(i.removeAbortListener=r)}n?.aborted&&this.reject(e,g(n.reason))})}resolve(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.resolve(t))}reject(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(t))}cancel(e,t){this.reject(e,t??g(void 0))}rejectAll(e){for(let[t,n]of this.pending.entries())clearTimeout(n.timeoutId),n.removeAbortListener?.(),n.reject(e);this.pending.clear()}cleanup(){this.rejectAll(Error(`Transport disconnected`))}};const xe=_(`bus:lifecycle`,ue).subjects;function Q(e,t){let n={},r={},i={};for(let[t,a]of e)n[t]=a.priorities,r[t]=a.deliveryClass??`relayable`,a.filter!==void 0&&(i[t]=a.filter);return{type:`subscribe`,...t===void 0?{}:{ackId:t},subjects:n,deliveryClasses:r,...Object.keys(i).length>0&&{filters:i}}}function Se(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Ce(e,t){let n=e.trim();if(n.length===0||n.startsWith(`extension:`))throw Error(`Invalid extensionName: expected a non-empty extension name without the "extension:" prefix.`);let r=n;return{..._(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function we(){let e=new Map;return{register(t){let n=$(t.namespace,t.subject);return e.set(n,t),()=>{e.get(n)===t&&e.delete(n)}},get(t,n){return e.get($(t,n))}}}const Te=t.fact.$meta.namespace,Ee=t.fact.subject;function De(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function Oe(e,t,n,r,i,a){let o=C({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Te,subject:Ee,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function ke(e,t,n,r,i){return async function(a,o){if(!De(a))return!0;if(await Oe(e,a,t,n,r,i),a.type===`request`)throw Error(`Projected telemetry transport cannot satisfy request responses; exclude it from request routing.`);return a.type===`broadcast`?[]:!0}}function Ae(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:ke(t,n,r,i,a),onReceive(e){return t.onReceive(async()=>{})},connect(){return t.connect()},disconnect(){return t.disconnect()},subscribe(){return Promise.resolve()},unsubscribe(){return Promise.resolve()},get ready(){return t.ready},get onNewReadySession(){return t.onNewReadySession},set onNewReadySession(e){t.onNewReadySession=e},get onConnected(){return t.onConnected},set onConnected(e){t.onConnected=e},get onDisconnected(){return t.onDisconnected},set onDisconnected(e){t.onDisconnected=e},isReady(){return t.isReady?.()??!0},cancelRequest(e,n){t.cancelRequest?.(e,n)},onBroadcastResults(e,n,r){t.onBroadcastResults?.(e,n,r)}};return t.reconnect&&(o.reconnect=()=>t.reconnect()),o}export{c as BusAbortError,s as BusError,xe as BusLifecycle,ee as CONNECTION_LOST_ERROR_CODE,h as ChannelAuthError,n as ChannelClosedError,_e as ChannelOnlyError,p as ConnectionLostError,be as CorrelationTracker,pe as DEFAULT_REQUEST_TIMEOUT_MS,L as LOCAL_ORIGIN,l as LocalSubjectError,j as MakaioBus,re as NO_HANDLER_ERROR_CODE,o as NoHandlerError,N as OnceAbortError,de as REMOTE_ORIGIN,te as RequestError,z as SystemChannelSchemas,f as TimeoutError,b as ValidationError,le as __resetWarnedSubjects,Q as buildSubscribeMessage,Se as buildUnsubscribeMessage,k as channelSubject,e as collectorOnlySubject,O as createBusContext,he as createBusInstance,ve as createChannelEndpoint,Ce as createExtensionNamespace,S as createFilteredBus,Ae as createProjectedTelemetryTransport,we as createSubjectTelemetryProjectorRegistry,fe as defaultTransports,T as defineSubjectExtension,ae as deserializeTransportError,A as extendSubject,a as findInErrorChain,ie as getFullSubjectForSubjectDefinition,d as getPath,i as getSubjectFromBusMessage,I as handleCorrelationResponse,M as hostLocalRequest,ne as isNoHandlerErrorForSubject,oe as isRequestCancellation,ge as isRequestSchema,w as localSubject,ce as matchesAnySubscription,D as matchesFilter,se as matchesSubscription,u as mergeFilters,ye as openChannel,P as parseBusUrl,C as projectSubjectTelemetryFacts,m as serializeTransportError,r as shouldReceiveMessage,F as trackMessageCorrelation,x as transportErrorData,me as waitForSubscriptionPropagation};