@mcp-com-ai/plugin-capability-graph 1.2.0 → 1.3.0

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 (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -137,7 +137,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
137
137
  `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
138
138
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0;if((Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment")i?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Ji(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,n=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&t.sep&&!t.value){let r=[];for(let s=0;s<t.sep.length;++s){let o=t.sep[s];switch(o.type){case"newline":r.push(s);break;case"space":break;case"comment":if(o.indent>e.indent)r.length=0;break;default:r.length=0}}if(r.length>=2)a=t.sep.splice(r[1])}switch(this.type){case"anchor":case"tag":if(n||t.value)a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(n||t.value)a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(Se(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let r=st(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Se(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Zo(t.key)&&!Se(t.sep,"newline")){let r=st(t.start),{key:s,sep:o}=t;o.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:s,sep:o}]})}else if(a.length>0)t.sep=t.sep.concat(a,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||n)e.items.push({start:a,key:null,sep:[this.sourceToken]});else if(Se(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);if(n||t.value)e.items.push({start:a,key:r,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(r);else Object.assign(t,{key:r,sep:[]}),this.onKeyLine=!0;return}default:{let r=this.startBlockValue(e);if(r){if(r.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Se(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(i)e.items.push({start:a});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0;if((Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment")i?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Ji(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||Se(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:n,sep:[]});else if(t.sep)this.stack.push(n);else Object.assign(t,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);if(i)this.stack.push(i);else yield*this.pop(),yield*this.step()}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=Ui(i),a=st(n);Qo(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
139
139
  `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
140
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ui(e),i=st(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Ui(e),i=st(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((i)=>i.type==="newline"||i.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}Fb.Parser=el});var rl=C(function(Bb){var tl=Na(),Db=Nt(),Mt=$t(),Lb=zn(),Mb=I(),Rb=za(),il=Ba();function nl(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Rb.LineCounter||null,prettyErrors:t}}function _b(e,t={}){let{lineCounter:i,prettyErrors:n}=nl(t),a=new il.Parser(i?.addNewLine),r=new tl.Composer(t),s=Array.from(r.compose(a.parse(e)));if(n&&i)for(let o of s)o.errors.forEach(Mt.prettifyError(e,i)),o.warnings.forEach(Mt.prettifyError(e,i));if(s.length>0)return s;return Object.assign([],{empty:!0},r.streamInfo())}function al(e,t={}){let{lineCounter:i,prettyErrors:n}=nl(t),a=new il.Parser(i?.addNewLine),r=new tl.Composer(t),s=null;for(let o of r.compose(a.parse(e),!0,e.length))if(!s)s=o;else if(s.options.logLevel!=="silent"){s.errors.push(new Mt.YAMLParseError(o.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(n&&i)s.errors.forEach(Mt.prettifyError(e,i)),s.warnings.forEach(Mt.prettifyError(e,i));return s}function jb(e,t,i){let n=void 0;if(typeof t==="function")n=t;else if(i===void 0&&t&&typeof t==="object")i=t;let a=al(e,i);if(!a)return null;if(a.warnings.forEach((r)=>Lb.warn(a.options.logLevel,r)),a.errors.length>0)if(a.options.logLevel!=="silent")throw a.errors[0];else a.errors=[];return a.toJS(Object.assign({reviver:n},i))}function zb(e,t,i){let n=null;if(typeof t==="function"||Array.isArray(t))n=t;else if(i===void 0&&t)i=t;if(typeof i==="string")i=i.length;if(typeof i==="number"){let a=Math.round(i);i=a<1?void 0:a>8?{indent:8}:{indent:a}}if(e===void 0){let{keepUndefined:a}=i??t??{};if(!a)return}if(Mb.isDocument(e)&&!n)return e.toString(i);return new Db.Document(e,n,i).toString(i)}Bb.parse=jb;Bb.parseAllDocuments=_b;Bb.parseDocument=al;Bb.stringify=zb});import{pkg as Hw,registerCapabilityGraphClassifierFactory as Ww,registerCapabilityGraphRuntimeProvider as Xw}from"@mcp-com-ai/core";import{definePlugin as Qw,HAPI_CLI_API_VERSION as Zw}from"@mcp-com-ai/plugin-sdk";var lr="@mcp-com-ai/plugin-capability-graph",cr="1.2.0",pr="Compile OpenAPI documents into deterministic HAPI capability graphs.";var $l=new Set(["a","an","and","as","at","be","by","for","from","in","it","of","on","or","the","them","this","to","user","without"]);class fe{id="deterministic-v1";async classify(e){ur(e.signal);let t=[],i=e.query.trim();if(!i)return{outcome:"no-match",matches:[],diagnostics:t};if(i.length>2000)return{outcome:"no-match",matches:[],diagnostics:[{code:"query-too-long",severity:"error",message:"Capability graph queries are limited to 2000 characters"}]};let n=new Map(e.graph.operations.map((c)=>[c.id,c])),a=new Map(e.graph.capabilities.map((c)=>[c.id,c.label])),r=e.mode==="regex"?Ll(i,t):void 0;if(e.mode==="regex"&&!r)return{outcome:"no-match",matches:[],diagnostics:t};let s=[];for(let c of e.candidates){ur(e.signal);let p=n.get(c.operationId);if(!p||!Be(p,e.principal))continue;let d=r?ql(r,c.toolName,p,a):Fl(i,c.toolName,p,a);if(d.score<=0)continue;s.push({toolName:c.toolName,operationId:p.id,score:d.score,reason:d.reason})}s.sort(Rl);let o=Ml(e.limit),l=s.slice(0,o);return{outcome:l.length>0?"ranked":"no-match",matches:l,diagnostics:t}}}function Be(e,t){if(e.authorization.length===0)return!0;if(!jl(t))return t===void 0;if(t.authorizedOperationIds)return t.authorizedOperationIds.includes(e.id);let i=new Set(t.scopes??[]),n=t.schemes??{};return e.authorization.some((a)=>a.schemes.every((r)=>{let s=n[r.scheme];if(s){let o=new Set(s);return r.scopes.every((l)=>o.has(l))}return r.scopes.length>0&&r.scopes.every((o)=>i.has(o))}))}function Fl(e,t,i,n){let a=on(e),r=fr(t,i,n),s=0,o=[];for(let l of r.positive){let c=dr(a,on(l.text));if(c===0)continue;s+=c*l.weight,o.push(l.label)}for(let l of i.avoidWhen){let c=dr(a,on(l));if(c>0)s-=c*100,o.push("avoid-when penalty")}return{score:_l(s),reason:[...new Set(o)].join(", ")||"no lexical overlap"}}function ql(e,t,i,n){let a=fr(t,i,n).positive.map((r)=>r.text).join(" ");return e.lastIndex=0,e.test(a)?{score:1,reason:"regex match"}:{score:0,reason:"no regex match"}}function fr(e,t,i){let n=t.capabilityIds.flatMap((o)=>[o,i.get(o)??""]).join(" "),a=t.inputs.flatMap((o)=>[o.name,o.description??""]).join(" "),r=t.outputs.flatMap((o)=>[o.description??"",...o.fields]).join(" "),s=t.bodyVariants.map((o)=>`${o.title??""} ${JSON.stringify(o.schema)}`).join(" ");return{positive:[{text:`${e} ${t.id} ${t.sourceOperationId??""}`,weight:8,label:"operation identity"},{text:n,weight:6,label:"capability taxonomy"},{text:t.purpose,weight:5,label:"purpose"},{text:t.useWhen.join(" "),weight:5,label:"use-when"},{text:a,weight:2,label:"inputs"},{text:s,weight:5,label:"body variants"},{text:r,weight:2,label:"outputs"},{text:t.prerequisites.join(" "),weight:1,label:"prerequisites"}]}}function on(e){let i=e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().match(/[\p{L}\p{N}]+/gu)??[];return new Set(i.map(Dl).filter((n)=>n.length>1&&!$l.has(n)))}function Dl(e){if(e.length>5&&e.endsWith("ing")){let t=e.slice(0,-3);return t.endsWith("s")?`${t}e`:t}if(e.length>4&&e.endsWith("ed"))return e.slice(0,-2);if(e.length>3&&e.endsWith("s"))return e.slice(0,-1);return e}function dr(e,t){let i=0;for(let n of e)if(t.has(n))i++;return i}function Ll(e,t){try{return new RegExp(e,"iu")}catch{t.push({code:"invalid-regex",severity:"error",message:`Invalid capability graph regex: ${e}`});return}}function Ml(e){if(!Number.isFinite(e))return 5;return Math.min(50,Math.max(1,Math.floor(e)))}function Rl(e,t){return t.score-e.score||e.operationId.localeCompare(t.operationId)||e.toolName.localeCompare(t.toolName)}function _l(e){return Math.round(e*1000)/1000}function ur(e){if(!e?.aborted)return;if(typeof e.throwIfAborted==="function")e.throwIfAborted();throw new DOMException("Capability graph classification aborted","AbortError")}function jl(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var pn="x-hapi-planning",zl=Object.freeze({type:"object",additionalProperties:!1,required:["produces"],properties:{requires:{type:"array",items:{$ref:"#/$defs/fact"}},produces:{type:"array",minItems:1,items:{$ref:"#/$defs/fact"}},removes:{type:"array",items:{$ref:"#/$defs/fact"}},cost:{type:"number",minimum:0}},$defs:{fact:{type:"object",additionalProperties:!1,required:["predicate"],properties:{predicate:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$"},value:{}}}}}),Bl=new Set(["read","create","update","delete","action"]),yr=["side-effecting","destructive","idempotent","requires-confirmation"];function gr(e,t,i,n){return{capabilities:Jl(e,t,i,n),intent:Yl(e,t,i,n),effects:Hl(e,t,i,n),prerequisites:Wl(e,t,i,n),planning:br(e,t,i,n)}}function br(e,t,i,n){if(!("x-hapi-planning"in e))return;let r=e["x-hapi-planning"],s=`${t}/x-hapi-planning`;if(!he(r)){A(n,i,s,"invalid-planning","x-hapi-planning must be an object");return}let o=new Set(["requires","produces","removes","cost"]),l=Object.keys(r).filter((h)=>!o.has(h));if(l.length>0){A(n,i,s,"invalid-planning-field",`x-hapi-planning contains unknown field${l.length===1?"":"s"}: ${l.sort().join(", ")}`);return}let c=Ee(r.requires??[],`${s}/requires`,i,n),p=Ee(r.produces,`${s}/produces`,i,n),d=Ee(r.removes??[],`${s}/removes`,i,n),u=r.cost??1;if(!Array.isArray(r.produces)||r.produces.length===0)A(n,i,`${s}/produces`,"invalid-planning-produces","x-hapi-planning.produces must be a non-empty array of canonical facts");if(typeof u!=="number"||!Number.isFinite(u)||u<0)A(n,i,`${s}/cost`,"invalid-planning-cost","x-hapi-planning.cost must be a finite nonnegative number");if(!c||!p||!d||typeof u!=="number")return;let f=new Set(p.map(ie));if(d.filter((h)=>f.has(ie(h))).length>0){A(n,i,s,"conflicting-planning-fact","x-hapi-planning cannot produce and remove the same fact");return}if(!Number.isFinite(u)||u<0||p.length===0)return;return{requires:c,produces:p,removes:d,cost:u}}var Ue="x-hapi-outcome";function Kl(e){return/^2(?:\d\d|xx)$/i.test(e)}function Cr(e,t,i,n,a){let r=Ue;if(Kl(i)){A(a,n,t,"outcome-on-success-response",`${r} cannot be declared on success response ${i}; use x-hapi-planning`);return}if(!he(e)){A(a,n,t,"invalid-outcome",`${r} must be an object`);return}let s=Object.keys(e).filter((p)=>p!=="produces"&&p!=="removes");if(s.length>0){A(a,n,t,"invalid-outcome-field",`${r} contains unknown field${s.length===1?"":"s"}: ${s.sort().join(", ")}`);return}let o=Ee(e.produces??[],`${t}/produces`,n,a),l=Ee(e.removes??[],`${t}/removes`,n,a);if(!o||!l)return;if(o.length===0&&l.length===0){A(a,n,t,"empty-outcome",`${r} must produce or remove at least one fact`);return}let c=new Set(o.map(ie));if(l.some((p)=>c.has(ie(p)))){A(a,n,t,"conflicting-outcome-fact",`${r} cannot produce and remove the same fact`);return}return{produces:o,removes:l}}var Jt="x-hapi-client-facts";function wr(e,t){let i=Jt,n=`/${i}`;if(!Array.isArray(e)){t.push({code:"invalid-client-facts",severity:"error",message:`${i} must be an array of facts`,pointer:n});return}let a=[],r=new Set;for(let[s,o]of e.entries()){let l=`${n}/${s}`,c=(m,g)=>t.push({code:m,severity:"error",message:g,pointer:l});if(!he(o)){c("invalid-client-fact","A client fact must be an object");continue}let p=Object.keys(o).filter((m)=>!["predicate","value","description"].includes(m));if(p.length){c("invalid-client-fact-field",`A client fact contains unknown field${p.length===1?"":"s"}: ${p.sort().join(", ")}`);continue}if(o.description!==void 0&&(typeof o.description!=="string"||o.description.trim()==="")){c("invalid-client-fact-description","description must be a non-empty string");continue}let{description:d,...u}=o,y=Ee([u],l,"document",t)?.[0];if(!y)continue;let h=ie(y);if(r.has(h)){c("duplicate-client-fact","Client facts cannot contain duplicates");continue}r.add(h),a.push({fact:y,...typeof d==="string"?{description:d.trim()}:{},pointer:l})}return a.sort((s,o)=>ie(s.fact).localeCompare(ie(o.fact)))}var ye="x-hapi-event";function vr(e,t,i,n){let a=ye;if(!he(e)){A(n,i,t,"invalid-event",`${a} must be an object`);return}let r=Object.keys(e).filter((s)=>s!=="produces");if(r.length>0){A(n,i,t,"invalid-event-field",`${a} contains unknown field${r.length===1?"":"s"}: ${r.sort().join(", ")}`);return}if(!Array.isArray(e.produces)||e.produces.length===0){A(n,i,`${t}/produces`,"invalid-event-produces",`${a}.produces must be a non-empty array of canonical facts`);return}return Ee(e.produces,`${t}/produces`,i,n)}function Ee(e,t,i,n){if(!Array.isArray(e)){A(n,i,t,"invalid-planning-facts","Planning facts must be an array");return}let a=[];for(let[s,o]of e.entries()){let l=`${t}/${s}`;if(!he(o)||Object.keys(o).some((c)=>c!=="predicate"&&c!=="value")||typeof o.predicate!=="string"||!Ul.test(o.predicate)||Object.hasOwn(o,"value")&&!cn(o.value)){A(n,i,l,"invalid-planning-fact","A planning fact requires a canonical lowercase predicate and optional JSON-safe value");continue}a.push({predicate:o.predicate,...Object.hasOwn(o,"value")?{value:o.value}:{}})}if(a.length!==e.length)return;let r=a.map(ie);if(new Set(r).size!==r.length){A(n,i,t,"duplicate-planning-fact","Planning fact arrays cannot contain duplicates");return}return a.sort((s,o)=>ie(s).localeCompare(ie(o)))}var Ul=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;function ie(e){return`${e.predicate}:${ln(e.value??null)}`}function ln(e){if(Array.isArray(e))return`[${e.map(ln).join(",")}]`;if(he(e))return`{${Object.keys(e).sort().map((t)=>`${JSON.stringify(t)}:${ln(e[t])}`).join(",")}}`;return JSON.stringify(e)}function cn(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(!e||typeof e!=="object"||t.has(e))return!1;let i=new Set(t).add(e);if(Array.isArray(e))return e.every((n)=>cn(n,i));if(Object.getPrototypeOf(e)!==Object.prototype)return!1;return Object.values(e).every((n)=>cn(n,i))}function Jl(e,t,i,n){if(!("x-hapi-capability"in e))return;let r=e["x-hapi-capability"],s=typeof r==="string"?[r]:r;if(!Xl(s)){A(n,i,`${t}/x-hapi-capability`,"invalid-capability","x-hapi-capability must be a non-empty string or array of non-empty strings");return}return Ut(s.map((o)=>o.trim()))}function Yl(e,t,i,n){if(!("x-hapi-intent"in e))return;let r=e["x-hapi-intent"];if(!he(r)){A(n,i,`${t}/x-hapi-intent`,"invalid-intent","x-hapi-intent must be an object");return}let s=Object.keys(r).filter((c)=>!["use-when","avoid-when"].includes(c)),o=r["use-when"]??[],l=r["avoid-when"]??[];if(s.length>0||!Kt(o)||!Kt(l)){A(n,i,`${t}/x-hapi-intent`,"invalid-intent","x-hapi-intent accepts only use-when and avoid-when arrays of non-empty strings");return}return{useWhen:Ut(o.map((c)=>c.trim())),avoidWhen:Ut(l.map((c)=>c.trim()))}}function Hl(e,t,i,n){if(!("x-hapi-effects"in e))return;let r=e["x-hapi-effects"];if(!he(r)){A(n,i,`${t}/x-hapi-effects`,"invalid-effects","x-hapi-effects must be an object");return}let s=new Set(["mode",...yr]),o=r.mode,l=yr.find((p)=>r[p]!==void 0&&typeof r[p]!=="boolean");if(typeof o!=="string"||!Bl.has(o)||l||Object.keys(r).some((p)=>!s.has(p))){A(n,i,`${t}/x-hapi-effects`,"invalid-effects","x-hapi-effects requires a valid mode and accepts only boolean effect flags");return}let c=Ke(o);return{mode:o,sideEffecting:hr(r,"side-effecting",c.sideEffecting),destructive:hr(r,"destructive",c.destructive),idempotent:mr(r,"idempotent",c.idempotent),requiresConfirmation:mr(r,"requires-confirmation",c.requiresConfirmation)}}function Wl(e,t,i,n){if(!("x-hapi-prerequisites"in e))return;let r=e["x-hapi-prerequisites"];if(!Kt(r)){A(n,i,`${t}/x-hapi-prerequisites`,"invalid-prerequisites","x-hapi-prerequisites must be an array of non-empty strings");return}return Ut(r.map((s)=>s.trim()))}function xr(e){let t=e.toLowerCase();if(["get","head","options"].includes(t))return Ke("read");if(t==="post")return Ke("create");if(t==="delete")return Ke("delete");if(["put","patch"].includes(t))return{...Ke("update"),idempotent:t==="put"};return Ke("action")}function Ke(e){let t=e==="read",i=e==="delete";return{mode:e,sideEffecting:!t,destructive:i,idempotent:t||e==="delete",requiresConfirmation:i}}function A(e,t,i,n,a){e.push({code:n,severity:"error",message:a,pointer:i,operationId:t})}function hr(e,t,i){return typeof e[t]==="boolean"?e[t]:i}function mr(e,t,i){return typeof e[t]==="boolean"?e[t]:i}function he(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}function Kt(e){return Array.isArray(e)&&e.every((t)=>typeof t==="string"&&t.trim()!=="")}function Xl(e){return Kt(e)&&e.length>0}function Ut(e){return[...new Set(e)].sort((t,i)=>t.localeCompare(i))}var Yt=["delete","get","head","options","patch","post","put","trace"];function S(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}function P(e){return typeof e==="string"&&e.trim()!==""?e.trim():void 0}function oe(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function dn(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function H(e,t){if(!S(t)||typeof t.$ref!=="string"||!t.$ref.startsWith("#/"))return t;let i=e;for(let n of t.$ref.slice(2).split("/").map(dn)){if(!S(i))return t;i=i[n]}return i??t}function kr(e,t,i){let n=[],a=e.webhooks;if(S(a))for(let r of Object.keys(a).sort()){let s=H(e,a[r]),o=`/webhooks/${oe(r)}`;if(!S(s)){un(i,o);continue}n.push(...Sr(s,o,i,(l)=>({id:`webhook:${r}:${l}`,kind:"webhook",name:r})))}for(let r of t){let s=r.operation.callbacks;if(!S(s))continue;for(let o of Object.keys(s).sort()){let l=H(e,s[o]),c=`${r.pointer}/callbacks/${oe(o)}`;if(!S(l)){un(i,c);continue}for(let p of Object.keys(l).sort()){if(p.startsWith("x-"))continue;let d=H(e,l[p]),u=`${c}/${oe(p)}`;if(!S(d)){un(i,u);continue}n.push(...Sr(d,u,i,(f)=>({id:`callback:${r.id}:${o}:${f}`,kind:"callback",name:o,expression:p,operationId:r.id})))}}}return n.sort((r,s)=>r.id.localeCompare(s.id))}function Vr(e,t){if(!(ye in e.operation))return;t.push({code:"event-on-path-operation",severity:"warning",message:`${ye} applies only to webhook and callback operations and is ignored here`,pointer:`${e.pointer}/${ye}`,operationId:e.id})}function Sr(e,t,i,n){let a=[];for(let r of Yt){let s=e[r];if(!S(s))continue;let o=n(r),l=`${t}/${r}`,c=[];if(ye in s){let p=vr(s[ye],`${l}/${ye}`,o.id,i);if(!p)continue;c=p}a.push({...o,method:r,purpose:P(s.summary)??P(s.description)??o.name,produces:c,provenance:{kind:"document",pointer:l}})}return a}function un(e,t){e.push({code:"unresolved-trigger",severity:"warning",message:"Webhook or callback could not be resolved and is skipped",pointer:t})}var Ql=new Set(["allOf","anyOf","enum","oneOf","required"]);function yn(e,t={}){return fn(e,t.schema===!0,new WeakSet,void 0)}function E(e){return JSON.stringify(yn(e))}function ut(e){return JSON.stringify(yn(e,{schema:!0}))}async function ne(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(i)].map((n)=>n.toString(16).padStart(2,"0")).join("")}async function hn(e){return ne(ut(e))}function Ht(e){return`${E(e)}
140
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ui(e),i=st(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Ui(e),i=st(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((i)=>i.type==="newline"||i.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}Fb.Parser=el});var rl=C(function(Bb){var tl=Na(),Db=Nt(),Mt=$t(),Lb=zn(),Mb=I(),Rb=za(),il=Ba();function nl(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Rb.LineCounter||null,prettyErrors:t}}function _b(e,t={}){let{lineCounter:i,prettyErrors:n}=nl(t),a=new il.Parser(i?.addNewLine),r=new tl.Composer(t),s=Array.from(r.compose(a.parse(e)));if(n&&i)for(let o of s)o.errors.forEach(Mt.prettifyError(e,i)),o.warnings.forEach(Mt.prettifyError(e,i));if(s.length>0)return s;return Object.assign([],{empty:!0},r.streamInfo())}function al(e,t={}){let{lineCounter:i,prettyErrors:n}=nl(t),a=new il.Parser(i?.addNewLine),r=new tl.Composer(t),s=null;for(let o of r.compose(a.parse(e),!0,e.length))if(!s)s=o;else if(s.options.logLevel!=="silent"){s.errors.push(new Mt.YAMLParseError(o.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(n&&i)s.errors.forEach(Mt.prettifyError(e,i)),s.warnings.forEach(Mt.prettifyError(e,i));return s}function jb(e,t,i){let n=void 0;if(typeof t==="function")n=t;else if(i===void 0&&t&&typeof t==="object")i=t;let a=al(e,i);if(!a)return null;if(a.warnings.forEach((r)=>Lb.warn(a.options.logLevel,r)),a.errors.length>0)if(a.options.logLevel!=="silent")throw a.errors[0];else a.errors=[];return a.toJS(Object.assign({reviver:n},i))}function zb(e,t,i){let n=null;if(typeof t==="function"||Array.isArray(t))n=t;else if(i===void 0&&t)i=t;if(typeof i==="string")i=i.length;if(typeof i==="number"){let a=Math.round(i);i=a<1?void 0:a>8?{indent:8}:{indent:a}}if(e===void 0){let{keepUndefined:a}=i??t??{};if(!a)return}if(Mb.isDocument(e)&&!n)return e.toString(i);return new Db.Document(e,n,i).toString(i)}Bb.parse=jb;Bb.parseAllDocuments=_b;Bb.parseDocument=al;Bb.stringify=zb});import{pkg as Hw,registerCapabilityGraphClassifierFactory as Ww,registerCapabilityGraphRuntimeProvider as Xw}from"@mcp-com-ai/core";import{definePlugin as Qw,HAPI_CLI_API_VERSION as Zw}from"@mcp-com-ai/plugin-sdk";var lr="@mcp-com-ai/plugin-capability-graph",cr="1.3.0",pr="Compile OpenAPI documents into deterministic HAPI capability graphs.";var $l=new Set(["a","an","and","as","at","be","by","for","from","in","it","of","on","or","the","them","this","to","user","without"]);class fe{id="deterministic-v1";async classify(e){ur(e.signal);let t=[],i=e.query.trim();if(!i)return{outcome:"no-match",matches:[],diagnostics:t};if(i.length>2000)return{outcome:"no-match",matches:[],diagnostics:[{code:"query-too-long",severity:"error",message:"Capability graph queries are limited to 2000 characters"}]};let n=new Map(e.graph.operations.map((c)=>[c.id,c])),a=new Map(e.graph.capabilities.map((c)=>[c.id,c.label])),r=e.mode==="regex"?Ll(i,t):void 0;if(e.mode==="regex"&&!r)return{outcome:"no-match",matches:[],diagnostics:t};let s=[];for(let c of e.candidates){ur(e.signal);let p=n.get(c.operationId);if(!p||!Be(p,e.principal))continue;let d=r?ql(r,c.toolName,p,a):Fl(i,c.toolName,p,a);if(d.score<=0)continue;s.push({toolName:c.toolName,operationId:p.id,score:d.score,reason:d.reason})}s.sort(Rl);let o=Ml(e.limit),l=s.slice(0,o);return{outcome:l.length>0?"ranked":"no-match",matches:l,diagnostics:t}}}function Be(e,t){if(e.authorization.length===0)return!0;if(!jl(t))return t===void 0;if(t.authorizedOperationIds)return t.authorizedOperationIds.includes(e.id);let i=new Set(t.scopes??[]),n=t.schemes??{};return e.authorization.some((a)=>a.schemes.every((r)=>{let s=n[r.scheme];if(s){let o=new Set(s);return r.scopes.every((l)=>o.has(l))}return r.scopes.length>0&&r.scopes.every((o)=>i.has(o))}))}function Fl(e,t,i,n){let a=on(e),r=fr(t,i,n),s=0,o=[];for(let l of r.positive){let c=dr(a,on(l.text));if(c===0)continue;s+=c*l.weight,o.push(l.label)}for(let l of i.avoidWhen){let c=dr(a,on(l));if(c>0)s-=c*100,o.push("avoid-when penalty")}return{score:_l(s),reason:[...new Set(o)].join(", ")||"no lexical overlap"}}function ql(e,t,i,n){let a=fr(t,i,n).positive.map((r)=>r.text).join(" ");return e.lastIndex=0,e.test(a)?{score:1,reason:"regex match"}:{score:0,reason:"no regex match"}}function fr(e,t,i){let n=t.capabilityIds.flatMap((o)=>[o,i.get(o)??""]).join(" "),a=t.inputs.flatMap((o)=>[o.name,o.description??""]).join(" "),r=t.outputs.flatMap((o)=>[o.description??"",...o.fields]).join(" "),s=t.bodyVariants.map((o)=>`${o.title??""} ${JSON.stringify(o.schema)}`).join(" ");return{positive:[{text:`${e} ${t.id} ${t.sourceOperationId??""}`,weight:8,label:"operation identity"},{text:n,weight:6,label:"capability taxonomy"},{text:t.purpose,weight:5,label:"purpose"},{text:t.useWhen.join(" "),weight:5,label:"use-when"},{text:a,weight:2,label:"inputs"},{text:s,weight:5,label:"body variants"},{text:r,weight:2,label:"outputs"},{text:t.prerequisites.join(" "),weight:1,label:"prerequisites"}]}}function on(e){let i=e.replace(/([a-z\d])([A-Z])/g,"$1 $2").toLowerCase().match(/[\p{L}\p{N}]+/gu)??[];return new Set(i.map(Dl).filter((n)=>n.length>1&&!$l.has(n)))}function Dl(e){if(e.length>5&&e.endsWith("ing")){let t=e.slice(0,-3);return t.endsWith("s")?`${t}e`:t}if(e.length>4&&e.endsWith("ed"))return e.slice(0,-2);if(e.length>3&&e.endsWith("s"))return e.slice(0,-1);return e}function dr(e,t){let i=0;for(let n of e)if(t.has(n))i++;return i}function Ll(e,t){try{return new RegExp(e,"iu")}catch{t.push({code:"invalid-regex",severity:"error",message:`Invalid capability graph regex: ${e}`});return}}function Ml(e){if(!Number.isFinite(e))return 5;return Math.min(50,Math.max(1,Math.floor(e)))}function Rl(e,t){return t.score-e.score||e.operationId.localeCompare(t.operationId)||e.toolName.localeCompare(t.toolName)}function _l(e){return Math.round(e*1000)/1000}function ur(e){if(!e?.aborted)return;if(typeof e.throwIfAborted==="function")e.throwIfAborted();throw new DOMException("Capability graph classification aborted","AbortError")}function jl(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var pn="x-hapi-planning",zl=Object.freeze({type:"object",additionalProperties:!1,required:["produces"],properties:{requires:{type:"array",items:{$ref:"#/$defs/fact"}},produces:{type:"array",minItems:1,items:{$ref:"#/$defs/fact"}},removes:{type:"array",items:{$ref:"#/$defs/fact"}},cost:{type:"number",minimum:0}},$defs:{fact:{type:"object",additionalProperties:!1,required:["predicate"],properties:{predicate:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$"},value:{}}}}}),Bl=new Set(["read","create","update","delete","action"]),yr=["side-effecting","destructive","idempotent","requires-confirmation"];function gr(e,t,i,n){return{capabilities:Jl(e,t,i,n),intent:Yl(e,t,i,n),effects:Hl(e,t,i,n),prerequisites:Wl(e,t,i,n),planning:br(e,t,i,n)}}function br(e,t,i,n){if(!("x-hapi-planning"in e))return;let r=e["x-hapi-planning"],s=`${t}/x-hapi-planning`;if(!he(r)){A(n,i,s,"invalid-planning","x-hapi-planning must be an object");return}let o=new Set(["requires","produces","removes","cost"]),l=Object.keys(r).filter((h)=>!o.has(h));if(l.length>0){A(n,i,s,"invalid-planning-field",`x-hapi-planning contains unknown field${l.length===1?"":"s"}: ${l.sort().join(", ")}`);return}let c=Ee(r.requires??[],`${s}/requires`,i,n),p=Ee(r.produces,`${s}/produces`,i,n),d=Ee(r.removes??[],`${s}/removes`,i,n),u=r.cost??1;if(!Array.isArray(r.produces)||r.produces.length===0)A(n,i,`${s}/produces`,"invalid-planning-produces","x-hapi-planning.produces must be a non-empty array of canonical facts");if(typeof u!=="number"||!Number.isFinite(u)||u<0)A(n,i,`${s}/cost`,"invalid-planning-cost","x-hapi-planning.cost must be a finite nonnegative number");if(!c||!p||!d||typeof u!=="number")return;let f=new Set(p.map(ie));if(d.filter((h)=>f.has(ie(h))).length>0){A(n,i,s,"conflicting-planning-fact","x-hapi-planning cannot produce and remove the same fact");return}if(!Number.isFinite(u)||u<0||p.length===0)return;return{requires:c,produces:p,removes:d,cost:u}}var Ue="x-hapi-outcome";function Kl(e){return/^2(?:\d\d|xx)$/i.test(e)}function Cr(e,t,i,n,a){let r=Ue;if(Kl(i)){A(a,n,t,"outcome-on-success-response",`${r} cannot be declared on success response ${i}; use x-hapi-planning`);return}if(!he(e)){A(a,n,t,"invalid-outcome",`${r} must be an object`);return}let s=Object.keys(e).filter((p)=>p!=="produces"&&p!=="removes");if(s.length>0){A(a,n,t,"invalid-outcome-field",`${r} contains unknown field${s.length===1?"":"s"}: ${s.sort().join(", ")}`);return}let o=Ee(e.produces??[],`${t}/produces`,n,a),l=Ee(e.removes??[],`${t}/removes`,n,a);if(!o||!l)return;if(o.length===0&&l.length===0){A(a,n,t,"empty-outcome",`${r} must produce or remove at least one fact`);return}let c=new Set(o.map(ie));if(l.some((p)=>c.has(ie(p)))){A(a,n,t,"conflicting-outcome-fact",`${r} cannot produce and remove the same fact`);return}return{produces:o,removes:l}}var Jt="x-hapi-client-facts";function wr(e,t){let i=Jt,n=`/${i}`;if(!Array.isArray(e)){t.push({code:"invalid-client-facts",severity:"error",message:`${i} must be an array of facts`,pointer:n});return}let a=[],r=new Set;for(let[s,o]of e.entries()){let l=`${n}/${s}`,c=(m,g)=>t.push({code:m,severity:"error",message:g,pointer:l});if(!he(o)){c("invalid-client-fact","A client fact must be an object");continue}let p=Object.keys(o).filter((m)=>!["predicate","value","description"].includes(m));if(p.length){c("invalid-client-fact-field",`A client fact contains unknown field${p.length===1?"":"s"}: ${p.sort().join(", ")}`);continue}if(o.description!==void 0&&(typeof o.description!=="string"||o.description.trim()==="")){c("invalid-client-fact-description","description must be a non-empty string");continue}let{description:d,...u}=o,y=Ee([u],l,"document",t)?.[0];if(!y)continue;let h=ie(y);if(r.has(h)){c("duplicate-client-fact","Client facts cannot contain duplicates");continue}r.add(h),a.push({fact:y,...typeof d==="string"?{description:d.trim()}:{},pointer:l})}return a.sort((s,o)=>ie(s.fact).localeCompare(ie(o.fact)))}var ye="x-hapi-event";function vr(e,t,i,n){let a=ye;if(!he(e)){A(n,i,t,"invalid-event",`${a} must be an object`);return}let r=Object.keys(e).filter((s)=>s!=="produces");if(r.length>0){A(n,i,t,"invalid-event-field",`${a} contains unknown field${r.length===1?"":"s"}: ${r.sort().join(", ")}`);return}if(!Array.isArray(e.produces)||e.produces.length===0){A(n,i,`${t}/produces`,"invalid-event-produces",`${a}.produces must be a non-empty array of canonical facts`);return}return Ee(e.produces,`${t}/produces`,i,n)}function Ee(e,t,i,n){if(!Array.isArray(e)){A(n,i,t,"invalid-planning-facts","Planning facts must be an array");return}let a=[];for(let[s,o]of e.entries()){let l=`${t}/${s}`;if(!he(o)||Object.keys(o).some((c)=>c!=="predicate"&&c!=="value")||typeof o.predicate!=="string"||!Ul.test(o.predicate)||Object.hasOwn(o,"value")&&!cn(o.value)){A(n,i,l,"invalid-planning-fact","A planning fact requires a canonical lowercase predicate and optional JSON-safe value");continue}a.push({predicate:o.predicate,...Object.hasOwn(o,"value")?{value:o.value}:{}})}if(a.length!==e.length)return;let r=a.map(ie);if(new Set(r).size!==r.length){A(n,i,t,"duplicate-planning-fact","Planning fact arrays cannot contain duplicates");return}return a.sort((s,o)=>ie(s).localeCompare(ie(o)))}var Ul=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;function ie(e){return`${e.predicate}:${ln(e.value??null)}`}function ln(e){if(Array.isArray(e))return`[${e.map(ln).join(",")}]`;if(he(e))return`{${Object.keys(e).sort().map((t)=>`${JSON.stringify(t)}:${ln(e[t])}`).join(",")}}`;return JSON.stringify(e)}function cn(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(!e||typeof e!=="object"||t.has(e))return!1;let i=new Set(t).add(e);if(Array.isArray(e))return e.every((n)=>cn(n,i));if(Object.getPrototypeOf(e)!==Object.prototype)return!1;return Object.values(e).every((n)=>cn(n,i))}function Jl(e,t,i,n){if(!("x-hapi-capability"in e))return;let r=e["x-hapi-capability"],s=typeof r==="string"?[r]:r;if(!Xl(s)){A(n,i,`${t}/x-hapi-capability`,"invalid-capability","x-hapi-capability must be a non-empty string or array of non-empty strings");return}return Ut(s.map((o)=>o.trim()))}function Yl(e,t,i,n){if(!("x-hapi-intent"in e))return;let r=e["x-hapi-intent"];if(!he(r)){A(n,i,`${t}/x-hapi-intent`,"invalid-intent","x-hapi-intent must be an object");return}let s=Object.keys(r).filter((c)=>!["use-when","avoid-when"].includes(c)),o=r["use-when"]??[],l=r["avoid-when"]??[];if(s.length>0||!Kt(o)||!Kt(l)){A(n,i,`${t}/x-hapi-intent`,"invalid-intent","x-hapi-intent accepts only use-when and avoid-when arrays of non-empty strings");return}return{useWhen:Ut(o.map((c)=>c.trim())),avoidWhen:Ut(l.map((c)=>c.trim()))}}function Hl(e,t,i,n){if(!("x-hapi-effects"in e))return;let r=e["x-hapi-effects"];if(!he(r)){A(n,i,`${t}/x-hapi-effects`,"invalid-effects","x-hapi-effects must be an object");return}let s=new Set(["mode",...yr]),o=r.mode,l=yr.find((p)=>r[p]!==void 0&&typeof r[p]!=="boolean");if(typeof o!=="string"||!Bl.has(o)||l||Object.keys(r).some((p)=>!s.has(p))){A(n,i,`${t}/x-hapi-effects`,"invalid-effects","x-hapi-effects requires a valid mode and accepts only boolean effect flags");return}let c=Ke(o);return{mode:o,sideEffecting:hr(r,"side-effecting",c.sideEffecting),destructive:hr(r,"destructive",c.destructive),idempotent:mr(r,"idempotent",c.idempotent),requiresConfirmation:mr(r,"requires-confirmation",c.requiresConfirmation)}}function Wl(e,t,i,n){if(!("x-hapi-prerequisites"in e))return;let r=e["x-hapi-prerequisites"];if(!Kt(r)){A(n,i,`${t}/x-hapi-prerequisites`,"invalid-prerequisites","x-hapi-prerequisites must be an array of non-empty strings");return}return Ut(r.map((s)=>s.trim()))}function xr(e){let t=e.toLowerCase();if(["get","head","options"].includes(t))return Ke("read");if(t==="post")return Ke("create");if(t==="delete")return Ke("delete");if(["put","patch"].includes(t))return{...Ke("update"),idempotent:t==="put"};return Ke("action")}function Ke(e){let t=e==="read",i=e==="delete";return{mode:e,sideEffecting:!t,destructive:i,idempotent:t||e==="delete",requiresConfirmation:i}}function A(e,t,i,n,a){e.push({code:n,severity:"error",message:a,pointer:i,operationId:t})}function hr(e,t,i){return typeof e[t]==="boolean"?e[t]:i}function mr(e,t,i){return typeof e[t]==="boolean"?e[t]:i}function he(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}function Kt(e){return Array.isArray(e)&&e.every((t)=>typeof t==="string"&&t.trim()!=="")}function Xl(e){return Kt(e)&&e.length>0}function Ut(e){return[...new Set(e)].sort((t,i)=>t.localeCompare(i))}var Yt=["delete","get","head","options","patch","post","put","trace"];function S(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}function P(e){return typeof e==="string"&&e.trim()!==""?e.trim():void 0}function oe(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function dn(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function H(e,t){if(!S(t)||typeof t.$ref!=="string"||!t.$ref.startsWith("#/"))return t;let i=e;for(let n of t.$ref.slice(2).split("/").map(dn)){if(!S(i))return t;i=i[n]}return i??t}function kr(e,t,i){let n=[],a=e.webhooks;if(S(a))for(let r of Object.keys(a).sort()){let s=H(e,a[r]),o=`/webhooks/${oe(r)}`;if(!S(s)){un(i,o);continue}n.push(...Sr(s,o,i,(l)=>({id:`webhook:${r}:${l}`,kind:"webhook",name:r})))}for(let r of t){let s=r.operation.callbacks;if(!S(s))continue;for(let o of Object.keys(s).sort()){let l=H(e,s[o]),c=`${r.pointer}/callbacks/${oe(o)}`;if(!S(l)){un(i,c);continue}for(let p of Object.keys(l).sort()){if(p.startsWith("x-"))continue;let d=H(e,l[p]),u=`${c}/${oe(p)}`;if(!S(d)){un(i,u);continue}n.push(...Sr(d,u,i,(f)=>({id:`callback:${r.id}:${o}:${f}`,kind:"callback",name:o,expression:p,operationId:r.id})))}}}return n.sort((r,s)=>r.id.localeCompare(s.id))}function Vr(e,t){if(!(ye in e.operation))return;t.push({code:"event-on-path-operation",severity:"warning",message:`${ye} applies only to webhook and callback operations and is ignored here`,pointer:`${e.pointer}/${ye}`,operationId:e.id})}function Sr(e,t,i,n){let a=[];for(let r of Yt){let s=e[r];if(!S(s))continue;let o=n(r),l=`${t}/${r}`,c=[];if(ye in s){let p=vr(s[ye],`${l}/${ye}`,o.id,i);if(!p)continue;c=p}a.push({...o,method:r,purpose:P(s.summary)??P(s.description)??o.name,produces:c,provenance:{kind:"document",pointer:l}})}return a}function un(e,t){e.push({code:"unresolved-trigger",severity:"warning",message:"Webhook or callback could not be resolved and is skipped",pointer:t})}var Ql=new Set(["allOf","anyOf","enum","oneOf","required"]);function yn(e,t={}){return fn(e,t.schema===!0,new WeakSet,void 0)}function E(e){return JSON.stringify(yn(e))}function ut(e){return JSON.stringify(yn(e,{schema:!0}))}async function ne(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return[...new Uint8Array(i)].map((n)=>n.toString(16).padStart(2,"0")).join("")}async function hn(e){return ne(ut(e))}function Ht(e){return`${E(e)}
141
141
  `}function fn(e,t,i,n){if(e===null||typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e)){let r=e.map((s)=>fn(s,t,i,n));if(t&&n&&Ql.has(n))return r.sort(Zl);return r}if(!e||typeof e!=="object")return String(e);if(i.has(e))throw TypeError("Cannot canonicalize a cyclic object; use document references instead");i.add(e);let a={};for(let r of Object.keys(e).sort()){let s=e[r];if(s!==void 0)a[r]=fn(s,t,i,r)}return i.delete(e),a}function Zl(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}class Wt extends Error{diagnostics;constructor(e){let t=e.filter((i)=>i.severity==="error").length;super(`Capability graph compilation failed with ${t} error${t===1?"":"s"}`);this.diagnostics=e;this.name="CapabilityGraphCompilationError"}}async function Pe(e,t={}){let i=[],n=ec(e,i);if(!n)throw new Wt(gn(i));let a=tc(n,i);await ic(a);for(let g of a)g.extensions=gr(g.operation,g.pointer,g.id,i),g.outcomes=hc(n,g,i),Vr(g,i);let r=kr(n,a,i),s=Jt in n?wr(n[Jt],i):void 0;if(Gr(i))throw new Wt(gn(i));let o=new Map,l=[];for(let g of a){let w=nc(n,g);for(let b of w)if(!o.has(b.node.id))o.set(b.node.id,b.node);l.push(await ac(n,g,w))}let c=[...o.values()].sort(wn);l.sort(wn);let p=pc(n,a,l,i),d=gc(a,l,p),u=mc(s,d,i),f=vc(n,t.source),y=gn(i),h={schemaVersion:"1",source:f,capabilities:c,operations:l,edges:p,...d?{planning:d}:{},...r.length?{triggers:r}:{},...u?.length?{clientFacts:u}:{},diagnostics:y},m=await xc(h);return Or({...h,fingerprint:m})}function ec(e,t){if(!S(e)){t.push(bn("invalid-document","OpenAPI document root must be an object",""));return}if(typeof e.openapi!=="string"||!e.openapi.startsWith("3."))t.push(bn("unsupported-openapi-version","Capability graphs require an OpenAPI 3.x document","/openapi"));if(!S(e.paths))t.push(bn("invalid-paths","OpenAPI document paths must be an object","/paths"));return Gr(t)?void 0:e}function tc(e,t){let i=e.paths,n=[];for(let a of Object.keys(i).sort()){let r=i[a];if(!S(r))continue;for(let s of Yt){let o=r[s];if(!S(o))continue;let l=`/paths/${oe(a)}/${s}`,c=P(o.operationId);if(o.operationId!==void 0&&!c)t.push({code:"invalid-operation-id",severity:"warning",message:"operationId is not a non-empty string; a stable identity was inferred",pointer:`${l}/operationId`});let p=c?Je(c):Je(`${s}-${a}`);n.push({path:a,method:s,pointer:l,pathItem:r,operation:o,sourceOperationId:c,baseId:p,id:p})}}return n}async function ic(e){let t=new Map;for(let i of e){let n=t.get(i.baseId)??[];n.push(i),t.set(i.baseId,n)}for(let i of t.values()){if(i.length===1)continue;let n=new Map;for(let a of i.sort(Gc)){let r=Je(`${a.method}-${a.path}`),s=n.get(r)??[];s.push(a),n.set(r,s)}for(let[a,r]of n)for(let s of r){let o=r.length>1?`-${(await ne(`${s.method}:${s.path}`)).slice(0,12)}`:"";s.id=`${s.baseId}--${a}${o}`}}}function nc(e,t){let i=t.extensions?.capabilities,n=Array.isArray(t.operation.tags)?t.operation.tags.filter((l)=>typeof l==="string"&&l.trim()!==""):[],a=i&&i.length>0?i:n.length>0?[...new Set(n.map((l)=>l.trim()))].sort():[Vc(t.path)],r=i?{kind:"extension",pointer:`${t.pointer}/x-hapi-capability`}:n.length>0?{kind:"document",pointer:`${t.pointer}/tags`}:{kind:"inferred",pointer:t.pointer,detail:"first static path segment"},s=Sc(e),o=new Map;for(let l of a){let c=kc(l),p=c.map(Ec).join(".")||"root";o.set(p,{provenance:r,node:{id:p,label:l,path:c,description:s.get(l),provenance:r}})}return[...o.values()].sort((l,c)=>l.node.id.localeCompare(c.node.id))}async function ac(e,t,i){let n=P(t.operation.summary)??P(t.operation.description)??t.id,a=t.extensions?.intent??{useWhen:[n],avoidWhen:[]},r=rc(e,t),s=H(e,t.operation.requestBody),o=await oc(s),l=sc(r,s),c=t.extensions?.prerequisites??wc(l,Boolean(S(s)&&s.required===!0)),p=t.extensions?.effects,d=Object.hasOwn(t.operation,"security")?`${t.pointer}/security`:"/security";return{id:t.id,...t.sourceOperationId?{sourceOperationId:t.sourceOperationId}:{},capabilityIds:i.map((u)=>u.node.id),purpose:n,useWhen:a.useWhen,avoidWhen:a.avoidWhen,transport:{kind:"http",method:t.method.toUpperCase(),path:t.path},inputs:l,bodyVariants:o,outputs:lc(e,t.operation.responses),effects:p??xr(t.method),authorization:cc(e,t.operation),prerequisites:c,provenance:{identity:t.sourceOperationId?{kind:"document",pointer:`${t.pointer}/operationId`}:{kind:"inferred",pointer:t.pointer,detail:"HTTP method and path"},capabilities:i[0]?.provenance,purpose:P(t.operation.summary)?{kind:"document",pointer:`${t.pointer}/summary`}:P(t.operation.description)?{kind:"document",pointer:`${t.pointer}/description`}:{kind:"inferred",pointer:t.pointer,detail:"stable operation identity"},intent:t.extensions?.intent?{kind:"extension",pointer:`${t.pointer}/x-hapi-intent`}:{kind:"inferred",pointer:t.pointer,detail:"operation purpose"},transport:{kind:"document",pointer:t.pointer},inputs:{kind:"document",pointer:t.pointer},outputs:{kind:"document",pointer:`${t.pointer}/responses`},effects:p?{kind:"extension",pointer:`${t.pointer}/x-hapi-effects`}:{kind:"inferred",pointer:t.pointer,detail:"HTTP method semantics"},authorization:{kind:"document",pointer:d},prerequisites:t.extensions?.prerequisites?{kind:"extension",pointer:`${t.pointer}/x-hapi-prerequisites`}:{kind:"inferred",pointer:t.pointer,detail:"required inputs"}}}}function rc(e,t){let i=new Map;for(let n of[t.pathItem.parameters,t.operation.parameters]){if(!Array.isArray(n))continue;for(let a of n){let r=H(e,a);if(!S(r))continue;let s=P(r.name),o=P(r.in);if(s&&o)i.set(`${o}:${s}`,r)}}return[...i.values()].sort((n,a)=>`${n.in}:${n.name}`.localeCompare(`${a.in}:${a.name}`))}function sc(e,t){let i=e.map((n)=>({name:String(n.name),location:Pc(n.in),required:n.in==="path"||n.required===!0,...P(n.description)?{description:P(n.description)}:{},...S(n.schema)?{schema:Qt(n.schema)}:{}}));if(S(t))i.push({name:"body",location:"body",required:t.required===!0,...P(t.description)?{description:P(t.description)}:{},...Ir(t)?{schema:Qt(Ir(t))}:{}});return i.sort((n,a)=>`${n.location}:${n.name}`.localeCompare(`${a.location}:${a.name}`))}async function oc(e){if(!S(e)||!S(e.content))return[];let t=[];for(let i of Object.keys(e.content).sort()){let n=e.content[i];if(!S(n)||!S(n.schema))continue;let a=Array.isArray(n.schema.oneOf)&&n.schema.oneOf.length>0?[...n.schema.oneOf].filter(S).sort((r,s)=>ut(r).localeCompare(ut(s))):[n.schema];for(let r of a){let s=await hn(r);t.push({id:`${Je(i)}-${s.slice(0,12)}`,mediaType:i,required:e.required===!0,...P(r.title)?{title:P(r.title)}:{},schemaHash:s,schema:Qt(r)})}}return Ac(t,(i)=>`${i.mediaType}:${i.schemaHash}`).sort((i,n)=>i.id.localeCompare(n.id))}function lc(e,t){if(!S(t))return[];let i=[];for(let n of Object.keys(t).sort()){let a=H(e,t[n]);if(!S(a))continue;let r=S(a.content)?a.content:{},s=Object.keys(r).sort(),o=new Set;for(let l of s){let c=r[l];if(!S(c)||!S(c.schema))continue;for(let p of Cc(c.schema))o.add(p)}i.push({status:n,...P(a.description)?{description:P(a.description)}:{},mediaTypes:s,fields:[...o].sort()})}return i}function cc(e,t){let i=Object.hasOwn(t,"security")?t.security:e.security;if(!Array.isArray(i))return[];return i.filter(S).map((n)=>({schemes:Object.keys(n).sort().map((a)=>({scheme:a,scopes:Array.isArray(n[a])?n[a].filter((r)=>typeof r==="string").sort():[]}))})).sort((n,a)=>E(n).localeCompare(E(a)))}function pc(e,t,i,n){let a=[];for(let r of i)for(let s of r.capabilityIds)a.push({id:`capability:${s}->operation:${r.id}`,type:"capability-operation",from:s,to:r.id,planningEligible:!1,provenance:r.provenance.capabilities??{kind:"inferred"}});return a.push(...dc(e,t,i,n)),a.sort(Oc)}function dc(e,t,i,n){let a=[],r=new Map,s=new Map(t.map((l)=>[`${l.method} ${l.path}`,l])),o=new Map(i.map((l)=>[l.id,l]));for(let l of t){if(!l.sourceOperationId)continue;let c=r.get(l.sourceOperationId)??[];c.push(l),r.set(l.sourceOperationId,c)}for(let l of t){let c=S(l.operation.responses)?l.operation.responses:{};for(let p of Object.keys(c).sort()){let d=H(e,c[p]);if(!S(d)||!S(d.links))continue;for(let u of Object.keys(d.links).sort()){let f=H(e,d.links[u]);if(!S(f))continue;let y=uc(f,r,s),h=`${l.pointer}/responses/${oe(p)}/links/${oe(u)}`;if(!y){n.push({code:"unresolved-operation-link",severity:"warning",message:`OpenAPI Link '${u}' does not resolve to one compiled operation`,pointer:h,operationId:l.id});continue}let m=fc(f,o.get(y.id),h,l.id,u,n);a.push({id:`link:${l.id}->${y.id}:${Je(u)}`,type:"operation-link",from:l.id,to:y.id,label:u,planningEligible:m,provenance:{kind:"document",pointer:h}})}}}return a}function uc(e,t,i){let n=P(e.operationId);if(n){let s=t.get(n);return s?.length===1?s[0]:void 0}let a=P(e.operationRef);if(!a?.startsWith("#/paths/"))return;let r=a.slice(2).split("/").map(dn);if(r.length!==3||r[0]!=="paths")return;return i.get(`${r[2]?.toLowerCase()} ${r[1]}`)}function fc(e,t,i,n,a,r){if(!t)return!1;let s=e.parameters??{};if(!S(s))return Er(r,n,i,a,"parameters must be an object"),!1;let o=t.inputs.filter((y)=>y.location!=="body"),l=new Set(o.map((y)=>y.name)),c=Object.keys(s).filter((y)=>!l.has(y)),p=Object.entries(s).find(([,y])=>!Xt(y)),d=o.filter((y)=>y.required&&!Object.hasOwn(s,y.name)).map((y)=>y.name),f=!t.inputs.some((y)=>y.location==="body"&&y.required)||Xt(e.requestBody);if(c.length>0||p||d.length>0||!f){let y=[...c.length?[`unknown parameters: ${c.sort().join(", ")}`]:[],...p?[`invalid mapping for ${p[0]}`]:[],...d.length?[`missing required parameters: ${d.sort().join(", ")}`]:[],...!f?["missing or invalid required requestBody mapping"]:[]];return Er(r,n,i,a,y.join("; ")),!1}return!0}function Er(e,t,i,n,a){e.push({code:"ineligible-operation-link",severity:"warning",message:`OpenAPI Link '${n}' is descriptive-only: ${a}`,pointer:i,operationId:t})}function Xt(e){if(typeof e==="string")return!e.startsWith("$")||yc(e);if(e===null||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(Array.isArray(e))return e.every(Xt);if(!S(e))return!1;return Object.values(e).every(Xt)}function yc(e){return/^\$(?:url|method|statusCode)$/.test(e)||/^\$(?:request|response)\.(?:path|query|header)\.[^\s.]+$/.test(e)||/^\$(?:request|response)\.body#(?:\/.*)?$/.test(e)}function hc(e,t,i){let n=t.operation.responses;if(!S(n))return;let a=[];for(let r of Object.keys(n).sort()){let s=H(e,n[r]);if(!S(s)||!(Ue in s))continue;let o=`${t.pointer}/responses/${oe(r)}/${Ue}`,l=Cr(s[Ue],o,r,t.id,i);if(!l)continue;if(!(pn in t.operation)){i.push({code:"outcome-without-planning",severity:"warning",message:`${Ue} on response ${r} is ignored because the operation has no x-hapi-planning`,pointer:o,operationId:t.id});continue}a.push({status:r,produces:l.produces,removes:l.removes,provenance:{kind:"extension",pointer:o}})}return a.length?a:void 0}function mc(e,t,i){if(!e?.length)return;let n=new Set((t?.transitions??[]).flatMap((a)=>a.requires.map((r)=>E(r))));return e.map((a)=>{if(!n.has(E(a.fact)))i.push({code:"unused-client-fact",severity:"warning",message:`Client fact ${a.fact.predicate} is not required by any planning transition`,pointer:a.pointer});return{fact:a.fact,...a.description?{description:a.description}:{},provenance:{kind:"extension",pointer:a.pointer}}})}function gc(e,t,i){let n=new Map(t.map((s)=>[s.id,s])),a=new Map(e.map((s)=>[s.id,s])),r=new Map;for(let s of t){let o=a.get(s.id),l=o?.extensions?.planning;if(!o||!l)continue;let c=mn(s,l,{kind:"x-hapi-planning",provenance:{kind:"extension",pointer:`${o.pointer}/x-hapi-planning`}});r.set(s.id,o.outcomes?.length?{...c,outcomes:o.outcomes}:c)}for(let s of i){if(s.type!=="operation-link"||!s.planningEligible)continue;let o=n.get(s.from),l=n.get(s.to);if(!o||!l)continue;let c={kind:"openapi-link",provenance:s.provenance},p=r.get(o.id)??mn(o,void 0,c);r.set(o.id,{...p,produces:ft([...p.produces,Cn(o.id)]),sources:Pr([...p.sources,c])});let d=r.get(l.id)??mn(l,void 0,c);r.set(l.id,{...d,requires:ft([...d.requires,Cn(o.id)]),sources:Pr([...d.sources,c])})}if(r.size===0)return;return{schemaVersion:"1",transitions:[...r.values()].sort(wn)}}function mn(e,t,i){return{id:`operation:${e.id}`,target:{kind:"operation",id:e.id},requires:ft(t?.requires??[]),produces:ft([...t?.produces??[],Cn(e.id)]),removes:ft(t?.removes??[]),cost:t?.cost??1,gates:bc(e),sources:[i]}}function bc(e){let t=[];if(e.authorization.length>0)t.push({kind:"authorization",status:"required",code:"operation-authorization"});if(e.effects.destructive)t.push({kind:"risk",status:"required",code:"destructive-operation"});if(e.effects.requiresConfirmation)t.push({kind:"confirmation",status:"required",code:"mutation-confirmation"});return t.sort((i,n)=>`${i.kind}:${i.code}`.localeCompare(`${n.kind}:${n.code}`))}function Cn(e){return{predicate:`operation.${Je(e).toLowerCase()}.completed`}}function ft(e){return[...new Map(e.map((i)=>[E(i),i])).entries()].sort(([i],[n])=>i.localeCompare(n)).map(([,i])=>i)}function Pr(e){return[...new Map(e.map((i)=>[E(i),i])).entries()].sort(([i],[n])=>i.localeCompare(n)).map(([,i])=>i)}function Qt(e){if(!S(e))return{};let t=P(e.$ref);if(t)return{ref:t};let i=S(e.properties)?Object.keys(e.properties).sort():void 0,n=Array.isArray(e.required)?e.required.filter((r)=>typeof r==="string").sort():void 0,a=Array.isArray(e.enum)?e.enum.filter(Ic).sort((r,s)=>JSON.stringify(r).localeCompare(JSON.stringify(s))):void 0;return{...P(e.type)?{type:P(e.type)}:{},...P(e.format)?{format:P(e.format)}:{},...P(e.title)?{title:P(e.title)}:{},...P(e.description)?{description:P(e.description)}:{},...a&&a.length>0?{enum:a}:{},...n&&n.length>0?{required:n}:{},...i&&i.length>0?{properties:i}:{},...S(e.items)?{items:Qt(e.items)}:{}}}function Cc(e){if(S(e.properties))return Object.keys(e.properties).sort();if(S(e.items)&&S(e.items.properties))return Object.keys(e.items.properties).sort();return[]}function wc(e,t){let i=e.filter((n)=>n.required&&n.location!=="body").map((n)=>`Provide required ${n.location} parameter '${n.name}'`);if(t)i.push("Provide the required request body");return i.sort()}function Ir(e){if(!S(e.content))return;for(let t of Object.keys(e.content).sort()){let i=e.content[t];if(S(i)&&S(i.schema))return i.schema}return}function vc(e,t){let i=S(e.info)?e.info:{};return{kind:t?.kind??"openapi",identifier:t?.identifier??P(i.title)??"in-memory",...t?.canonicalUri?{canonicalUri:t.canonicalUri}:{},documentVersion:String(e.openapi),...P(i.title)?{title:P(i.title)}:{},...P(i.version)?{version:P(i.version)}:{}}}async function xc(e){return ne(E({schemaVersion:e.schemaVersion,source:{kind:e.source.kind,documentVersion:e.source.documentVersion,title:e.source.title,version:e.source.version},capabilities:e.capabilities,operations:e.operations,edges:e.edges,planning:e.planning,triggers:e.triggers,clientFacts:e.clientFacts}))}function Sc(e){let t=new Map;if(!Array.isArray(e.tags))return t;for(let i of e.tags){if(!S(i))continue;let n=P(i.name),a=P(i.description);if(n&&a)t.set(n,a)}return t}function kc(e){let t=e.split(/[./>]+/).map((i)=>i.trim()).filter(Boolean);return t.length>0?t:["root"]}function Vc(e){return e.split("/").find((t)=>t&&!t.startsWith("{"))??"root"}function Ec(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"root"}function Je(e){return e.trim().replace(/[^A-Za-z0-9_.-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"operation"}function Pc(e){return["path","query","header","cookie"].includes(String(e))?String(e):"query"}function gn(e){return[...e].sort((t,i)=>`${t.severity}:${t.pointer??""}:${t.code}:${t.operationId??""}`.localeCompare(`${i.severity}:${i.pointer??""}:${i.code}:${i.operationId??""}`))}function Gr(e){return e.some((t)=>t.severity==="error")}function bn(e,t,i){return{code:e,severity:"error",message:t,pointer:i}}function Ic(e){return e===null||["string","number","boolean"].includes(typeof e)}function wn(e,t){return e.id.localeCompare(t.id)}function Gc(e,t){return`${e.method}:${e.path}`.localeCompare(`${t.method}:${t.path}`)}function Oc(e,t){return`${e.type}:${e.from}:${e.to}:${e.id}`.localeCompare(`${t.type}:${t.from}:${t.to}:${t.id}`)}function Ac(e,t){let i=new Set;return e.filter((n)=>{let a=t(n);if(i.has(a))return!1;return i.add(a),!0})}function Or(e){if(!e||typeof e!=="object"||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Or(t);return e}function Zt(e,t,i,n){if(e.kind==="authorization")return n;return i.has(e.code)||i.has(`${t}:${e.code}`)}var _=Object.freeze({maxDepth:12,maxStates:2000,maxFrontier:1000,maxExpansionsPerState:100});class U{id="deterministic-planner-v1";async plan(e){Tr(e.signal);let t=L(e.initialFacts),i=L(e.goalFacts),n=await ti(t),a={schemaVersion:"1",graphFingerprint:e.graph.fingerprint,initialStateDigest:n},r=Tc(e);if(r.length>0)return{...a,outcome:"unplannable",totalCost:0,steps:[],missingFacts:i,unsatisfiedGates:[],diagnostics:r};if(xn(t,i))return{...a,outcome:"complete",planDigest:await vn(e.graph.fingerprint,t,i,[]),totalCost:0,steps:[],missingFacts:[],unsatisfiedGates:[],diagnostics:[]};let{transitions:s,diagnostics:o}=Nc(e),l=Fc(t,i,s,e.bounds,e.signal);if(!l.node){let f=Lc(t,i,s),y=f.length>0?{code:"missing-planning-facts",severity:"warning",phase:"search",message:"Planning requires additional explicit state facts that no transition can produce"}:void 0;return{...a,outcome:f.length>0?"clarification-required":"unplannable",totalCost:0,steps:[],missingFacts:f,unsatisfiedGates:[],diagnostics:[...o,y,l.diagnostic].filter((h)=>Boolean(h))}}let c=Dc(l.node.transitions),p=new Set(e.satisfiedGates??[]),d=e.principal!==void 0,u=c.flatMap((f)=>f.gates.filter((y)=>!Zt(y,f.transitionId,p,d))).sort(Rc);return{...a,outcome:u.length>0?"clarification-required":"planned",planDigest:await vn(e.graph.fingerprint,t,i,c.map((f)=>f.transitionId)),totalCost:l.node.cost,steps:c,missingFacts:[],unsatisfiedGates:u,diagnostics:o}}}function L(e){let t=new Map;for(let i of e)t.set(W(i),i);return[...t.entries()].sort(([i],[n])=>i.localeCompare(n)).map(([,i])=>i)}async function ti(e){return ne(E(L(e)))}async function vn(e,t,i,n){return ne(E({graphFingerprint:e,initialFacts:L(t),goalFacts:L(i),transitionIds:[...n]}))}function Tc(e){let t=[],i=e.bounds;for(let[n,a]of Object.entries(i))if(!Number.isSafeInteger(a)||a<1)t.push({code:"invalid-planning-bound",severity:"error",phase:"validation",message:`${n} must be a positive safe integer`});for(let n of e.graph.planning?.transitions??[])if(!Number.isFinite(n.cost)||n.cost<0)t.push({code:"invalid-transition-cost",severity:"error",phase:"validation",transitionId:n.id,message:`Transition '${n.id}' has a non-finite or negative cost`});return t.sort(_c)}function Nc(e){let t=new Map(e.graph.operations.map((a)=>[a.id,a])),i=[],n=[];for(let a of e.graph.planning?.transitions??[]){let r=$c(a,t);if(r&&!Be(r,e.principal)){n.push({code:"transition-unauthorized",severity:"warning",phase:"eligibility",transitionId:a.id,message:`Transition '${a.id}' is not authorized for the supplied principal`});continue}i.push(a)}return i.sort((a,r)=>a.id.localeCompare(r.id)),{transitions:i,diagnostics:n}}function $c(e,t){return e.target.kind==="operation"?t.get(e.target.id):void 0}function Fc(e,t,i,n,a){let r={facts:e,key:Ar(e),cost:0,transitionIds:[],transitions:[]},s=[r],o=new Map([[r.key,{cost:0,path:""}]]),l=1,c=!1;while(s.length>0){Tr(a),s.sort(Mc);let p=s.shift();if(xn(p.facts,t))return{node:p};if(p.transitions.length>=n.maxDepth){c=!0;continue}let d=i.filter((f)=>xn(p.facts,f.requires));if(d.length>n.maxExpansionsPerState)return{diagnostic:ei("max-expansions-per-state-exceeded",n.maxExpansionsPerState)};let u=d.slice(0,n.maxExpansionsPerState);for(let f of u){let y=qc(p.facts,f),h=Ar(y),m=[...p.transitionIds,f.id],g=p.cost+f.cost,w=m.join("\x00"),b=o.get(h);if(b&&(b.cost<g||b.cost===g&&b.path<=w))continue;if(!b){if(l++,l>n.maxStates)return{diagnostic:ei("max-states-exceeded",n.maxStates)}}if(o.set(h,{cost:g,path:w}),s.push({facts:y,key:h,cost:g,transitionIds:m,transitions:[...p.transitions,f]}),s.length>n.maxFrontier)return{diagnostic:ei("max-frontier-exceeded",n.maxFrontier)}}}if(c)return{diagnostic:ei("max-depth-exceeded",n.maxDepth)};return{diagnostic:{code:"goal-unreachable",severity:"warning",phase:"search",message:"No eligible bounded transition sequence reaches the requested goal"}}}function qc(e,t){let i=new Map(e.map((n)=>[W(n),n]));for(let n of t.removes)i.delete(W(n));for(let n of t.produces)i.set(W(n),n);return L([...i.values()])}function Dc(e){let t=0;return e.map((i,n)=>(t+=i.cost,{index:n,transitionId:i.id,target:i.target,cost:i.cost,cumulativeCost:t,requires:i.requires,produces:i.produces,removes:i.removes,gates:i.gates,sources:i.sources,...i.outcomes?.length?{outcomes:i.outcomes}:{}}))}function xn(e,t){let i=new Set(e.map(W));return t.every((n)=>i.has(W(n)))}function Lc(e,t,i){let n=new Set(e.map(W)),a=new Set(t.map(W)),r=new Map;for(let c of i)for(let p of c.produces){let d=r.get(W(p))??[];d.push(c),r.set(W(p),d)}let s=[...t],o=new Set,l=[];while(s.length>0){let c=s.shift(),p=W(c);if(n.has(p)||o.has(p))continue;o.add(p);let d=r.get(p)??[];if(d.length===0){if(!a.has(p))l.push(c);continue}for(let u of d)s.push(...u.requires)}return L(l)}function W(e){return E(e)}function Ar(e){return E(L(e))}function Mc(e,t){return e.cost-t.cost||e.transitionIds.join("\x00").localeCompare(t.transitionIds.join("\x00"))||e.key.localeCompare(t.key)}function Rc(e,t){return`${e.kind}:${e.code}`.localeCompare(`${t.kind}:${t.code}`)}function _c(e,t){return`${e.phase}:${e.transitionId??""}:${e.code}`.localeCompare(`${t.phase}:${t.transitionId??""}:${t.code}`)}function ei(e,t){return{code:e,severity:"warning",phase:"search",message:`Planning stopped at configured bound ${t}`}}function Tr(e){if(!e?.aborted)return;if(typeof e.throwIfAborted==="function")e.throwIfAborted();throw new DOMException("Capability graph planning aborted","AbortError")}import{resolveCapabilityExecutionConfirmationVerifier as jc}from"@mcp-com-ai/core/capability-execution";async function Sn(e){return ni(e??null,"principal")}async function Nr(e){return ni(e,"step arguments")}async function ii(e,t,i){let n=new Map(e.operations.map((s)=>[s.id,s])),a=new Map(i.map((s)=>[s.index,s])),r=[];for(let s of t){let o=s.target.kind==="operation"?n.get(s.target.id):void 0;if(!(s.target.kind==="workflow"||o?.effects.sideEffecting===!0||o?.effects.destructive===!0||o!==void 0&&o.effects.mode!=="read"||s.gates.some((p)=>p.kind==="confirmation")))continue;let c=a.get(s.index);if(!c)continue;r.push({index:s.index,transitionId:s.transitionId,target:s.target,argumentDigest:await Nr(c.arguments),...c.workflowSourceFingerprint?{workflowSourceFingerprint:c.workflowSourceFingerprint}:{}})}return r}async function $r(e){return ni(e,"mutation set")}async function kn(e,t){let i=await Sn(e.principal),n=await ii(t,e.plan.steps,e.stepArguments);return{schemaVersion:"1",planDigest:e.plan.planDigest??"",graphFingerprint:t.fingerprint,principalDigest:i,mutationSetDigest:await $r(n)}}async function Vn(e){let t=await Sn(e.principal);return ni({schemaVersion:e.schemaVersion,graphFingerprint:e.graphFingerprint,planDigest:e.plan.planDigest??null,initialFacts:L(e.initialFacts),goalFacts:L(e.goalFacts),currentFacts:L(e.currentFacts),satisfiedGates:[...e.satisfiedGates??[]].sort(),principalDigest:t,planningBounds:e.planningBounds,stepArguments:e.stepArguments.map((i)=>({index:i.index,transitionId:i.transitionId,arguments:i.arguments,bodyVariantId:i.bodyVariantId??null,workflowSourceFingerprint:i.workflowSourceFingerprint??null})),limits:e.limits},"execution envelope")}async function ni(e,t){return Fr(e,t,new Set),ne(E(e))}function Fr(e,t,i){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number"){if(Number.isFinite(e))return;throw TypeError(`${t} must contain only finite JSON numbers`)}if(!e||typeof e!=="object")throw TypeError(`${t} must be JSON-safe`);if(i.has(e))throw TypeError(`${t} must not contain cyclic values`);let n=Object.getPrototypeOf(e);if(!Array.isArray(e)&&n!==Object.prototype&&n!==null)throw TypeError(`${t} must contain only JSON objects and arrays`);i.add(e);let a=Array.isArray(e)?e:Object.values(e);for(let r of a)Fr(r,t,i);i.delete(e)}async function Pn(e,t,i={}){Lr(t.signal);let n=Yc(e,t),a=n.length===0?await zc(e,t,n):Dr();if(n.length===0&&!await Bc(e,t,i.planner))n.push(ep());if(n.length===0&&a.binding)n.push(...await qr(t,a.mutations,a.binding,i.confirmation));return{ok:n.length===0,...a.executionDigest?{executionDigest:a.executionDigest}:{},...a.binding?{binding:a.binding}:{},mutations:a.mutations,transitions:a.transitions,diagnostics:n}}async function zc(e,t,i){let n=Qc(e,t);try{let[a,r,s]=await Promise.all([Vn(t),ii(e,t.plan.steps,t.stepArguments),kn(t,e)]);return{executionDigest:a,mutations:r,binding:s,transitions:n}}catch{return i.push(Zc()),{...Dr(),transitions:n}}}async function Bc(e,t,i){let n=await(i??new U).plan({schemaVersion:"1",graph:e,initialFacts:t.initialFacts,goalFacts:t.goalFacts,satisfiedGates:t.satisfiedGates,principal:t.principal,bounds:t.planningBounds,signal:t.signal});return tp(n,t.plan)}async function qr(e,t,i,n={}){if(t.length===0)return[];if(e.confirmations.length===0)return[X("execution-confirmation-required","The planned mutation set requires a trusted confirmation receipt","confirmation")];let a=(n.now??Date.now)(),r=n.clockSkewMs??30000,s=n.maxReceiptLifetimeMs??300000,o=new Set;for(let l of e.confirmations){Lr(e.signal);let c=await Kc(l,i,e.signal,a,r,s);if(c==="valid")return[];o.add(c)}return[X(Jc(o),"No trusted confirmation receipt validates the exact execution binding","confirmation")]}async function Kc(e,t,i,n,a,r){if(!np(e,t))return"binding";if(!Uc(e,n,a,r))return"time";let s=jc(e.verifierId);if(!s)return"verifier";try{return await s.verify(e,t,i)?"valid":"proof"}catch{return"proof"}}function Uc(e,t,i,n){let a=Date.parse(e.issuedAt),r=Date.parse(e.expiresAt);return Number.isFinite(a)&&Number.isFinite(r)&&r>a&&a<=t+i&&r>=t-i&&r-a<=n}function Jc(e){if(e.has("binding"))return"execution-confirmation-binding-mismatch";if(e.has("time"))return"execution-confirmation-expired";if(e.has("verifier"))return"execution-confirmation-verifier-unavailable";return"execution-confirmation-invalid"}function Yc(e,t){let i=[];return Hc(e,t,i),Xc(t,i),Wc(e,t,i),i}function Hc(e,t,i){if(t.schemaVersion!=="1")i.push(X("unsupported-execution-version","Execution request schemaVersion must be '1'","envelope"));if(t.graphFingerprint!==e.fingerprint||t.plan.graphFingerprint!==e.fingerprint)i.push(X("execution-graph-mismatch","The execution request does not match the retained graph fingerprint","envelope"));if(t.plan.outcome!=="planned"&&t.plan.outcome!=="complete"||!t.plan.planDigest)i.push(X("execution-plan-not-executable","Guarded execution requires a planned or complete result with a plan digest","envelope"));if(t.plan.steps.length>t.limits.maxPlanSteps)i.push(X("execution-step-limit-exceeded","The plan exceeds the configured execution step limit","envelope"))}function Wc(e,t,i){if(t.stepArguments.length!==t.plan.steps.length)i.push(X("execution-step-arguments-mismatch","Execution arguments must contain exactly one ordered entry per plan step","envelope"));let n=new Set,a=new Map((e.planning?.transitions??[]).map((s)=>[s.id,s])),r=0;for(let[s,o]of t.plan.steps.entries()){let l=t.stepArguments[s],c=a.get(o.transitionId);if(r+=c?.cost??0,n.has(o.transitionId))i.push(En("execution-duplicate-transition","An execution plan cannot repeat a transition",s,o.transitionId));if(n.add(o.transitionId),!c||!ip(o,c,s,r))i.push(En("execution-transition-mismatch","A plan step does not match its retained graph transition",s,o.transitionId));if(!l||l.index!==s||l.transitionId!==o.transitionId)i.push(En("execution-step-arguments-mismatch","Step arguments are missing, reordered, or bound to another transition",s,o.transitionId))}}function Xc(e,t){for(let[i,n]of Object.entries(e.limits)){let a=i==="maxRetriesPerStep";if(!Number.isSafeInteger(n)||n<(a?0:1))t.push(X("invalid-execution-limit",`${i} must be ${a?"a nonnegative":"a positive"} safe integer`,"envelope"))}}function Qc(e,t){let i=new Map((e.planning?.transitions??[]).map((n)=>[n.id,n]));return t.plan.steps.map((n)=>i.get(n.transitionId)).filter((n)=>n!==void 0)}function Dr(){return{mutations:[],transitions:[]}}function Zc(){return X("execution-envelope-not-json-safe","The execution envelope must contain only finite JSON-safe values","envelope")}function ep(){return X("execution-plan-not-canonical","The supplied plan is not the canonical current plan for this graph and request","envelope")}function tp(e,t){return e.outcome===t.outcome&&e.planDigest===t.planDigest&&e.initialStateDigest===t.initialStateDigest&&e.totalCost===t.totalCost&&E(e.steps)===E(t.steps)}function ip(e,t,i,n){return E(e)===E({index:i,transitionId:t.id,target:t.target,cost:t.cost,cumulativeCost:n,requires:t.requires,produces:t.produces,removes:t.removes,gates:t.gates,sources:t.sources,...t.outcomes?.length?{outcomes:t.outcomes}:{}})}function np(e,t){return e.schemaVersion===t.schemaVersion&&e.planDigest===t.planDigest&&e.graphFingerprint===t.graphFingerprint&&e.principalDigest===t.principalDigest&&e.mutationSetDigest===t.mutationSetDigest}function X(e,t,i){return{code:e,message:t,phase:i,severity:"error"}}function En(e,t,i,n){return{...X(e,t,"envelope"),stepIndex:i,transitionId:n}}function Lr(e){if(!e?.aborted)return;if(typeof e.throwIfAborted==="function")e.throwIfAborted();throw new DOMException("Capability execution validation aborted","AbortError")}function ht(e,t){let i=[];return Ie(e,t,"",e,i,new Set),i}function Ie(e,t,i,n,a,r){if(e===!0||e===void 0)return;if(e===!1||!yt(e)){a.push({instancePath:i,keyword:"false-schema"});return}if(typeof e.$ref==="string"){let s=e.$ref;if(!s.startsWith("#/")||r.has(s)){a.push({instancePath:i,keyword:"$ref"});return}let o=cp(n,s.slice(1));if(o===void 0){a.push({instancePath:i,keyword:"$ref"});return}Ie(o,t,i,n,a,new Set(r).add(s))}if(Array.isArray(e.allOf))for(let s of e.allOf)Ie(s,t,i,n,a,r);if(Mr("anyOf",e.anyOf,t,i,n,a,r),Mr("oneOf",e.oneOf,t,i,n,a,r),e.const!==void 0&&!_r(t,e.const))a.push({instancePath:i,keyword:"const"});if(Array.isArray(e.enum)&&!e.enum.some((s)=>_r(t,s)))a.push({instancePath:i,keyword:"enum"});if(e.type!==void 0&&!lp(t,e.type)){a.push({instancePath:i,keyword:"type"});return}if(typeof t==="string")ap(e,t,i,a);if(typeof t==="number")rp(e,t,i,a);if(Array.isArray(t))sp(e,t,i,n,a,r);if(yt(t))op(e,t,i,n,a,r)}function Mr(e,t,i,n,a,r,s){if(!Array.isArray(t))return;let o=t.filter((l)=>{let c=[];return Ie(l,i,n,a,c,s),c.length===0}).length;if(e==="anyOf"&&o===0||e==="oneOf"&&o!==1)r.push({instancePath:n,keyword:e})}function ap(e,t,i,n){if(typeof e.minLength==="number"&&t.length<e.minLength)n.push({instancePath:i,keyword:"minLength"});if(typeof e.maxLength==="number"&&t.length>e.maxLength)n.push({instancePath:i,keyword:"maxLength"});if(typeof e.pattern==="string")try{if(!new RegExp(e.pattern).test(t))n.push({instancePath:i,keyword:"pattern"})}catch{n.push({instancePath:i,keyword:"pattern"})}}function rp(e,t,i,n){if(typeof e.minimum==="number"&&t<e.minimum)n.push({instancePath:i,keyword:"minimum"});if(typeof e.maximum==="number"&&t>e.maximum)n.push({instancePath:i,keyword:"maximum"})}function sp(e,t,i,n,a,r){if(typeof e.minItems==="number"&&t.length<e.minItems)a.push({instancePath:i,keyword:"minItems"});if(typeof e.maxItems==="number"&&t.length>e.maxItems)a.push({instancePath:i,keyword:"maxItems"});if(e.items!==void 0)t.forEach((s,o)=>Ie(e.items,s,`${i}/${o}`,n,a,r))}function op(e,t,i,n,a,r){let s=yt(e.properties)?e.properties:{};for(let o of Array.isArray(e.required)?e.required:[])if(typeof o==="string"&&!(o in t))a.push({instancePath:i,keyword:"required"});for(let[o,l]of Object.entries(t))if(s[o]!==void 0)Ie(s[o],l,`${i}/${Rr(o)}`,n,a,r);else if(e.additionalProperties===!1)a.push({instancePath:i,keyword:"additionalProperties"});else if(e.additionalProperties!==void 0&&e.additionalProperties!==!0)Ie(e.additionalProperties,l,`${i}/${Rr(o)}`,n,a,r)}function lp(e,t){return(Array.isArray(t)?t:[t]).some((n)=>{if(n==="null")return e===null;if(n==="array")return Array.isArray(e);if(n==="object")return yt(e);if(n==="integer")return typeof e==="number"&&Number.isInteger(e);return typeof e===n})}function cp(e,t){return t.split("/").slice(1).reduce((i,n)=>{if(!yt(i)&&!Array.isArray(i))return;let a=n.replaceAll("~1","/").replaceAll("~0","~");return i[a]},e)}function Rr(e){return e.replaceAll("~","~0").replaceAll("/","~1")}function yt(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function _r(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function In(e,t,i,n,a){Ep(t.signal);let r=await Pn(e,t,{confirmation:a.confirmation}),s=[...r.diagnostics];if(!r.ok)return{ok:!1,envelope:r,diagnostics:s};if(xp(a))return s.push(kp(i)),{ok:!1,envelope:r,diagnostics:s};let o=pp(e,t,r,i,a,s);if(!o)return{ok:!1,envelope:r,diagnostics:s};let l=L(n);return s.push(...await dp(o,t,l,i,a),...yp(o,t,i)),{ok:s.length===0,envelope:r,transition:o.transition,...o.descriptor?{descriptor:o.descriptor}:{},diagnostics:s}}function pp(e,t,i,n,a,r){let s=t.plan.steps[n],o=i.transitions[n];if(!s||!o){r.push(Vp(n));return}let l=a.descriptors.get(o.target.id);if(!Sp(o,l))r.push(Q("execution-target-descriptor-mismatch","The retained runtime descriptor does not match the planned target",n,o.id,"preflight"));let c=o.target.kind==="operation"?e.operations.find((p)=>p.id===o.target.id):void 0;return{transition:o,operation:c,descriptor:l}}async function dp(e,t,i,n,a){let r=[];if(!vp(i,e.transition.requires))r.push(ai("execution-prerequisite-missing","Current state does not satisfy every planned transition prerequisite",e.transition,n));if(!await up(e,t,a))r.push(ai("execution-authorization-denied","Current authorization does not permit the planned transition",e.transition,n));if(e.transition.gates.some((s)=>s.status==="denied"))r.push(ai("execution-gate-denied","A planned transition gate is currently denied",e.transition,n));if(!await fp(e,t,i,a))r.push(ai("execution-policy-denied","Current policy does not permit the planned transition",e.transition,n));return r}async function up(e,t,i){if(i.authorize)return i.authorize({transition:e.transition,operation:e.operation,principal:t.principal});if(e.operation)return Be(e.operation,t.principal);return!e.transition.gates.some((n)=>n.kind==="authorization")}async function fp(e,t,i,n){if(!e.transition.gates.some((a)=>a.kind==="policy"))return!0;return n.evaluatePolicy?n.evaluatePolicy({transition:e.transition,principal:t.principal,currentFacts:i}):!1}function yp(e,t,i){let n=t.stepArguments[i];if(!e.descriptor||!n)return[];return[...hp(e.operation,e.transition,e.descriptor,n,i),...ht(e.descriptor.inputSchema,n.arguments).map((r)=>Q("execution-arguments-invalid",`Argument schema validation failed${r.instancePath?` at ${r.instancePath}`:""} (${r.keyword})`,i,e.transition.id,"arguments"))]}async function Gn(e,t,i){if(!e.ok||!e.transition||!e.descriptor)return{ok:!1,facts:L(t),diagnostics:e.diagnostics};let{transition:n,descriptor:a}=e,r=[];if(a.kind==="operation"&&(i.status===void 0||i.status<200||i.status>=300))r.push(Q("execution-response-unsuccessful","The operation did not satisfy its success status contract",jr(e),n.id,"response"));let s=Cp(a,i);if(s!==void 0)for(let l of ht(s,i.body))r.push(Q("execution-response-invalid",`Response schema validation failed${l.instancePath?` at ${l.instancePath}`:""} (${l.keyword})`,jr(e),n.id,"response"));if(r.length>0)return{ok:!1,facts:L(t),diagnostics:r};let o=wp(t,n);return{ok:!0,facts:o,stateDigest:await ti(o),diagnostics:[]}}function hp(e,t,i,n,a){if(i.kind==="workflow")return n.workflowSourceFingerprint===i.sourceFingerprint?[]:[bp(a,t.id)];if(!e)return[Q("execution-operation-not-found","The planned operation is absent from the retained graph",a,t.id,"preflight")];return mp(e,t,i,n,a)}function mp(e,t,i,n,a){let r=[];if(n.bodyVariantId){if(!e.bodyVariants.some((s)=>s.id===n.bodyVariantId))r.push(Q("execution-body-variant-mismatch","The selected request body variant is absent from the retained graph operation",a,t.id,"arguments"));r.push(...gp(i,n,t.id,a))}else if(e.bodyVariants.length>1)r.push(Q("execution-body-variant-required","A canonical request body variant must be selected before execution",a,t.id,"arguments"));return r}function gp(e,t,i,n){let a=e.bodyVariants?.find((r)=>r.id===t.bodyVariantId);if(!a)return[Q("execution-body-schema-missing","The retained tool descriptor has no schema for the selected request body variant",n,i,"arguments")];return ht(a.schema,t.arguments[a.argumentName]).map((r)=>Q("execution-body-invalid",`Request body schema validation failed${r.instancePath?` at ${r.instancePath}`:""} (${r.keyword})`,n,i,"arguments"))}function bp(e,t){return Q("execution-workflow-fingerprint-mismatch","The planned workflow source no longer matches its validated runtime descriptor",e,t,"preflight")}function Cp(e,t){if(e.kind==="workflow")return e.outputSchema;if(t.status===void 0)return;let i=String(t.status),n=`${i[0]}XX`,a=e.responseSchemas.filter((s)=>s.status===i||s.status.toUpperCase()===n||s.status.toLowerCase()==="default"),r=t.mediaType?.split(";",1)[0]?.trim().toLowerCase();return a.find((s)=>!s.mediaType||s.mediaType.toLowerCase()===r)?.schema??a[0]?.schema}function wp(e,t){let i=new Map(L(e).map((n)=>[mt(n),n]));for(let n of t.removes)i.delete(mt(n));for(let n of t.produces)i.set(mt(n),n);return L([...i.values()])}function vp(e,t){let i=new Set(e.map(mt));return t.every((n)=>i.has(mt(n)))}function mt(e){return E(e)}function xp(e){return e.deadlineEpochMs!==void 0&&(e.now??Date.now)()>=e.deadlineEpochMs}function Sp(e,t){return Boolean(t&&t.targetId===e.target.id&&t.kind===e.target.kind)}function kp(e){return zr("execution-deadline-exceeded","The execution deadline was reached before step preflight",e)}function Vp(e){return zr("execution-step-not-found","The requested execution step is absent from the validated plan",e)}function ai(e,t,i,n){return Q(e,t,n,i.id,"preflight")}function jr(e){return Math.max(0,e.envelope.transitions.findIndex((t)=>t.id===e.transition?.id))}function zr(e,t,i){return{code:e,message:t,phase:"preflight",severity:"error",stepIndex:i}}function Q(e,t,i,n,a){return{code:e,message:t,phase:a,severity:"error",stepIndex:i,transitionId:n}}function Ep(e){if(!e?.aborted)return;if(typeof e.throwIfAborted==="function")e.throwIfAborted();throw new DOMException("Capability execution preflight aborted","AbortError")}function Br(e,t){if(!e?.length||t===void 0)return;let i=String(t),n=`${i[0]}XX`;return e.find((a)=>a.status===i)??e.find((a)=>a.status.toUpperCase()===n)??e.find((a)=>a.status==="default")}var Kr=Object.freeze({maxPlanSteps:50,maxTotalTimeMs:300000,maxStepTimeMs:60000,maxTotalAttempts:100,maxRetriesPerStep:3,maxResponseBytes:10485760,maxResultRecords:100,maxEventRecords:500}),Ur=Object.freeze({maxPlanSteps:12,maxTotalTimeMs:60000,maxStepTimeMs:15000,maxTotalAttempts:16,maxRetriesPerStep:1,maxResponseBytes:1048576,maxResultRecords:50,maxEventRecords:100});class An{options;id="guarded-capability-executor-v1";constructor(e){this.options=e}async execute(e){let t=this.options.bindings.now??Date.now,i=this.options.bindings.createCorrelationId?.()??crypto.randomUUID(),n=Pp(e.limits,this.options.bindings.limits),a={...e,limits:n},r=t(),s=r+n.maxTotalTimeMs,o=new Jr(this.options.bindings.eventSink,n.maxEventRecords),l=a.plan.planDigest??"unavailable";await o.emit(On("execution-start",i,a));let c={facts:a.currentFacts,results:[],diagnostics:[],totalAttempts:0},p,d="unavailable";for(let f=0;f<a.plan.steps.length;f+=1){if(p)break;if(f>=n.maxPlanSteps){p=Ap(c,f,"execution-step-limit-exceeded");break}let y;try{y=await this.executeStep({request:a,index:f,state:c,correlationId:i,deadlineEpochMs:s,now:t,events:o})}catch{let h=a.signal?.aborted===!0;y=Ye(c,f,a.plan.steps[f]?.transitionId,0,t(),t,h?"cancelled":"failed",h?"execution-cancelled":"execution-internal-failure")}d=y.executionDigest??d,p=y.terminal}Tp(a,c,n.maxResultRecords);let u=p?.outcome??"completed";return await o.emit({...On(u==="completed"?"execution-complete":$p(u),i,a),durationMs:Math.max(0,t()-r),outcome:u,reasonCode:p?.reasonCode}),{schemaVersion:"1",outcome:u,correlationId:i,graphFingerprint:this.options.graph.fingerprint,planDigest:l,executionDigest:d,steps:c.results.slice(0,n.maxResultRecords),diagnostics:c.diagnostics.slice(0,n.maxResultRecords)}}async executeStep(e){let{request:t,index:i,state:n,correlationId:a,deadlineEpochMs:r,now:s,events:o}=e,l=Gp(this.options.graph,t,i),c=Op(this.options.graph,l),p=Ip(c,l,t.limits),d=s(),u;for(let f=1;f<=p+1;f+=1){if(n.totalAttempts>=t.limits.maxTotalAttempts)return Ye(n,i,l?.id,f-1,d,s,"rejected","execution-attempt-limit-exceeded");n.totalAttempts+=1,await o.emit(He("step-start",a,t,i,f));let y=await this.preflight(t,i,n.facts,r);if(u=y.envelope.executionDigest,!y.ok||!y.transition){n.diagnostics.push(...y.diagnostics);let g=y.diagnostics[0]?.code??"execution-preflight-rejected";return await o.emit({...He("step-failure",a,t,i,f),reasonCode:g}),Ye(n,i,l?.id,f,d,s,"rejected",g,y.diagnostics[0],u)}let h=await this.invokeAttempt(t,i,f,a,r,s),m=await this.handleInvocation({request:t,index:i,attempt:f,state:n,correlationId:a,deadlineEpochMs:r,stepStartedAt:d,now:s,events:o,preflight:y,invocation:h,canRetry:f<=p,executionDigest:u});if(m.retry){await Fp(h.retryAfterMs,t.signal);continue}return m.result}return{executionDigest:u}}preflight(e,t,i,n){return In(this.options.graph,e,t,i,{descriptors:this.options.descriptors,deadlineEpochMs:n,now:this.options.bindings.now,confirmation:this.options.confirmation,authorize:this.options.bindings.authorize,evaluatePolicy:this.options.bindings.evaluatePolicy})}async invokeAttempt(e,t,i,n,a,r){let s=e.plan.steps[t],o=e.stepArguments[t],l=Math.max(1,Math.min(e.limits.maxStepTimeMs,a-r())),c=new AbortController,p=setTimeout(()=>c.abort("step-timeout"),l),d=()=>c.abort(e.signal?.reason??"cancelled");e.signal?.addEventListener("abort",d,{once:!0});try{return await this.options.bindings.invoker.invoke({correlationId:n,stepIndex:t,transitionId:s.transitionId,target:s.target,arguments:o.arguments,attempt:i,timeoutMs:l,maxResponseBytes:e.limits.maxResponseBytes,signal:c.signal})}catch{return{outcome:e.signal?.aborted?"failure":"indeterminate",reasonCode:e.signal?.aborted?"execution-cancelled":"execution-invocation-unknown",retryable:!e.signal?.aborted}}finally{clearTimeout(p),e.signal?.removeEventListener("abort",d)}}async handleInvocation(e){let{request:t,index:i,attempt:n,state:a,correlationId:r,stepStartedAt:s,now:o,events:l,preflight:c,invocation:p,canRetry:d,executionDigest:u}=e;if(t.signal?.aborted)return await l.emit(He("step-cancel",r,t,i,n)),{retry:!1,result:Ye(a,i,c.transition.id,n,s,o,"cancelled","execution-cancelled",void 0,u)};if(p.outcome!=="success"){if(d&&p.retryable)return await l.emit({...He("step-retry",r,t,i,n),responseStatus:p.status,reasonCode:p.reasonCode??"execution-transient-failure"}),{retry:!0};let y=p.outcome==="indeterminate"?"indeterminate":"failed",h=p.reasonCode??(y==="indeterminate"?"execution-upstream-indeterminate":"execution-upstream-failed"),m=Nn(h,i,c.transition.id);return a.diagnostics.push(m),await l.emit({...He("step-failure",r,t,i,n),responseStatus:p.status,reasonCode:h}),{retry:!1,result:Ye(a,i,c.transition.id,n,s,o,y,h,m,u,p.status,Br(c.transition.outcomes,p.status))}}let f=await Gn(c,a.facts,p);if(!f.ok){a.diagnostics.push(...f.diagnostics);let y=f.diagnostics[0]?.code??"execution-response-invalid";return{retry:!1,result:Ye(a,i,c.transition.id,n,s,o,"failed",y,f.diagnostics[0],u,p.status)}}return a.facts=f.facts,a.results.push({index:i,transitionId:c.transition.id,status:"completed",attempts:n,durationMs:Math.max(0,o()-s),responseStatus:p.status,appliedStateDigest:f.stateDigest}),await l.emit({...He("step-success",r,t,i,n),responseStatus:p.status,durationMs:Math.max(0,o()-s)}),{retry:!1,result:{executionDigest:u}}}}function Tn(e,t){return{id:"guarded-capability-executor-factory-v1",create(i){return new An({graph:e,descriptors:i.descriptors,bindings:i,confirmation:t})}}}class Jr{sink;limit;count=0;constructor(e,t){this.sink=e;this.limit=t}async emit(e){if(!this.sink||this.count>=this.limit)return;this.count+=1;try{await this.sink(e)}catch{}}}function Pp(e,t){return Object.fromEntries(Object.entries(Kr).map(([i,n])=>{let a=i,r=t?.[a]??Ur[a];return[i,Math.min(e[a],r,n)]}))}function Ip(e,t,i){if(!e||t?.target.kind!=="operation")return 0;return e.effects.mode==="read"||e.effects.idempotent?i.maxRetriesPerStep:0}function Gp(e,t,i){let n=t.plan.steps[i]?.transitionId;return e.planning?.transitions.find((a)=>a.id===n)}function Op(e,t){return t?.target.kind==="operation"?e.operations.find((i)=>i.id===t.target.id):void 0}function Ye(e,t,i,n,a,r,s,o,l,c,p,d){let u=l??Np(o,t,i);if(!l)e.diagnostics.push(u);e.results.push({index:t,transitionId:i??"unknown",status:s,attempts:n,durationMs:Math.max(0,r()-a),responseStatus:p,diagnostic:u,...d?{declaredOutcome:{status:d.status,produces:d.produces,removes:d.removes}}:{}});let f=s==="cancelled"?"cancelled":e.results.some((y)=>y.index<t&&y.status==="completed")?"partial":s==="rejected"?"rejected":"failed";return{executionDigest:c,terminal:{outcome:f,reasonCode:o}}}function Ap(e,t,i){return e.diagnostics.push(Nn(i,t)),{outcome:e.results.some((n)=>n.status==="completed")?"partial":"rejected",reasonCode:i}}function Tp(e,t,i){let n=new Set(t.results.map((a)=>a.index));for(let[a,r]of e.plan.steps.entries()){if(t.results.length>=i)break;if(!n.has(a))t.results.push({index:a,transitionId:r.transitionId,status:"not-started",attempts:0,durationMs:0})}t.results.sort((a,r)=>a.index-r.index)}function Nn(e,t,i){return{code:e,severity:"error",message:"Guarded execution stopped at this step",phase:"invocation",stepIndex:t,transitionId:i}}function Np(e,t,i){return Nn(e,t,i)}function On(e,t,i){return{schemaVersion:"1",name:e,correlationId:t,graphFingerprint:i.graphFingerprint,planDigest:i.plan.planDigest??"unavailable"}}function He(e,t,i,n,a){return{...On(e,t,i),stepIndex:n,transitionId:i.plan.steps[n]?.transitionId,attempt:a}}function $p(e){return e==="cancelled"?"execution-cancel":"execution-failure"}async function Fp(e,t){let i=Math.max(0,Math.min(e??25,1000));if(i===0)return;await new Promise((n)=>{let a=setTimeout(n,i);t?.addEventListener("abort",()=>{clearTimeout(a),n()},{once:!0})})}function ri(e){let t=['<?xml version="1.0" encoding="UTF-8"?>','<graphml xmlns="http://graphml.graphdrawing.org/xmlns">',' <key id="kind" for="node" attr.name="kind" attr.type="string"/>',' <key id="label" for="node" attr.name="label" attr.type="string"/>',' <key id="edgeType" for="edge" attr.name="type" attr.type="string"/>',' <key id="planningEligible" for="edge" attr.name="planningEligible" attr.type="boolean"/>',` <graph id="${le(e.fingerprint)}" edgedefault="directed">`];for(let i of e.capabilities)t.push(` <node id="${le(i.id)}"><data key="kind">capability</data><data key="label">${le(i.label)}</data></node>`);for(let i of e.operations)t.push(` <node id="${le(i.id)}"><data key="kind">operation</data><data key="label">${le(i.purpose)}</data></node>`);for(let i of e.edges)t.push(` <edge id="${le(i.id)}" source="${le(i.from)}" target="${le(i.to)}"><data key="edgeType">${le(i.type)}</data><data key="planningEligible">${String(i.planningEligible)}</data></edge>`);return t.push(" </graph>","</graphml>"),`${t.join(`
142
142
  `)}
143
143
  `}function le(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}async function $n(e,t,i){return Promise.all(t.cases.map(async(n)=>{let a=await i.classify({graph:e,candidates:e.operations.map((l)=>({toolName:l.sourceOperationId??l.id,operationId:l.id,description:l.purpose})),query:n.query,mode:"lexical",limit:10,principal:n.principalScopes?{scopes:n.principalScopes}:void 0,authority:"decision"}),r=a.matches.map((l)=>l.operationId),s=Yr(e,n.query,a),o=[];for(let l of n.expectedOperationIds??[])if(!r.includes(l))o.push(`missing expected operation ${l}`);for(let l of n.excludedOperationIds??[])if(r.includes(l))o.push(`included excluded operation ${l}`);if(n.expectedOperationIds?.length===0&&r.length>0)o.push(`expected no matches, received ${r.join(", ")}`);if(n.expectedStatus&&n.expectedStatus!==s)o.push(`expected status ${n.expectedStatus}, received ${s}`);return{id:n.id,passed:o.length===0,status:s,operationIds:r,diagnostics:a.diagnostics,failures:o}}))}function Yr(e,t,i){let[n,a]=i.matches;if(!n)return"no-match";if(a&&a.score>=n.score*0.75)return"ambiguous";let r=e.operations.find((s)=>s.id===n.operationId);if(r&&qp(r,t))return"clarification-required";return"matched"}function qp(e,t){let i=e.inputs.filter((o)=>o.required).map((o)=>o.name),n=e.bodyVariants.some((o)=>o.required);if(i.length===0&&!n)return!1;let a=t.toLowerCase(),r=i.some((o)=>a.includes(o.toLowerCase())),s=/\b\d+\b|["'][^"']+["']/.test(t);return!r&&!s}var Hr={id:"capability-graph-v1",async create(e,t){let i=await Pe(e,t);return{graph:i,classifier:new fe,planner:new U,executorFactory:Tn(i),authority:"decision"}}},Wr={version:"1",id:"deterministic",create(){return new fe}};import{readFile as vw,mkdtemp as xw,rename as Sw,rm as kw,writeFile as El}from"fs/promises";import{basename as Vw,dirname as Ew,join as Vl,resolve as ir}from"path";import{fileURLToPath as Pw,pathToFileURL as Iw}from"url";import{DEFAULT_DOCUMENT_SOURCE_POLICY as pt,assertRemoteDocumentUrl as Gw,defineCommand as Ve,redactDocumentUrl as dt}from"@mcp-com-ai/plugin-sdk";var Hb=Na(),Wb=Nt(),Xb=ga(),Ka=$t(),Qb=Ct(),ke=I(),Zb=Ce(),eC=N(),tC=ve(),iC=xe(),v1=Bi(),nC=ja(),aC=za(),rC=Ba(),Yi=rl(),sl=gt();var sC=Hb.Composer,oC=Wb.Document,lC=Xb.Schema,{YAMLError:cC,YAMLParseError:pC,YAMLWarning:dC}=Ka,uC=Qb.Alias,{isAlias:fC,isCollection:yC,isDocument:hC,isMap:mC,isNode:gC,isPair:bC,isScalar:CC,isSeq:wC}=ke,vC=Zb.Pair,xC=eC.Scalar,SC=tC.YAMLMap,kC=iC.YAMLSeq;var VC=nC.Lexer,EC=aC.LineCounter,PC=rC.Parser,{parse:Ua,parseAllDocuments:IC,parseDocument:GC,stringify:OC}=Yi,{visit:AC,visitAsync:TC}=sl;function Hi(e){return/^operation\..+\.completed$/u.test(e.predicate)}function B(e){return E(e)}function K(e){return{predicate:e.predicate,...e.value!==void 0?{value:JSON.parse(E(e.value))}:{}}}function j(e){return`viz-${[...new TextEncoder().encode(e)].map((t)=>t.toString(16).padStart(2,"0")).join("")}`}function de(e){return e.flatMap((t)=>typeof t==="string"?[t]:[]).join(" ").normalize("NFKC").toLocaleLowerCase("en-US")}var ol="flow-card:start",ll="flow-card:outcome",pl=(e)=>`flow-card:step:${e}`;function dl(e,t){let{result:i}=t,n=new Map(e.operations.map((c)=>[c.id,c])),a=qe(t.initialFacts),r=NC(i.steps),s=$C(r),o=LC(t),l=i.steps.map((c)=>RC(c,{operation:ul(c,n),dependsOn:r[c.index].map((p)=>pl(p+1)),level:s[c.index],waits:c.gates.filter((p)=>o(p,c)).map(MC),inputHint:FC(e,i.steps,c,n)}));return{schemaVersion:"1",outcome:i.outcome,levelCount:l.length===0?0:Math.max(...s)+1,cards:[jC(a,qe(t.goalFacts),_C(e,a)),...l,zC(i)]}}function NC(e){return e.map((t,i)=>{let n=new Set;for(let a of t.requires){let r=BC(e,i,B(a));if(r!==void 0)n.add(r)}for(let a=0;a<i;a++){let r=e[a];if(cl(r.removes,[...t.requires,...t.produces])||cl(t.removes,[...r.requires,...r.produces]))n.add(a)}return[...n].sort((a,r)=>a-r)})}function $C(e){let t=[];return e.forEach((i,n)=>{t[n]=i.length?Math.max(...i.map((a)=>t[a]))+1:0}),t}function FC(e,t,i,n){let a=ul(i,n);if(!a)return;let r=qC(a),s=new Map;for(let l of t.slice(0,i.index))if(l.target.kind==="operation")s.set(l.target.id,l.index+1);let o=e.edges.filter((l)=>l.type==="operation-link"&&l.planningEligible&&l.to===a.id&&s.has(l.from)).map((l)=>({edgeIdentity:`edge:${l.id}`,fromStep:s.get(l.from),...l.label?{label:l.label}:{}})).sort((l,c)=>l.fromStep-c.fromStep||l.edgeIdentity.localeCompare(c.edgeIdentity));if(r.length===0&&o.length===0)return;return{status:o.length?"may-be-linked":"needs-input",inputs:r,links:o}}function qC(e){let t=new Map;for(let i of e.inputs){if(!i.required)continue;if(i.location!=="body"){t.set(`${i.location}:${i.name}`,{name:i.name,location:i.location});continue}let n=DC(e,i.schema?.required);for(let a of n.length?n:["body"])t.set(`body:${a}`,{name:a,location:"body"})}return[...t.entries()].sort(([i],[n])=>i.localeCompare(n)).map(([,i])=>i)}function DC(e,t){if(t?.length)return[...t];return[...new Set(e.bodyVariants.filter((i)=>i.required).flatMap((i)=>i.schema.required??[]))]}function LC(e){if(e.satisfiedGates&&e.principalSupplied!==void 0){let i=new Set(e.satisfiedGates),n=e.principalSupplied;return(a,r)=>!Zt(a,r.transitionId,i,n)}let t=new Set(e.result.unsatisfiedGates.map((i)=>`${i.kind}:${i.code}`));return(i)=>t.has(`${i.kind}:${i.code}`)}function MC(e){return{kind:e.kind,code:e.code,...e.detail?{detail:e.detail}:{}}}function RC(e,t){let i=pl(e.index+1),n=t.operation?.purpose||e.target.id,a=qe(e.requires),r=qe(e.produces),s=qe(e.removes);return{identity:i,domId:j(i),kind:"action",label:n,step:e.index+1,level:t.level,dependsOn:t.dependsOn,transitionId:e.transitionId,target:{...e.target},...t.operation?{effectMode:t.operation.effects.mode,purpose:t.operation.purpose}:{},requires:a,produces:r,removes:s,waits:t.waits,...e.outcomes?.length?{otherwise:e.outcomes.map((o)=>({status:o.status,produces:qe(o.produces),removes:qe(o.removes)}))}:{},...t.inputHint?{inputHint:t.inputHint}:{},searchText:de([n,e.transitionId,e.target.id,...[...a,...r,...s].map((o)=>o.predicate)])}}function _C(e,t){let i=new Set(t.map(B));return(e.triggers??[]).filter((n)=>n.produces.some((a)=>i.has(B(a)))).map((n)=>n.id).sort((n,a)=>n.localeCompare(a))}function jC(e,t,i){return{identity:ol,domId:j(ol),kind:"start",label:"Start when the goal is requested",dependsOn:[],requires:[],produces:[],removes:[],waits:[],initialFacts:e,goalFacts:t,...i.length?{triggerIds:[...i]}:{},searchText:de(["start",...i,...[...e,...t].map((n)=>n.predicate)])}}function zC(e){let t=[...new Set(e.diagnostics.map((i)=>i.code))].sort((i,n)=>i.localeCompare(n));return{identity:ll,domId:j(ll),kind:"outcome",label:`Outcome: ${e.outcome}`,dependsOn:[],requires:[],produces:[],removes:[],waits:[],outcome:e.outcome,diagnosticCodes:t,searchText:de(["outcome",e.outcome,...t])}}function ul(e,t){return e.target.kind==="operation"?t.get(e.target.id):void 0}function BC(e,t,i){for(let n=t-1;n>=0;n--)if(e[n].produces.some((a)=>B(a)===i))return n;return}function cl(e,t){let i=new Set(t.map(B));return e.some((n)=>i.has(B(n)))}function qe(e){return[...new Map(e.map((t)=>[B(t),K(t)]))].sort(([t],[i])=>t.localeCompare(i)).map(([,t])=>t)}function Xi(e,t=[]){let i=e.planning?.transitions??[],n=new Map,a=new Map,r=new Map,s=(y,h,m)=>{if(Hi(h))return;let g=B(h);n.set(g,h),y.set(g,(y.get(g)??new Set).add(m))},o=new Map;for(let y of i){for(let h of y.requires)s(a,h,y.target.id);for(let h of y.produces)s(r,h,y.target.id);for(let h of y.outcomes??[])for(let m of h.produces)s(o,m,`${y.target.id} ${h.status}`)}let l=new Map;for(let y of e.triggers??[])for(let h of y.produces)s(l,h,y.id);let c=KC(e,t),p=new Set(c.keys()),d=(y,h)=>({fact:K(n.get(y)),label:Qi(n.get(y)),operations:[...h.get(y)].sort((m,g)=>m.localeCompare(g))}),u=Wi(a),f=new Set(i.map((y)=>y.target.id));return{schemaVersion:"1",orphanRequirements:u.filter((y)=>!r.has(y)&&!o.has(y)&&!l.has(y)&&!p.has(y)).map((y)=>d(y,a)),clientVerifiedFacts:u.filter((y)=>p.has(y)).map((y)=>({...d(y,a),origins:[...c.get(y)].sort()})),outcomes:Wi(r).filter((y)=>!a.has(y)).map((y)=>d(y,r)),responseFacts:Wi(o).map((y)=>d(y,o)),eventFacts:Wi(l).map((y)=>d(y,l)),discoveryOnlyOperations:e.operations.map((y)=>y.id).filter((y)=>!f.has(y)).sort((y,h)=>y.localeCompare(h))}}function KC(e,t=[]){let i=new Map,n=(a,r)=>i.set(B(a),(i.get(B(a))??new Set).add(r));for(let a of e.clientFacts??[])n(a.fact,"contract");for(let a of t)n(a,"option");return i}function fl(e,t=[]){let i=new Map;for(let n of e.clientFacts??[])i.set(B(n.fact),n.fact);for(let n of t)i.set(B(n),n);return[...i.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([,n])=>K(n))}function Qi(e){return e.value===void 0?e.predicate:`${e.predicate}=${JSON.stringify(e.value)}`}function Wi(e){return[...e.keys()].sort((t,i)=>t.localeCompare(i))}var yl=Object.freeze({maxInputBytes:16777216,maxNodes:5000,maxEdges:20000,maxPlanningTransitions:1e4,maxPlanningFacts:1e4,maxStateRelations:50000,maxPlanTraceSteps:1000,maxDiagnostics:2000,maxOutputBytes:33554432}),Zi=Object.freeze(["topology","business-states","planning","plan-trace","flow-cards"]);class De extends Error{code;details;constructor(e,t,i){super(t);this.code=e;this.details=i;this.name="CapabilityGraphVisualizationError"}}function ot(e){return e.value===void 0?e.predicate:`${e.predicate}=${UC(e.value)}`}function UC(e){return JSON.stringify(e)}var lt=340,te=54,bl={capability:48,operation:580},nn=22,_t=56;function Ha(e,t={}){let i=Wa(t.limits);hl(e,i);let n=HC(e,i);if(t.planTrace)hl(t.planTrace,i),iw(n,t.planTrace,i);let a=tn(n.capabilities.map((b)=>b.id),"capability"),r=tn(n.operations.map((b)=>b.id),"operation");for(let b of a)if(r.has(b))G("duplicate-node-id","graph.nodes");nw(n,a,r);let s=[...n.capabilities].sort(en),o=[...n.operations].sort(en),l=[...s.map((b,v)=>aw(b,v,n.operations)),...o.map((b,v)=>rw(b,v,n.capabilities))],c=new Map(l.map((b)=>[b.graphId,b])),p=[...n.edges].sort(en).map((b)=>sw(b,c)),d=n.planning?.transitions?[...n.planning.transitions].sort(en).map(ow):void 0,u=d?lw(d,i):void 0,f=t.planTrace?dw(n,t.planTrace,i):void 0,y=t.planTrace?dl(n,t.planTrace):void 0;if(y)se("maxPlanTraceSteps",y.cards.length-2,i.maxPlanTraceSteps);let h=YC(t.initialView);t.clientVerifiedFacts?.forEach((b,v)=>Me(b,`options.clientVerifiedFacts[${v}]`));let m=n.planning?Xi(n,t.clientVerifiedFacts):void 0,g=[...n.diagnostics].sort((b,v)=>`${b.severity}:${b.code}:${b.operationId??""}:${b.pointer??""}`.localeCompare(`${v.severity}:${v.code}:${v.operationId??""}:${v.pointer??""}`)).map((b,v)=>uw(b,v)),w=Math.max(s.length,o.length,1);return{schemaVersion:"1",graphSchemaVersion:"1",graphFingerprint:n.fingerprint,source:yw(n.source),counts:{capabilities:s.length,operations:o.length,edges:p.length,planningTransitions:d?.length??0,planningFacts:u?.counts.facts??0,businessFacts:u?.counts.businessFacts??0,technicalFacts:u?.counts.technicalFacts??0,stateRelations:u?.counts.relations??0,diagnostics:g.length},layout:{width:970,height:_t*2+w*(te+nn),nodeWidth:lt,nodeHeight:te},nodes:l,edges:p,...d?{planning:{schemaVersion:"1",transitions:d}}:{},...u?{businessStates:u}:{},...f?{planTrace:f}:{},...y?{flowCards:y}:{},...m?{factAudit:m}:{},...n.triggers?.length?{triggers:n.triggers.map(JC)}:{},...h?{initialView:h}:{},diagnostics:g,filters:fw(l,p,g)}}function JC(e){return{id:e.id,kind:e.kind,name:e.name,method:e.method,...e.expression?{expression:e.expression}:{},...e.operationId?{operationId:e.operationId}:{},purpose:e.purpose,produces:e.produces.map(K)}}function YC(e){if(e===void 0)return;if(!Zi.includes(e))G("unknown-initial-view","options.initialView");return e}function Wa(e={}){return Object.fromEntries(Object.entries(yl).map(([t,i])=>{let n=e[t];return[t,typeof n==="number"&&Number.isFinite(n)&&n>0?Math.min(Math.floor(n),i):i]}))}function hl(e,t){let i;try{i=JSON.stringify(e)}catch{G("non-json-input","graph")}let n=new TextEncoder().encode(i).byteLength;se("maxInputBytes",n,t.maxInputBytes),Ya(e,"graph",new WeakSet)}function Ya(e,t,i){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number"){if(!Number.isFinite(e))G("non-json-number",t);return}if(!e||typeof e!=="object")G("non-json-value",t);if(i.has(e))G("cyclic-input",t);if(i.add(e),Array.isArray(e))e.forEach((n,a)=>Ya(n,`${t}[${a}]`,i));else for(let[n,a]of Object.entries(e)){if(a===void 0)continue;Ya(a,`${t}.${n}`,i)}i.delete(e)}function HC(e,t){let i=R(e,"graph");if(i.schemaVersion!=="1")throw new De("unsupported-graph-version","Visualization supports CapabilityGraphV1 schemaVersion '1' only",{path:"graph.schemaVersion"});if(typeof i.fingerprint!=="string"||!/^[a-f0-9]{64}$/.test(i.fingerprint))G("invalid-fingerprint","graph.fingerprint");let n=R(i.source,"graph.source");F(n.kind,"graph.source.kind"),F(n.identifier,"graph.source.identifier");let a=T(i.capabilities,"graph.capabilities"),r=T(i.operations,"graph.operations"),s=T(i.edges,"graph.edges"),o=T(i.diagnostics,"graph.diagnostics"),l=i.triggers===void 0?[]:T(i.triggers,"graph.triggers");if(se("maxNodes",a.length+r.length+l.length,t.maxNodes),l.forEach((c,p)=>tw(c,p)),se("maxEdges",s.length,t.maxEdges),se("maxDiagnostics",o.length,t.maxDiagnostics),a.forEach((c,p)=>WC(c,p)),r.forEach((c,p)=>XC(c,p)),s.forEach((c,p)=>QC(c,p)),o.forEach((c,p)=>ZC(c,p)),i.planning!==void 0){let c=R(i.planning,"graph.planning");if(c.schemaVersion!=="1")G("invalid-planning-version","graph.planning.schemaVersion");let p=T(c.transitions,"graph.planning.transitions");se("maxPlanningTransitions",p.length,t.maxPlanningTransitions),p.forEach((d,u)=>ew(d,u))}return i}function WC(e,t){let i=`graph.capabilities[${t}]`,n=R(e,i);F(n.id,`${i}.id`),F(n.label,`${i}.label`),Rt(n.path,`${i}.path`),Cl(n.provenance,`${i}.provenance`)}function XC(e,t){let i=`graph.operations[${t}]`,n=R(e,i);F(n.id,`${i}.id`),Rt(n.capabilityIds,`${i}.capabilityIds`),F(n.purpose,`${i}.purpose`),Rt(n.useWhen,`${i}.useWhen`),Rt(n.avoidWhen,`${i}.avoidWhen`);let a=R(n.transport,`${i}.transport`);F(a.kind,`${i}.transport.kind`),T(n.inputs,`${i}.inputs`),T(n.bodyVariants,`${i}.bodyVariants`),T(n.outputs,`${i}.outputs`),R(n.effects,`${i}.effects`),T(n.authorization,`${i}.authorization`),Rt(n.prerequisites,`${i}.prerequisites`),R(n.provenance,`${i}.provenance`)}function QC(e,t){let i=`graph.edges[${t}]`,n=R(e,i);if(F(n.id,`${i}.id`),n.type!=="capability-operation"&&n.type!=="operation-link")G("invalid-edge-type",`${i}.type`);if(F(n.from,`${i}.from`),F(n.to,`${i}.to`),typeof n.planningEligible!=="boolean")G("invalid-edge",`${i}.planningEligible`);Cl(n.provenance,`${i}.provenance`)}function ZC(e,t){let i=`graph.diagnostics[${t}]`,n=R(e,i);if(F(n.code,`${i}.code`),n.severity!=="warning"&&n.severity!=="error")G("invalid-diagnostic-severity",`${i}.severity`);F(n.message,`${i}.message`)}function ew(e,t){let i=`graph.planning.transitions[${t}]`,n=R(e,i);F(n.id,`${i}.id`);let a=R(n.target,`${i}.target`);if(a.kind!=="operation"&&a.kind!=="workflow")G("invalid-target-kind",`${i}.target.kind`);F(a.id,`${i}.target.id`);for(let r of["requires","produces","removes"])T(n[r],`${i}.${r}`).forEach((s,o)=>Me(s,`${i}.${r}[${o}]`));if(typeof n.cost!=="number"||!Number.isFinite(n.cost)||n.cost<0)G("invalid-transition-cost",`${i}.cost`);T(n.gates,`${i}.gates`),T(n.sources,`${i}.sources`)}function tw(e,t){let i=`graph.triggers[${t}]`,n=R(e,i);for(let a of["id","name","method","purpose"])F(n[a],`${i}.${a}`);if(n.kind!=="webhook"&&n.kind!=="callback")G("invalid-trigger-kind",`${i}.kind`);T(n.produces,`${i}.produces`).forEach((a,r)=>Me(a,`${i}.produces[${r}]`))}function iw(e,t,i){t.initialFacts.forEach((s,o)=>Me(s,`options.planTrace.initialFacts[${o}]`)),t.goalFacts.forEach((s,o)=>Me(s,`options.planTrace.goalFacts[${o}]`));let n=R(t.result,"options.planTrace.result");if(n.schemaVersion!=="1")G("invalid-plan-trace-version","options.planTrace.result.schemaVersion");if(F(n.graphFingerprint,"options.planTrace.result.graphFingerprint"),!new Set(["planned","clarification-required","complete","unplannable"]).has(String(n.outcome)))G("invalid-plan-trace-outcome","options.planTrace.result.outcome");if(typeof n.totalCost!=="number"||!Number.isFinite(n.totalCost)||n.totalCost<0)G("invalid-plan-trace-cost","options.planTrace.result.totalCost");let a=T(n.steps,"options.planTrace.result.steps");se("maxPlanTraceSteps",a.length,i.maxPlanTraceSteps);let r=new Set((e.planning?.transitions??[]).map((s)=>s.id));a.forEach((s,o)=>{let l=R(s,`options.planTrace.result.steps[${o}]`);if(l.index!==o)G("invalid-plan-trace-index",`options.planTrace.result.steps[${o}].index`);let c=F(l.transitionId,`options.planTrace.result.steps[${o}].transitionId`);if(!r.has(c))G("unknown-plan-trace-transition",`options.planTrace.result.steps[${o}].transitionId`);for(let p of["requires","produces","removes"])T(l[p],`options.planTrace.result.steps[${o}].${p}`).forEach((d,u)=>Me(d,`options.planTrace.result.steps[${o}].${p}[${u}]`));if(l.outcomes!==void 0)T(l.outcomes,`options.planTrace.result.steps[${o}].outcomes`).forEach((p,d)=>{let u=`options.planTrace.result.steps[${o}].outcomes[${d}]`,f=R(p,u);F(f.status,`${u}.status`);for(let y of["produces","removes"])T(f[y],`${u}.${y}`).forEach((h,m)=>Me(h,`${u}.${y}[${m}]`))})}),T(n.unsatisfiedGates,"options.planTrace.result.unsatisfiedGates"),T(n.diagnostics,"options.planTrace.result.diagnostics")}function Me(e,t){let i=R(e,t);F(i.predicate,`${t}.predicate`)}function Cl(e,t){let i=R(e,t);if(!new Set(["extension","document","inferred"]).has(String(i.kind)))G("invalid-provenance",`${t}.kind`)}function nw(e,t,i){let n=new Set([...t,...i]);for(let r of e.operations)for(let s of r.capabilityIds)if(!t.has(s))G("unknown-capability-reference","graph.operations.capabilityIds");tn(e.edges.map((r)=>r.id),"edge");for(let r of e.edges){if(!n.has(r.from)||!n.has(r.to))G("unknown-edge-reference","graph.edges");if(r.type==="capability-operation"&&(!t.has(r.from)||!i.has(r.to)))G("invalid-membership-edge","graph.edges");if(r.type==="operation-link"&&(!i.has(r.from)||!i.has(r.to)))G("invalid-operation-link","graph.edges")}let a=e.planning?.transitions??[];tn(a.map((r)=>r.id),"planning-transition");for(let r of a)if(r.target.kind==="operation"&&!i.has(r.target.id))G("unknown-transition-target","graph.planning.transitions");for(let r of e.diagnostics)if(r.operationId&&!i.has(r.operationId))G("unknown-diagnostic-operation","graph.diagnostics")}function aw(e,t,i){let n=`capability:${e.id}`,a=i.filter((r)=>r.capabilityIds.includes(e.id)).map((r)=>`operation:${r.id}`).sort();return{identity:n,graphId:e.id,domId:j(n),kind:"capability",label:e.label,...e.description?{description:e.description}:{},taxonomy:[...e.path],provenance:ct(e.provenance),relatedIdentities:a,position:{x:bl.capability,y:_t+t*(te+nn)},searchText:de([e.id,e.label,e.description,...e.path])}}function rw(e,t,i){let n=`operation:${e.id}`,a=i.filter((s)=>e.capabilityIds.includes(s.id)).flatMap((s)=>s.path).filter(bw).sort(),r=e.authorization.flatMap((s)=>s.schemes.flatMap((o)=>[o.scheme,...o.scopes]));return{identity:n,graphId:e.id,domId:j(n),kind:"operation",label:e.sourceOperationId??e.id,purpose:e.purpose,taxonomy:a,...e.transport.method?{method:e.transport.method}:{},...e.transport.path?{path:e.transport.path}:{},useWhen:[...e.useWhen],avoidWhen:[...e.avoidWhen],inputs:e.inputs.map(hw),bodyVariants:e.bodyVariants.map(mw),outputs:e.outputs.map(gw),effects:{...e.effects},authorization:e.authorization.map((s)=>({schemes:s.schemes.map((o)=>({scheme:o.scheme,scopes:[...o.scopes]}))})),prerequisites:[...e.prerequisites],fieldProvenance:Object.fromEntries(Object.entries(e.provenance).filter((s)=>Boolean(s[1])).map(([s,o])=>[s,ct(o)])),provenance:ct(e.provenance.identity??{kind:"inferred"}),relatedIdentities:e.capabilityIds.map((s)=>`capability:${s}`).sort(),position:{x:bl.operation,y:_t+t*(te+nn)},searchText:de([e.id,e.sourceOperationId,e.purpose,e.transport.method,e.transport.path,e.effects.mode,...a,...e.useWhen,...e.avoidWhen,...e.prerequisites,...r])}}function sw(e,t){let i=t.get(e.from),n=t.get(e.to),a=`edge:${e.id}`;return{identity:a,graphId:e.id,domId:j(a),type:e.type,sourceIdentity:i.identity,targetIdentity:n.identity,path:`M ${i.position.x+lt} ${i.position.y+te/2} L ${n.position.x} ${n.position.y+te/2}`,...e.label?{label:e.label}:{},planningEligible:e.planningEligible,provenance:ct(e.provenance)}}function ow(e){let t=`transition:${e.id}`;return{identity:t,graphId:e.id,domId:j(t),target:{...e.target},requires:e.requires.map(K),produces:e.produces.map(K),removes:e.removes.map(K),cost:e.cost,gates:e.gates.map((i)=>({kind:i.kind,status:i.status,code:i.code,...i.detail?{detail:i.detail}:{}})),sources:e.sources.map((i)=>({kind:i.kind,provenance:ct(i.provenance)})),searchText:de([e.id,e.target.kind,e.target.id,...e.requires.map(ot),...e.produces.map(ot),...e.removes.map(ot),...e.gates.flatMap((i)=>[i.kind,i.status,i.code,i.detail]),...e.sources.map((i)=>i.kind)])}}function lw(e,t){let i=new Map,n=[];for(let f of e)for(let y of["requires","produces","removes"])for(let h of f[y]){let m=E(h);i.set(m,K(h)),n.push({kind:y,factKey:m,transition:f})}se("maxPlanningFacts",i.size,t.maxPlanningFacts),se("maxStateRelations",n.length,t.maxStateRelations);let a=[...i.keys()].sort(),r=e.map((f)=>f.identity),s=cw(a,r,n),o=a.map((f)=>{let y=i.get(f),h=Xa(y),m=n.filter((g)=>g.factKey===f);return{identity:h,domId:j(h),fact:y,label:ot(y),technical:Hi(y),position:s.get(h),producerIdentities:Ja(m,"produces"),consumerIdentities:Ja(m,"requires"),removerIdentities:Ja(m,"removes"),searchText:de([y.predicate,ot(y)])}}),l=e.map((f)=>({identity:f.identity,domId:j(`state-${f.identity}`),transitionIdentity:f.identity,label:f.target.id,position:s.get(f.identity),searchText:f.searchText})),c=n.map((f)=>pw(f,s)).sort((f,y)=>f.identity.localeCompare(y.identity)),p=Math.max(0,...[...s.values()].map((f)=>f.x)),d=Math.max(0,...[...s.values()].map((f)=>f.y)),u=o.filter((f)=>f.technical).length;return{schemaVersion:"1",facts:o,transitions:l,relations:c,layout:{width:Math.max(970,p+lt+48),height:Math.max(240,d+te+_t),nodeWidth:lt,nodeHeight:te},counts:{facts:o.length,businessFacts:o.length-u,technicalFacts:u,relations:c.length}}}function cw(e,t,i){let n=new Map(e.map((m)=>[m,Xa(JSON.parse(m))])),a=[...n.values(),...t].sort(),r=new Map(a.map((m)=>[m,[]])),s=new Map(a.map((m)=>[m,0]));for(let m of i){let g=n.get(m.factKey),w=m.transition.identity,[b,v]=m.kind==="requires"?[g,w]:[w,g];r.get(b).push(v),s.set(v,(s.get(v)??0)+1)}for(let m of r.values())m.sort();let o=new Map(a.map((m)=>[m,0])),l=a.filter((m)=>s.get(m)===0).sort(),c=new Set;while(l.length){let m=l.shift();c.add(m);for(let g of r.get(m)??[])if(o.set(g,Math.max(o.get(g)??0,(o.get(m)??0)+1)),s.set(g,(s.get(g)??0)-1),s.get(g)===0)l.push(g),l.sort()}let p=Math.max(0,...[...c].map((m)=>o.get(m)??0)),d=a.filter((m)=>!c.has(m)),u=d.filter((m)=>m.startsWith("fact:")),f=d.filter((m)=>m.startsWith("transition:"));for(let m of u)o.set(m,p+1);for(let m of f)o.set(m,p+2);let y=new Map;for(let m of a){let g=o.get(m)??0,w=y.get(g)??[];w.push(m),y.set(g,w)}let h=new Map;for(let[m,g]of[...y].sort(([w],[b])=>w-b))g.sort(),g.forEach((w,b)=>h.set(w,{x:48+m*390,y:_t+b*(te+nn)}));return h}function pw(e,t){let i=Xa(JSON.parse(e.factKey)),n=e.transition.identity,[a,r]=e.kind==="requires"?[i,n]:[n,i],s=t.get(a),o=t.get(r),l=`state-relation:${e.kind}:${n}:${e.factKey}`;return{identity:l,domId:j(l),kind:e.kind,factIdentity:i,transitionIdentity:n,sourceIdentity:a,targetIdentity:r,path:`M ${s.x+lt/2} ${s.y+te/2} L ${o.x+lt/2} ${o.y+te/2}`,sources:e.transition.sources.map((c)=>({kind:c.kind,provenance:ct(c.provenance)}))}}function Ja(e,t){return Le(e.filter((i)=>i.kind===t).map((i)=>i.transition.identity))}function Xa(e){return`fact:${E(e)}`}function dw(e,t,i){if(t.result.graphFingerprint!==e.fingerprint)G("plan-trace-fingerprint-mismatch","options.planTrace.result.graphFingerprint");se("maxPlanTraceSteps",t.result.steps.length,i.maxPlanTraceSteps);let n=ml(t.initialFacts),a=ml(t.goalFacts),r=n,s=[{identity:"plan-state:0",domId:j("plan-state:0"),index:0,label:"Initial state",facts:r,added:r,removed:[]}];for(let o of t.result.steps){let l=new Map(r.map((f)=>[E(f),f])),c=new Map(l);for(let f of o.removes)c.delete(E(f));for(let f of o.produces)c.set(E(f),K(f));r=[...c.entries()].sort(([f],[y])=>f.localeCompare(y)).map(([,f])=>f);let p=r.filter((f)=>!l.has(E(f))),d=[...l.entries()].filter(([f])=>!c.has(f)).sort(([f],[y])=>f.localeCompare(y)).map(([,f])=>f),u=`plan-state:${o.index+1}`;s.push({identity:u,domId:j(u),index:o.index+1,label:`After ${o.transitionId}`,facts:r,added:p,removed:d,transitionId:o.transitionId,target:{...o.target}})}return{schemaVersion:"1",outcome:t.result.outcome,graphFingerprint:t.result.graphFingerprint,initialFacts:n,goalFacts:a,totalCost:t.result.totalCost,states:s,unsatisfiedGates:t.result.unsatisfiedGates.map((o)=>({...o})),diagnostics:t.result.diagnostics.map((o)=>({code:o.code,severity:o.severity,message:o.message,...o.pointer?{pointer:o.pointer}:{},...o.operationId?{operationId:o.operationId}:{}}))}}function ml(e){return[...new Map(e.map((t)=>[E(t),K(t)])).entries()].sort(([t],[i])=>t.localeCompare(i)).map(([,t])=>t)}function uw(e,t){let i=`diagnostic:${t}:${e.code}`;return{identity:i,domId:j(i),code:e.code,severity:e.severity,message:e.message,...e.pointer?{pointer:e.pointer}:{},...e.operationId?{operationIdentity:`operation:${e.operationId}`}:{}}}function fw(e,t,i){return{taxonomy:Le(e.flatMap((n)=>n.taxonomy)),methods:Le(e.flatMap((n)=>n.method?[n.method.toUpperCase()]:[])),effects:Le(e.flatMap((n)=>n.effects?[n.effects.mode]:[])),provenanceKinds:Le(e.map((n)=>n.provenance.kind)),diagnosticSeverities:Le(i.map((n)=>n.severity)),edgeTypes:Le(t.map((n)=>n.type))}}function yw(e){return{kind:e.kind,identifier:gl(e.identifier),...e.canonicalUri?{canonicalUri:gl(e.canonicalUri)}:{},...e.documentVersion?{documentVersion:e.documentVersion}:{},...e.title?{title:e.title}:{},...e.version?{version:e.version}:{}}}function gl(e){if(/^file:/i.test(e)||e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e))return e.split(/[\\/]/).filter(Boolean).at(-1)??"local-source";return e}function hw(e){return{name:e.name,location:e.location,required:e.required,...e.description?{description:e.description}:{},...e.schema?{schema:Qa(e.schema)}:{}}}function mw(e){return{id:e.id,mediaType:e.mediaType,required:e.required,...e.title?{title:e.title}:{},schemaHash:e.schemaHash,schema:Qa(e.schema)}}function gw(e){return{status:e.status,description:e.description,mediaTypes:[...e.mediaTypes],fields:[...e.fields]}}function Qa(e){return{...e.ref?{ref:e.ref}:{},...e.type?{type:e.type}:{},...e.format?{format:e.format}:{},...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.enum?{enum:[...e.enum]}:{},...e.required?{required:[...e.required]}:{},...e.properties?{properties:[...e.properties]}:{},...e.items?{items:Qa(e.items)}:{}}}function ct(e){return{kind:e.kind,...e.pointer?{pointer:e.pointer}:{},...e.detail?{detail:e.detail}:{}}}function Le(e){return[...new Set(e)].sort((t,i)=>t.localeCompare(i))}function bw(e,t,i){return i.indexOf(e)===t}function tn(e,t){let i=new Set;for(let n of e){if(i.has(n))G(`duplicate-${t}-id`,`graph.${t}`);i.add(n)}return i}function en(e,t){return e.id.localeCompare(t.id)}function se(e,t,i){if(t<=i)return;throw new De("visualization-limit-exceeded",`Visualization ${e} exceeded: ${t} > ${i}`,{limit:e,count:t,maximum:i})}function G(e,t){throw new De(e,`Capability graph is invalid for visualization at ${t}`,{path:t})}function R(e,t){if(!e||typeof e!=="object"||Array.isArray(e))G("expected-object",t);return e}function T(e,t){if(!Array.isArray(e))G("expected-array",t);return e}function F(e,t){if(typeof e!=="string"||e.length===0)G("expected-string",t);return e}function Rt(e,t){return T(e,t).map((i,n)=>F(i,`${t}[${n}]`))}async function wl(e,t={}){let i=fl(e,t.clientVerifiedFacts),n=Xi(e,t.clientVerifiedFacts),a=t.reachability===!1?void 0:await Cw(e,{clientVerifiedFacts:i,goalFacts:t.goalFacts?.length?t.goalFacts:n.outcomes.map((s)=>s.fact),bounds:t.bounds??_}),r=a?.results.filter((s)=>!s.reachable).length??0;return{...n,graphFingerprint:e.fingerprint,...a?{reachability:a}:{},clean:n.orphanRequirements.length===0&&r===0}}async function Cw(e,t){let i=e.planning?.transitions??[],n=Za(i.map((l)=>l.target.id)),a=Za(i.flatMap((l)=>l.gates.filter((c)=>c.kind!=="authorization").map((c)=>c.code))),r=t.clientVerifiedFacts,s=new U,o=[];for(let l of t.goalFacts){let c=await s.plan({schemaVersion:"1",graph:e,initialFacts:r,goalFacts:[l],satisfiedGates:a,principal:{authorizedOperationIds:n},bounds:t.bounds});o.push({goal:l,label:Qi(l),outcome:c.outcome,reachable:c.outcome==="planned"||c.outcome==="complete",diagnostics:Za(c.diagnostics.map((p)=>p.code))})}return{kind:"topology-check",initialFacts:[...r],satisfiedGates:a,results:o.sort((l,c)=>l.label.localeCompare(c.label))}}function vl(e){let t=[`Graph fingerprint: ${e.graphFingerprint}`,""],i=(n,a)=>{t.push(`${n}:`),t.push(...a.length?a.map((r)=>` ${r}`):[" none"]),t.push("")};if(i("Orphan requirements (required, never produced, not client-verified)",e.orphanRequirements.map((n)=>`\u2717 ${n.label} required by ${n.operations.join(", ")}`)),i("Client-verified facts",e.clientVerifiedFacts.map((n)=>`\u2022 ${n.label} required by ${n.operations.join(", ")} [${(n.origins??[]).join(", ")}]`)),i("Outcomes (candidate goals)",e.outcomes.map((n)=>`\u2022 ${n.label} produced by ${n.operations.join(", ")}`)),e.responseFacts.length)i("Response outcome facts (established by an observed response, never planned)",e.responseFacts.map((n)=>`\u2022 ${n.label} from ${n.operations.join(", ")}`));if(e.eventFacts.length)i("Event facts (signalled by a declared webhook or callback; HAPI never receives it)",e.eventFacts.map((n)=>`\u2022 ${n.label} from ${n.operations.join(", ")}`));if(i("Discovery-only operations",e.discoveryOnlyOperations),e.reachability){let n=e.reachability;t.push("Reachability (topology check: all operations eligible, all non-authorization gates treated as satisfied; not an authorization or confirmation):"),t.push(` from {${n.initialFacts.map(Qi).join(", ")}}`);for(let a of n.results)t.push(a.reachable?` \u2713 ${a.label}: ${a.outcome}`:` \u2717 ${a.label}: ${a.outcome} (${a.diagnostics.join(", ")||"-"})`);t.push("")}return t.push(e.clean?"Result: clean":"Result: gaps found"),`${t.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcp-com-ai/plugin-capability-graph",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Compile OpenAPI documents into deterministic HAPI capability graphs.",
5
5
  "license": "LRL-CL",
6
6
  "repository": {