skills-layer 0.2.25 → 0.2.26

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.
@@ -26,7 +26,7 @@ ${n}`)+"'";return t.implicitKey?r:ei.foldFlowLines(r,n,ei.FOLD_FLOW,tp(t,!1))}fu
26
26
  `);h===-1?d="-":n===m||h!==m.length-1?(d="+",o&&o()):d="",m&&(n=n.slice(0,-m.length),m[m.length-1]===`
27
27
  `&&(m=m.slice(0,-1)),m=m.replace(nv,`$&${c}`));let g=!1,y,v=-1;for(y=0;y<n.length;++y){let C=n[y];if(C===" ")g=!0;else if(C===`
28
28
  `)v=y;else break}let b=n.substring(0,v<y?v+1:y);b&&(n=n.substring(b.length),b=b.replace(/\n+/g,`$&${c}`));let _=(g?c?"2":"1":"")+d;if(e&&(_+=" "+a(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let C=n.replace(/\n+/g,`
29
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),P=!1,N=tp(r,!0);s!=="folded"&&t!==Tn.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{P=!0});let O=ei.foldFlowLines(`${b}${C}${m}`,c,ei.FOLD_BLOCK,N);if(!P)return`>${_}
29
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),A=!1,N=tp(r,!0);s!=="folded"&&t!==Tn.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{A=!0});let O=ei.foldFlowLines(`${b}${C}${m}`,c,ei.FOLD_BLOCK,N);if(!A)return`>${_}
30
30
  ${c}${O}`}return n=n.replace(/\n+/g,`$&${c}`),`|${_}
31
31
  ${c}${b}${n}${m}`}function lG(e,t,n,r){let{type:i,value:o}=e,{actualString:s,implicitKey:a,indent:l,indentStep:c,inFlow:u}=t;if(a&&o.includes(`
32
32
  `)||u&&/[[\]{},]/.test(o))return hs(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||u||!o.includes(`
@@ -34,16 +34,16 @@ ${c}${b}${n}${m}`}function lG(e,t,n,r){let{type:i,value:o}=e,{actualString:s,imp
34
34
  `))return ep(e,t,n,r);if(np(o)){if(l==="")return t.forceBlockIndent=!0,ep(e,t,n,r);if(a&&l===c)return hs(o,t)}let d=o.replace(/\n+/g,`$&
35
35
  ${l}`);if(s){let p=g=>g.default&&g.tag!=="tag:yaml.org,2002:str"&&g.test?.test(d),{compat:m,tags:h}=t.doc.schema;if(h.some(p)||m?.some(p))return hs(o,t)}return a?d:ei.foldFlowLines(d,l,ei.FOLD_FLOW,tp(t,!1))}function cG(e,t,n,r){let{implicitKey:i,inFlow:o}=t,s=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Tn.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(a=Tn.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case Tn.Scalar.BLOCK_FOLDED:case Tn.Scalar.BLOCK_LITERAL:return i||o?hs(s.value,t):ep(s,t,n,r);case Tn.Scalar.QUOTE_DOUBLE:return Ll(s.value,t);case Tn.Scalar.QUOTE_SINGLE:return tv(s.value,t);case Tn.Scalar.PLAIN:return lG(s,t,n,r);default:return null}},c=l(a);if(c===null){let{defaultKeyType:u,defaultStringType:d}=t.options,p=i&&u||d;if(c=l(p),c===null)throw new Error(`Unsupported default string type ${p}`)}return c}Y0.stringifyString=cG});var Nl=z(rv=>{"use strict";var uG=Kd(),ti=ge(),dG=Tl(),pG=jl();function fG(e,t){let n=Object.assign({blockQuote:!0,commentString:dG.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function mG(e,t){if(t.tag){let i=e.filter(o=>o.tag===t.tag);if(i.length>0)return i.find(o=>o.format===t.format)??i[0]}let n,r;if(ti.isScalar(t)){r=t.value;let i=e.filter(o=>o.identify?.(r));if(i.length>1){let o=i.filter(s=>s.test);o.length>0&&(i=o)}n=i.find(o=>o.format===t.format)??i.find(o=>!o.format)}else r=t,n=e.find(i=>i.nodeClass&&r instanceof i.nodeClass);if(!n){let i=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${i} value`)}return n}function gG(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let i=[],o=(ti.isScalar(e)||ti.isCollection(e))&&e.anchor;o&&uG.anchorIsValid(o)&&(n.add(o),i.push(`&${o}`));let s=e.tag??(t.default?null:t.tag);return s&&i.push(r.directives.tagString(s)),i.join(" ")}function hG(e,t,n,r){if(ti.isPair(e))return e.toString(t,n,r);if(ti.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,o=ti.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>i=l});i??(i=mG(t.doc.schema.tags,o));let s=gG(o,i,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);let a=typeof i.stringify=="function"?i.stringify(o,t,n,r):ti.isScalar(o)?pG.stringifyString(o,t,n,r):o.toString(t,n,r);return s?ti.isScalar(o)||a[0]==="{"||a[0]==="["?`${s} ${a}`:`${s}
36
36
  ${t.indent}${a}`:a}rv.createStringifyContext=fG;rv.stringify=hG});var t$=z(e$=>{"use strict";var Sr=ge(),X0=He(),Q0=Nl(),Fl=Tl();function yG({key:e,value:t},n,r,i){let{allNullValues:o,doc:s,indent:a,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=n,p=Sr.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Sr.isCollection(e)||!Sr.isNode(e)&&typeof e=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let m=!d&&(!e||p&&t==null&&!n.inFlow||Sr.isCollection(e)||(Sr.isScalar(e)?e.type===X0.Scalar.BLOCK_FOLDED||e.type===X0.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!m&&(d||!o),indent:a+l});let h=!1,g=!1,y=Q0.stringify(e,n,()=>h=!0,()=>g=!0);if(!m&&!n.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(n.inFlow){if(o||t==null)return h&&r&&r(),y===""?"?":m?`? ${y}`:y}else if(o&&!d||t==null&&m)return y=`? ${y}`,p&&!h?y+=Fl.lineComment(y,n.indent,c(p)):g&&i&&i(),y;h&&(p=null),m?(p&&(y+=Fl.lineComment(y,n.indent,c(p))),y=`? ${y}
37
- ${a}:`):(y=`${y}:`,p&&(y+=Fl.lineComment(y,n.indent,c(p))));let v,b,w;Sr.isNode(t)?(v=!!t.spaceBefore,b=t.commentBefore,w=t.comment):(v=!1,b=null,w=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!m&&!p&&Sr.isScalar(t)&&(n.indentAtStart=y.length+1),g=!1,!u&&l.length>=2&&!n.inFlow&&!m&&Sr.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let _=!1,C=Q0.stringify(t,n,()=>_=!0,()=>g=!0),P=" ";if(p||v||b){if(P=v?`
38
- `:"",b){let N=c(b);P+=`
39
- ${Fl.indentComment(N,n.indent)}`}C===""&&!n.inFlow?P===`
40
- `&&w&&(P=`
37
+ ${a}:`):(y=`${y}:`,p&&(y+=Fl.lineComment(y,n.indent,c(p))));let v,b,w;Sr.isNode(t)?(v=!!t.spaceBefore,b=t.commentBefore,w=t.comment):(v=!1,b=null,w=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!m&&!p&&Sr.isScalar(t)&&(n.indentAtStart=y.length+1),g=!1,!u&&l.length>=2&&!n.inFlow&&!m&&Sr.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let _=!1,C=Q0.stringify(t,n,()=>_=!0,()=>g=!0),A=" ";if(p||v||b){if(A=v?`
38
+ `:"",b){let N=c(b);A+=`
39
+ ${Fl.indentComment(N,n.indent)}`}C===""&&!n.inFlow?A===`
40
+ `&&w&&(A=`
41
41
 
42
- `):P+=`
42
+ `):A+=`
43
43
  ${n.indent}`}else if(!m&&Sr.isCollection(t)){let N=C[0],O=C.indexOf(`
44
- `),X=O!==-1,G=n.inFlow??t.flow??t.items.length===0;if(X||!G){let ee=!1;if(X&&(N==="&"||N==="!")){let te=C.indexOf(" ");N==="&"&&te!==-1&&te<O&&C[te+1]==="!"&&(te=C.indexOf(" ",te+1)),(te===-1||O<te)&&(ee=!0)}ee||(P=`
44
+ `),X=O!==-1,G=n.inFlow??t.flow??t.items.length===0;if(X||!G){let ee=!1;if(X&&(N==="&"||N==="!")){let te=C.indexOf(" ");N==="&"&&te!==-1&&te<O&&C[te+1]==="!"&&(te=C.indexOf(" ",te+1)),(te===-1||O<te)&&(ee=!0)}ee||(A=`
45
45
  ${n.indent}`)}}else(C===""||C[0]===`
46
- `)&&(P="");return y+=P+C,n.inFlow?_&&r&&r():w&&!_?y+=Fl.lineComment(y,n.indent,c(w)):g&&i&&i(),y}e$.stringifyPair=yG});var ov=z(iv=>{"use strict";var n$=qi("process");function vG(e,...t){e==="debug"&&console.log(...t)}function kG(e,t){(e==="debug"||e==="warn")&&(typeof n$.emitWarning=="function"?n$.emitWarning(t):console.warn(t))}iv.debug=vG;iv.warn=kG});var ap=z(sp=>{"use strict";var op=ge(),r$=He(),rp="<<",ip={identify:e=>e===rp||typeof e=="symbol"&&e.description===rp,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new r$.Scalar(Symbol(rp)),{addToJSMap:i$}),stringify:()=>rp},wG=(e,t)=>(ip.identify(t)||op.isScalar(t)&&(!t.type||t.type===r$.Scalar.PLAIN)&&ip.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===ip.tag&&n.default);function i$(e,t,n){let r=o$(e,n);if(op.isSeq(r))for(let i of r.items)sv(e,t,i);else if(Array.isArray(r))for(let i of r)sv(e,t,i);else sv(e,t,r)}function sv(e,t,n){let r=o$(e,n);if(!op.isMap(r))throw new Error("Merge sources must be maps or map aliases");let i=r.toJSON(null,e,Map);for(let[o,s]of i)t instanceof Map?t.has(o)||t.set(o,s):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function o$(e,t){return e&&op.isAlias(t)?t.resolve(e.doc,e):t}sp.addMergeToJSMap=i$;sp.isMergeKey=wG;sp.merge=ip});var lv=z(l$=>{"use strict";var bG=ov(),s$=ap(),_G=Nl(),a$=ge(),av=Xr();function SG(e,t,{key:n,value:r}){if(a$.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(s$.isMergeKey(e,n))s$.addMergeToJSMap(e,t,r);else{let i=av.toJS(n,"",e);if(t instanceof Map)t.set(i,av.toJS(r,i,e));else if(t instanceof Set)t.add(i);else{let o=xG(n,i,e),s=av.toJS(r,o,e);o in t?Object.defineProperty(t,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[o]=s}}return t}function xG(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(a$.isNode(e)&&n?.doc){let r=_G.createStringifyContext(n.doc,{});r.anchors=new Set;for(let o of n.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let i=e.toString(r);if(!n.mapKeyWarned){let o=JSON.stringify(i);o.length>40&&(o=o.substring(0,36)+'..."'),bG.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return i}return JSON.stringify(t)}l$.addPairToJSMap=SG});var ni=z(cv=>{"use strict";var c$=Dl(),CG=t$(),IG=lv(),lp=ge();function PG(e,t,n){let r=c$.createNode(e,void 0,n),i=c$.createNode(t,void 0,n);return new cp(r,i)}var cp=class e{constructor(t,n=null){Object.defineProperty(this,lp.NODE_TYPE,{value:lp.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return lp.isNode(n)&&(n=n.clone(t)),lp.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return IG.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?CG.stringifyPair(this,t,n,r):JSON.stringify(this)}};cv.Pair=cp;cv.createPair=PG});var uv=z(d$=>{"use strict";var Wi=ge(),u$=Nl(),up=Tl();function AG(e,t,n){return(t.inFlow??e.flow?EG:RG)(e,t,n)}function RG({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:o,onChompKeep:s,onComment:a}){let{indent:l,options:{commentString:c}}=n,u=Object.assign({},n,{indent:o,type:null}),d=!1,p=[];for(let h=0;h<t.length;++h){let g=t[h],y=null;if(Wi.isNode(g))!d&&g.spaceBefore&&p.push(""),dp(n,p,g.commentBefore,d),g.comment&&(y=g.comment);else if(Wi.isPair(g)){let b=Wi.isNode(g.key)?g.key:null;b&&(!d&&b.spaceBefore&&p.push(""),dp(n,p,b.commentBefore,d))}d=!1;let v=u$.stringify(g,u,()=>y=null,()=>d=!0);y&&(v+=up.lineComment(v,o,c(y))),d&&y&&(d=!1),p.push(r+v)}let m;if(p.length===0)m=i.start+i.end;else{m=p[0];for(let h=1;h<p.length;++h){let g=p[h];m+=g?`
46
+ `)&&(A="");return y+=A+C,n.inFlow?_&&r&&r():w&&!_?y+=Fl.lineComment(y,n.indent,c(w)):g&&i&&i(),y}e$.stringifyPair=yG});var ov=z(iv=>{"use strict";var n$=qi("process");function vG(e,...t){e==="debug"&&console.log(...t)}function kG(e,t){(e==="debug"||e==="warn")&&(typeof n$.emitWarning=="function"?n$.emitWarning(t):console.warn(t))}iv.debug=vG;iv.warn=kG});var ap=z(sp=>{"use strict";var op=ge(),r$=He(),rp="<<",ip={identify:e=>e===rp||typeof e=="symbol"&&e.description===rp,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new r$.Scalar(Symbol(rp)),{addToJSMap:i$}),stringify:()=>rp},wG=(e,t)=>(ip.identify(t)||op.isScalar(t)&&(!t.type||t.type===r$.Scalar.PLAIN)&&ip.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===ip.tag&&n.default);function i$(e,t,n){let r=o$(e,n);if(op.isSeq(r))for(let i of r.items)sv(e,t,i);else if(Array.isArray(r))for(let i of r)sv(e,t,i);else sv(e,t,r)}function sv(e,t,n){let r=o$(e,n);if(!op.isMap(r))throw new Error("Merge sources must be maps or map aliases");let i=r.toJSON(null,e,Map);for(let[o,s]of i)t instanceof Map?t.has(o)||t.set(o,s):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function o$(e,t){return e&&op.isAlias(t)?t.resolve(e.doc,e):t}sp.addMergeToJSMap=i$;sp.isMergeKey=wG;sp.merge=ip});var lv=z(l$=>{"use strict";var bG=ov(),s$=ap(),_G=Nl(),a$=ge(),av=Xr();function SG(e,t,{key:n,value:r}){if(a$.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(s$.isMergeKey(e,n))s$.addMergeToJSMap(e,t,r);else{let i=av.toJS(n,"",e);if(t instanceof Map)t.set(i,av.toJS(r,i,e));else if(t instanceof Set)t.add(i);else{let o=xG(n,i,e),s=av.toJS(r,o,e);o in t?Object.defineProperty(t,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[o]=s}}return t}function xG(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(a$.isNode(e)&&n?.doc){let r=_G.createStringifyContext(n.doc,{});r.anchors=new Set;for(let o of n.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let i=e.toString(r);if(!n.mapKeyWarned){let o=JSON.stringify(i);o.length>40&&(o=o.substring(0,36)+'..."'),bG.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return i}return JSON.stringify(t)}l$.addPairToJSMap=SG});var ni=z(cv=>{"use strict";var c$=Dl(),CG=t$(),IG=lv(),lp=ge();function PG(e,t,n){let r=c$.createNode(e,void 0,n),i=c$.createNode(t,void 0,n);return new cp(r,i)}var cp=class e{constructor(t,n=null){Object.defineProperty(this,lp.NODE_TYPE,{value:lp.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return lp.isNode(n)&&(n=n.clone(t)),lp.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return IG.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?CG.stringifyPair(this,t,n,r):JSON.stringify(this)}};cv.Pair=cp;cv.createPair=PG});var uv=z(d$=>{"use strict";var Wi=ge(),u$=Nl(),up=Tl();function AG(e,t,n){return(t.inFlow??e.flow?EG:RG)(e,t,n)}function RG({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:o,onChompKeep:s,onComment:a}){let{indent:l,options:{commentString:c}}=n,u=Object.assign({},n,{indent:o,type:null}),d=!1,p=[];for(let h=0;h<t.length;++h){let g=t[h],y=null;if(Wi.isNode(g))!d&&g.spaceBefore&&p.push(""),dp(n,p,g.commentBefore,d),g.comment&&(y=g.comment);else if(Wi.isPair(g)){let b=Wi.isNode(g.key)?g.key:null;b&&(!d&&b.spaceBefore&&p.push(""),dp(n,p,b.commentBefore,d))}d=!1;let v=u$.stringify(g,u,()=>y=null,()=>d=!0);y&&(v+=up.lineComment(v,o,c(y))),d&&y&&(d=!1),p.push(r+v)}let m;if(p.length===0)m=i.start+i.end;else{m=p[0];for(let h=1;h<p.length;++h){let g=p[h];m+=g?`
47
47
  ${l}${g}`:`
48
48
  `}}return e?(m+=`
49
49
  `+up.indentComment(c(e),l),a&&a()):d&&s&&s(),m}function EG({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:o,flowCollectionPadding:s,options:{commentString:a}}=t;r+=o;let l=Object.assign({},t,{indent:r,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let h=0;h<e.length;++h){let g=e[h],y=null;if(Wi.isNode(g))g.spaceBefore&&d.push(""),dp(t,d,g.commentBefore,!1),g.comment&&(y=g.comment);else if(Wi.isPair(g)){let b=Wi.isNode(g.key)?g.key:null;b&&(b.spaceBefore&&d.push(""),dp(t,d,b.commentBefore,!1),b.comment&&(c=!0));let w=Wi.isNode(g.value)?g.value:null;w?(w.comment&&(y=w.comment),w.commentBefore&&(c=!0)):g.value==null&&b?.comment&&(y=b.comment)}y&&(c=!0);let v=u$.stringify(g,l,()=>y=null);c||(c=d.length>u||v.includes(`
@@ -61,12 +61,12 @@ ${o.comment}`:r.comment}r=i}e.items[n]=wp.isPair(r)?r:new Sv.Pair(r)}}else t("Ex
61
61
 
62
62
  ${s}
63
63
  ${c}
64
- `}};Zl.YAMLError=Wl;Zl.YAMLParseError=Hv;Zl.YAMLWarning=Kv;Zl.prettifyError=l8});var Yl=z(cD=>{"use strict";function c8(e,{flow:t,indicator:n,next:r,offset:i,onError:o,parentIndent:s,startOnNewline:a}){let l=!1,c=a,u=a,d="",p="",m=!1,h=!1,g=null,y=null,v=null,b=null,w=null,_=null,C=null;for(let O of e)switch(h&&(O.type!=="space"&&O.type!=="newline"&&O.type!=="comma"&&o(O.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),g&&(c&&O.type!=="comment"&&O.type!=="newline"&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),O.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&O.source.includes(" ")&&(g=O),u=!0;break;case"comment":{u||o(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let X=O.source.substring(1)||" ";d?d+=p+X:d=X,p="",c=!1;break}case"newline":c?d?d+=O.source:(!_||n!=="seq-item-ind")&&(l=!0):p+=O.source,c=!0,m=!0,(y||v)&&(b=O),u=!0;break;case"anchor":y&&o(O,"MULTIPLE_ANCHORS","A node can have at most one anchor"),O.source.endsWith(":")&&o(O.offset+O.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=O,C??(C=O.offset),c=!1,u=!1,h=!0;break;case"tag":{v&&o(O,"MULTIPLE_TAGS","A node can have at most one tag"),v=O,C??(C=O.offset),c=!1,u=!1,h=!0;break}case n:(y||v)&&o(O,"BAD_PROP_ORDER",`Anchors and tags must be after the ${O.source} indicator`),_&&o(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${t??"collection"}`),_=O,c=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(t){w&&o(O,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=O,c=!1,u=!1;break}default:o(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),c=!1,u=!1}let P=e[e.length-1],N=P?P.offset+P.source.length:i;return h&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(c&&g.indent<=s||r?.type==="block-map"||r?.type==="block-seq")&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:_,spaceBefore:l,comment:d,hasNewline:m,anchor:y,tag:v,newlineAfterProp:b,end:N,start:C??N}}cD.resolveProps=c8});var Dp=z(uD=>{"use strict";function Wv(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
64
+ `}};Zl.YAMLError=Wl;Zl.YAMLParseError=Hv;Zl.YAMLWarning=Kv;Zl.prettifyError=l8});var Yl=z(cD=>{"use strict";function c8(e,{flow:t,indicator:n,next:r,offset:i,onError:o,parentIndent:s,startOnNewline:a}){let l=!1,c=a,u=a,d="",p="",m=!1,h=!1,g=null,y=null,v=null,b=null,w=null,_=null,C=null;for(let O of e)switch(h&&(O.type!=="space"&&O.type!=="newline"&&O.type!=="comma"&&o(O.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),g&&(c&&O.type!=="comment"&&O.type!=="newline"&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),g=null),O.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&O.source.includes(" ")&&(g=O),u=!0;break;case"comment":{u||o(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let X=O.source.substring(1)||" ";d?d+=p+X:d=X,p="",c=!1;break}case"newline":c?d?d+=O.source:(!_||n!=="seq-item-ind")&&(l=!0):p+=O.source,c=!0,m=!0,(y||v)&&(b=O),u=!0;break;case"anchor":y&&o(O,"MULTIPLE_ANCHORS","A node can have at most one anchor"),O.source.endsWith(":")&&o(O.offset+O.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=O,C??(C=O.offset),c=!1,u=!1,h=!0;break;case"tag":{v&&o(O,"MULTIPLE_TAGS","A node can have at most one tag"),v=O,C??(C=O.offset),c=!1,u=!1,h=!0;break}case n:(y||v)&&o(O,"BAD_PROP_ORDER",`Anchors and tags must be after the ${O.source} indicator`),_&&o(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${t??"collection"}`),_=O,c=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(t){w&&o(O,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=O,c=!1,u=!1;break}default:o(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),c=!1,u=!1}let A=e[e.length-1],N=A?A.offset+A.source.length:i;return h&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g&&(c&&g.indent<=s||r?.type==="block-map"||r?.type==="block-seq")&&o(g,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:_,spaceBefore:l,comment:d,hasNewline:m,anchor:y,tag:v,newlineAfterProp:b,end:N,start:C??N}}cD.resolveProps=c8});var Dp=z(uD=>{"use strict";function Wv(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
65
65
  `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(Wv(t.key)||Wv(t.value))return!0}return!1;default:return!0}}uD.containsNewline=Wv});var Zv=z(dD=>{"use strict";var u8=Dp();function d8(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&u8.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}dD.flowIndentCheck=d8});var Jv=z(fD=>{"use strict";var pD=ge();function p8(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r=="function"?r:(o,s)=>o===s||pD.isScalar(o)&&pD.isScalar(s)&&o.value===s.value;return t.some(o=>i(o.key,n))}fD.mapIncludes=p8});var kD=z(vD=>{"use strict";var mD=ni(),f8=ii(),gD=Yl(),m8=Dp(),hD=Zv(),g8=Jv(),yD="All mapping items must start at the same column";function h8({composeNode:e,composeEmptyNode:t},n,r,i,o){let s=o?.nodeClass??f8.YAMLMap,a=new s(n.schema);n.atRoot&&(n.atRoot=!1);let l=r.offset,c=null;for(let u of r.items){let{start:d,key:p,sep:m,value:h}=u,g=gD.resolveProps(d,{indicator:"explicit-key-ind",next:p??m?.[0],offset:l,onError:i,parentIndent:r.indent,startOnNewline:!0}),y=!g.found;if(y){if(p&&(p.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==r.indent&&i(l,"BAD_INDENT",yD)),!g.anchor&&!g.tag&&!m){c=g.end,g.comment&&(a.comment?a.comment+=`
66
66
  `+g.comment:a.comment=g.comment);continue}(g.newlineAfterProp||m8.containsNewline(p))&&i(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else g.found?.indent!==r.indent&&i(l,"BAD_INDENT",yD);n.atKey=!0;let v=g.end,b=p?e(n,p,g,i):t(n,v,d,null,g,i);n.schema.compat&&hD.flowIndentCheck(r.indent,p,i),n.atKey=!1,g8.mapIncludes(n,a.items,b)&&i(v,"DUPLICATE_KEY","Map keys must be unique");let w=gD.resolveProps(m??[],{indicator:"map-value-ind",next:h,offset:b.range[2],onError:i,parentIndent:r.indent,startOnNewline:!p||p.type==="block-scalar"});if(l=w.end,w.found){y&&(h?.type==="block-map"&&!w.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&g.start<w.found.offset-1024&&i(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=h?e(n,h,w,i):t(n,l,m,null,w,i);n.schema.compat&&hD.flowIndentCheck(r.indent,h,i),l=_.range[2];let C=new mD.Pair(b,_);n.options.keepSourceTokens&&(C.srcToken=u),a.items.push(C)}else{y&&i(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),w.comment&&(b.comment?b.comment+=`
67
- `+w.comment:b.comment=w.comment);let _=new mD.Pair(b);n.options.keepSourceTokens&&(_.srcToken=u),a.items.push(_)}}return c&&c<l&&i(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,l,c??l],a}vD.resolveBlockMap=h8});var bD=z(wD=>{"use strict";var y8=oi(),v8=Yl(),k8=Zv();function w8({composeNode:e,composeEmptyNode:t},n,r,i,o){let s=o?.nodeClass??y8.YAMLSeq,a=new s(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset,c=null;for(let{start:u,value:d}of r.items){let p=v8.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?i(p.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{c=p.end,p.comment&&(a.comment=p.comment);continue}let m=d?e(n,d,p,i):t(n,p.end,u,null,p,i);n.schema.compat&&k8.flowIndentCheck(r.indent,d,i),l=m.range[2],a.items.push(m)}return a.range=[r.offset,l,c??l],a}wD.resolveBlockSeq=w8});var _s=z(_D=>{"use strict";function b8(e,t,n,r){let i="";if(e){let o=!1,s="";for(let a of e){let{source:l,type:c}=a;switch(c){case"space":o=!0;break;case"comment":{n&&!o&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";i?i+=s+u:i=u,s="";break}case"newline":i&&(s+=l),o=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=l.length}}return{comment:i,offset:t}}_D.resolveEnd=b8});var ID=z(CD=>{"use strict";var _8=ge(),S8=ni(),SD=ii(),x8=oi(),C8=_s(),xD=Yl(),I8=Dp(),P8=Jv(),Yv="Block collections are not allowed within flow collections",Xv=e=>e&&(e.type==="block-map"||e.type==="block-seq");function A8({composeNode:e,composeEmptyNode:t},n,r,i,o){let s=r.start.source==="{",a=s?"flow map":"flow sequence",l=o?.nodeClass??(s?SD.YAMLMap:x8.YAMLSeq),c=new l(n.schema);c.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let y=0;y<r.items.length;++y){let v=r.items[y],{start:b,key:w,sep:_,value:C}=v,P=xD.resolveProps(b,{flow:a,indicator:"explicit-key-ind",next:w??_?.[0],offset:d,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!P.found){if(!P.anchor&&!P.tag&&!_&&!C){y===0&&P.comma?i(P.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<r.items.length-1&&i(P.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),P.comment&&(c.comment?c.comment+=`
68
- `+P.comment:c.comment=P.comment),d=P.end;continue}!s&&n.options.strict&&I8.containsNewline(w)&&i(w,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)P.comma&&i(P.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(P.comma||i(P.start,"MISSING_CHAR",`Missing , between ${a} items`),P.comment){let N="";e:for(let O of b)switch(O.type){case"comma":case"space":break;case"comment":N=O.source.substring(1);break e;default:break e}if(N){let O=c.items[c.items.length-1];_8.isPair(O)&&(O=O.value??O.key),O.comment?O.comment+=`
69
- `+N:O.comment=N,P.comment=P.comment.substring(N.length+1)}}if(!s&&!_&&!P.found){let N=C?e(n,C,P,i):t(n,P.end,_,null,P,i);c.items.push(N),d=N.range[2],Xv(C)&&i(N.range,"BLOCK_IN_FLOW",Yv)}else{n.atKey=!0;let N=P.end,O=w?e(n,w,P,i):t(n,N,b,null,P,i);Xv(w)&&i(O.range,"BLOCK_IN_FLOW",Yv),n.atKey=!1;let X=xD.resolveProps(_??[],{flow:a,indicator:"map-value-ind",next:C,offset:O.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(X.found){if(!s&&!P.found&&n.options.strict){if(_)for(let te of _){if(te===X.found)break;if(te.type==="newline"){i(te,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}P.start<X.found.offset-1024&&i(X.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?i(C,"MISSING_CHAR",`Missing space after : in ${a}`):i(X.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let G=C?e(n,C,X,i):X.found?t(n,X.end,_,null,X,i):null;G?Xv(C)&&i(G.range,"BLOCK_IN_FLOW",Yv):X.comment&&(O.comment?O.comment+=`
67
+ `+w.comment:b.comment=w.comment);let _=new mD.Pair(b);n.options.keepSourceTokens&&(_.srcToken=u),a.items.push(_)}}return c&&c<l&&i(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,l,c??l],a}vD.resolveBlockMap=h8});var bD=z(wD=>{"use strict";var y8=oi(),v8=Yl(),k8=Zv();function w8({composeNode:e,composeEmptyNode:t},n,r,i,o){let s=o?.nodeClass??y8.YAMLSeq,a=new s(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset,c=null;for(let{start:u,value:d}of r.items){let p=v8.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?i(p.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{c=p.end,p.comment&&(a.comment=p.comment);continue}let m=d?e(n,d,p,i):t(n,p.end,u,null,p,i);n.schema.compat&&k8.flowIndentCheck(r.indent,d,i),l=m.range[2],a.items.push(m)}return a.range=[r.offset,l,c??l],a}wD.resolveBlockSeq=w8});var _s=z(_D=>{"use strict";function b8(e,t,n,r){let i="";if(e){let o=!1,s="";for(let a of e){let{source:l,type:c}=a;switch(c){case"space":o=!0;break;case"comment":{n&&!o&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";i?i+=s+u:i=u,s="";break}case"newline":i&&(s+=l),o=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=l.length}}return{comment:i,offset:t}}_D.resolveEnd=b8});var ID=z(CD=>{"use strict";var _8=ge(),S8=ni(),SD=ii(),x8=oi(),C8=_s(),xD=Yl(),I8=Dp(),P8=Jv(),Yv="Block collections are not allowed within flow collections",Xv=e=>e&&(e.type==="block-map"||e.type==="block-seq");function A8({composeNode:e,composeEmptyNode:t},n,r,i,o){let s=r.start.source==="{",a=s?"flow map":"flow sequence",l=o?.nodeClass??(s?SD.YAMLMap:x8.YAMLSeq),c=new l(n.schema);c.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let y=0;y<r.items.length;++y){let v=r.items[y],{start:b,key:w,sep:_,value:C}=v,A=xD.resolveProps(b,{flow:a,indicator:"explicit-key-ind",next:w??_?.[0],offset:d,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!A.found){if(!A.anchor&&!A.tag&&!_&&!C){y===0&&A.comma?i(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<r.items.length-1&&i(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),A.comment&&(c.comment?c.comment+=`
68
+ `+A.comment:c.comment=A.comment),d=A.end;continue}!s&&n.options.strict&&I8.containsNewline(w)&&i(w,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)A.comma&&i(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(A.comma||i(A.start,"MISSING_CHAR",`Missing , between ${a} items`),A.comment){let N="";e:for(let O of b)switch(O.type){case"comma":case"space":break;case"comment":N=O.source.substring(1);break e;default:break e}if(N){let O=c.items[c.items.length-1];_8.isPair(O)&&(O=O.value??O.key),O.comment?O.comment+=`
69
+ `+N:O.comment=N,A.comment=A.comment.substring(N.length+1)}}if(!s&&!_&&!A.found){let N=C?e(n,C,A,i):t(n,A.end,_,null,A,i);c.items.push(N),d=N.range[2],Xv(C)&&i(N.range,"BLOCK_IN_FLOW",Yv)}else{n.atKey=!0;let N=A.end,O=w?e(n,w,A,i):t(n,N,b,null,A,i);Xv(w)&&i(O.range,"BLOCK_IN_FLOW",Yv),n.atKey=!1;let X=xD.resolveProps(_??[],{flow:a,indicator:"map-value-ind",next:C,offset:O.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(X.found){if(!s&&!A.found&&n.options.strict){if(_)for(let te of _){if(te===X.found)break;if(te.type==="newline"){i(te,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}A.start<X.found.offset-1024&&i(X.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?i(C,"MISSING_CHAR",`Missing space after : in ${a}`):i(X.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let G=C?e(n,C,X,i):X.found?t(n,X.end,_,null,X,i):null;G?Xv(C)&&i(G.range,"BLOCK_IN_FLOW",Yv):X.comment&&(O.comment?O.comment+=`
70
70
  `+X.comment:O.comment=X.comment);let ee=new S8.Pair(O,G);if(n.options.keepSourceTokens&&(ee.srcToken=v),s){let te=c;P8.mapIncludes(n,te.items,O)&&i(N,"DUPLICATE_KEY","Map keys must be unique"),te.items.push(ee)}else{let te=new SD.YAMLMap(n.schema);te.flow=!0,te.items.push(ee);let Q=(G??O).range;te.range=[O.range[0],Q[1],Q[2]],c.items.push(te)}d=G?G.range[2]:X.end}}let p=s?"}":"]",[m,...h]=r.end,g=d;if(m?.source===p)g=m.offset+m.source.length;else{let y=a[0].toUpperCase()+a.substring(1),v=u?`${y} must end with a ${p}`:`${y} in block collection must be sufficiently indented and end with a ${p}`;i(d,u?"MISSING_CHAR":"BAD_INDENT",v),m&&m.source.length!==1&&h.unshift(m)}if(h.length>0){let y=C8.resolveEnd(h,g,n.options.strict,i);y.comment&&(c.comment?c.comment+=`
71
71
  `+y.comment:c.comment=y.comment),c.range=[r.offset,g,y.offset]}else c.range=[r.offset,g,g];return c}CD.resolveFlowCollection=A8});var AD=z(PD=>{"use strict";var R8=ge(),E8=He(),$8=ii(),D8=oi(),T8=kD(),O8=bD(),L8=ID();function Qv(e,t,n,r,i,o){let s=n.type==="block-map"?T8.resolveBlockMap(e,t,n,r,o):n.type==="block-seq"?O8.resolveBlockSeq(e,t,n,r,o):L8.resolveFlowCollection(e,t,n,r,o),a=s.constructor;return i==="!"||i===a.tagName?(s.tag=a.tagName,s):(i&&(s.tag=i),s)}function j8(e,t,n,r,i){let o=r.tag,s=o?t.directives.tagName(o.source,p=>i(o,"TAG_RESOLVE_FAILED",p)):null;if(n.type==="block-seq"){let{anchor:p,newlineAfterProp:m}=r,h=p&&o?p.offset>o.offset?p:o:p??o;h&&(!m||m.offset<h.offset)&&i(h,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!o||!s||s==="!"||s===$8.YAMLMap.tagName&&a==="map"||s===D8.YAMLSeq.tagName&&a==="seq")return Qv(e,t,n,i,s);let l=t.schema.tags.find(p=>p.tag===s&&p.collection===a);if(!l){let p=t.schema.knownTags[s];if(p?.collection===a)t.schema.tags.push(Object.assign({},p,{default:!1})),l=p;else return p?i(o,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection??"scalar"}`,!0):i(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),Qv(e,t,n,i,s)}let c=Qv(e,t,n,i,s,l),u=l.resolve?.(c,p=>i(o,"TAG_RESOLVE_FAILED",p),t.options)??c,d=R8.isNode(u)?u:new E8.Scalar(u);return d.range=c.range,d.tag=s,l?.format&&(d.format=l.format),d}PD.composeCollection=j8});var tk=z(RD=>{"use strict";var ek=He();function N8(e,t,n){let r=t.offset,i=F8(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let o=i.mode===">"?ek.Scalar.BLOCK_FOLDED:ek.Scalar.BLOCK_LITERAL,s=t.source?B8(t.source):[],a=s.length;for(let g=s.length-1;g>=0;--g){let y=s[g][1];if(y===""||y==="\r")a=g;else break}if(a===0){let g=i.chomp==="+"&&s.length>0?`
72
72
  `.repeat(Math.max(1,s.length-1)):"",y=r+i.length;return t.source&&(y+=t.source.length),{value:g,type:o,comment:i.comment,range:[r,y,y]}}let l=t.indent+i.indent,c=t.offset+i.length,u=0;for(let g=0;g<a;++g){let[y,v]=s[g];if(v===""||v==="\r")i.indent===0&&y.length>l&&(l=y.length);else{y.length<l&&n(c+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(l=y.length),u=g,l===0&&!e.atRoot&&n(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=y.length+v.length+1}for(let g=s.length-1;g>=a;--g)s[g][0].length>l&&(a=g+1);let d="",p="",m=!1;for(let g=0;g<u;++g)d+=s[g][0].slice(l)+`
@@ -149,7 +149,7 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
149
149
  `)}function ld(e,t="creator"){if(e.status==="failed"&&(e.settlement||e.recovery)){let c=t==="admin"?`${String(e.payoutId)}: `:"",u=t==="admin"?"the creator's":"your",d=typeof e.failureMessage=="string"&&e.failureMessage.trim()?e.failureMessage.trim().replace(/[.!]+$/u,""):"Payout returned",m=e.recovery?.recoveredUsdCents,g=typeof m=="number"&&Number.isSafeInteger(m)&&m>=0&&typeof e.amountCents=="number"&&m<=e.amountCents?`${me(m)} is back in ${u} withdrawable balance.${m<e.amountCents?` The ${me(e.amountCents-m)} shortfall is borne by ${t==="admin"?"the creator":"you"} (Stripe fees or exchange-rate differences).`:""}`:"The money remains reserved pending admin review of Stripe recovery evidence.";return`${c}Returned by ${u} bank: ${d}. ${g} ${t==="admin"?"The creator can change their bank":"Change your bank"} with skills-layer creator payout-link.`}if(!e.settlement||typeof e.settlement!="object")return"";let n=e.settlement;if(typeof n.currency!="string"||typeof n.netAmount!="number"||typeof e.amountCents!="number")return"";let r=new Intl.NumberFormat("en",{style:"currency",currency:n.currency}).resolvedOptions().maximumFractionDigits,i=c=>new Intl.NumberFormat("en-GB",{style:"currency",currency:n.currency}).format(c/10**r),o=i(typeof n.bankAmount=="number"?n.bankAmount:n.netAmount),s=typeof n.exchangeRate=="number"?` \xB7 rate ${n.exchangeRate}`:"",a=typeof n.priorReturnDeduction=="number"&&n.priorReturnDeduction>0?` \xB7 ${i(n.priorReturnDeduction)} kept by Stripe to cover an earlier returned payout`:"";return`${t==="admin"?`${String(e.payoutId)}: `:""}${me(e.amountCents,"usd")} sent \xB7 ${o} to ${t==="admin"?"the creator's":"your"} bank${s}${a} \xB7 ${String(e.status)}`}function FA(e,t="creator"){return e.map(n=>ld(n,t)).filter(Boolean).join(`
150
150
  `)||"Payouts loaded."}function BA(e,t=Date.now()){return typeof e!="string"||!Number.isFinite(Date.parse(e))?"":`Eligible for approval at ${new Date(e).toISOString()} (in ${Math.max(0,Math.ceil((Date.parse(e)-t)/6e4))} min)`}function MA(e){let t=typeof e.payout=="object"&&e.payout!==null?e.payout:{},n=typeof t.currency=="string"?t.currency:"usd";return["Withdrawal requested.",typeof t.payoutId=="string"?`Payout: ${t.payoutId}`:"",typeof t.status=="string"?`Status: ${t.status}`:"",ld(t),typeof e.availableAfterRequestCents=="number"?`Available after request: ${me(e.availableAfterRequestCents,n)}`:""].filter(Boolean).join(`
151
151
  `)}function Ur(e){return!e||!Number.isFinite(Date.parse(e))?"Not recorded":new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC"}async function UA(e){try{return await e.request(e.session.grant)}catch(t){if(t?.details?.reasonCode!=="mfa_step_up_required")throw t;let r=e.code?.trim()||(e.interactive?(await e.promptSecret("Enter your 6-digit authenticator code: ")).trim():"");if(!r)throw t;return e.session.grant=await e.verify(r),await e.request(e.session.grant)}}function zA(e,t){return["Payout setup link created.",`URL: ${e}`,`Expires: ${typeof t=="string"?t:"not provided"}`,"","Next"," \u2192 Open this link to change your bank account or finish payout setup."].join(`
152
- `)}var qA="Your bank is reviewing a dispute on this payment. Access is paused until it is resolved.";var tl=["verified","published_with_findings","high_risk","pending","unavailable","blocked"],VA=["low","elevated","high"];var GA=["featured","trending","newest","name","relevance","security","effectiveness","platform_score","installs","cost"],Gce=tl.map(e=>({value:e,label:{verified:"Verified",published_with_findings:"Published with findings",high_risk:"High risk",pending:"Platform Score pending",unavailable:"Platform Score unavailable",blocked:"Blocked"}[e]}));var Wz="user_",HA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Zz=/^user_[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/u;function KA(e){let t=e.indexOf("__");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+2).trim();return!n.startsWith(Wz)||r.length===0?null:{ownerUserId:n,baseSlug:r}}function WA(e){if(/\s/u.test(e))return!1;if(HA.test(e))return!0;let t=KA(e);return t!==null&&Zz.test(t.ownerUserId)&&HA.test(t.baseSlug)}function zr(e){return KA(e)?.baseSlug??e}function nl(e){let t=new URL(e),n=t.hostname==="localhost"||t.hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(t.hostname);if(t.username||t.password||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("Backend URLs require HTTPS (HTTP is allowed only on loopback) and must not contain credentials, a query, or a fragment.");return t}async function ZA(e,t){nl(e);let n=!1;for(let r of["/","/health"])try{let i=await t(`${e.replace(/\/+$/u,"")}${r}`,{redirect:"error",signal:AbortSignal.timeout(5e3)});n=!0;let o=await i.json();if(i.ok&&o?.service==="skills-layer-api")return"ok"}catch{}return n?"backend_not_skills_layer":"backend_unreachable"}function JA(e){if(e===void 0)return 90;if(typeof e!="string"||!/^[1-9]\d*d$/iu.test(e.trim()))return null;let t=Number.parseInt(e.trim(),10);return Number.isSafeInteger(t)&&t<=365?t:null}function Kh(e){let t={...e};for(let n of["securityScore","scoreVector","publishedLedgerScore","effectiveBuyerTrustScore","scoreLabel"])delete t[n];for(let n of["securityPosture","trust","securityRuleSummary","ruleSummary"]){let r=t[n];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=Kh(r);n==="trust"&&delete i.score,t[n]=i}}return t}import{spawn as ZM}from"node:child_process";import{createHash as Ue,createPublicKey as dre,randomBytes as Ge}from"node:crypto";import{constants as jB}from"node:fs";import{access as JM,appendFile as pre,chmod as fre,lstat as Qu,mkdir as Uo,open as zo,readdir as mre,readFile as Ui,realpath as Bu,rename as qo,rm as Ze,stat as Ya,writeFile as QP}from"node:fs/promises";import{basename as ot,dirname as Me,join as K,posix as Lt,relative as Mu,resolve as Vo,win32 as st}from"node:path";import{createInterface as YM}from"node:readline/promises";import{spawn as m6}from"node:child_process";import{createHash as vR}from"node:crypto";import{chmod as Qh,lstat as kR,mkdir as wR,open as g6,readFile as ty,rename as h6,rm as Vi,writeFile as md}from"node:fs/promises";import{dirname as ey,posix as y6,win32 as v6}from"node:path";import{posix as Jz,win32 as eR}from"node:path";var Yz="https://github.com/vercel-labs/skills#supported-agents",fd="2026-07-15",Qt=["codex","claude-code","cursor","opencode","amp","kimi-code-cli","replit","universal","antigravity","augment","openclaw","cline","warp","codebuddy","command-code","continue","cortex","crush","deepagents","droid","gemini-cli","github-copilot","goose","junie","iflow-cli","kilo","kiro-cli","kode","mcpjam","mistral-vibe","mux","openhands","pi","qoder","qwen-code","roo","trae","trae-cn","windsurf","zencoder","neovate","pochi","adal","aider-desk","antigravity-cli","astrbot","autohand-code","bob","dexto","loaf","zed","codearts-agent","codemaker","codestudio","devin","eve","firebender","forgecode","hermes-agent","inference-sh","jazz","lingma","moxby","ona","qoder-cn","reasonix","rovodev","tabnine-cli","terramind","tinycloud","zcode","zenflow","promptscript"];var Xz={"kimi-cli":"kimi-code-cli"},dd=[Y("codex","Codex",".codex",{capabilities:Je({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),Y("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:Je({allowedTools:!0,hooks:!0,forkedContext:!0})}),Y("cursor","Cursor",".cursor",{capabilities:Je({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),Y("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:Je({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),yt("amp","Amp",".config/agents",{capabilities:Je({allowedTools:!0})}),yt("kimi-code-cli","Kimi Code CLI",".agents",{legacyEnvVars:["KIMI_CLI_HOME"],legacyGlobalSkillsRelativePaths:[".config/agents/skills"]}),yt("replit","Replit",".config/agents"),yt("universal","Universal",".config/agents"),yt("antigravity","Antigravity",".gemini/antigravity",{capabilities:Je({allowedTools:!0}),detectGlobal:!0}),Y("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",legacyEnvVars:[],capabilities:Je({allowedTools:!0}),adapterRevision:fd,targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills",projectCompatibleRelativePaths:[],projectLegacyRelativePaths:[],globalCompatibleRelativePaths:[],globalLegacyRelativePaths:[]},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},yt("cline","Cline",".agents",{capabilities:Je({allowedTools:!0,hooks:!0})}),yt("warp","Warp",".agents"),Y("codebuddy","CodeBuddy",".codebuddy",{capabilities:Je({allowedTools:!0})}),Y("command-code","Command Code",".commandcode",{capabilities:Je({allowedTools:!0})}),Y("continue","Continue",".continue"),Y("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),Y("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),yt("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),Y("droid","Droid",".factory"),yt("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),yt("github-copilot","GitHub Copilot",".copilot",{capabilities:Je({allowedTools:!0}),detectGlobal:!0}),Y("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),Y("junie","Junie",".junie"),Y("iflow-cli","iFlow CLI",".iflow"),Y("kilo","Kilo Code",".kilocode"),Y("kiro-cli","Kiro CLI",".kiro"),Y("kode","Kode",".kode"),Y("mcpjam","MCPJam",".mcpjam"),Y("mistral-vibe","Mistral Vibe",".vibe"),Y("mux","Mux",".mux"),Y("openhands","OpenHands",".openhands",{capabilities:Je({allowedTools:!0})}),Y("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:Je({allowedTools:!0})}),Y("qoder","Qoder",".qoder",{capabilities:Je({allowedTools:!0})}),Y("qwen-code","Qwen Code",".qwen"),Y("roo","Roo Code",".roo",{capabilities:Je({allowedTools:!0})}),Y("trae","Trae",".trae",{detectProject:!1}),Y("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),Y("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),Y("zencoder","Zencoder",".zencoder",{capabilities:Je({allowedTools:!0})}),Y("neovate","Neovate",".neovate",{capabilities:Je({allowedTools:!0})}),Y("pochi","Pochi",".pochi"),Y("adal","AdaL",".adal"),Y("aider-desk","AiderDesk",".aider-desk"),yt("antigravity-cli","Antigravity CLI",".gemini/antigravity-cli",{detectGlobal:!0}),Y("astrbot","AstrBot","data",{globalRootRelativePath:".astrbot",globalSkillsRelativePath:".astrbot/data/skills"}),Y("autohand-code","Autohand Code CLI",".autohand"),Y("bob","IBM Bob",".bob"),yt("dexto","Dexto",".agents"),yt("loaf","Loaf",".agents"),yt("zed","Zed",".agents"),Y("codearts-agent","CodeArts Agent",".codeartsdoer"),Y("codemaker","Codemaker",".codemaker"),Y("codestudio","Code Studio",".codestudio"),Y("devin","Devin for Terminal",".devin",{globalRootRelativePath:".config/devin"}),Y("eve","Eve","agent",{globalApplicable:!1}),yt("firebender","Firebender",".firebender",{detectGlobal:!0}),Y("forgecode","ForgeCode",".forge"),Y("hermes-agent","Hermes Agent",".hermes"),Y("inference-sh","inference.sh",".inferencesh"),Y("jazz","Jazz",".jazz"),Y("lingma","Lingma",".lingma"),Y("moxby","Moxby",".moxby"),Y("ona","Ona",".ona"),Y("qoder-cn","Qoder CN",".qoder",{globalRootRelativePath:".qoder-cn",detectProject:!1}),Y("reasonix","Reasonix",".reasonix"),Y("rovodev","Rovo Dev",".rovodev"),Y("tabnine-cli","Tabnine CLI",".tabnine/agent"),Y("terramind","Terramind",".terramind"),Y("tinycloud","Tinycloud",".tinycloud"),Y("zcode","ZCode",".zcode"),Y("zenflow","Zenflow",".zencoder",{detectProject:!1,detectGlobal:!1}),yt("promptscript","PromptScript",".agents",{globalApplicable:!1})];t6(Qt,Xz);r6();function et(e=process.env,t=process.platform,n=process.cwd()){let r=rR(t),i=nR(e,t);return dd.map(o=>{let s=oR(o,e,r),a=o.targets.globalSkillsRelativePath!==null,l=a&&i&&o.targets.globalRootRelativePath?Xo(r,i,o.targets.globalRootRelativePath):null,c=a&&i&&o.targets.globalSkillsRelativePath?Xo(r,i,o.targets.globalSkillsRelativePath):null,u=o.targets.projectRootRelativePath?Xo(r,n,o.targets.projectRootRelativePath):null,d=a?s??l:null,p=Xo(r,n,o.targets.projectSkillsRelativePath),m=a?s?r.join(s,"skills"):c:null,h=cd();return{id:o.id,displayName:o.displayName,envVar:o.envVar,capabilities:o.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:p,globalRoot:d,globalSkillsPath:m},installEvidence:h,adapterRevision:o.adapterRevision,pathContracts:{project:{status:"supported",preferredPath:p,preferredRelativePath:o.targets.projectSkillsRelativePath,compatibleReadOnlyPaths:ud(r,n,o.targets.projectCompatibleRelativePaths),legacyReadOnlyPaths:ud(r,n,o.targets.projectLegacyRelativePaths),evidence:cd()},global:a?{status:"supported",preferredPath:m,preferredRelativePath:o.targets.globalSkillsRelativePath,compatibleReadOnlyPaths:i?ud(r,i,o.targets.globalCompatibleRelativePaths):[],legacyReadOnlyPaths:i?ud(r,i,o.targets.globalLegacyRelativePaths):[],evidence:cd()}:{status:"not_applicable",preferredPath:null,preferredRelativePath:null,compatibleReadOnlyPaths:[],legacyReadOnlyPaths:[],evidence:cd()}}}})}async function tR(e={}){let t=e.env??process.env,n=e.platform??process.platform,r=e.cwd??process.cwd(),i=rR(n),o=nR(t,n),s=et(t,n,r),a=e.pathExists??(async()=>!1);return(await Promise.all(s.map(async l=>{let c=e6(l.id),u=[],d=oR(c,t,i);return(c.targets.globalSkillsRelativePath!==null&&d&&await a(d)||c.targets.globalSkillsRelativePath!==null&&d&&await a(i.join(d,"skills")))&&u.push("override"),c.detection.projectProbeRelativePaths.length>0&&await YA({basePath:r,relativePaths:c.detection.projectProbeRelativePaths,pathApi:i,pathExists:a})&&u.push("project"),o&&c.detection.globalProbeRelativePaths.length>0&&await YA({basePath:o,relativePaths:c.detection.globalProbeRelativePaths,pathApi:i,pathExists:a})&&u.push("global"),u.length===0?null:{...l,detectionSources:Qz(u)}}))).flatMap(l=>l?[l]:[])}function nR(e,t){return t==="win32"?pd(e.USERPROFILE,e.HOME):pd(e.HOME)}function rR(e){return e==="win32"?eR:Jz}function pd(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Qz(e){return[...new Set(e)]}async function YA(e){for(let t of e.relativePaths)if(await e.pathExists(Xo(e.pathApi,e.basePath,t)))return!0;return!1}function Xo(e,t,n){return e.join(t,...n.split("/"))}function Y(e,t,n,r={}){let i=r.globalRootRelativePath??n,o=r.detectProject??!0,s=r.globalApplicable??!0,a=r.globalSkillsRelativePath??`${i}/skills`;return{id:e,displayName:t,envVar:r.envVar??iR(e),legacyEnvVars:r.legacyEnvVars??[],capabilities:r.capabilities??Je(),adapterRevision:r.adapterRevision??fd,targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:s?i:null,globalSkillsRelativePath:s?a:null,projectCompatibleRelativePaths:r.compatibleProjectSkillsRelativePaths??[],projectLegacyRelativePaths:r.legacyProjectSkillsRelativePaths??[],globalCompatibleRelativePaths:r.compatibleGlobalSkillsRelativePaths??[],globalLegacyRelativePaths:r.legacyGlobalSkillsRelativePaths??[]},detection:{projectProbeRelativePaths:o?[n,`${n}/skills`]:[],globalProbeRelativePaths:s&&(r.detectGlobal??!0)?[i,a]:[]}}}function yt(e,t,n,r={}){let i=r.detectGlobal??!1,o=r.globalApplicable??!0;return{id:e,displayName:t,envVar:r.envVar??iR(e),legacyEnvVars:r.legacyEnvVars??[],capabilities:r.capabilities??Je(),adapterRevision:r.adapterRevision??fd,targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:o?n:null,globalSkillsRelativePath:o?`${n}/skills`:null,projectCompatibleRelativePaths:r.compatibleProjectSkillsRelativePaths??[],projectLegacyRelativePaths:r.legacyProjectSkillsRelativePaths??[],globalCompatibleRelativePaths:r.compatibleGlobalSkillsRelativePaths??[],globalLegacyRelativePaths:r.legacyGlobalSkillsRelativePaths??[]},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:i&&o?[n,`${n}/skills`]:[]}}}function Je(e={}){let t=["basic_skills"];return e.allowedTools&&t.push("allowed_tools"),e.hooks&&t.push("hooks"),e.forkedContext&&t.push("forked_context"),t.push("local_install"),t}function iR(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function e6(e){return dd.find(t=>t.id===e)}function t6(e,t){let n=new Set;for(let r of e){if(!XA(r))throw new Error(`Unsafe canonical agent id: ${JSON.stringify(r)}`);if(n.has(r))throw new Error(`Duplicate canonical agent id: ${r}`);n.add(r)}for(let r of Object.keys(t)){if(!XA(r))throw new Error(`Unsafe alias: ${JSON.stringify(r)}`);if(n.has(r))throw new Error(`Alias ${r} collides with a canonical agent id`);let i=new Set([r]),o=t[r];for(;!n.has(o);){if(i.has(o))throw new Error(`Agent alias cycle detected at ${o}`);i.add(o);let s=t[o];if(!s)throw new Error(`Agent alias ${r} has unknown target ${o}`);o=s}}}function XA(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}function cd(){return{sourceUrl:Yz,checkedAt:fd,state:"contract_tested",supportedPlatforms:["darwin","linux","win32"],hostVersion:null}}function ud(e,t,n){return n.map(r=>({path:Xo(e,t,r),relativePath:r,access:"read_only"}))}function oR(e,t,n){let r=[{envVar:e.envVar,value:pd(t[e.envVar])},...e.legacyEnvVars.map(i=>({envVar:i,value:pd(t[i])}))].filter(i=>i.value!==void 0);if(r.length>1&&new Set(r.map(o=>n6(n,o.value))).size>1)throw new Error(`Conflicting canonical and legacy overrides for ${e.id}: ${r.map(o=>o.envVar).join(", ")}`);return r[0]?.value}function n6(e,t){let n=e.normalize(t);return e===eR?n.toLowerCase():n}function r6(){let e=dd.map(t=>t.id);if(e.length!==Qt.length||e.some((t,n)=>t!==Qt[n]))throw new Error("Agent definitions must exactly match the canonical supported-agent inventory");for(let t of dd){if(!QA(t.targets.projectSkillsRelativePath))throw new Error(`Unsafe project path contract for ${t.id}`);let n=t.targets.globalSkillsRelativePath;if(n!==null&&!QA(n))throw new Error(`Unsafe global path contract for ${t.id}`);if(t.targets.globalRootRelativePath===null!=(n===null))throw new Error(`Inconsistent global path contract for ${t.id}`)}}function QA(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}import{posix as i6,win32 as o6}from"node:path";var s6="2026-10-25",a6="2026-11-24",Wh={codex:{aliases:[],vendor:"OpenAI",productSurface:"Codex CLI and desktop"},vscode:{aliases:["code","visual-studio-code"],vendor:"Microsoft",productSurface:"Visual Studio Code MCP host"},"github-copilot-cli":{aliases:["copilot-cli"],vendor:"GitHub",productSurface:"GitHub Copilot CLI"},"claude-code":{aliases:[],vendor:"Anthropic",productSurface:"Claude Code"},cursor:{aliases:[],vendor:"Anysphere",productSurface:"Cursor"},cline:{aliases:[],vendor:"Cline",productSurface:"Cline extension"},"gemini-cli":{aliases:[],vendor:"Google",productSurface:"Gemini CLI"},windsurf:{aliases:[],vendor:"Cognition",productSurface:"Windsurf"},opencode:{aliases:[],vendor:"OpenCode",productSurface:"OpenCode CLI"},"kiro-cli":{aliases:[],vendor:"AWS",productSurface:"Kiro CLI"},kilo:{aliases:["kilo-code"],vendor:"Kilo Code",productSurface:"Kilo Code"},"qwen-code":{aliases:[],vendor:"Alibaba Cloud",productSurface:"Qwen Code"}},vr=[gn("codex","Codex","codex_toml",[],"https://developers.openai.com/codex/mcp/","Codex stores user MCP servers in its user config.",e=>ye(e,$e(e),".codex","config.toml")),gn("vscode","Visual Studio Code","json_servers",["github-copilot-chat"],"https://code.visualstudio.com/docs/agent-customization/mcp-servers","VS Code supports MCP servers in the user profile and through --add-mcp.",sR,e=>[sR(e),dR(e),...d6(e),ye(e,$e(e),".vscode","extensions")]),gn("github-copilot-cli","GitHub Copilot CLI","json_copilot_mcp_servers",[],"https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-config-dir-reference","Copilot CLI stores user-level MCP definitions in ~/.copilot/mcp-config.json.",e=>ye(e,yr(e.env?.COPILOT_HOME,ye(e,$e(e),".copilot")),"mcp-config.json")),gn("claude-code","Claude Code","json_mcp_servers",[],"https://docs.anthropic.com/en/docs/claude-code/mcp","Claude Code supports user-scoped MCP servers.",e=>ye(e,$e(e),".claude.json")),gn("cursor","Cursor","json_mcp_servers",[],"https://cursor.com/docs/mcp","Cursor supports a global ~/.cursor/mcp.json configuration.",e=>ye(e,$e(e),".cursor","mcp.json")),gn("cline","Cline","json_mcp_servers",[],"https://github.com/cline/cline/blob/main/docs/mcp/mcp-overview.mdx","Cline stores global MCP settings in its user data directory.",e=>ye(e,$e(e),".cline","data","settings","cline_mcp_settings.json")),gn("gemini-cli","Gemini CLI","json_mcp_servers",[],"https://google-gemini.github.io/gemini-cli/docs/tools/mcp-server.html","Gemini CLI reads user MCP servers from ~/.gemini/settings.json.",e=>ye(e,$e(e),".gemini","settings.json")),gn("windsurf","Windsurf","json_mcp_servers",[],"https://docs.windsurf.com/windsurf/cascade/mcp","Windsurf stores the user MCP configuration under ~/.codeium/windsurf.",e=>ye(e,$e(e),".codeium","windsurf","mcp_config.json")),gn("opencode","OpenCode","json_opencode_mcp",[],"https://opencode.ai/docs/mcp-servers/","OpenCode supports local MCP servers in its global configuration.",e=>ye(e,Qo(e),"opencode","opencode.json")),gn("kiro-cli","Kiro CLI","json_mcp_servers",[],"https://kiro.dev/docs/mcp/configuration/","Kiro CLI supports a global MCP configuration under ~/.kiro/settings.",e=>ye(e,$e(e),".kiro","settings","mcp.json")),gn("kilo","Kilo Code","json_opencode_mcp",[],"https://kilo.ai/docs/automate/mcp/using-in-cli","Kilo Code supports MCP servers in its global configuration.",e=>ye(e,Qo(e),"kilo","kilo.json")),gn("qwen-code","Qwen Code","json_mcp_servers",[],"https://qwenlm.github.io/qwen-code-docs/en/users/features/mcp/","Qwen Code reads user MCP servers from ~/.qwen/settings.json.",e=>ye(e,$e(e),".qwen","settings.json"))],aR=new Map(vr.map(e=>[e.id,e])),l6=new Map([["code","vscode"],["visual-studio-code","vscode"],["copilot-cli","github-copilot-cli"]]),c6=new Map([["github-copilot","vscode"],["github-copilot-chat","vscode"]]);function rl(e){let t=e.trim().toLowerCase(),n=l6.get(t)??(aR.has(t)?t:null);if(n)return{status:"host",hostId:n};let r=c6.get(t);return r?{status:"consumer",consumerId:t==="github-copilot"?"github-copilot-chat":t,hostId:r}:{status:"unknown",requestedClient:e}}function Zh(e){return aR.get(e)}function lR(e){let t=vr.filter(n=>Date.parse(`${n.evidence.reviewAfter}T23:59:59.999Z`)<Date.parse(e));return{evidenceStale:t.length>0,warnings:t.length>0?[`MCP compatibility evidence is due for review: ${t.map(n=>n.id).join(", ")}. Update the CLI if a host connection fails.`]:[]}}function cR(e){if(e==="universal")return{installAgentId:e,classification:"skills_only",hostId:null};let t=rl(e);return t.status==="host"?{installAgentId:e,classification:"host",hostId:t.hostId}:t.status==="consumer"?{installAgentId:e,classification:"consumer",hostId:t.hostId}:{installAgentId:e,classification:"unverified",hostId:null}}var tue=Object.freeze([{id:"antigravity-cli",displayName:"Antigravity CLI",classification:"unverified",reason:"No fresh primary evidence in the Phase 126 evidence set proves a safe user-global automatic MCP lifecycle.",manualGuidance:"Do not mutate Antigravity configuration automatically; use its vendor documentation and request evidence review before promotion."}]);async function Jh(e){let t=[];for(let n of vr){let r=new Set([n.resolveConfigPath(e)]);n.id==="vscode"&&r.add(dR(e));let i=[...new Set(n.detectionPaths(e))],o=(await Promise.all(i.map(async m=>await e.pathExists(m)?m:null))).filter(m=>m!==null),s=await e.executableExists?.(n.id)??!1,a=o.map(m=>({kind:r.has(m)?"config":p6(m)?"application":"user_data",path:m}));s&&a.push({kind:"executable",path:n.id});let l=a.some(m=>m.kind==="config"),c=a.length>0,u=e.runningHostIds?.includes(n.id)??!1,p=l&&(e.staleConfigHostIds?.includes(n.id)??!1)?"stale":u?"running":l?"configured":c?"installed":"unavailable";t.push({hostId:n.id,displayName:n.displayName,state:p,installed:c,running:u,configured:l,consumers:n.consumers.map(m=>({id:m,detected:e.extensionIds?.includes("github.copilot-chat")??!1})),signals:a,reason:f6(p,a)})}return t}async function uR(e){return(await Jh(e)).filter(n=>n.installed).map(n=>{let r=Zh(n.hostId);return{hostId:n.hostId,displayName:n.displayName,detected:!0,configured:n.configured,consumers:n.consumers.filter(i=>i.detected).map(i=>i.id),evidence:r.evidence,signals:n.signals.map(i=>({kind:i.kind==="config"?"config":"installation",path:i.path}))}})}function gn(e,t,n,r,i,o,s,a){return{id:e,displayName:t,aliases:[...Wh[e].aliases],vendor:Wh[e].vendor,productSurface:Wh[e].productSurface,classification:"global_automatic",scope:"user_global",supportedPlatforms:["darwin","linux","win32"],supportedVersions:e==="windsurf"?"Legacy Windsurf releases using ~/.codeium/windsurf; the renamed Devin Desktop configuration is not claimed by this adapter.":"vendor-supported release with the cited global MCP mechanism",transport:"stdio",configKind:n,consumers:r,caveats:{reload:"Open a fresh agent session or restart the host after registration changes.",trust:"The host launches the existing tokenless Skills Layer bridge; raw remote credentials are never written to host config.",enterprisePolicy:"Managed enterprise policy can prevent or override user configuration and must be checked by the operator.",remote:"User-global scope is local to the active OS, WSL distribution, SSH host, container, or Codespace.",workspace:"Normal setup never writes workspace or project MCP configuration."},evidence:{sourceUrl:i,checkedAt:s6,reviewAfter:a6,owner:"mcp-client-support-owner",statement:o},resolveConfigPath:s,detectionPaths:a??(l=>[s(l),u6(e,l)])}}function u6(e,t){if(e==="claude-code")return ye(t,$e(t),".claude");if(e==="github-copilot-cli")return yr(t.env?.COPILOT_HOME,ye(t,$e(t),".copilot"));if(e==="windsurf")return ye(t,$e(t),".codeium","windsurf");if(e==="opencode")return ye(t,Qo(t),"opencode");if(e==="kiro-cli")return ye(t,$e(t),".kiro");if(e==="kilo")return ye(t,Qo(t),"kilo");let n={codex:".codex",cursor:".cursor",cline:".cline","gemini-cli":".gemini","qwen-code":".qwen"};return ye(t,$e(t),n[e]??`.${e}`)}function sR(e){let t=e.platform??process.platform;return t==="darwin"?ye(e,$e(e),"Library","Application Support","Code","User","mcp.json"):t==="win32"?ye(e,yr(e.env?.APPDATA,$e(e)),"Code","User","mcp.json"):ye(e,Qo(e),"Code","User","mcp.json")}function dR(e){let t=e.platform??process.platform;return t==="darwin"?ye(e,$e(e),"Library","Application Support","Code - Insiders","User","mcp.json"):t==="win32"?ye(e,yr(e.env?.APPDATA,$e(e)),"Code - Insiders","User","mcp.json"):ye(e,Qo(e),"Code - Insiders","User","mcp.json")}function d6(e){let t=e.platform??process.platform;return t==="darwin"?["/Applications/Visual Studio Code.app","/Applications/Visual Studio Code - Insiders.app",ye(e,$e(e),"Applications","Visual Studio Code.app"),ye(e,$e(e),"Applications","Visual Studio Code - Insiders.app")]:t==="win32"?[ye(e,yr(e.env?.LOCALAPPDATA,$e(e)),"Programs","Microsoft VS Code"),ye(e,yr(e.env?.LOCALAPPDATA,$e(e)),"Programs","Microsoft VS Code Insiders"),ye(e,yr(e.env?.ProgramFiles,"C:\\Program Files"),"Microsoft VS Code")]:["/usr/share/code","/usr/share/code-insiders","/var/lib/flatpak/app/com.visualstudio.code",ye(e,$e(e),".local","share","code")]}function p6(e){return/(?:\.app$|\/Applications\/|\\Programs\\|\/usr\/share\/|\/var\/lib\/flatpak\/)/u.test(e)}function f6(e,t){return e==="unavailable"?"No executable, application, user-data, or global configuration signal was found.":e==="stale"?"A global configuration exists but was marked stale by lifecycle inspection.":e==="running"?"The host is running and at least one installed or configured signal was found.":e==="configured"?"A verified user-global configuration file exists.":`Installed signals found: ${t.map(n=>n.kind).join(", ")}.`}function $e(e){let t=e.platform??process.platform;return yr(t==="win32"?e.env?.USERPROFILE:e.env?.HOME,e.env?.HOME,e.cwd,process.cwd())}function Qo(e){return yr(e.env?.XDG_CONFIG_HOME,ye(e,$e(e),".config"))}function ye(e,...t){return((e.platform??process.platform)==="win32"?o6:i6).join(...t)}function yr(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()??process.cwd()}if(new Set(vr.map(e=>e.id)).size!==vr.length)throw new Error("duplicate MCP host id");if(vr.some(e=>!e.evidence.sourceUrl.startsWith("https://")))throw new Error("automatic MCP hosts require primary HTTPS evidence");if(Qt.length!==73)throw new Error("MCP host registry must not mutate the skill-install inventory");var Yh=Object.freeze([Object.freeze({origin:"https://api.skills-layer.com",audience:"https://api.skills-layer.com/mcp",environment:"production"}),Object.freeze({origin:"https://skills-layer.com",audience:"https://skills-layer.com/mcp",environment:"production"}),Object.freeze({origin:"https://api.staging.findfigg.co.uk",audience:"https://api.staging.findfigg.co.uk/mcp",environment:"staging"}),Object.freeze({origin:"https://staging.findfigg.co.uk",audience:"https://staging.findfigg.co.uk/mcp",environment:"staging"}),Object.freeze({origin:"https://api.preprod.findfigg.co.uk",audience:"https://api.preprod.findfigg.co.uk/mcp",environment:"preproduction"}),Object.freeze({origin:"https://preprod.findfigg.co.uk",audience:"https://preprod.findfigg.co.uk/mcp",environment:"preproduction"})]),pR=Object.freeze(Yh.map(e=>e.origin)),fR=Object.freeze(Yh.map(e=>e.audience));function mR(e){return Yh.some(t=>t.origin===e)}var ny="skills-layer-local-broker";function k6(e){return`broker_${vR("sha256").update(`skills-layer-mcp-broker-v1\0${e}`).digest("hex").slice(0,32)}`}var Bt="skills-layer",w6="2025-06-18",b6=["mcp","skills-layer-mcp-proxy.mjs"],_6=["mcp","skills-layer-mcp-broker.mjs"],S6=["mcp","skills-layer-mcp-broker.lock"],x6=new Set(["universal"]);function ts(e){let t=lR(e.now),n=e.platform??process.platform,r=e.cwd??process.cwd(),i=e.stateDir??O6(e.env,n),o=e.mcpConfigPath??il(n,i,"mcp.json"),s=il(n,i,...b6),a=il(n,i,..._6),l=Gi(o).slice(0,32),c=n==="win32"?`\\\\.\\pipe\\skills-layer-mcp-${l}`:il(n,"/tmp",`skills-layer-mcp-${l}.sock`),u=il(n,i,...S6),d=e.nodePath??process.execPath,p=bR({mcpConfigPath:o}),m=(e.brokerSourceBuilder??_R)({mcpConfigPath:o,socketPath:c,lockPath:u}),h=Gi(p),g=Gi(m),y=new Set(vr.map(w=>w.id)),b=[...vr.map(w=>w.id),...Qt.filter(w=>!y.has(w))].map(w=>{if(y.has(w)){let C=Zh(w),P=C.resolveConfigPath({env:e.env,platform:n,cwd:r});return C6({agentId:w,displayName:C.displayName,configPath:P,configKind:C.configKind,bridgePath:s,brokerPath:a,brokerSocketPath:c,brokerLockPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:h,brokerChecksum:g,brokerSourceBuilder:e.brokerSourceBuilder})}if(x6.has(w))return hR({agentId:w,displayName:w,tier:"tier_3",status:"skills_only",verification:"skills_only",reason:"This agent is currently supported through Skills Layer skill files, not MCP auto-install.",instructions:[`Install skills for ${w} with \`skills-layer install <skill> --agent ${w}\`.`,"MCP auto-install is not claimed for this agent yet."]});let _=cR(w);return hR({agentId:w,displayName:w,tier:"tier_2",status:"manual_handoff",verification:"manual",reason:_.classification==="consumer"?`This install target consumes MCP through ${_.hostId}; configure that host instead.`:"MCP support or the safe writable global config shape has not been verified yet.",instructions:[`Add a local stdio MCP server named ${Bt}.`,`Command: ${d}`,`Args: ${s}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{...t,status:"mcp_registration_plan",serverName:Bt,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:s,brokerPath:a,brokerSocketPath:c,brokerLockPath:u,nodePath:d,mcpConfigPath:o,bridgeChecksum:h,brokerChecksum:g,automaticCount:b.filter(w=>w.status==="automatic").length,manualCount:b.filter(w=>w.status==="manual_handoff").length,skillsOnlyCount:b.filter(w=>w.status==="skills_only").length,unsupportedCount:b.filter(w=>w.status==="unsupported").length,targets:b}}async function Hi(e){let t=ts(e),n=L6(e.clientId),r=t.targets.find(y=>y.agentId===n),i=e.mcpConfig??await ol(t.mcpConfigPath,{allowMissing:!0});if(!i)return gR({plan:t,target:r,mcpConfig:null,tokenConfig:null,tokenPresent:!1,tokenRefPresent:!1,bridgeExists:!1,checksumMatches:!1,brokerExists:!1,brokerChecksumMatches:!1,brokerInstalledChecksum:null,targetConfigured:!1,rawTokenLeaked:!1});let o=await es(t.bridgePath),s=o!==null,a=o!==null&&Gi(o)===t.bridgeChecksum,l=await es(t.brokerPath),c=l!==null,u=l===null?null:Gi(l),d=u===t.brokerChecksum,p=j6(i,r.agentId),m=Ct(p,"token"),h=Ct(p,"tokenRef"),g=await E6(r,m);return gR({plan:t,target:r,mcpConfig:i,tokenConfig:p,tokenPresent:!!m,tokenRefPresent:!!h,bridgeExists:s,checksumMatches:a,brokerExists:c,brokerChecksumMatches:d,brokerInstalledChecksum:u,targetConfigured:g.configured,rawTokenLeaked:g.rawTokenLeaked})}function bR(e){return`#!/usr/bin/env node
152
+ `)}var qA="Your bank is reviewing a dispute on this payment. Access is paused until it is resolved.";var tl=["verified","published_with_findings","high_risk","pending","unavailable","blocked"],VA=["low","elevated","high"];var GA=["featured","trending","newest","name","relevance","security","effectiveness","platform_score","installs","cost"],Gce=tl.map(e=>({value:e,label:{verified:"Verified",published_with_findings:"Published with findings",high_risk:"High risk",pending:"Platform Score pending",unavailable:"Platform Score unavailable",blocked:"Blocked"}[e]}));var Wz="user_",HA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Zz=/^user_[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/u;function KA(e){let t=e.indexOf("__");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+2).trim();return!n.startsWith(Wz)||r.length===0?null:{ownerUserId:n,baseSlug:r}}function WA(e){if(/\s/u.test(e))return!1;if(HA.test(e))return!0;let t=KA(e);return t!==null&&Zz.test(t.ownerUserId)&&HA.test(t.baseSlug)}function zr(e){return KA(e)?.baseSlug??e}function nl(e){let t=new URL(e),n=t.hostname==="localhost"||t.hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(t.hostname);if(t.username||t.password||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("Backend URLs require HTTPS (HTTP is allowed only on loopback) and must not contain credentials, a query, or a fragment.");return t}async function ZA(e,t){nl(e);let n=!1;for(let r of["/","/health"])try{let i=await t(`${e.replace(/\/+$/u,"")}${r}`,{redirect:"error",signal:AbortSignal.timeout(5e3)});n=!0;let o=await i.json();if(i.ok&&o?.service==="skills-layer-api")return"ok"}catch{}return n?"backend_not_skills_layer":"backend_unreachable"}function JA(e){if(e===void 0)return 90;if(typeof e!="string"||!/^[1-9]\d*d$/iu.test(e.trim()))return null;let t=Number.parseInt(e.trim(),10);return Number.isSafeInteger(t)&&t<=365?t:null}function Kh(e){let t={...e};for(let n of["securityScore","scoreVector","publishedLedgerScore","effectiveBuyerTrustScore","scoreLabel"])delete t[n];for(let n of["securityPosture","trust","securityRuleSummary","ruleSummary"]){let r=t[n];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=Kh(r);n==="trust"&&delete i.score,t[n]=i}}return t}import{spawn as ZM}from"node:child_process";import{createHash as Ue,createPublicKey as dre,randomBytes as Ge}from"node:crypto";import{constants as jB}from"node:fs";import{access as JM,appendFile as pre,chmod as fre,lstat as Qu,mkdir as Uo,open as zo,readdir as mre,readFile as Ui,realpath as Bu,rename as qo,rm as Ze,stat as Ya,writeFile as QP}from"node:fs/promises";import{basename as ot,dirname as Me,join as K,posix as Lt,relative as Mu,resolve as Vo,win32 as st}from"node:path";import{createInterface as YM}from"node:readline/promises";import{spawn as m6}from"node:child_process";import{createHash as vR}from"node:crypto";import{chmod as Qh,lstat as kR,mkdir as wR,open as g6,readFile as ty,rename as h6,rm as Vi,writeFile as md}from"node:fs/promises";import{dirname as ey,posix as y6,win32 as v6}from"node:path";import{posix as Jz,win32 as eR}from"node:path";var Yz="https://github.com/vercel-labs/skills#supported-agents",fd="2026-07-15",Qt=["codex","claude-code","cursor","opencode","amp","kimi-code-cli","replit","universal","antigravity","augment","openclaw","cline","warp","codebuddy","command-code","continue","cortex","crush","deepagents","droid","gemini-cli","github-copilot","goose","junie","iflow-cli","kilo","kiro-cli","kode","mcpjam","mistral-vibe","mux","openhands","pi","qoder","qwen-code","roo","trae","trae-cn","windsurf","zencoder","neovate","pochi","adal","aider-desk","antigravity-cli","astrbot","autohand-code","bob","dexto","loaf","zed","codearts-agent","codemaker","codestudio","devin","eve","firebender","forgecode","hermes-agent","inference-sh","jazz","lingma","moxby","ona","qoder-cn","reasonix","rovodev","tabnine-cli","terramind","tinycloud","zcode","zenflow","promptscript"];var Xz={"kimi-cli":"kimi-code-cli"},dd=[Y("codex","Codex",".codex",{capabilities:Je({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),Y("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:Je({allowedTools:!0,hooks:!0,forkedContext:!0})}),Y("cursor","Cursor",".cursor",{capabilities:Je({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),Y("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:Je({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),yt("amp","Amp",".config/agents",{capabilities:Je({allowedTools:!0})}),yt("kimi-code-cli","Kimi Code CLI",".agents",{legacyEnvVars:["KIMI_CLI_HOME"],legacyGlobalSkillsRelativePaths:[".config/agents/skills"]}),yt("replit","Replit",".config/agents"),yt("universal","Universal",".config/agents"),yt("antigravity","Antigravity",".gemini/antigravity",{capabilities:Je({allowedTools:!0}),detectGlobal:!0}),Y("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",legacyEnvVars:[],capabilities:Je({allowedTools:!0}),adapterRevision:fd,targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills",projectCompatibleRelativePaths:[],projectLegacyRelativePaths:[],globalCompatibleRelativePaths:[],globalLegacyRelativePaths:[]},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},yt("cline","Cline",".agents",{capabilities:Je({allowedTools:!0,hooks:!0})}),yt("warp","Warp",".agents"),Y("codebuddy","CodeBuddy",".codebuddy",{capabilities:Je({allowedTools:!0})}),Y("command-code","Command Code",".commandcode",{capabilities:Je({allowedTools:!0})}),Y("continue","Continue",".continue"),Y("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),Y("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),yt("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),Y("droid","Droid",".factory"),yt("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),yt("github-copilot","GitHub Copilot",".copilot",{capabilities:Je({allowedTools:!0}),detectGlobal:!0}),Y("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),Y("junie","Junie",".junie"),Y("iflow-cli","iFlow CLI",".iflow"),Y("kilo","Kilo Code",".kilocode"),Y("kiro-cli","Kiro CLI",".kiro"),Y("kode","Kode",".kode"),Y("mcpjam","MCPJam",".mcpjam"),Y("mistral-vibe","Mistral Vibe",".vibe"),Y("mux","Mux",".mux"),Y("openhands","OpenHands",".openhands",{capabilities:Je({allowedTools:!0})}),Y("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:Je({allowedTools:!0})}),Y("qoder","Qoder",".qoder",{capabilities:Je({allowedTools:!0})}),Y("qwen-code","Qwen Code",".qwen"),Y("roo","Roo Code",".roo",{capabilities:Je({allowedTools:!0})}),Y("trae","Trae",".trae",{detectProject:!1}),Y("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),Y("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),Y("zencoder","Zencoder",".zencoder",{capabilities:Je({allowedTools:!0})}),Y("neovate","Neovate",".neovate",{capabilities:Je({allowedTools:!0})}),Y("pochi","Pochi",".pochi"),Y("adal","AdaL",".adal"),Y("aider-desk","AiderDesk",".aider-desk"),yt("antigravity-cli","Antigravity CLI",".gemini/antigravity-cli",{detectGlobal:!0}),Y("astrbot","AstrBot","data",{globalRootRelativePath:".astrbot",globalSkillsRelativePath:".astrbot/data/skills"}),Y("autohand-code","Autohand Code CLI",".autohand"),Y("bob","IBM Bob",".bob"),yt("dexto","Dexto",".agents"),yt("loaf","Loaf",".agents"),yt("zed","Zed",".agents"),Y("codearts-agent","CodeArts Agent",".codeartsdoer"),Y("codemaker","Codemaker",".codemaker"),Y("codestudio","Code Studio",".codestudio"),Y("devin","Devin for Terminal",".devin",{globalRootRelativePath:".config/devin"}),Y("eve","Eve","agent",{globalApplicable:!1}),yt("firebender","Firebender",".firebender",{detectGlobal:!0}),Y("forgecode","ForgeCode",".forge"),Y("hermes-agent","Hermes Agent",".hermes"),Y("inference-sh","inference.sh",".inferencesh"),Y("jazz","Jazz",".jazz"),Y("lingma","Lingma",".lingma"),Y("moxby","Moxby",".moxby"),Y("ona","Ona",".ona"),Y("qoder-cn","Qoder CN",".qoder",{globalRootRelativePath:".qoder-cn",detectProject:!1}),Y("reasonix","Reasonix",".reasonix"),Y("rovodev","Rovo Dev",".rovodev"),Y("tabnine-cli","Tabnine CLI",".tabnine/agent"),Y("terramind","Terramind",".terramind"),Y("tinycloud","Tinycloud",".tinycloud"),Y("zcode","ZCode",".zcode"),Y("zenflow","Zenflow",".zencoder",{detectProject:!1,detectGlobal:!1}),yt("promptscript","PromptScript",".agents",{globalApplicable:!1})];t6(Qt,Xz);r6();function et(e=process.env,t=process.platform,n=process.cwd()){let r=rR(t),i=nR(e,t);return dd.map(o=>{let s=oR(o,e,r),a=o.targets.globalSkillsRelativePath!==null,l=a&&i&&o.targets.globalRootRelativePath?Xo(r,i,o.targets.globalRootRelativePath):null,c=a&&i&&o.targets.globalSkillsRelativePath?Xo(r,i,o.targets.globalSkillsRelativePath):null,u=o.targets.projectRootRelativePath?Xo(r,n,o.targets.projectRootRelativePath):null,d=a?s??l:null,p=Xo(r,n,o.targets.projectSkillsRelativePath),m=a?s?r.join(s,"skills"):c:null,h=cd();return{id:o.id,displayName:o.displayName,envVar:o.envVar,capabilities:o.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:p,globalRoot:d,globalSkillsPath:m},installEvidence:h,adapterRevision:o.adapterRevision,pathContracts:{project:{status:"supported",preferredPath:p,preferredRelativePath:o.targets.projectSkillsRelativePath,compatibleReadOnlyPaths:ud(r,n,o.targets.projectCompatibleRelativePaths),legacyReadOnlyPaths:ud(r,n,o.targets.projectLegacyRelativePaths),evidence:cd()},global:a?{status:"supported",preferredPath:m,preferredRelativePath:o.targets.globalSkillsRelativePath,compatibleReadOnlyPaths:i?ud(r,i,o.targets.globalCompatibleRelativePaths):[],legacyReadOnlyPaths:i?ud(r,i,o.targets.globalLegacyRelativePaths):[],evidence:cd()}:{status:"not_applicable",preferredPath:null,preferredRelativePath:null,compatibleReadOnlyPaths:[],legacyReadOnlyPaths:[],evidence:cd()}}}})}async function tR(e={}){let t=e.env??process.env,n=e.platform??process.platform,r=e.cwd??process.cwd(),i=rR(n),o=nR(t,n),s=et(t,n,r),a=e.pathExists??(async()=>!1);return(await Promise.all(s.map(async l=>{let c=e6(l.id),u=[],d=oR(c,t,i);return(c.targets.globalSkillsRelativePath!==null&&d&&await a(d)||c.targets.globalSkillsRelativePath!==null&&d&&await a(i.join(d,"skills")))&&u.push("override"),c.detection.projectProbeRelativePaths.length>0&&await YA({basePath:r,relativePaths:c.detection.projectProbeRelativePaths,pathApi:i,pathExists:a})&&u.push("project"),o&&c.detection.globalProbeRelativePaths.length>0&&await YA({basePath:o,relativePaths:c.detection.globalProbeRelativePaths,pathApi:i,pathExists:a})&&u.push("global"),u.length===0?null:{...l,detectionSources:Qz(u)}}))).flatMap(l=>l?[l]:[])}function nR(e,t){return t==="win32"?pd(e.USERPROFILE,e.HOME):pd(e.HOME)}function rR(e){return e==="win32"?eR:Jz}function pd(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Qz(e){return[...new Set(e)]}async function YA(e){for(let t of e.relativePaths)if(await e.pathExists(Xo(e.pathApi,e.basePath,t)))return!0;return!1}function Xo(e,t,n){return e.join(t,...n.split("/"))}function Y(e,t,n,r={}){let i=r.globalRootRelativePath??n,o=r.detectProject??!0,s=r.globalApplicable??!0,a=r.globalSkillsRelativePath??`${i}/skills`;return{id:e,displayName:t,envVar:r.envVar??iR(e),legacyEnvVars:r.legacyEnvVars??[],capabilities:r.capabilities??Je(),adapterRevision:r.adapterRevision??fd,targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:s?i:null,globalSkillsRelativePath:s?a:null,projectCompatibleRelativePaths:r.compatibleProjectSkillsRelativePaths??[],projectLegacyRelativePaths:r.legacyProjectSkillsRelativePaths??[],globalCompatibleRelativePaths:r.compatibleGlobalSkillsRelativePaths??[],globalLegacyRelativePaths:r.legacyGlobalSkillsRelativePaths??[]},detection:{projectProbeRelativePaths:o?[n,`${n}/skills`]:[],globalProbeRelativePaths:s&&(r.detectGlobal??!0)?[i,a]:[]}}}function yt(e,t,n,r={}){let i=r.detectGlobal??!1,o=r.globalApplicable??!0;return{id:e,displayName:t,envVar:r.envVar??iR(e),legacyEnvVars:r.legacyEnvVars??[],capabilities:r.capabilities??Je(),adapterRevision:r.adapterRevision??fd,targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:o?n:null,globalSkillsRelativePath:o?`${n}/skills`:null,projectCompatibleRelativePaths:r.compatibleProjectSkillsRelativePaths??[],projectLegacyRelativePaths:r.legacyProjectSkillsRelativePaths??[],globalCompatibleRelativePaths:r.compatibleGlobalSkillsRelativePaths??[],globalLegacyRelativePaths:r.legacyGlobalSkillsRelativePaths??[]},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:i&&o?[n,`${n}/skills`]:[]}}}function Je(e={}){let t=["basic_skills"];return e.allowedTools&&t.push("allowed_tools"),e.hooks&&t.push("hooks"),e.forkedContext&&t.push("forked_context"),t.push("local_install"),t}function iR(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function e6(e){return dd.find(t=>t.id===e)}function t6(e,t){let n=new Set;for(let r of e){if(!XA(r))throw new Error(`Unsafe canonical agent id: ${JSON.stringify(r)}`);if(n.has(r))throw new Error(`Duplicate canonical agent id: ${r}`);n.add(r)}for(let r of Object.keys(t)){if(!XA(r))throw new Error(`Unsafe alias: ${JSON.stringify(r)}`);if(n.has(r))throw new Error(`Alias ${r} collides with a canonical agent id`);let i=new Set([r]),o=t[r];for(;!n.has(o);){if(i.has(o))throw new Error(`Agent alias cycle detected at ${o}`);i.add(o);let s=t[o];if(!s)throw new Error(`Agent alias ${r} has unknown target ${o}`);o=s}}}function XA(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}function cd(){return{sourceUrl:Yz,checkedAt:fd,state:"contract_tested",supportedPlatforms:["darwin","linux","win32"],hostVersion:null}}function ud(e,t,n){return n.map(r=>({path:Xo(e,t,r),relativePath:r,access:"read_only"}))}function oR(e,t,n){let r=[{envVar:e.envVar,value:pd(t[e.envVar])},...e.legacyEnvVars.map(i=>({envVar:i,value:pd(t[i])}))].filter(i=>i.value!==void 0);if(r.length>1&&new Set(r.map(o=>n6(n,o.value))).size>1)throw new Error(`Conflicting canonical and legacy overrides for ${e.id}: ${r.map(o=>o.envVar).join(", ")}`);return r[0]?.value}function n6(e,t){let n=e.normalize(t);return e===eR?n.toLowerCase():n}function r6(){let e=dd.map(t=>t.id);if(e.length!==Qt.length||e.some((t,n)=>t!==Qt[n]))throw new Error("Agent definitions must exactly match the canonical supported-agent inventory");for(let t of dd){if(!QA(t.targets.projectSkillsRelativePath))throw new Error(`Unsafe project path contract for ${t.id}`);let n=t.targets.globalSkillsRelativePath;if(n!==null&&!QA(n))throw new Error(`Unsafe global path contract for ${t.id}`);if(t.targets.globalRootRelativePath===null!=(n===null))throw new Error(`Inconsistent global path contract for ${t.id}`)}}function QA(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}import{posix as i6,win32 as o6}from"node:path";var s6="2026-10-25",a6="2026-11-24",Wh={codex:{aliases:[],vendor:"OpenAI",productSurface:"Codex CLI and desktop"},vscode:{aliases:["code","visual-studio-code"],vendor:"Microsoft",productSurface:"Visual Studio Code MCP host"},"github-copilot-cli":{aliases:["copilot-cli"],vendor:"GitHub",productSurface:"GitHub Copilot CLI"},"claude-code":{aliases:[],vendor:"Anthropic",productSurface:"Claude Code"},cursor:{aliases:[],vendor:"Anysphere",productSurface:"Cursor"},cline:{aliases:[],vendor:"Cline",productSurface:"Cline extension"},"gemini-cli":{aliases:[],vendor:"Google",productSurface:"Gemini CLI"},windsurf:{aliases:[],vendor:"Cognition",productSurface:"Windsurf"},opencode:{aliases:[],vendor:"OpenCode",productSurface:"OpenCode CLI"},"kiro-cli":{aliases:[],vendor:"AWS",productSurface:"Kiro CLI"},kilo:{aliases:["kilo-code"],vendor:"Kilo Code",productSurface:"Kilo Code"},"qwen-code":{aliases:[],vendor:"Alibaba Cloud",productSurface:"Qwen Code"}},vr=[gn("codex","Codex","codex_toml",[],"https://developers.openai.com/codex/mcp/","Codex stores user MCP servers in its user config.",e=>ye(e,$e(e),".codex","config.toml")),gn("vscode","Visual Studio Code","json_servers",["github-copilot-chat"],"https://code.visualstudio.com/docs/agent-customization/mcp-servers","VS Code supports MCP servers in the user profile and through --add-mcp.",sR,e=>[sR(e),dR(e),...d6(e),ye(e,$e(e),".vscode","extensions")]),gn("github-copilot-cli","GitHub Copilot CLI","json_copilot_mcp_servers",[],"https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-config-dir-reference","Copilot CLI stores user-level MCP definitions in ~/.copilot/mcp-config.json.",e=>ye(e,yr(e.env?.COPILOT_HOME,ye(e,$e(e),".copilot")),"mcp-config.json")),gn("claude-code","Claude Code","json_mcp_servers",[],"https://docs.anthropic.com/en/docs/claude-code/mcp","Claude Code supports user-scoped MCP servers.",e=>ye(e,$e(e),".claude.json")),gn("cursor","Cursor","json_mcp_servers",[],"https://cursor.com/docs/mcp","Cursor supports a global ~/.cursor/mcp.json configuration.",e=>ye(e,$e(e),".cursor","mcp.json")),gn("cline","Cline","json_mcp_servers",[],"https://github.com/cline/cline/blob/main/docs/mcp/mcp-overview.mdx","Cline stores global MCP settings in its user data directory.",e=>ye(e,$e(e),".cline","data","settings","cline_mcp_settings.json")),gn("gemini-cli","Gemini CLI","json_mcp_servers",[],"https://google-gemini.github.io/gemini-cli/docs/tools/mcp-server.html","Gemini CLI reads user MCP servers from ~/.gemini/settings.json.",e=>ye(e,$e(e),".gemini","settings.json")),gn("windsurf","Windsurf","json_mcp_servers",[],"https://docs.windsurf.com/windsurf/cascade/mcp","Windsurf stores the user MCP configuration under ~/.codeium/windsurf.",e=>ye(e,$e(e),".codeium","windsurf","mcp_config.json")),gn("opencode","OpenCode","json_opencode_mcp",[],"https://opencode.ai/docs/mcp-servers/","OpenCode supports local MCP servers in its global configuration.",e=>ye(e,Qo(e),"opencode","opencode.json")),gn("kiro-cli","Kiro CLI","json_mcp_servers",[],"https://kiro.dev/docs/mcp/configuration/","Kiro CLI supports a global MCP configuration under ~/.kiro/settings.",e=>ye(e,$e(e),".kiro","settings","mcp.json")),gn("kilo","Kilo Code","json_opencode_mcp",[],"https://kilo.ai/docs/automate/mcp/using-in-cli","Kilo Code supports MCP servers in its global configuration.",e=>ye(e,Qo(e),"kilo","kilo.json")),gn("qwen-code","Qwen Code","json_mcp_servers",[],"https://qwenlm.github.io/qwen-code-docs/en/users/features/mcp/","Qwen Code reads user MCP servers from ~/.qwen/settings.json.",e=>ye(e,$e(e),".qwen","settings.json"))],aR=new Map(vr.map(e=>[e.id,e])),l6=new Map([["code","vscode"],["visual-studio-code","vscode"],["copilot-cli","github-copilot-cli"]]),c6=new Map([["github-copilot","vscode"],["github-copilot-chat","vscode"]]);function rl(e){let t=e.trim().toLowerCase(),n=l6.get(t)??(aR.has(t)?t:null);if(n)return{status:"host",hostId:n};let r=c6.get(t);return r?{status:"consumer",consumerId:t==="github-copilot"?"github-copilot-chat":t,hostId:r}:{status:"unknown",requestedClient:e}}function Zh(e){return aR.get(e)}function lR(e){let t=vr.filter(n=>Date.parse(`${n.evidence.reviewAfter}T23:59:59.999Z`)<Date.parse(e));return{evidenceStale:t.length>0,warnings:t.length>0?[`MCP compatibility evidence is due for review: ${t.map(n=>n.id).join(", ")}. Update the CLI if a host connection fails.`]:[]}}function cR(e){if(e==="universal")return{installAgentId:e,classification:"skills_only",hostId:null};let t=rl(e);return t.status==="host"?{installAgentId:e,classification:"host",hostId:t.hostId}:t.status==="consumer"?{installAgentId:e,classification:"consumer",hostId:t.hostId}:{installAgentId:e,classification:"unverified",hostId:null}}var tue=Object.freeze([{id:"antigravity-cli",displayName:"Antigravity CLI",classification:"unverified",reason:"No fresh primary evidence in the Phase 126 evidence set proves a safe user-global automatic MCP lifecycle.",manualGuidance:"Do not mutate Antigravity configuration automatically; use its vendor documentation and request evidence review before promotion."}]);async function Jh(e){let t=[];for(let n of vr){let r=new Set([n.resolveConfigPath(e)]);n.id==="vscode"&&r.add(dR(e));let i=[...new Set(n.detectionPaths(e))],o=(await Promise.all(i.map(async m=>await e.pathExists(m)?m:null))).filter(m=>m!==null),s=await e.executableExists?.(n.id)??!1,a=o.map(m=>({kind:r.has(m)?"config":p6(m)?"application":"user_data",path:m}));s&&a.push({kind:"executable",path:n.id});let l=a.some(m=>m.kind==="config"),c=a.length>0,u=e.runningHostIds?.includes(n.id)??!1,p=l&&(e.staleConfigHostIds?.includes(n.id)??!1)?"stale":u?"running":l?"configured":c?"installed":"unavailable";t.push({hostId:n.id,displayName:n.displayName,state:p,installed:c,running:u,configured:l,consumers:n.consumers.map(m=>({id:m,detected:e.extensionIds?.includes("github.copilot-chat")??!1})),signals:a,reason:f6(p,a)})}return t}async function uR(e){return(await Jh(e)).filter(n=>n.installed).map(n=>{let r=Zh(n.hostId);return{hostId:n.hostId,displayName:n.displayName,detected:!0,configured:n.configured,consumers:n.consumers.filter(i=>i.detected).map(i=>i.id),evidence:r.evidence,signals:n.signals.map(i=>({kind:i.kind==="config"?"config":"installation",path:i.path}))}})}function gn(e,t,n,r,i,o,s,a){return{id:e,displayName:t,aliases:[...Wh[e].aliases],vendor:Wh[e].vendor,productSurface:Wh[e].productSurface,classification:"global_automatic",scope:"user_global",supportedPlatforms:["darwin","linux","win32"],supportedVersions:e==="windsurf"?"Legacy Windsurf releases using ~/.codeium/windsurf; the renamed Devin Desktop configuration is not claimed by this adapter.":"vendor-supported release with the cited global MCP mechanism",transport:"stdio",configKind:n,consumers:r,caveats:{reload:"Open a fresh agent session or restart the host after registration changes.",trust:"The host launches the existing tokenless Skills Layer bridge; raw remote credentials are never written to host config.",enterprisePolicy:"Managed enterprise policy can prevent or override user configuration and must be checked by the operator.",remote:"User-global scope is local to the active OS, WSL distribution, SSH host, container, or Codespace.",workspace:"Normal setup never writes workspace or project MCP configuration."},evidence:{sourceUrl:i,checkedAt:s6,reviewAfter:a6,owner:"mcp-client-support-owner",statement:o},resolveConfigPath:s,detectionPaths:a??(l=>[s(l),u6(e,l)])}}function u6(e,t){if(e==="claude-code")return ye(t,$e(t),".claude");if(e==="github-copilot-cli")return yr(t.env?.COPILOT_HOME,ye(t,$e(t),".copilot"));if(e==="windsurf")return ye(t,$e(t),".codeium","windsurf");if(e==="opencode")return ye(t,Qo(t),"opencode");if(e==="kiro-cli")return ye(t,$e(t),".kiro");if(e==="kilo")return ye(t,Qo(t),"kilo");let n={codex:".codex",cursor:".cursor",cline:".cline","gemini-cli":".gemini","qwen-code":".qwen"};return ye(t,$e(t),n[e]??`.${e}`)}function sR(e){let t=e.platform??process.platform;return t==="darwin"?ye(e,$e(e),"Library","Application Support","Code","User","mcp.json"):t==="win32"?ye(e,yr(e.env?.APPDATA,$e(e)),"Code","User","mcp.json"):ye(e,Qo(e),"Code","User","mcp.json")}function dR(e){let t=e.platform??process.platform;return t==="darwin"?ye(e,$e(e),"Library","Application Support","Code - Insiders","User","mcp.json"):t==="win32"?ye(e,yr(e.env?.APPDATA,$e(e)),"Code - Insiders","User","mcp.json"):ye(e,Qo(e),"Code - Insiders","User","mcp.json")}function d6(e){let t=e.platform??process.platform;return t==="darwin"?["/Applications/Visual Studio Code.app","/Applications/Visual Studio Code - Insiders.app",ye(e,$e(e),"Applications","Visual Studio Code.app"),ye(e,$e(e),"Applications","Visual Studio Code - Insiders.app")]:t==="win32"?[ye(e,yr(e.env?.LOCALAPPDATA,$e(e)),"Programs","Microsoft VS Code"),ye(e,yr(e.env?.LOCALAPPDATA,$e(e)),"Programs","Microsoft VS Code Insiders"),ye(e,yr(e.env?.ProgramFiles,"C:\\Program Files"),"Microsoft VS Code")]:["/usr/share/code","/usr/share/code-insiders","/var/lib/flatpak/app/com.visualstudio.code",ye(e,$e(e),".local","share","code")]}function p6(e){return/(?:\.app$|\/Applications\/|\\Programs\\|\/usr\/share\/|\/var\/lib\/flatpak\/)/u.test(e)}function f6(e,t){return e==="unavailable"?"No executable, application, user-data, or global configuration signal was found.":e==="stale"?"A global configuration exists but was marked stale by lifecycle inspection.":e==="running"?"The host is running and at least one installed or configured signal was found.":e==="configured"?"A verified user-global configuration file exists.":`Installed signals found: ${t.map(n=>n.kind).join(", ")}.`}function $e(e){let t=e.platform??process.platform;return yr(t==="win32"?e.env?.USERPROFILE:e.env?.HOME,e.env?.HOME,e.cwd,process.cwd())}function Qo(e){return yr(e.env?.XDG_CONFIG_HOME,ye(e,$e(e),".config"))}function ye(e,...t){return((e.platform??process.platform)==="win32"?o6:i6).join(...t)}function yr(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()??process.cwd()}if(new Set(vr.map(e=>e.id)).size!==vr.length)throw new Error("duplicate MCP host id");if(vr.some(e=>!e.evidence.sourceUrl.startsWith("https://")))throw new Error("automatic MCP hosts require primary HTTPS evidence");if(Qt.length!==73)throw new Error("MCP host registry must not mutate the skill-install inventory");var Yh=Object.freeze([Object.freeze({origin:"https://api.skills-layer.com",audience:"https://api.skills-layer.com/mcp",environment:"production"}),Object.freeze({origin:"https://skills-layer.com",audience:"https://skills-layer.com/mcp",environment:"production"}),Object.freeze({origin:"https://api.staging.findfigg.co.uk",audience:"https://api.staging.findfigg.co.uk/mcp",environment:"staging"}),Object.freeze({origin:"https://staging.findfigg.co.uk",audience:"https://staging.findfigg.co.uk/mcp",environment:"staging"}),Object.freeze({origin:"https://api.preprod.findfigg.co.uk",audience:"https://api.preprod.findfigg.co.uk/mcp",environment:"preproduction"}),Object.freeze({origin:"https://preprod.findfigg.co.uk",audience:"https://preprod.findfigg.co.uk/mcp",environment:"preproduction"})]),pR=Object.freeze(Yh.map(e=>e.origin)),fR=Object.freeze(Yh.map(e=>e.audience));function mR(e){return Yh.some(t=>t.origin===e)}var ny="skills-layer-local-broker";function k6(e){return`broker_${vR("sha256").update(`skills-layer-mcp-broker-v1\0${e}`).digest("hex").slice(0,32)}`}var Bt="skills-layer",w6="2025-06-18",b6=["mcp","skills-layer-mcp-proxy.mjs"],_6=["mcp","skills-layer-mcp-broker.mjs"],S6=["mcp","skills-layer-mcp-broker.lock"],x6=new Set(["universal"]);function ts(e){let t=lR(e.now),n=e.platform??process.platform,r=e.cwd??process.cwd(),i=e.stateDir??O6(e.env,n),o=e.mcpConfigPath??il(n,i,"mcp.json"),s=il(n,i,...b6),a=il(n,i,..._6),l=Gi(o).slice(0,32),c=n==="win32"?`\\\\.\\pipe\\skills-layer-mcp-${l}`:il(n,"/tmp",`skills-layer-mcp-${l}.sock`),u=il(n,i,...S6),d=e.nodePath??process.execPath,p=bR({mcpConfigPath:o}),m=(e.brokerSourceBuilder??_R)({mcpConfigPath:o,socketPath:c,lockPath:u}),h=Gi(p),g=Gi(m),y=new Set(vr.map(w=>w.id)),b=[...vr.map(w=>w.id),...Qt.filter(w=>!y.has(w))].map(w=>{if(y.has(w)){let C=Zh(w),A=C.resolveConfigPath({env:e.env,platform:n,cwd:r});return C6({agentId:w,displayName:C.displayName,configPath:A,configKind:C.configKind,bridgePath:s,brokerPath:a,brokerSocketPath:c,brokerLockPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:h,brokerChecksum:g,brokerSourceBuilder:e.brokerSourceBuilder})}if(x6.has(w))return hR({agentId:w,displayName:w,tier:"tier_3",status:"skills_only",verification:"skills_only",reason:"This agent is currently supported through Skills Layer skill files, not MCP auto-install.",instructions:[`Install skills for ${w} with \`skills-layer install <skill> --agent ${w}\`.`,"MCP auto-install is not claimed for this agent yet."]});let _=cR(w);return hR({agentId:w,displayName:w,tier:"tier_2",status:"manual_handoff",verification:"manual",reason:_.classification==="consumer"?`This install target consumes MCP through ${_.hostId}; configure that host instead.`:"MCP support or the safe writable global config shape has not been verified yet.",instructions:[`Add a local stdio MCP server named ${Bt}.`,`Command: ${d}`,`Args: ${s}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{...t,status:"mcp_registration_plan",serverName:Bt,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:s,brokerPath:a,brokerSocketPath:c,brokerLockPath:u,nodePath:d,mcpConfigPath:o,bridgeChecksum:h,brokerChecksum:g,automaticCount:b.filter(w=>w.status==="automatic").length,manualCount:b.filter(w=>w.status==="manual_handoff").length,skillsOnlyCount:b.filter(w=>w.status==="skills_only").length,unsupportedCount:b.filter(w=>w.status==="unsupported").length,targets:b}}async function Hi(e){let t=ts(e),n=L6(e.clientId),r=t.targets.find(y=>y.agentId===n),i=e.mcpConfig??await ol(t.mcpConfigPath,{allowMissing:!0});if(!i)return gR({plan:t,target:r,mcpConfig:null,tokenConfig:null,tokenPresent:!1,tokenRefPresent:!1,bridgeExists:!1,checksumMatches:!1,brokerExists:!1,brokerChecksumMatches:!1,brokerInstalledChecksum:null,targetConfigured:!1,rawTokenLeaked:!1});let o=await es(t.bridgePath),s=o!==null,a=o!==null&&Gi(o)===t.bridgeChecksum,l=await es(t.brokerPath),c=l!==null,u=l===null?null:Gi(l),d=u===t.brokerChecksum,p=j6(i,r.agentId),m=Ct(p,"token"),h=Ct(p,"tokenRef"),g=await E6(r,m);return gR({plan:t,target:r,mcpConfig:i,tokenConfig:p,tokenPresent:!!m,tokenRefPresent:!!h,bridgeExists:s,checksumMatches:a,brokerExists:c,brokerChecksumMatches:d,brokerInstalledChecksum:u,targetConfigured:g.configured,rawTokenLeaked:g.rawTokenLeaked})}function bR(e){return`#!/usr/bin/env node
153
153
  import { spawn } from "node:child_process";
154
154
  import { randomBytes } from "node:crypto";
155
155
  import { createConnection } from "node:net";
@@ -697,13 +697,13 @@ process.once("SIGINT", () => server.close(() => void cleanup().finally(() => pro
697
697
  `),i.push(o.configPath)}return{applied:!0,plannedPaths:n.map(o=>o.configPath),cleanedPaths:i,skipped:r}}function TR(e,t,n,r){return!al(e)||e.command!==t||!Array.isArray(e.args)?!1:e.args[0]===n&&(e.args.length===1||e.args.length===3&&e.args[1]==="--client"&&e.args[2]===r)}async function q6(e,t){await F6(U6(e),{recursive:!0,mode:448});let n=e+".skills-layer-migration.lock",r=e+`.skills-layer-migration-stage-${process.pid}`,i=e+".skills-layer-migration-backup",o=await B6(n,"wx",384).catch(s=>{throw s.code==="EEXIST"?new Error(`mcp_legacy_migration_locked: ${e}`):s});try{await AR(i,await py(e),{mode:384}),await PR(i,384),await dy(r,{force:!0}),await AR(r,t,{encoding:"utf8",flag:"wx",mode:384}),await M6(r,e),await PR(e,384)}finally{await o.close(),await Promise.all([dy(r,{force:!0}),dy(n,{force:!0})])}}function sl(e,t,n,r,i,o){return{hostId:e.hostId,configPath:t,containerKey:e.containerKey,status:n,reason:r,bridgePath:i,nodePath:o}}function al(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{createHmac as _q,sign as wue,timingSafeEqual as Sq,verify as xq}from"node:crypto";import{createHash as V6}from"node:crypto";import{posix as BR,win32 as MR}from"node:path";var en=Object.freeze({codex:"codex-pre-tool-use-v4-2026-10-01","claude-code":"claude-code-pre-tool-use-v2-2026-10-01",cline:"cline-pre-tool-use-v2-2026-10-01","gemini-cli":"gemini-cli-before-tool-v2-2026-10-01",cursor:"cursor-pre-tool-use-v2-2026-10-01","github-copilot":"github-copilot-pre-tool-use-v2-2026-10-01",opencode:"opencode-tool-execute-before-v2-2026-10-01",windsurf:"windsurf-cascade-pre-action-v2-2026-10-01",antigravity:"antigravity-pre-tool-use-v2-2026-10-01","antigravity-cli":"antigravity-cli-pre-tool-use-v2-2026-10-01","kiro-cli":"kiro-cli-pre-tool-use-v2-2026-10-01"}),OR=256*1024,G6=16,H6=4096,K6=1024,W6=512,cl=65536,kt=4096,Z6=1024,UR=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,J6=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,Y6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,X6=new Set(["__proto__","constructor","prototype"]),LR=Object.freeze({codex:Object.freeze({agentId:"codex",adapterRevision:en.codex,eventName:"PreToolUse",sourceUrl:"https://learn.chatgpt.com/docs/hooks",sourceCheckedAt:"2026-10-01",blockingContract:"hookSpecificOutput.permissionDecision=deny; malformed hook output fails open"}),"claude-code":Object.freeze({agentId:"claude-code",adapterRevision:en["claude-code"],eventName:"PreToolUse",sourceUrl:"https://code.claude.com/docs/en/hooks",sourceCheckedAt:"2026-07-16",blockingContract:"hookSpecificOutput.permissionDecision=deny or command exit 2"}),cline:Object.freeze({agentId:"cline",adapterRevision:en.cline,eventName:"PreToolUse",sourceUrl:"https://docs.cline.bot/customization/hooks",sourceCheckedAt:"2026-07-16",blockingContract:"cancel=true"}),"gemini-cli":Object.freeze({agentId:"gemini-cli",adapterRevision:en["gemini-cli"],eventName:"BeforeTool",sourceUrl:"https://geminicli.com/docs/hooks/reference/",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny or command exit 2"}),cursor:Object.freeze({agentId:"cursor",adapterRevision:en.cursor,eventName:"preToolUse",sourceUrl:"https://cursor.com/docs/hooks",sourceCheckedAt:"2026-09-25",blockingContract:"permission=deny with failClosed=true"}),"github-copilot":Object.freeze({agentId:"github-copilot",adapterRevision:en["github-copilot"],eventName:"PreToolUse",sourceUrl:"https://docs.github.com/en/copilot/reference/hooks-reference",sourceCheckedAt:"2026-09-25",blockingContract:"non-zero exit denies, but command-hook timeout fails open"}),opencode:Object.freeze({agentId:"opencode",adapterRevision:en.opencode,eventName:"tool.execute.before",sourceUrl:"https://opencode.ai/docs/plugins/",sourceCheckedAt:"2026-09-25",blockingContract:"plugin tool.execute.before throws before tool execution"}),windsurf:Object.freeze({agentId:"windsurf",adapterRevision:en.windsurf,eventName:"pre_run_command",sourceUrl:"https://docs.windsurf.com/windsurf/cascade/hooks",sourceCheckedAt:"2026-09-25",blockingContract:"exit code 2 blocks supported Cascade pre-hooks"}),antigravity:Object.freeze({agentId:"antigravity",adapterRevision:en.antigravity,eventName:"PreToolUse",sourceUrl:"https://antigravity.google/docs/hooks?tab=ide",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny"}),"antigravity-cli":Object.freeze({agentId:"antigravity-cli",adapterRevision:en["antigravity-cli"],eventName:"PreToolUse",sourceUrl:"https://antigravity.google/docs/hooks?tab=cli",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny"}),"kiro-cli":Object.freeze({agentId:"kiro-cli",adapterRevision:en["kiro-cli"],eventName:"preToolUse",sourceUrl:"https://kiro.dev/docs/hooks/types/",sourceCheckedAt:"2026-09-25",blockingContract:"non-zero command exit blocks"})}),Q6=new Set(["bash","exec_command","shell","shell_command","execute_command","run_shell_command","run_command","execute_bash"]),eq=new Set(["read","read_file","view","glob","grep","list_files","search_files","list_code_definition_names","view_file","fs_read"]),tq=new Set(["write","write_file","edit","create","apply_patch","notebookedit","write_to_file","replace_in_file","insert_content","replace","replace_file_content","multi_replace_file_content","fs_write"]),nq=new Set(["webfetch","websearch","web_fetch","web_search","google_web_search"]),rq=new Set(["browser","browser_action","computer"]),iq=new Set(["device","device_action","computer_use"]);function Hn(e){return Object.prototype.hasOwnProperty.call(LR,e)?LR[e]:null}function kr(e){return Hn(e)!==null}function zR(e){let t=Hn(e.agentId);if(!t)throw new Error(`No strict hook adapter is implemented for ${e.agentId}.`);kq(e.platform),VR(e.hostVersion,"host version"),ll(e.expectedSessionId,"expected session id");let n=hq(e.attribution),r=yq(e.payload),i=e.agentId==="cline"?sq(r,e):e.agentId==="gemini-cli"?aq(r,e):e.agentId==="cursor"?lq(r,e):e.agentId==="github-copilot"?cq(r,e):e.agentId==="opencode"?uq(r,e):e.agentId==="windsurf"?dq(r,e):e.agentId==="antigravity"||e.agentId==="antigravity-cli"?pq(r,e):e.agentId==="kiro-cli"?fq(r,e):oq(r,e),o=mq({agentId:e.agentId,platform:e.platform,cwd:i.cwd,toolName:i.toolName,toolInput:i.toolInput}),s=my(bq(i.toolInput)),a=my({actionVersion:1,actionFamily:o.actionFamily,command:o.command,cwdRealPath:i.cwd,fileTargets:Object.freeze(o.fileTargets),networkTargets:Object.freeze(o.networkTargets),toolName:i.toolName,toolInput:s,toolInputSha256:NR(ns(s)),host:Object.freeze({agentId:e.agentId,hostVersion:e.hostVersion,platform:e.platform,sessionId:i.sessionId,toolUseId:i.toolUseId}),skill:Object.freeze(n)});return Object.freeze({adapterRevision:t.adapterRevision,action:a,actionSha256:NR(ns(a))})}function rs(e,t){if(!Hn(e))throw new Error(`No strict hook adapter is implemented for ${e}.`);if(t.decision!=="allow"&&t.decision!=="deny")throw new Error("Strict hook decision must be allow or deny.");if(wq(t.reason,"decision reason",Z6),e==="kiro-cli"||e==="opencode"||e==="windsurf"||e==="github-copilot")return Object.freeze(t.decision==="deny"?{exitCode:2,stdout:"",stderr:t.reason}:{exitCode:0,stdout:"",stderr:""});let n=e==="cline"?t.decision==="deny"?{cancel:!0,errorMessage:t.reason}:{cancel:!1}:e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"?{decision:t.decision,reason:t.reason}:e==="cursor"?{permission:t.decision,user_message:t.reason,agent_message:t.reason}:e==="codex"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t.decision,...t.decision==="deny"?{permissionDecisionReason:t.reason}:{}}}:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t.decision,permissionDecisionReason:t.reason}};return Object.freeze({exitCode:0,stdout:JSON.stringify(n),stderr:""})}function oq(e,t){if(e.hook_event_name!=="PreToolUse")throw new Error("Strict host hook accepts only the PreToolUse event.");let n=re(e.session_id,"hook session id",256);if(n!==t.expectedSessionId)throw new Error("Hook session does not match the bound session.");let r=wr(re(e.cwd,"hook cwd",kt),t.platform),i=re(e.tool_name,"hook tool name",256),o=re(e.tool_use_id,"hook tool use id",256),s=Mt(e.tool_input,"hook tool input");return{sessionId:n,cwd:r,toolName:i,toolUseId:o,toolInput:s}}function sq(e,t){if(e.hookName!=="PreToolUse")throw new Error("Strict Cline hook accepts only the PreToolUse event.");let n=re(e.taskId,"Cline task id",256);if(n!==t.expectedSessionId)throw new Error("Cline task does not match the bound session.");re(e.clineVersion,"Cline version",128);let r=re(e.timestamp,"Cline timestamp",32);if(!/^\d{13}$/u.test(r)||!Number.isFinite(Number(r)))throw new Error("Cline timestamp must be milliseconds since epoch encoded as a string.");re(e.userId,"Cline user id",256);let i=Mt(e.model,"Cline model");if(re(i.provider,"Cline model provider",256),re(i.slug,"Cline model slug",256),!Array.isArray(e.workspaceRoots)||e.workspaceRoots.length===0||e.workspaceRoots.length>64)throw new Error("Cline workspaceRoots must contain between one and 64 paths.");let o=e.workspaceRoots.map(c=>wr(re(c,"Cline workspace root",kt),t.platform)),s=Mt(e.preToolUse,"Cline preToolUse"),a=re(s.tool,"Cline tool name",256),l=Mt(s.parameters,"Cline tool parameters");return{sessionId:n,cwd:o[0],toolName:a,toolUseId:null,toolInput:l}}function aq(e,t){if(e.hook_event_name!=="BeforeTool")throw new Error("Strict Gemini CLI hook accepts only the BeforeTool event.");let n=re(e.session_id,"Gemini CLI session id",256);if(n!==t.expectedSessionId)throw new Error("Gemini CLI session does not match the bound session.");let r=wr(re(e.cwd,"Gemini CLI cwd",kt),t.platform),i=re(e.tool_name,"Gemini CLI tool name",256),o=Mt(e.tool_input,"Gemini CLI tool input"),s=yd(e.tool_use_id,"Gemini CLI tool use id");return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function lq(e,t){if(e.hook_event_name!=="preToolUse")throw new Error("Strict Cursor hook accepts only the preToolUse event.");let n=re(e.conversation_id,"Cursor conversation id",256);if(n!==t.expectedSessionId)throw new Error("Cursor conversation does not match the bound session.");re(e.cursor_version,"Cursor version",128);let r=qR(e.workspace_roots,"Cursor workspace roots",t.platform),i=typeof e.cwd=="string"?e.cwd:r[0],o=wr(re(i,"Cursor cwd",kt),t.platform),s=re(e.tool_name,"Cursor tool name",256),a=Mt(e.tool_input,"Cursor tool input"),l=yd(e.tool_use_id,"Cursor tool use id");return{sessionId:n,cwd:o,toolName:s,toolUseId:l,toolInput:a}}function cq(e,t){if(e.hook_event_name!=="PreToolUse")throw new Error("Guardian accepts only GitHub Copilot's PascalCase PreToolUse event.");let n=re(e.session_id,"GitHub Copilot session id",256);if(n!==t.expectedSessionId)throw new Error("GitHub Copilot session does not match the bound session.");let r=wr(re(e.cwd,"GitHub Copilot cwd",kt),t.platform),i=re(e.tool_name,"GitHub Copilot tool name",256),o=Mt(e.tool_input,"GitHub Copilot tool input");return{sessionId:n,cwd:r,toolName:i,toolUseId:null,toolInput:o}}function uq(e,t){if(e.hook_event_name!=="tool.execute.before")throw new Error("Strict OpenCode plugin accepts only the tool.execute.before event.");let n=re(e.session_id,"OpenCode session id",256);if(n!==t.expectedSessionId)throw new Error("OpenCode session does not match the bound session.");let r=wr(re(e.cwd,"OpenCode cwd",kt),t.platform),i=re(e.tool_name,"OpenCode tool name",256),o=Mt(e.tool_input,"OpenCode tool input"),s=re(e.call_id,"OpenCode call id",256);return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function dq(e,t){let n=re(e.agent_action_name,"Windsurf action name",128);if(!new Set(["pre_read_code","pre_write_code","pre_run_command","pre_mcp_tool_use"]).has(n))throw new Error("Guardian accepts only blocking Windsurf pre-action events.");let i=re(e.trajectory_id,"Windsurf trajectory id",256);if(i!==t.expectedSessionId)throw new Error("Windsurf trajectory does not match the bound session.");let o=re(e.execution_id,"Windsurf execution id",256),s=Mt(e.tool_info,"Windsurf tool info"),a=n==="pre_run_command"&&typeof s.cwd=="string"?s.cwd:e.cwd,l=wr(re(a,"Windsurf cwd",kt),t.platform);if(n==="pre_read_code"||n==="pre_write_code"){let p=re(s.file_path,"Windsurf file path",kt);return{sessionId:i,cwd:l,toolName:n==="pre_read_code"?"read_file":"write_file",toolUseId:o,toolInput:{path:p}}}if(n==="pre_run_command")return{sessionId:i,cwd:l,toolName:"shell_command",toolUseId:o,toolInput:{command:re(s.command_line,"Windsurf command",cl)}};let c=re(s.mcp_server_name,"Windsurf MCP server",256),u=re(s.mcp_tool_name,"Windsurf MCP tool",256),d=Mt(s.mcp_tool_arguments,"Windsurf MCP arguments");return{sessionId:i,cwd:l,toolName:`mcp__${c}__${u}`,toolUseId:o,toolInput:d}}function pq(e,t){if(e.hook_event_name!==void 0&&e.hook_event_name!=="PreToolUse")throw new Error("Strict Antigravity hook accepts only the PreToolUse event.");let n=re(e.conversationId,"Antigravity conversation id",256);if(n!==t.expectedSessionId)throw new Error("Antigravity conversation does not match the bound session.");let r=qR(e.workspacePaths,"Antigravity workspace paths",t.platform),i=Mt(e.toolCall,"Antigravity tool call"),o=re(i.name,"Antigravity tool name",256),s=Mt(i.args,"Antigravity tool arguments"),a=yd(i.id,"Antigravity tool call id");return{sessionId:n,cwd:r[0],toolName:o,toolUseId:a,toolInput:s}}function fq(e,t){if(e.hook_event_name!=="preToolUse")throw new Error("Strict Kiro hook accepts only the preToolUse event.");let n=re(e.session_id,"Kiro session id",256);if(n!==t.expectedSessionId)throw new Error("Kiro session does not match the bound session.");let r=wr(re(e.cwd,"Kiro cwd",kt),t.platform),i=re(e.tool_name,"Kiro tool name",256),o=Mt(e.tool_input,"Kiro tool input"),s=yd(e.tool_use_id,"Kiro tool use id");return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function mq(e){let t=e.toolName.toLowerCase();if(Q6.has(t)){let n=e.toolInput.command??e.toolInput.cmd??e.toolInput.CommandLine,r=re(n,`${e.toolName} command`,cl);if(r.trim().length===0)throw new Error(`${e.toolName} command cannot be empty.`);return{actionFamily:"shell_execution",command:r,fileTargets:[],networkTargets:[]}}if(eq.has(t)){let n=fy(e.toolInput,e.cwd,e.platform);return n.length===0&&n.push(e.cwd),{actionFamily:"filesystem_read",command:null,fileTargets:FR(n),networkTargets:[]}}if(tq.has(t)){let n=t==="apply_patch"?gq(e.toolInput,e.cwd,e.platform):fy(e.toolInput,e.cwd,e.platform);if(n.length===0)throw new Error(`${e.toolName} has no complete file target for strict mapping.`);return{actionFamily:"filesystem_write",command:null,fileTargets:FR(n),networkTargets:[]}}if(nq.has(t)){let n=e.toolInput.url,r=e.toolInput.query;if(t==="webfetch"||t==="web_fetch"){let i=HR(re(n,`${e.toolName} URL`,kt));return{actionFamily:"network_access",command:null,fileTargets:[],networkTargets:[i]}}return re(r,`${e.toolName} query`,cl),{actionFamily:"network_access",command:null,fileTargets:[],networkTargets:[]}}if(rq.has(t)||t.startsWith("browser__"))return{actionFamily:"browser_access",command:null,fileTargets:[],networkTargets:jR(e.toolInput)};if(iq.has(t))return{actionFamily:"device_control",command:null,fileTargets:[],networkTargets:[]};if(t==="use_aws"||t.startsWith("@")||t.startsWith("mcp__")||t.startsWith("mcp."))return{actionFamily:"api_access",command:null,fileTargets:fy(e.toolInput,e.cwd,e.platform),networkTargets:jR(e.toolInput)};throw new Error(`Tool ${e.toolName} has no strict mapping for ${e.agentId}.`)}function fy(e,t,n){let r=[],i=["file_path","path","notebook_path","directory","target_path","old_path","new_path","AbsolutePath"];for(let o of i)e[o]!==void 0&&r.push(re(e[o],`${o} path`,kt));if(e.paths!==void 0){if(!Array.isArray(e.paths)||e.paths.length>64)throw new Error("Tool paths must be an array with no more than 64 entries.");for(let o of e.paths)r.push(re(o,"tool path",kt))}return r.map(o=>GR(o,t,n))}function gq(e,t,n){let r=re(e.patch??e.command,"apply_patch payload",cl),i=[];for(let o of r.split(/\r?\n/u)){if(!o.startsWith("*** ")||o==="*** Begin Patch"||o==="*** End Patch")continue;let s=/^(?:\*\*\* (?:Add|Update|Delete) File: |\*\*\* Move to: )(.*)$/u.exec(o);if(!s)throw new Error(`apply_patch contains an unsupported file directive: ${o}`);let a=s[1]?.trim();if(!a)throw new Error("apply_patch contains an empty file target.");i.push(GR(a,t,n))}if(i.length===0)throw new Error("apply_patch payload has no recognized file targets.");return i}function jR(e){return e.url===void 0?[]:[HR(re(e.url,"tool URL",kt))]}function hq(e){if(!e||typeof e!="object")throw new Error("Strict hook attribution is required.");if(!Y6.test(e.skillSlug))throw new Error("Strict hook attribution skill slug is invalid.");return VR(e.version,"attribution version"),ll(e.generationId,"attribution generation id"),ll(e.actorId,"attribution actor id"),ll(e.tenantId,"attribution tenant id"),e.workspaceId!==void 0&&ll(e.workspaceId,"attribution workspace id"),{skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,actorId:e.actorId,tenantId:e.tenantId,...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId}}}function yq(e){let t=e;if(typeof e=="string"){if(Buffer.byteLength(e,"utf8")>OR)throw new Error("Host hook payload exceeds the maximum 256 KiB size.");try{t=JSON.parse(e)}catch{throw new Error("Host hook payload must be valid JSON.")}}vq(t);let n=ns(t);if(Buffer.byteLength(n,"utf8")>OR)throw new Error("Host hook payload exceeds the maximum 256 KiB size.");return Mt(t,"host hook payload")}function vq(e){let t=0,n=new Set,r=(i,o)=>{if(t+=1,t>H6)throw new Error("Host hook JSON contains too many values.");if(o>G6)throw new Error("Host hook JSON exceeds the maximum depth.");if(!(i===null||typeof i=="boolean")){if(typeof i=="string"){if(i.length>cl)throw new Error("Host hook JSON string is too long.");if(i.includes("\0"))throw new Error("Host hook JSON cannot contain NUL characters.");return}if(typeof i=="number"){if(!Number.isFinite(i))throw new Error("Host hook JSON numbers must be finite.");return}if(typeof i!="object")throw new Error("Host hook payload must contain JSON-compatible values only.");if(n.has(i))throw new Error("Host hook payload cannot contain cyclic objects.");if(n.add(i),Array.isArray(i)){if(i.length>K6)throw new Error("Host hook JSON array is too large.");for(let s of i)r(s,o+1)}else{let s=Object.getPrototypeOf(i);if(s!==Object.prototype&&s!==null)throw new Error("Host hook JSON objects must use a plain object prototype.");let a=Object.entries(i);if(a.length>W6)throw new Error("Host hook JSON object has too many keys.");for(let[l,c]of a){if(X6.has(l))throw new Error(`Host hook JSON contains unsafe key ${l}.`);if(l.length===0||l.length>256)throw new Error("Host hook JSON key length is invalid.");r(c,o+1)}}n.delete(i)}};r(e,0)}function Mt(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object.`);return e}function re(e,t,n){if(typeof e!="string"||e.length===0||e.length>n||e.includes("\0"))throw new Error(`${t} must be a non-empty bounded string.`);return e}function yd(e,t){if(e==null)return null;let n=re(e,t,256);if(!UR.test(n))throw new Error(`${t} is invalid.`);return n}function qR(e,t,n){if(!Array.isArray(e)||e.length===0||e.length>64)throw new Error(`${t} must contain between one and 64 paths.`);return e.map(r=>wr(re(r,t,kt),n))}function ll(e,t){if(typeof e!="string"||!UR.test(e))throw new Error(`${t} is invalid.`)}function VR(e,t){if(typeof e!="string"||!J6.test(e))throw new Error(`${t} is invalid.`)}function kq(e){if(e!=="darwin"&&e!=="linux"&&e!=="win32")throw new Error("Strict hook platform is unsupported.")}function wq(e,t,n){if(typeof e!="string"||e.trim().length===0||e.length>n||/[\u0000\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(e))throw new Error(`${t} is invalid.`)}function wr(e,t){if(e.length>kt||e.includes("\0"))throw new Error("Hook path is invalid.");let n=t==="win32"?MR:BR;if(!n.isAbsolute(e))throw new Error(`Hook path must be absolute for ${t}.`);return n.normalize(e)}function GR(e,t,n){let r=n==="win32"?MR:BR;if(e.length>kt||e.includes("\0"))throw new Error("Tool path is invalid.");return r.normalize(r.isAbsolute(e)?e:r.resolve(t,e))}function HR(e){let t;try{t=new URL(e)}catch{throw new Error("Network target must be a valid absolute URL.")}if(t.protocol!=="https:"&&t.protocol!=="http:"||t.username||t.password)throw new Error("Network target must be an HTTP(S) URL without embedded credentials.");return t.hash="",t.toString()}function bq(e){return JSON.parse(ns(e))}function my(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))my(t)}return e}function ns(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(n=>ns(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${ns(t[n])}`).join(",")}}`}function NR(e){return`sha256:${V6("sha256").update(e).digest("hex")}`}function FR(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}var Cq=32,Iq=1024,Pq=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,KR=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,Aq=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Rq=/^hmac-sha256:[a-f0-9]{64}$/u,Eq=/^ed25519:[A-Za-z0-9_-]{86}$/u,$q=/^(?:sha256:)?[a-f0-9]{64}$/u,Dq=/^[a-f0-9]{64}$/u,WR=Object.freeze({disabled:0,warning:1,enforce:2});function dl(e){let t=e.envelope;if(!t||typeof t!="object"||t.version!==1&&t.version!==2)throw new Error("Guardian attribution envelope version is invalid.");if(t.version===2){if(t.algorithm!=="ed25519"||t.issuer!=="skills-layer-cloud"||!Eq.test(t.signature))throw new Error("Guardian attribution signature is invalid.");qr(t.keyId,"Guardian attribution key id");let s=e.publicKeys?.[t.keyId];if(!s)throw new Error("Guardian attribution key is unknown.");let a=Tq(t.claims),l={version:2,algorithm:"ed25519",keyId:t.keyId,issuer:t.issuer,claims:a},c=Buffer.from(t.signature.slice(8),"base64url");if(!xq(null,Buffer.from(vd(l),"utf8"),s,c))throw new Error("Guardian attribution signature verification failed.");return ZR(a,e)}if(!e.key)throw new Error("Guardian attribution key is required.");if(jq(e.key),qr(t.keyId,"Guardian attribution key id"),typeof t.signature!="string"||!Rq.test(t.signature))throw new Error("Guardian attribution signature is invalid.");let n=YR(t.claims),r=Lq({version:1,keyId:t.keyId,claims:n},e.key),i=Buffer.from(t.signature.slice(12),"hex"),o=Buffer.from(r.slice(12),"hex");if(i.byteLength!==o.byteLength||!Sq(i,o))throw new Error("Guardian attribution signature verification failed.");return ZR(n,e)}async function gy(e){try{if(!e.attributionEnvelope||!e.attributionKey&&!e.attributionPublicKeys)throw new Error("Signed Guardian attribution is required.");let t=dl({...e.attributionKey?{key:e.attributionKey}:{},...e.attributionPublicKeys?{publicKeys:e.attributionPublicKeys}:{},envelope:e.attributionEnvelope,expectedAgentId:e.agentId,expectedPlatform:e.platform,now:e.now}),n=zR({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,expectedSessionId:t.sessionId,attribution:t,payload:e.rawPayload});if(Oq(t.requestedMode,t.workspaceRequiredMode)==="disabled")return rs(e.agentId,{decision:"allow",reason:"Guardian is disabled for this personal skill session."});let i=await e.evaluate(n);return Nq(i),rs(e.agentId,{decision:i.decision,reason:XR(i.reason)})}catch{return rs(e.agentId,{decision:"deny",reason:"Guardian could not verify this action."})}}function YR(e){if(!e||typeof e!="object")throw new Error("Guardian attribution claims are required.");if(!kr(e.agentId))throw new Error("Guardian attribution agent is invalid.");if(e.platform!=="darwin"&&e.platform!=="linux"&&e.platform!=="win32")throw new Error("Guardian attribution platform is invalid.");if(!KR.test(e.hostVersion))throw new Error("Guardian attribution host version is invalid.");if(qr(e.sessionId,"Guardian attribution session id"),!Aq.test(e.skillSlug))throw new Error("Guardian attribution skill slug is invalid.");if(!KR.test(e.version))throw new Error("Guardian attribution skill version is invalid.");return qr(e.generationId,"Guardian attribution generation id"),qr(e.actorId,"Guardian attribution actor id"),qr(e.tenantId,"Guardian attribution tenant id"),e.workspaceId!==void 0&&qr(e.workspaceId,"Guardian attribution workspace id"),JR(e.requestedMode,"Guardian requested mode"),e.workspaceRequiredMode!==null&&JR(e.workspaceRequiredMode,"Guardian workspace-required mode"),ul(e.issuedAt,"Guardian attribution issuedAt"),ul(e.expiresAt,"Guardian attribution expiresAt"),hy({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,sessionId:e.sessionId,skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,actorId:e.actorId,tenantId:e.tenantId,...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId},requestedMode:e.requestedMode,workspaceRequiredMode:e.workspaceRequiredMode,issuedAt:e.issuedAt,expiresAt:e.expiresAt})}function Tq(e){let t=YR(e);if(!$q.test(e.contractDigest))throw new Error("Guardian attribution contract digest is invalid.");if(!Dq.test(e.archiveSha256))throw new Error("Guardian attribution archive digest is invalid.");if(!Number.isSafeInteger(e.policyRevision)||e.policyRevision<1)throw new Error("Guardian attribution policy revision is invalid.");return qr(e.trustLedgerId,"Guardian attribution Trust Ledger id"),hy({...t,contractDigest:e.contractDigest,archiveSha256:e.archiveSha256,policyRevision:e.policyRevision,trustLedgerId:e.trustLedgerId})}function ZR(e,t){if(e.agentId!==t.expectedAgentId)throw new Error("Guardian attribution agent does not match this hook.");if(e.platform!==t.expectedPlatform)throw new Error("Guardian attribution platform does not match this hook.");let n=ul(t.now,"Guardian runtime timestamp"),r=ul(e.issuedAt,"Guardian attribution issuedAt"),i=ul(e.expiresAt,"Guardian attribution expiresAt");if(i.getTime()<=r.getTime())throw new Error("Guardian attribution expiry must follow issuance.");if(n.getTime()<r.getTime())throw new Error("Guardian attribution is not valid yet.");if(n.getTime()>i.getTime())throw new Error("Guardian attribution has expired.");return e}function Oq(e,t){return t!==null&&WR[t]>WR[e]?t:e}function Lq(e,t){return`hmac-sha256:${_q("sha256",t).update(vd(e)).digest("hex")}`}function jq(e){if(!(e instanceof Uint8Array)||e.byteLength<Cq||e.byteLength>Iq)throw new Error("Guardian attribution key must contain between 32 and 1024 bytes.")}function qr(e,t){if(typeof e!="string"||!Pq.test(e))throw new Error(`${t} is invalid.`)}function JR(e,t){if(e!=="enforce"&&e!=="warning"&&e!=="disabled")throw new Error(`${t} is invalid.`)}function ul(e,t){let n=Date.parse(e);if(!Number.isFinite(n)||new Date(n).toISOString()!==e)throw new Error(`${t} is invalid.`);return new Date(n)}function Nq(e){if(!e||e.decision!=="allow"&&e.decision!=="deny")throw new Error("Guardian policy evaluator returned an invalid decision.");XR(e.reason)}function XR(e){if(typeof e!="string"||e.trim().length===0||e.length>900||/[\u0000\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(e))throw new Error("Guardian policy reason is invalid.");return e}function vd(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(vd).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${vd(t[n])}`).join(",")}}`}function hy(e){if(e&&typeof e=="object"){for(let t of Object.values(e))hy(t);Object.freeze(e)}return e}import{createHash as QR}from"node:crypto";var eE=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,Fq=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,is=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,tE=/^sha256:[a-f0-9]{64}$/u,nE=4096;function rE(){return Object.freeze({version:2,revision:0,associations:Object.freeze({})})}function iE(e){if(!Kn(e)||e.version!==2||!Number.isSafeInteger(e.revision)||Number(e.revision)<0||!Kn(e.associations))throw new Error("Guardian session association index is invalid.");let t={};for(let[n,r]of Object.entries(e.associations)){if(!Kn(r))throw new Error("Guardian session association record is invalid.");let i=r;if(lE(i),tt(i)!==n)throw new Error("Guardian session association key does not match its exact identity.");t[n]=Gr({...i})}return Gr({version:2,revision:Number(e.revision),associations:t})}function Hr(e){let t={targetDir:e.targetDir,generation:e.generation,archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256,files:[...e.files].map(n=>({path:n.path,sizeBytes:n.sizeBytes,sha256:n.sha256})).sort((n,r)=>yy(n.path,r.path))};return Bq(kd(t))}function tt(e){return cE(e),`association_${QR("sha256").update(kd({scope:e.scope,agentId:e.agentId,sessionId:e.sessionId,skillSlug:e.skillSlug,skillVersion:e.skillVersion,generationId:e.generationId}),"utf8").digest("hex")}`}function oE(e,t,n){if(bd(e),e.revision!==n)throw new Error("Guardian association compare-and-swap revision changed.");lE(t);let r=tt(t),i=e.associations[r],o=Gr({...t,revision:i?i.revision+1:1,createdAt:i?.createdAt??t.createdAt});return Gr({version:2,revision:e.revision+1,associations:{...e.associations,[r]:o}})}function sE(e,t){if(bd(e),e.revision!==t.expectedIndexRevision)throw new Error("Guardian association compare-and-swap revision changed.");let n=e.associations[t.key];if(!n)throw new Error("Guardian session association was not found.");ss(t.updatedAt,"Guardian association update timestamp"),t.attributionExpiresAt!==void 0&&ss(t.attributionExpiresAt,"Guardian attribution expiry"),t.trustLedgerId!==void 0&&Vr(t.trustLedgerId,"Guardian Trust Ledger id"),t.reasonCode!==void 0&&os(t.reasonCode,"Guardian association reason code");let r=Gr({...n,revision:n.revision+1,state:t.state,updatedAt:t.updatedAt,...t.attributionExpiresAt===void 0?{}:{attributionExpiresAt:t.attributionExpiresAt},...t.trustLedgerId===void 0?{}:{trustLedgerId:t.trustLedgerId},...t.reasonCode===void 0?{}:{reasonCode:t.reasonCode}});return Gr({version:2,revision:e.revision+1,associations:{...e.associations,[t.key]:r}})}function fl(e,t){bd(e),Vr(t.sessionId,"Guardian host session id");let n=ss(t.asOf,"Guardian association lookup timestamp"),r=Object.values(e.associations).filter(s=>s.agentId===t.agentId&&s.sessionId===t.sessionId).sort((s,a)=>yy(tt(s),tt(a)));if(r.length===0)return{status:"unrelated",associations:[]};let i=r.filter(s=>s.state==="active");if(i.length>1)return{status:"ambiguous",associations:i};if(i.length===1){let s=i[0],a=s.attributionExpiresAt?Date.parse(s.attributionExpiresAt):Number.NaN;return Number.isFinite(a)&&a>n?{status:"active",associations:[s]}:{status:"active_authority_stale",associations:[s]}}let o=r.filter(s=>s.state==="pending_authority"||s.state==="stale");return o.length>0?{status:"expected_missing_authority",associations:o}:{status:"terminal",associations:r}}function aE(e,t){if(bd(e),e.revision!==t.expectedIndexRevision)throw new Error("Guardian association compare-and-swap revision changed.");if(!is.test(t.skillSlug)||!eE.test(t.generationId)||!tE.test(t.receiptSha256))throw new Error("Guardian association forget identity is invalid.");let n=Object.entries(e.associations).flatMap(([i,o])=>o.skillSlug===t.skillSlug&&o.generationId===t.generationId&&o.receiptSha256===t.receiptSha256&&(o.state==="externally_removed"||o.state==="host_detached")?[i]:[]);if(n.length===0)return{index:e,removedKeys:[]};let r=new Set(n);return{index:Gr({version:2,revision:e.revision+1,associations:Object.fromEntries(Object.entries(e.associations).filter(([i])=>!r.has(i)))}),removedKeys:[...n]}}function wd(e,t){if(!Kn(t))return null;if(e==="claude-code"){let n=En(t.session_id);if(t.hook_event_name==="UserPromptExpansion"&&t.expansion_type==="slash_command"){let r=En(t.command_name);if(n&&r&&is.test(r))return pl(n,r,"slug","claude_user_prompt_expansion",`UserPromptExpansion:${r}`)}if(t.hook_event_name==="PreToolUse"&&t.tool_name==="Skill"){let r=Kn(t.tool_input)?t.tool_input:null,i=r?En(r.skill)??En(r.name):null;if(n&&i&&is.test(i))return pl(n,i,"slug","claude_skill_tool",`Skill:${i}`)}return null}if(e==="gemini-cli"){let n=En(t.session_id),r=Kn(t.tool_input)?t.tool_input:null,i=r?En(r.name):null;return t.hook_event_name==="BeforeTool"&&t.tool_name==="activate_skill"&&n&&i&&is.test(i)?pl(n,i,"slug","gemini_activate_skill",`activate_skill:${i}`):null}if(e==="antigravity"||e==="antigravity-cli"){let n=En(t.conversationId),r=Kn(t.toolCall)?t.toolCall:null,i=r&&Kn(r.args)?r.args:null,o=i?En(i.AbsolutePath):null;if(r?.name==="view_file"&&i?.IsSkillFile===!0&&n&&o)return pl(n,o,"path","antigravity_skill_file",`view_file:${o}`)}if(e==="opencode"){let n=En(t.session_id),r=Kn(t.tool_input)?t.tool_input:null,i=r?En(r.name)??En(r.skill):null;if(t.hook_event_name==="tool.execute.before"&&t.tool_name==="skill"&&n&&i&&is.test(i))return pl(n,i,"slug","opencode_skill_tool",`skill:${i}`)}return null}function pl(e,t,n,r,i){return Vr(e,"Guardian activation session id"),os(t,"Guardian activation skill reference"),os(i,"Guardian activation evidence"),Object.freeze({sessionId:e,skillReference:t,referenceKind:n,source:r,evidence:i})}function bd(e){if(!e||e.version!==2||!Number.isSafeInteger(e.revision)||e.revision<0||!Kn(e.associations))throw new Error("Guardian session association index is invalid.")}function lE(e){if(!e||e.version!==2||!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Guardian session association version is invalid.");if(cE(e),!tE.test(e.receiptSha256))throw new Error("Guardian association receipt digest is invalid.");if(e.requestedPreference!=="enforce"&&e.requestedPreference!=="warning_only"&&e.requestedPreference!=="disabled")throw new Error("Guardian association preference is invalid.");if(!["pending_authority","active","stale","externally_removed","host_detached"].includes(e.state))throw new Error("Guardian association state is invalid.");if(!["claude_skill_tool","claude_user_prompt_expansion","gemini_activate_skill","antigravity_skill_file","opencode_skill_tool","approved_launcher","manual_recovery"].includes(e.activationSource))throw new Error("Guardian activation source is invalid.");os(e.activationEvidence,"Guardian activation evidence"),os(e.adapterRevision,"Guardian adapter revision"),ss(e.createdAt,"Guardian association creation timestamp"),ss(e.updatedAt,"Guardian association update timestamp"),e.attributionExpiresAt!==void 0&&ss(e.attributionExpiresAt,"Guardian attribution expiry"),e.trustLedgerId!==void 0&&Vr(e.trustLedgerId,"Guardian Trust Ledger id"),e.workspaceId!==void 0&&Vr(e.workspaceId,"Guardian workspace id"),e.reasonCode!==void 0&&os(e.reasonCode,"Guardian association reason code")}function cE(e){if(e.scope!=="project"&&e.scope!=="global")throw new Error("Guardian association scope is invalid.");if(Vr(e.agentId,"Guardian association agent id"),Vr(e.sessionId,"Guardian association session id"),!is.test(e.skillSlug))throw new Error("Guardian association skill slug is invalid.");if(!Fq.test(e.skillVersion))throw new Error("Guardian association skill version is invalid.");Vr(e.generationId,"Guardian association generation id")}function Vr(e,t){if(typeof e!="string"||!eE.test(e))throw new Error(`${t} is invalid.`)}function os(e,t){if(typeof e!="string"||e.length===0||e.length>nE||/[\u0000-\u001f\u007f]/u.test(e))throw new Error(`${t} is invalid.`)}function ss(e,t){let n=Date.parse(e);if(!Number.isFinite(n)||new Date(n).toISOString()!==e)throw new Error(`${t} is invalid.`);return n}function En(e){return typeof e=="string"&&e.length>0&&e.length<=nE?e:null}function Kn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Bq(e){return`sha256:${QR("sha256").update(e,"utf8").digest("hex")}`}function kd(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(kd).join(",")}]`;let t=e;return`{${Object.keys(t).sort(yy).map(n=>`${JSON.stringify(n)}:${kd(t[n])}`).join(",")}}`}function yy(e,t){return e<t?-1:e>t?1:0}function Gr(e){if(e&&typeof e=="object"){for(let t of Object.values(e))Gr(t);Object.freeze(e)}return e}import{constants as uE}from"node:fs";import{lstat as Mq,open as Uq}from"node:fs/promises";import{createHash as zq}from"node:crypto";import{posix as mE,win32 as gE}from"node:path";var qq=/^sha256:[a-f0-9]{64}$/u,dE=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,hE=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,Vq=4096,yE=6;function Gq(e){return _d(ml(e))}function vE(e){let t=Wq(e.asOf,"asOf"),n=[],r=e.evidence;if(!r||typeof r!="object"||r.evidenceVersion!==1)return n.push("evidence_version_invalid"),{capability:"unverified",reasons:n};Kq(r.sourceUrl)||n.push("evidence_source_not_https");let i=by(r.checkedAt);if(!i)n.push("evidence_checked_at_invalid");else{i.getTime()>t.getTime()&&n.push("evidence_from_future");let l=new Date(i.getTime());l.setUTCMonth(l.getUTCMonth()+yE),t.getTime()>l.getTime()&&n.push("evidence_stale")}pE(r.binding,"evidence",n),pE(e.currentBinding,"current",n);let o=r.binding&&typeof r.binding=="object"?Gq(r.binding):null;(!as(r.bindingDigest)||o===null||r.bindingDigest!==o)&&n.push("evidence_binding_digest_invalid"),(!r.binding||typeof r.binding!="object"||!e.currentBinding||typeof e.currentBinding!="object"||ml(fE(r.binding))!==ml(fE(e.currentBinding)))&&n.push("current_installation_binding_changed");let s=[r.allowCanary,r.denyCanary,r.argumentMutationCanary,r.missingAttributionCanary,r.enterpriseNonDowngradeCanary,r.handlerFailureCanary,r.handlerTimeoutCanary,r.activationCanary];Kr(r.allowCanary,"allow","allowed",!0,!1,r.bindingDigest,i,t,n),Kr(r.denyCanary,"deny","denied",!1,!1,r.bindingDigest,i,t,n),Kr(r.argumentMutationCanary,"argument_mutation","denied",!1,!1,r.bindingDigest,i,t,n),Kr(r.missingAttributionCanary,"missing_attribution","denied",!1,!1,r.bindingDigest,i,t,n),Kr(r.enterpriseNonDowngradeCanary,"enterprise_non_downgrade","denied",!1,!1,r.bindingDigest,i,t,n),Kr(r.handlerFailureCanary,"handler_failure","denied",!1,!1,r.bindingDigest,i,t,n),Kr(r.handlerTimeoutCanary,"handler_timeout","denied",!1,!1,r.bindingDigest,i,t,n),Kr(r.activationCanary,"activation_association","allowed",!1,!0,r.bindingDigest,i,t,n);let a=s.filter(l=>!!(l&&typeof l=="object"));if(new Set(a.map(l=>l.observationId)).size!==a.length&&n.push("canary_observations_not_distinct"),new Set(a.map(l=>l.fixtureId)).size!==a.length&&n.push("canary_fixtures_not_distinct"),new Set(a.map(l=>l.actionSha256)).size!==a.length&&n.push("canary_actions_not_distinct"),r.activationRoute!=="native_activation"&&r.activationRoute!=="approved_launcher"&&n.push("activation_route_invalid"),!r.qualification||typeof r.qualification!="object")n.push("qualification_missing");else{r.qualification.driver!=="skills-layer-real-host-canary-v1"&&n.push("qualification_driver_invalid");let l=r.binding?.platform;(l!=="darwin"&&l!=="linux"&&l!=="win32"||!wy(r.qualification.hostExecutablePath,l))&&n.push("qualification_host_executable_not_absolute"),as(r.qualification.hostExecutableSha256)||n.push("qualification_host_digest_invalid"),as(r.qualification.planSha256)||n.push("qualification_plan_digest_invalid")}return r.changedArgumentsInvalidateApproval||n.push("argument_mutation_not_verified"),r.missingAttributionFailsClosed||n.push("missing_attribution_not_fail_closed"),r.enterpriseEnforceNonDowngradeVerified||n.push("enterprise_mode_downgrade_not_blocked"),n.length===0?{capability:"strict",reasons:[]}:{capability:"unverified",reasons:[...new Set(n)]}}async function kE(e){if(!Hn(e.agentId))throw new Error(`No strict hook adapter exists for ${e.agentId}.`);if(e.adapterRevision!==en[e.agentId])throw new Error("Strict hook adapter revision does not match the implemented adapter.");if(!hE.test(e.hostVersion))throw new Error("Strict hook host version is invalid.");Hq(e.platform);let n=ky(e.hookConfigPath,e.platform,"hook config path"),r=ky(e.hookScriptPath,e.platform,"hook script path"),i=ky(e.absoluteCliPath,e.platform,"CLI path");if(new Set([n,r,i]).size!==3)throw new Error("Strict hook config, script, and CLI paths must be distinct.");let[o,s,a]=await Promise.all([vy(n,!1),vy(r,e.platform!=="win32"),vy(i,e.platform!=="win32")]);return Object.freeze({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,adapterRevision:e.adapterRevision,hookConfigPath:n,hookConfigSha256:_d(o),hookScriptPath:r,hookScriptSha256:_d(s),absoluteCliPath:i,cliSha256:_d(a)})}function pE(e,t,n){if(!e||typeof e!="object"){n.push(`${t}_binding_missing`);return}let r=Hn(e.agentId);if(r||n.push(`${t}_agent_has_no_strict_adapter`),e.platform!=="darwin"&&e.platform!=="linux"&&e.platform!=="win32"){n.push(`${t}_platform_invalid`);return}hE.test(e.hostVersion)||n.push(`${t}_host_version_invalid`),(!r||e.adapterRevision!==r.adapterRevision)&&n.push(`${t}_adapter_revision_invalid`);let i=[e.hookConfigPath,e.hookScriptPath,e.absoluteCliPath];for(let[o,s]of i.entries())wy(s,e.platform)||n.push(`${t}_path_${o}_not_absolute`);new Set(i).size!==i.length&&n.push(`${t}_paths_not_distinct`);for(let[o,s]of[e.hookConfigSha256,e.hookScriptSha256,e.cliSha256].entries())as(s)||n.push(`${t}_digest_${o}_invalid`)}function fE(e){let{hostVersion:t,...n}=e;return n}function Kr(e,t,n,r,i,o,s,a,l){if(!e||typeof e!="object"){l.push(`${t}_canary_missing`);return}e.kind!==t&&l.push(`${t}_canary_kind_invalid`),dE.test(e.observationId)||l.push(`${t}_observation_id_invalid`),dE.test(e.fixtureId)||l.push(`${t}_fixture_id_invalid`);let c=by(e.observedAt);if(!c)l.push(`${t}_observed_at_invalid`);else if(s&&c.getTime()>s.getTime())l.push(`${t}_observation_after_evidence`);else{let u=new Date(c.getTime());u.setUTCMonth(u.getUTCMonth()+yE),a.getTime()>u.getTime()&&l.push(`${t}_canary_stale`)}e.realHostExecution||l.push(`${t}_not_real_host_execution`),(!as(e.bindingDigest)||e.bindingDigest!==o)&&l.push(`${t}_binding_digest_mismatch`),as(e.actionSha256)||l.push(`${t}_action_digest_invalid`),e.hostOutcome!==n&&l.push(`${t}_host_outcome_invalid`),e.sideEffectObserved!==r&&l.push(`${t}_side_effect_invalid`),e.associationObserved!==i&&l.push(`${t}_association_invalid`)}async function vy(e,t){let n=await Mq(e);if(n.isSymbolicLink())throw new Error(`Strict hook path is a symbolic link: ${e}`);if(!n.isFile())throw new Error(`Strict hook path must be a regular file: ${e}`);let r=await Uq(e,uE.O_RDONLY|uE.O_NOFOLLOW);try{let i=await r.stat();if(!i.isFile())throw new Error(`Strict hook path must be a regular file: ${e}`);if(t&&(i.mode&73)===0)throw new Error(`Strict hook executable path has no execute bit: ${e}`);return new Uint8Array(await r.readFile())}finally{await r.close()}}function ky(e,t,n){if(!wy(e,t))throw new Error(`Strict ${n} must be absolute for ${t}.`);return(t==="win32"?gE:mE).normalize(e)}function wy(e,t){return typeof e!="string"||e.length===0||e.length>Vq||e.includes("\0")?!1:(t==="win32"?gE:mE).isAbsolute(e)}function Hq(e){if(e!=="darwin"&&e!=="linux"&&e!=="win32")throw new Error("Strict hook platform is unsupported.")}function as(e){return typeof e=="string"&&qq.test(e)}function Kq(e){if(typeof e!="string")return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.username.length===0&&t.password.length===0}catch{return!1}}function Wq(e,t){let n=by(e);if(!n)throw new Error(`${t} must be a valid ISO date.`);return n}function by(e){if(typeof e!="string"||e.length===0)return null;let t=Date.parse(e);if(!Number.isFinite(t))return null;let n=new Date(t);return n.toISOString()===e?n:null}function ml(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(ml).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${ml(t[n])}`).join(",")}}`}function _d(e){return`sha256:${zq("sha256").update(e).digest("hex")}`}import{createHash as Zq}from"node:crypto";import{constants as Wr}from"node:fs";import{open as bE}from"node:fs/promises";import{isAbsolute as Jq}from"node:path";var hl="skills-layer-real-host-canary-v1",Yq=new Set(["allow","deny","argument_mutation","missing_attribution","enterprise_non_downgrade","handler_failure","handler_timeout","activation_association"]),Xq=/^[A-Za-z0-9_-]{43}$/u,_E=/^association_[a-f0-9]{64}$/u,Qq=4096,e4=512*1024,t4=16*1024;function cs(e){return yl(e)?.scenario??null}async function Sy(e){let t=yl(e.env);if(!t||e.activationEvent&&t.scenario!=="activation_association")return!1;let n=e.reportingSource??"hook";if(n==="hook"&&(e.delegatedExecution===!0||wE(e.agentId,e.result)?.value?.includes("atomic guarded execution wrapper")||t.scenario!=="activation_association"&&t.sideEffectPath&&!n4(e.rawPayloadBase64,t.sideEffectPath)))return!1;let r="invalid";try{let i=e.rawPayloadBase64??"";if(Buffer.byteLength(i,"utf8")>e4)throw new Error("Guardian canary payload is too large.");if(r=n==="guarded_execution"?e.result.exitCode===0?"allowed":"denied":i4(e.agentId,e.result),t.scenario==="missing_attribution"){if(e.associationState!=="missing"||r!=="denied")throw new Error("Guardian missing attribution canary requires no active association and a denied host outcome.")}else if(e.associationState!=="active")throw new Error("Guardian canary requires an active exact skill-session association.");let o=Sd(t.challenge),s=Sd(`${t.scenario}\0${i}`);try{await xd(t.resultPath,{challenge:t.challenge,driver:hl,agentId:e.agentId,scenario:t.scenario,associationState:e.associationState,observationId:`guardian-canary-${t.scenario}-${o.slice(7,31)}`,fixtureId:`guardian-fixture-${e.agentId}-${t.scenario}-${s.slice(7,23)}`,actionSha256:s,hostOutcome:r})}catch(a){if(a.code==="EEXIST")return!1;throw a}return!0}catch(i){let o=wE(e.agentId,e.result);throw await xd(t.diagnosticPath,{schemaVersion:"skills-layer.guardian-canary-diagnostic.v1",challengeDigest:Sd(t.challenge),driver:hl,agentId:e.agentId,scenario:t.scenario,associationState:e.associationState,activationEvent:e.activationEvent,hostOutcome:r,failureCode:r4(i),...o?{decisionReasonCode:o.code,decisionReasonSha256:Sd(o.value)}:{}}).catch(()=>{}),i}}async function SE(e){let t=yl(e);return!t||t.scenario!=="activation_association"?!1:(await xd(t.associationPath,{challenge:t.challenge,associationEstablished:!0}),!0)}async function xE(e){let t=yl(e.env);if(!t)return!1;if(!_E.test(e.associationKey))throw new Error("Guardian canary delegation association key is invalid.");try{await xd(t.delegationPath,{challenge:t.challenge,driver:hl,agentId:e.agentId,scope:e.scope,skillSlug:e.skillSlug,associationKey:e.associationKey})}catch(n){if(n.code==="EEXIST")return!1;throw n}return!0}async function CE(e){let t=yl(e.env);if(!t)return null;let n;try{n=await o4(t.delegationPath)}catch(r){if(r.code==="ENOENT")return null;throw r}if(!ls(n)||n.challenge!==t.challenge||n.driver!==hl||typeof n.agentId!="string"||typeof n.scope!="string"||typeof n.skillSlug!="string"||typeof n.associationKey!="string"||!_E.test(n.associationKey))throw new Error("Guardian canary delegation receipt is invalid.");return n.agentId!==e.agentId||n.scope!==e.scope||n.skillSlug!==e.skillSlug?null:{associationKey:n.associationKey}}function yl(e){let t=e.SKILLS_LAYER_GUARDIAN_CANARY_DRIVER,n=e.SKILLS_LAYER_GUARDIAN_CANARY_SCENARIO,r=e.SKILLS_LAYER_GUARDIAN_CANARY_CHALLENGE,i=e.SKILLS_LAYER_GUARDIAN_CANARY_RESULT_PATH,o=e.SKILLS_LAYER_GUARDIAN_CANARY_ASSOCIATION_PATH,s=e.SKILLS_LAYER_GUARDIAN_CANARY_DELEGATION_PATH,a=e.SKILLS_LAYER_GUARDIAN_CANARY_DIAGNOSTIC_PATH,l=e.SKILLS_LAYER_GUARDIAN_CANARY_SIDE_EFFECT_PATH;if([t,n,r,i,o,s,a].filter(u=>u!==void 0).length===0)return null;if(t!==hl||!n||!Yq.has(n)||!r||!Xq.test(r)||!gl(i)||!gl(o)||!gl(s)||!gl(a)||l!==void 0&&!gl(l)||new Set([i,o,s,a,...l?[l]:[]]).size!==(l?5:4))throw new Error("Guardian canary context is invalid.");return{scenario:n,challenge:r,resultPath:i,associationPath:o,delegationPath:s,diagnosticPath:a,...l?{sideEffectPath:l}:{}}}function n4(e,t){if(!e)return!1;try{let n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return _y(n,t,0)}catch{return!1}}function _y(e,t,n){return n>16?!1:typeof e=="string"?e.includes(t):Array.isArray(e)?e.some(r=>_y(r,t,n+1)):ls(e)?Object.values(e).some(r=>_y(r,t,n+1)):!1}function r4(e){let t=e instanceof Error?e.message:String(e);return t.includes("payload is too large")?"payload_too_large":t.includes("hook result is invalid")?"hook_result_invalid":t.includes("decision output is invalid")?"hook_decision_invalid":t.includes("missing attribution canary")?"missing_attribution_contract_mismatch":t.includes("active exact skill-session association")?"exact_association_not_active":"canary_result_rejected"}function wE(e,t){let n=t.exitCode===0?void 0:t.stderr;if(t.exitCode===0)try{let o=JSON.parse(t.stdout);ls(o)&&(e==="cline"?n=o.errorMessage:e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"?n=o.reason:e==="cursor"?n=o.user_message??o.agent_message:n=(ls(o.hookSpecificOutput)?o.hookSpecificOutput:null)?.permissionDecisionReason)}catch{return}if(typeof n!="string"||n.length===0)return;let r=n.slice(0,1024),i=r.match(/verified enforcement is unavailable \(([a-z][a-z0-9_]{0,127})\)/u)?.[1];return i?{code:i,value:r}:r.includes("Guardian attribution is not valid yet.")?{code:"guardian_attribution_not_valid_yet",value:r}:r.includes("could not establish exact skill-session authority")?{code:"guardian_session_authority_unavailable",value:r}:r.includes("could not safely record this exact skill-session association")?{code:"guardian_association_persistence_failed",value:r}:r.includes("managed launch no longer matches the exact installed generation")?{code:"guardian_managed_launch_generation_mismatch",value:r}:r.includes("invalid, expired, replayed, or host-mismatched managed launch token")?{code:"guardian_managed_launch_rejected",value:r}:{code:"unclassified_guardian_decision",value:r}}function i4(e,t){if(!Number.isSafeInteger(t.exitCode)||typeof t.stdout!="string"||typeof t.stderr!="string")throw new Error("Guardian canary hook result is invalid.");if(t.exitCode!==0)return"denied";if(e==="kiro-cli"||e==="opencode"||e==="windsurf"||e==="github-copilot")return"allowed";let n;try{n=JSON.parse(t.stdout)}catch{throw new Error("Guardian canary hook decision output is invalid.")}if(!ls(n))throw new Error("Guardian canary hook decision output is invalid.");if(e==="cline")return n.cancel===!0?"denied":"allowed";if(e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"){if(n.decision==="deny")return"denied";if(n.decision==="allow")return"allowed"}else if(e==="cursor"){if(n.permission==="deny")return"denied";if(n.permission==="allow")return"allowed"}else{let r=ls(n.hookSpecificOutput)?n.hookSpecificOutput:null;if(r?.permissionDecision==="deny")return"denied";if(r?.permissionDecision==="allow")return"allowed"}throw new Error("Guardian canary hook decision output is invalid.")}async function xd(e,t){let n=typeof Wr.O_NOFOLLOW=="number"?Wr.O_NOFOLLOW:0,r=await bE(e,Wr.O_CREAT|Wr.O_EXCL|Wr.O_WRONLY|n,384);try{await r.writeFile(`${JSON.stringify(t)}
698
698
  `,"utf8"),await r.sync()}finally{await r.close()}}async function o4(e){let t=typeof Wr.O_NOFOLLOW=="number"?Wr.O_NOFOLLOW:0,n=await bE(e,Wr.O_RDONLY|t);try{let r=await n.stat();if(!r.isFile()||r.size>t4)throw new Error("Guardian canary delegation receipt is invalid.");return JSON.parse(await n.readFile("utf8"))}catch(r){throw r instanceof SyntaxError?new Error("Guardian canary delegation receipt is invalid."):r}finally{await n.close()}}function gl(e){return typeof e=="string"&&Buffer.byteLength(e,"utf8")<=Qq&&Jq(e)}function Sd(e){return`sha256:${Zq("sha256").update(e,"utf8").digest("hex")}`}function ls(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}var IE=Object.freeze(["SKILLS_LAYER_GUARDIAN_CANARY_DRIVER","SKILLS_LAYER_GUARDIAN_CANARY_SIDE_EFFECT_PATH"]);function PE(e){let t=s4(e.command,e.platform);if(!t)return!1;let n;try{n=RE(e)}catch{return!1}return t.length>n.length&&n.every((r,i)=>t[i]===r)}function AE(e){return RE(e).map(n=>a4(n,e.platform)).join(" ")}function RE(e){let t=e.approvedEnvironmentKeys??[];if(t.length>16||new Set(t).size!==t.length||t.some(r=>!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(r)))throw new Error("Strict Guardian execution route has an invalid environment key contract.");let n=e.platform==="win32"?["&",e.runtimeExecutablePath,e.cliPath,"guardian","exec",e.skillSlug]:[e.cliPath,"guardian","exec",e.skillSlug];for(let r of t)n.push("--secret-env",r);return n.push("--"),n}function s4(e,t){if(e.length===0||e.length>65536||/[\r\n\0]/u.test(e))return null;let n=[],r="",i=!1,o=null,s=0;if(t==="win32"){let a=/^\s*/u.exec(e)[0].length;if(e[a]!=="&"||!/\s/u.test(e[a+1]??""))return null;n.push("&"),s=a+1}for(let a=s;a<e.length;a+=1){let l=e[a];if(o==="single"){l==="'"?o=null:r+=l;continue}if(o==="double"){if(l==='"')o=null;else{if(t==="win32"?l==="%"||l==="!"||l==="$"||l==="`":l==="$"||l==="`")return null;if(t!=="win32"&&l==="\\"){let u=e[++a];if(u===void 0)return null;r+=u}else r+=l}continue}if(/\s/u.test(l)){i&&(n.push(r),r="",i=!1);continue}if(l==="'"){if(t==="win32")return null;o="single",i=!0;continue}if(l==='"'){o="double",i=!0;continue}if((t==="win32"?/[;&|<>^()%!$`{}]/u:/[;&|<>()[\]{}*?~#$`]/u).test(l))return null;if(t!=="win32"&&l==="\\"){let u=e[++a];if(u===void 0)return null;r+=u}else r+=l;i=!0}return o?null:(i&&n.push(r),n)}function a4(e,t){return t==="win32"&&e==="&"||/^[A-Za-z0-9_./:\\-]+$/u.test(e)?e:t==="win32"?`"${e.replaceAll('"','\\"')}"`:`'${e.replaceAll("'",`'"'"'`)}'`}var EE={disabled:0,warning:1,enforce:2},l4=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u;function $E(e){DE(e.requestedMode),e.workspacePolicy!==null&&c4(e.workspacePolicy);let t=e.workspacePolicy?.requiredMode,n=t!==void 0&&EE[t]>EE[e.requestedMode]?t:e.requestedMode;if(n==="enforce"){if(e.strictAdapterVerified)return{status:"active",effectiveMode:"enforce",protectionLabel:"strict_enforced",countedAsEnforced:!0,activationAllowed:!0,reasonCode:t==="enforce"?"workspace_enforce_non_downgrade":"verified_strict_adapter"};if(e.verifiedGuardedWrapper)return{status:"active",effectiveMode:"enforce",protectionLabel:"strict_enforced_via_wrapper",countedAsEnforced:!0,activationAllowed:!0,reasonCode:t==="enforce"?"workspace_enforce_via_wrapper":"verified_guarded_wrapper"};let r=t==="enforce";return{status:r?"refused":"unavailable",effectiveMode:null,protectionLabel:r?"strict_required_unavailable":"strict_unavailable",countedAsEnforced:!1,activationAllowed:!1,reasonCode:r?"workspace_strict_route_unavailable":"no_verified_strict_route"}}return n==="warning"?{status:"active",effectiveMode:"warning",protectionLabel:"warning_only",countedAsEnforced:!1,activationAllowed:!0,reasonCode:t==="warning"?"workspace_warning_non_downgrade":"personal_warning"}:{status:"active",effectiveMode:"disabled",protectionLabel:"disabled",countedAsEnforced:!1,activationAllowed:!0,reasonCode:t==="disabled"?"workspace_mode_satisfied":"personal_disabled"}}function c4(e){if(DE(e.requiredMode),!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Workspace Guardian policy revision is invalid.");if(!l4.test(e.updatedBy))throw new Error("Workspace Guardian policy updater is invalid.");if(!u4(e.updatedAt))throw new Error("Workspace Guardian policy timestamp is invalid.")}function DE(e){if(e!=="enforce"&&e!=="warning"&&e!=="disabled")throw new Error("Guardian host mode is invalid.")}function u4(e){let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}var d4=Object.freeze([$n("codex",["cli"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","explicit deny","https://github.com/openai/codex","exact_activation_signal_unverified"),$n("claude-code",["cli","ide"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny or exit 2","https://code.claude.com/docs/en/hooks","live_canary_required"),$n("cline",["ide"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","cancel=true","https://docs.cline.bot/customization/hooks","exact_activation_signal_unverified"),$n("gemini-cli",["cli"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny or exit 2","https://geminicli.com/docs/hooks/reference/","live_canary_required"),$n("antigravity",["ide"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny","https://antigravity.google/docs/hooks?tab=ide","failure_timeout_canary_required"),$n("antigravity-cli",["cli"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny","https://antigravity.google/docs/hooks?tab=cli","failure_timeout_canary_required"),$n("cursor",["local_ide"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","permission=deny and failClosed=true","https://cursor.com/docs/hooks","exact_activation_signal_unavailable"),$n("kiro-cli",["cli"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","non-zero exit blocks","https://kiro.dev/docs/hooks/types/","exact_activation_signal_unverified"),$n("windsurf",["local_ide"],!0,"unavailable","best_effort","warning_audit","event-specific exit 2","https://docs.windsurf.com/windsurf/cascade/hooks","privileged_surface_incomplete"),$n("github-copilot",["cli","cloud_agent"],!0,"unavailable","best_effort","warning_audit","command-hook errors deny but timeouts always fail open","https://docs.github.com/en/copilot/reference/hooks-reference","hook_timeout_fail_open"),$n("opencode",["cli"],!0,"native_activation","inspectable_local_state","strict_candidate","plugin tool.execute.before throws before execution","https://opencode.ai/docs/plugins/","plugin_canary_required")]);function br(e){return d4.find(t=>t.agentId===e)??null}function vl(e){if(e.materializationState==="externally_removed"||e.associationState==="externally_removed")return Zr("externally_removed","exact_target_absent");if(e.materializationState==="host_detached"||e.associationState==="host_detached")return Zr("host_detached","host_registration_detached");if(e.materializationState==="unreadable"||e.materializationState==="drifted"||e.associationState==="stale")return Zr("stale_binding","exact_local_authority_stale");let t=$E({requestedMode:e.requestedMode,strictAdapterVerified:e.strictHookVerified,verifiedGuardedWrapper:e.completeWrapperVerified,workspacePolicy:e.workspacePolicy});return t.effectiveMode==="warning"?Object.freeze({label:"warning_only",countedAsEnforced:!1,activationAllowed:!0,runtimeGuardian:e.hookInstalled&&e.associationState==="active",reasonCode:e.hookInstalled&&e.associationState==="active"?t.reasonCode:"activation_scan_only"}):t.effectiveMode==="disabled"?Object.freeze({label:"disabled",countedAsEnforced:!1,activationAllowed:!0,runtimeGuardian:!1,reasonCode:t.reasonCode}):e.hostSupported?e.strictHookVerified&&!e.exactActivationVerified&&!e.completeWrapperVerified?Zr("candidate_unverified","no_verified_exact_activation_route"):e.hookInstalled&&!e.strictHookVerified&&!e.completeWrapperVerified?Zr("candidate_unverified",t.reasonCode):t.activationAllowed?e.evaluationContext==="runtime"&&!e.completeWrapperVerified&&e.associationState!=="active"?Zr("candidate_unverified",e.associationState==="pending_authority"?"exact_skill_session_authority_pending":"exact_skill_session_not_active"):Object.freeze({label:t.protectionLabel==="strict_enforced_via_wrapper"?"strict_enforced_via_wrapper":"strict_enforced",countedAsEnforced:!0,activationAllowed:!0,runtimeGuardian:!0,reasonCode:t.reasonCode}):Zr("unavailable",t.reasonCode):Zr("host_unsupported","host_has_no_supported_guardian_route")}function $n(e,t,n,r,i,o,s,a,l){return Object.freeze({agentId:e,surfaces:Object.freeze([...t]),adapterImplemented:n,automaticAssociation:r,uninstallSignal:i,maximumTier:o,failureContract:s,sourceUrl:a,sourceCheckedAt:"2026-09-25",reasonCode:l})}function Zr(e,t){return Object.freeze({label:e,countedAsEnforced:!1,activationAllowed:!1,runtimeGuardian:!1,reasonCode:t})}import{createHash as p4,randomBytes as f4}from"node:crypto";import{constants as Ut}from"node:fs";import{chmod as TE,lstat as FE,open as wl,realpath as m4,rename as OE,unlink as kl}from"node:fs/promises";import{basename as Cd,dirname as g4,isAbsolute as BE,join as Id}from"node:path";var h4=1024*1024,y4=32,v4=2e4,ME=4096,k4=/^sha256:[a-f0-9]{64}$/u,w4=new Set(["__proto__","constructor","prototype"]);function b4(e){let t=S4(e.agentId),n=x4(t,e.eventName);I4(e.absoluteScriptPath);let r=LE(e.existingJson),i=A4(r,n),o=_4(t,n,e.absoluteScriptPath),s=NE(o),a=Object.freeze({owner:"skills-layer",agentId:t,eventName:n,entrySha256:s}),l;if(e.operation==="install"){if(e.previousOwnership!==void 0)throw new Error("Install must not supply previous Skills Layer ownership evidence.");l=[...i,o]}else{let u=C4(e.previousOwnership,t,n),d=i.flatMap((m,h)=>NE(m)===u.entrySha256?[h]:[]);if(d.length===0)throw new Error("Previous Skills Layer hook ownership could not be proven; refusing to modify host config.");let p=d[0];l=[];for(let[m,h]of i.entries())m===p&&l.push(o),d.includes(m)||l.push(h)}R4(r,n,l);let c=bl(LE(e.existingJson))!==bl(r);return{json:c?`${JSON.stringify(r,null,2)}
699
699
  `:e.existingJson,changed:c,ownership:a}}async function Ad(e){if(!BE(e.configPath)||e.configPath.length>ME||e.configPath.includes("\0"))throw new Error("Host hook config path must be an absolute bounded path.");let t=g4(e.configPath),n=await FE(t);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("Host hook config parent must be a real directory, not a symbolic link.");let r=await m4(t),i=Id(r,Cd(e.configPath)),o=f4(12).toString("hex"),s=Id(r,`.${Cd(i)}.skills-layer.lock`),a=Id(r,`.${Cd(i)}.skills-layer-stage-${o}`),l=Id(r,`.${Cd(i)}.skills-layer-backup-${o}`),c=null,u=!1,d=null,p=null,m=384,h=!1,g=!1;try{c=await wl(s,Ut.O_CREAT|Ut.O_EXCL|Ut.O_WRONLY,384),u=!0,await c.writeFile(`${process.pid}
700
- `,"utf8"),await c.sync();let y=await Cy(i);p=y?.bytes??null,m=y?.mode??384;let v=p===null?"{}":Buffer.from(p).toString("utf8"),b=b4({...e.update,existingJson:v});if(!b.changed)return{...b,configPath:i,configSha256:Py(p)};let w=new TextEncoder().encode(b.json);if(d=await wl(a,Ut.O_CREAT|Ut.O_EXCL|Ut.O_WRONLY|Ut.O_NOFOLLOW,384),await d.writeFile(w),await d.sync(),await d.close(),d=null,p!==null){let P=await wl(l,Ut.O_CREAT|Ut.O_EXCL|Ut.O_WRONLY|Ut.O_NOFOLLOW,384);try{await P.writeFile(p),await P.sync()}finally{await P.close()}h=!0}await Pd(r),await e.checkpoint?.("after_backup");let _=await Cy(i);if(!E4(p,_?.bytes??null))throw new Error("Host hook config changed concurrently; refusing to overwrite it.");await OE(a,i),g=!0,await TE(i,384),await Pd(r),await e.checkpoint?.("after_replace");let C=await jE(i);if(!Iy(C.bytes,w))throw new Error("Atomic host hook config verification failed after replacement.");return h&&(await kl(l),h=!1),await Pd(r),{...b,configPath:i,configSha256:Py(C.bytes)}}catch(y){if(g)try{if(p===null)await kl(i).catch(v=>{if(v.code!=="ENOENT")throw v});else{if(!h)throw new Error("Host hook rollback backup is unavailable.");await TE(l,m&511),await OE(l,i),h=!1;let v=await jE(i);if(!Iy(v.bytes,p))throw new Error("Host hook rollback verification failed.")}await Pd(r)}catch(v){throw new AggregateError([y,v],"Host hook config update and exact rollback both failed.")}throw y}finally{d&&await d.close().catch(()=>{}),c&&await c.close(),await kl(a).catch(xy),h&&await kl(l).catch(xy),u&&await kl(s).catch(xy)}}function _4(e,t,n){return e==="cursor"?{command:n,matcher:"*",failClosed:!0}:e==="windsurf"?{command:n,show_output:!0}:{matcher:e==="codex"?".*":t==="UserPromptExpansion"?"*":"",hooks:[{type:"command",command:n,timeout:10}]}}function S4(e){if(e==="cline")throw new Error("Cline uses file-based hook discovery; JSON hook configuration is not supported.");if(e!=="codex"&&e!=="claude-code"&&e!=="gemini-cli"&&e!=="cursor"&&e!=="windsurf"&&e!=="antigravity"&&e!=="antigravity-cli")throw new Error(`${e} does not use the Claude-compatible owned JSON hook configuration.`);return e}function x4(e,t){let n=e==="gemini-cli"?"BeforeTool":e==="cursor"?"preToolUse":e==="windsurf"?"pre_run_command":"PreToolUse",r=t??n;if(r==="UserPromptExpansion"&&e==="claude-code"||e==="windsurf"&&(r==="pre_read_code"||r==="pre_write_code"||r==="pre_run_command"||r==="pre_mcp_tool_use"))return r;if(r!==n)throw new Error(`Hook event ${r} is not valid for ${e}.`);return r}function C4(e,t,n){if(!e||e.owner!=="skills-layer"||e.agentId!==t||e.eventName!==n||!k4.test(e.entrySha256))throw new Error("Valid prior Skills Layer hook ownership evidence is required.");return e}function I4(e){if(!BE(e)||e.length===0||e.length>ME||e.includes("\0"))throw new Error("Guardian hook script path must be absolute and bounded.")}function LE(e){if(typeof e!="string"||Buffer.byteLength(e,"utf8")>h4)throw new Error("Host hook config exceeds the 1 MiB maximum.");let t;try{t=JSON.parse(e)}catch{throw new Error("Host hook config must be valid JSON.")}if(P4(t),!Rd(t))throw new Error("Host hook config root must be a JSON object.");return t}function P4(e){let t=0,n=(r,i)=>{if(t+=1,t>v4)throw new Error("Host hook config contains too many JSON values.");if(i>y4)throw new Error("Host hook config exceeds the maximum JSON depth.");if(!(r===null||typeof r=="string"||typeof r=="boolean")){if(typeof r=="number"){if(!Number.isFinite(r))throw new Error("Host hook config contains a non-finite number.");return}if(Array.isArray(r)){for(let o of r)n(o,i+1);return}if(!Rd(r))throw new Error("Host hook config contains a non-JSON value.");for(let[o,s]of Object.entries(r)){if(w4.has(o))throw new Error(`Host hook config contains unsafe key ${o}.`);n(s,i+1)}}};n(e,0)}function A4(e,t){if(e.hooks===void 0&&(e.hooks={}),!Rd(e.hooks))throw new Error("Host hook config hooks field must be an object.");if(e.hooks[t]===void 0&&(e.hooks[t]=[]),!Array.isArray(e.hooks[t]))throw new Error(`Host hook config hooks.${t} must be an array.`);return e.hooks[t]}function R4(e,t,n){let r=e.hooks;if(!Rd(r))throw new Error("Host hook config hooks field must be an object.");r[t]=n}function Rd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}async function Cy(e){let t;try{t=await FE(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t.isSymbolicLink())throw new Error(`Host hook config target is a symbolic link: ${e}`);if(!t.isFile())throw new Error(`Host hook config target must be a regular file: ${e}`);let n=await wl(e,Ut.O_RDONLY|Ut.O_NOFOLLOW);try{let r=await n.stat();if(!r.isFile())throw new Error(`Host hook config target must be a regular file: ${e}`);return{bytes:new Uint8Array(await n.readFile()),mode:r.mode}}finally{await n.close()}}async function jE(e){let t=await Cy(e);if(!t)throw new Error(`Host hook config disappeared: ${e}`);return t}async function Pd(e){let t=await wl(e,Ut.O_RDONLY);try{await t.sync()}finally{await t.close()}}function E4(e,t){return e===null||t===null?e===t:Iy(e,t)}function Iy(e,t){return e.byteLength===t.byteLength&&Buffer.from(e).equals(Buffer.from(t))}function xy(e){if(e.code!=="ENOENT")throw e}function NE(e){return Py(bl(e))}function bl(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(bl).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${bl(t[n])}`).join(",")}}`}function Py(e){return`sha256:${p4("sha256").update(e).digest("hex")}`}import{createHash as $4,randomBytes as D4}from"node:crypto";import{constants as zt}from"node:fs";import{chmod as UE,lstat as VE,open as Sl,realpath as T4,rename as zE,unlink as _l}from"node:fs/promises";import{basename as Ed,dirname as O4,isAbsolute as L4,join as $d}from"node:path";var GE=1024*1024,j4=4096,N4=/^sha256:[a-f0-9]{64}$/u;async function Ry(e){B4(e.filePath);let t=M4(e.content),n=HE(t),r=Object.freeze({owner:"skills-layer",fileSha256:n}),i=O4(e.filePath),o=await VE(i);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("Owned hook parent must be a real directory, not a symbolic link.");let s=await T4(i),a=$d(s,Ed(e.filePath)),l=D4(12).toString("hex"),c=$d(s,`.${Ed(a)}.skills-layer.lock`),u=$d(s,`.${Ed(a)}.skills-layer-stage-${l}`),d=$d(s,`.${Ed(a)}.skills-layer-backup-${l}`),p=null,m=null,h=null,g=!1,y=!1;try{if(p=await Sl(c,zt.O_CREAT|zt.O_EXCL|zt.O_WRONLY,384),await p.writeFile(`${process.pid}
700
+ `,"utf8"),await c.sync();let y=await Cy(i);p=y?.bytes??null,m=y?.mode??384;let v=p===null?"{}":Buffer.from(p).toString("utf8"),b=b4({...e.update,existingJson:v});if(!b.changed)return{...b,configPath:i,configSha256:Py(p)};let w=new TextEncoder().encode(b.json);if(d=await wl(a,Ut.O_CREAT|Ut.O_EXCL|Ut.O_WRONLY|Ut.O_NOFOLLOW,384),await d.writeFile(w),await d.sync(),await d.close(),d=null,p!==null){let A=await wl(l,Ut.O_CREAT|Ut.O_EXCL|Ut.O_WRONLY|Ut.O_NOFOLLOW,384);try{await A.writeFile(p),await A.sync()}finally{await A.close()}h=!0}await Pd(r),await e.checkpoint?.("after_backup");let _=await Cy(i);if(!E4(p,_?.bytes??null))throw new Error("Host hook config changed concurrently; refusing to overwrite it.");await OE(a,i),g=!0,await TE(i,384),await Pd(r),await e.checkpoint?.("after_replace");let C=await jE(i);if(!Iy(C.bytes,w))throw new Error("Atomic host hook config verification failed after replacement.");return h&&(await kl(l),h=!1),await Pd(r),{...b,configPath:i,configSha256:Py(C.bytes)}}catch(y){if(g)try{if(p===null)await kl(i).catch(v=>{if(v.code!=="ENOENT")throw v});else{if(!h)throw new Error("Host hook rollback backup is unavailable.");await TE(l,m&511),await OE(l,i),h=!1;let v=await jE(i);if(!Iy(v.bytes,p))throw new Error("Host hook rollback verification failed.")}await Pd(r)}catch(v){throw new AggregateError([y,v],"Host hook config update and exact rollback both failed.")}throw y}finally{d&&await d.close().catch(()=>{}),c&&await c.close(),await kl(a).catch(xy),h&&await kl(l).catch(xy),u&&await kl(s).catch(xy)}}function _4(e,t,n){return e==="cursor"?{command:n,matcher:"*",failClosed:!0}:e==="windsurf"?{command:n,show_output:!0}:{matcher:e==="codex"?".*":t==="UserPromptExpansion"?"*":"",hooks:[{type:"command",command:n,timeout:10}]}}function S4(e){if(e==="cline")throw new Error("Cline uses file-based hook discovery; JSON hook configuration is not supported.");if(e!=="codex"&&e!=="claude-code"&&e!=="gemini-cli"&&e!=="cursor"&&e!=="windsurf"&&e!=="antigravity"&&e!=="antigravity-cli")throw new Error(`${e} does not use the Claude-compatible owned JSON hook configuration.`);return e}function x4(e,t){let n=e==="gemini-cli"?"BeforeTool":e==="cursor"?"preToolUse":e==="windsurf"?"pre_run_command":"PreToolUse",r=t??n;if(r==="UserPromptExpansion"&&e==="claude-code"||e==="windsurf"&&(r==="pre_read_code"||r==="pre_write_code"||r==="pre_run_command"||r==="pre_mcp_tool_use"))return r;if(r!==n)throw new Error(`Hook event ${r} is not valid for ${e}.`);return r}function C4(e,t,n){if(!e||e.owner!=="skills-layer"||e.agentId!==t||e.eventName!==n||!k4.test(e.entrySha256))throw new Error("Valid prior Skills Layer hook ownership evidence is required.");return e}function I4(e){if(!BE(e)||e.length===0||e.length>ME||e.includes("\0"))throw new Error("Guardian hook script path must be absolute and bounded.")}function LE(e){if(typeof e!="string"||Buffer.byteLength(e,"utf8")>h4)throw new Error("Host hook config exceeds the 1 MiB maximum.");let t;try{t=JSON.parse(e)}catch{throw new Error("Host hook config must be valid JSON.")}if(P4(t),!Rd(t))throw new Error("Host hook config root must be a JSON object.");return t}function P4(e){let t=0,n=(r,i)=>{if(t+=1,t>v4)throw new Error("Host hook config contains too many JSON values.");if(i>y4)throw new Error("Host hook config exceeds the maximum JSON depth.");if(!(r===null||typeof r=="string"||typeof r=="boolean")){if(typeof r=="number"){if(!Number.isFinite(r))throw new Error("Host hook config contains a non-finite number.");return}if(Array.isArray(r)){for(let o of r)n(o,i+1);return}if(!Rd(r))throw new Error("Host hook config contains a non-JSON value.");for(let[o,s]of Object.entries(r)){if(w4.has(o))throw new Error(`Host hook config contains unsafe key ${o}.`);n(s,i+1)}}};n(e,0)}function A4(e,t){if(e.hooks===void 0&&(e.hooks={}),!Rd(e.hooks))throw new Error("Host hook config hooks field must be an object.");if(e.hooks[t]===void 0&&(e.hooks[t]=[]),!Array.isArray(e.hooks[t]))throw new Error(`Host hook config hooks.${t} must be an array.`);return e.hooks[t]}function R4(e,t,n){let r=e.hooks;if(!Rd(r))throw new Error("Host hook config hooks field must be an object.");r[t]=n}function Rd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}async function Cy(e){let t;try{t=await FE(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t.isSymbolicLink())throw new Error(`Host hook config target is a symbolic link: ${e}`);if(!t.isFile())throw new Error(`Host hook config target must be a regular file: ${e}`);let n=await wl(e,Ut.O_RDONLY|Ut.O_NOFOLLOW);try{let r=await n.stat();if(!r.isFile())throw new Error(`Host hook config target must be a regular file: ${e}`);return{bytes:new Uint8Array(await n.readFile()),mode:r.mode}}finally{await n.close()}}async function jE(e){let t=await Cy(e);if(!t)throw new Error(`Host hook config disappeared: ${e}`);return t}async function Pd(e){let t=await wl(e,Ut.O_RDONLY);try{await t.sync()}finally{await t.close()}}function E4(e,t){return e===null||t===null?e===t:Iy(e,t)}function Iy(e,t){return e.byteLength===t.byteLength&&Buffer.from(e).equals(Buffer.from(t))}function xy(e){if(e.code!=="ENOENT")throw e}function NE(e){return Py(bl(e))}function bl(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(bl).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${bl(t[n])}`).join(",")}}`}function Py(e){return`sha256:${p4("sha256").update(e).digest("hex")}`}import{createHash as $4,randomBytes as D4}from"node:crypto";import{constants as zt}from"node:fs";import{chmod as UE,lstat as VE,open as Sl,realpath as T4,rename as zE,unlink as _l}from"node:fs/promises";import{basename as Ed,dirname as O4,isAbsolute as L4,join as $d}from"node:path";var GE=1024*1024,j4=4096,N4=/^sha256:[a-f0-9]{64}$/u;async function Ry(e){B4(e.filePath);let t=M4(e.content),n=HE(t),r=Object.freeze({owner:"skills-layer",fileSha256:n}),i=O4(e.filePath),o=await VE(i);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("Owned hook parent must be a real directory, not a symbolic link.");let s=await T4(i),a=$d(s,Ed(e.filePath)),l=D4(12).toString("hex"),c=$d(s,`.${Ed(a)}.skills-layer.lock`),u=$d(s,`.${Ed(a)}.skills-layer-stage-${l}`),d=$d(s,`.${Ed(a)}.skills-layer-backup-${l}`),p=null,m=null,h=null,g=!1,y=!1;try{if(p=await Sl(c,zt.O_CREAT|zt.O_EXCL|zt.O_WRONLY,384),await p.writeFile(`${process.pid}
701
701
  `,"utf8"),await p.sync(),h=await Ay(a),F4(e,h),h!==null&&Od(h,t))return{filePath:a,fileSha256:n,changed:!1,ownership:r};if(m=await Sl(u,zt.O_CREAT|zt.O_EXCL|zt.O_WRONLY|zt.O_NOFOLLOW,448),await m.writeFile(t),await m.sync(),await m.close(),m=null,h!==null){let w=await Sl(d,zt.O_CREAT|zt.O_EXCL|zt.O_WRONLY|zt.O_NOFOLLOW,448);try{await w.writeFile(h),await w.sync()}finally{await w.close()}g=!0}await Dd(s),await e.checkpoint?.("after_backup");let v=await Ay(a);if(!U4(h,v))throw new Error("Owned hook changed concurrently; refusing to overwrite it.");await zE(u,a),y=!0,await UE(a,448),await Dd(s),await e.checkpoint?.("after_replace");let b=await qE(a);if(!Od(b,t))throw new Error("Atomic owned hook verification failed after replacement.");return g&&(await _l(d),g=!1),await Dd(s),{filePath:a,fileSha256:n,changed:!0,ownership:r}}catch(v){if(y)try{if(h===null)await _l(a).catch(Td);else{if(!g)throw new Error("Owned hook rollback backup is unavailable.");await zE(d,a),g=!1,await UE(a,448);let b=await qE(a);if(!Od(b,h))throw new Error("Owned hook rollback verification failed.")}await Dd(s)}catch(b){throw new AggregateError([v,b],"Owned hook update and exact rollback both failed.")}throw v}finally{m&&await m.close().catch(()=>{}),p&&await p.close(),await _l(u).catch(Td),g&&await _l(d).catch(Td),await _l(c).catch(Td)}}function F4(e,t){if(e.operation==="install"){if(e.previousOwnership!==void 0)throw new Error("Owned hook install must not supply previous ownership evidence.");if(t!==null)throw new Error("Owned hook target already exists; refusing to overwrite a foreign file.");return}let n=e.previousOwnership;if(!n||n.owner!=="skills-layer"||!N4.test(n.fileSha256))throw new Error("Valid prior Skills Layer hook ownership evidence is required for update.");if(t===null)throw new Error("Previously owned hook is missing; refusing an unproven update.");if(HE(t)!==n.fileSha256)throw new Error("Owned hook changed outside Skills Layer; ownership digest does not match.")}function B4(e){if(!L4(e)||e.includes("\0")||Buffer.byteLength(e,"utf8")>j4)throw new Error("Owned hook path must be an absolute bounded path.")}function M4(e){let t=typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e);if(t.byteLength===0)throw new Error("Owned hook content must not be empty.");if(t.byteLength>GE)throw new Error("Owned hook content exceeds the 1 MiB maximum.");return t}async function Ay(e){let t;try{t=await VE(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t.isSymbolicLink())throw new Error(`Owned hook target is a symbolic link: ${e}`);if(!t.isFile())throw new Error(`Owned hook target must be a regular file: ${e}`);let n=await Sl(e,zt.O_RDONLY|zt.O_NOFOLLOW);try{let r=await n.stat();if(!r.isFile())throw new Error(`Owned hook target must be a regular file: ${e}`);if(r.size>GE)throw new Error("Owned hook target exceeds the 1 MiB maximum.");return new Uint8Array(await n.readFile())}finally{await n.close()}}async function qE(e){let t=await Ay(e);if(t===null)throw new Error(`Owned hook disappeared: ${e}`);return t}async function Dd(e){let t=await Sl(e,zt.O_RDONLY);try{await t.sync()}finally{await t.close()}}function U4(e,t){return e===null||t===null?e===t:Od(e,t)}function Od(e,t){return e.byteLength===t.byteLength&&Buffer.from(e).equals(Buffer.from(t))}function HE(e){return`sha256:${$4("sha256").update(e).digest("hex")}`}function Td(e){if(e.code!=="ENOENT")throw e}import{createHash as YV,timingSafeEqual as XV}from"node:crypto";var Ld=class extends Error{issues;constructor(t){super(`Canonical bundle rejected: ${[...new Set(t.map(n=>n.code))].join(", ")}`),this.name="CanonicalBundleRejection",this.issues=z4(t)}};function z4(e){return Array.isArray(e)?e.flatMap(t=>!t||typeof t.path!="string"||typeof t.code!="string"||!/^[a-z][a-z0-9_]{0,79}$/u.test(t.code)||t.path.length===0||t.path.length>1024||/[\\\x00-\x1f\x7f:]/u.test(t.path)||t.path.startsWith("/")||t.path.split("/").includes("..")?[]:[{path:t.path,code:t.code}]).slice(0,100):[]}import{createHash as QE}from"node:crypto";function ve(e){let t=typeof e.content=="string",n=typeof e.contentBase64=="string";if(t&&n)throw new Error("Bundle file must contain exactly one of content or contentBase64.");if(!t&&!n)return new Uint8Array;if(t)return new TextEncoder().encode(e.content);let r=e.contentBase64;if(!q4(r))throw new Error("Bundle file contentBase64 must use canonical base64 encoding.");let i=new Uint8Array(Buffer.from(r,"base64"));if(Buffer.from(i).toString("base64")!==r)throw new Error("Bundle file contentBase64 must use canonical base64 encoding.");return i}function q4(e){if(e.length%4!==0)return!1;let t=e.indexOf("="),n=t<0?e.length:t,r=e.length-n;if(r>2||r>0&&!e.slice(n).split("").every(i=>i==="="))return!1;for(let i=0;i<n;i+=1){let o=e.charCodeAt(i);if(!(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===43||o===47))return!1}return!0}function tn(e,t){let n=Uint8Array.from(e),r=t?.split(";",1)[0]?.trim().toLowerCase(),i=n.length>=4&&String.fromCharCode(...n.subarray(0,4))==="%PDF",o=/^(?:image\/(?:png|jpeg|gif|webp)|audio\/wav|font\/(?:ttf|otf|woff2?)|application\/(?:pdf|gzip))$/u.test(r??"")||i;try{let s=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(n);if(!o&&!s.includes("\0")&&V4(n,new TextEncoder().encode(s)))return{content:s}}catch{}return{contentBase64:Buffer.from(n).toString("base64"),...r?{mediaType:r}:i?{mediaType:"application/pdf"}:{}}}function us(e){return ve(e).byteLength}function xl(e,t){let n=e.toLowerCase();return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=4&&String.fromCharCode(...t.slice(0,4))==="%PDF"?"application/pdf":n.endsWith(".gif")?"image/gif":n.endsWith(".webp")?"image/webp":n.endsWith(".wav")?"audio/wav":n.endsWith(".svg")?"image/svg+xml":n.endsWith(".woff2")?"font/woff2":n.endsWith(".woff")?"font/woff":n.endsWith(".ttf")?"font/ttf":n.endsWith(".otf")?"font/otf":n.endsWith(".tar.gz")?"application/gzip":"application/octet-stream"}function KE(e){let t=e.toLowerCase();return/(?:^|\/)(?:copying|dockerfile|gemfile|justfile|license|makefile|notice|procfile|rakefile|skill\.md|\.editorconfig|\.gitkeep|\.env(?:\.[a-z0-9_-]+)*|\.(?:clawhub|docker|eslint|git|npm|prettier|skill|skills)ignore)$/u.test(t)||/\.(?:bash|bb|c|cc|cjs|clj|cljc|cljs|conf|cpp|cs|css|cts|csv|dart|edn|eex|erb|gql|go|gradle|graphql|groovy|h|hbs|hcl|hpp|html?|http|ini|ipynb|java|js|json|jsx|kt|kts|less|liquid|lock|lua|markdown|md|mdx|mjs|mts|mustache|njk|php|properties|proto|ps1|py|r|rb|rs|scala|scss|sh|sol|sql|svg|svml|svrun|svs|svelte|swift|tex|tf|tfvars|tmpl|toml|tpl|ts|tsx|txt|vue|xml|ya?ml|zsh)$/u.test(t)}function V4(e,t){return e.byteLength===t.byteLength&&e.every((n,r)=>n===t[r])}var wt={maxFiles:100,maxDepth:12,maxPathBytes:240,maxFileBytes:512*1024,maxRasterBytes:10*1024*1024,maxPdfBytes:20*1024*1024,maxTotalBytes:2*1024*1024},G4=new Set([".skills-layer-install.json",".skills-layer-manifest.json",".skills-layer-quarantine","skills-lock.json"]),H4=new Set([".git",".hg",".next",".svn",".turbo","build","coverage","dist","node_modules"]),K4=/^(?:aux|com[1-9]|con|lpt[1-9]|nul|prn)(?:\.|$)/iu,WE=/\b(?<local>[A-Z0-9._%+-]+)@(?<domain>[A-Z0-9.-]+\.[A-Z]{2,})\b/giu,W4=new Set(["example.com","example.net","example.org"]),Z4=new Set(["abuse","admin","announce","contact","dev","help","hostmaster","info","noc","postmaster","security","support","users","webmaster"]),ZE=/(?:^|[^\p{L}\p{N}_])(?<phone>\+?[1-9]\d(?:[ \t().-]*\d){8,14})(?=$|[^\p{L}\p{N}_])/gu,JE=/\b(?:api[_-]?key|client[_-]?secret|password|private[_-]?token|secret|token)\s*[:=]\s*["']?(?<value>[A-Za-z0-9_./+=-]{20,})/giu,J4=[{code:"secret_aws",pattern:/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/u},{code:"secret_github",pattern:/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/u},{code:"secret_groq",pattern:/\bgsk_[A-Za-z0-9_-]{20,}\b/u},{code:"secret_private_key",pattern:/-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/u},{code:"secret_jwt",pattern:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/u}];function Jr(e){let t=Y4(e.limits),n=[],r=[],i=e.skillsIgnore??e.files.find(p=>p.path===".skillsignore")?.content??"",o=t0(i),s=[],a=new Map;for(let p of e.files){if(typeof p?.path!="string"||typeof p.content!="string"&&typeof p.contentBase64!="string"){n.push({severity:"error",code:"file_invalid",message:"Bundle entries must contain a string path and exactly one text or base64 byte payload."});continue}let m;try{m=ve(p)}catch{n.push({severity:"error",code:"file_invalid",path:p.path,message:"Bundle entries must contain exactly one text or canonical-base64 byte payload."});continue}let h=p.path,g=$y(h);if(!g.ok){n.push({severity:"error",code:g.code,path:h,message:g.message});continue}let y=g.path,v=e0(y);if(v){r.push({path:y,reason:v});continue}if(o(y)){r.push({path:y,reason:"skillsignore"});continue}let b=y.normalize("NFC").toLocaleLowerCase("en-US"),w=a.get(b);if(w){n.push({severity:"error",code:"path_collision",path:h,message:`Bundle path collides with ${w} after portable normalization.`});continue}a.set(b,y),s.push({path:y,file:p,bytes:m,originalPath:h})}s.length>t.maxFiles&&n.push({severity:"error",code:"file_count_exceeded",message:`Bundle contains ${s.length} files; the limit is ${t.maxFiles}.`});let l=0;for(let p of s){let m=Buffer.byteLength(p.path,"utf8"),h=p.path.split("/").length,g=p.bytes.byteLength;if(l+=g,h>t.maxDepth&&n.push({severity:"error",code:"path_depth_exceeded",path:p.originalPath,message:"Bundle path exceeds the depth limit."}),m>t.maxPathBytes&&n.push({severity:"error",code:"path_too_long",path:p.originalPath,message:"Bundle path exceeds the byte limit."}),e.contentPolicy!=="paths_only"){let y=r0(p.path,t);g>y&&n.push({severity:"error",code:"file_too_large",path:p.originalPath,message:"Bundle file exceeds the byte limit."}),eV(p,n),e.runDlp!==!1&&typeof p.file.content=="string"&&aV(p.originalPath,p.file.content,n)}i0("",p.path)&&n.push({severity:"error",code:"pii_path",path:p.originalPath,message:"Bundle path contains personal data."})}l>t.maxTotalBytes&&n.push({severity:"error",code:"total_bytes_exceeded",message:"Bundle exceeds the total byte limit."});let c=s.map(({path:p,file:m,bytes:h})=>({path:p,...Ty(p)===".pdf"?tn(h,"application/pdf"):{...typeof m.content=="string"?{content:m.content}:{},...typeof m.contentBase64=="string"?{contentBase64:m.contentBase64}:{},...typeof m.mediaType=="string"?{mediaType:m.mediaType}:{}}})).sort((p,m)=>p.path.localeCompare(m.path)),u=c.map(p=>({path:p.path,bytes:ve(p).byteLength,sha256:DV(ve(p))})),d={fileCount:c.length,totalBytes:l,files:u,bundleSha256:TV(c)};return{ok:n.length===0,files:c,excluded:r.sort((p,m)=>p.path.localeCompare(m.path)),issues:n,preview:d}}function Yr(e){let t=Jr(e);if(!t.ok)throw new Ld(t.issues.map(n=>({path:n.path??"SKILL.md",code:n.code})));return t}function Ey(e=""){let t=t0(e);return n=>{let r=$y(n);return r.ok?e0(r.path)??(t(r.path)?"skillsignore":null):null}}function Y4(e){let t={...wt,...e};for(let[n,r]of Object.entries(t))if(!Number.isInteger(r)||r<=0)throw new Error(`Canonical bundle ${n} must be a positive integer.`);return t}function $y(e){if(!e||e.includes("\0")||e.includes("\\")||e.startsWith("/")||/^[A-Za-z]:/u.test(e))return{ok:!1,code:"path_invalid",message:"Bundle path is not portable."};let t=e.normalize("NFC"),n=t.split("/");if(n.some(r=>!r||r==="."||r===".."))return{ok:!1,code:"path_traversal",message:"Bundle path contains an empty or traversal segment."};for(let r of n)if(/[<>:"|?*\u0000-\u001f]/u.test(r)||/[. ]$/u.test(r)||K4.test(r))return{ok:!1,code:"path_invalid",message:"Bundle path contains a reserved platform segment."};return G4.has(t.toLocaleLowerCase("en-US"))?{ok:!1,code:"reserved_path",message:"Bundle path is reserved for Skills Layer state."}:{ok:!0,path:t}}function Dy(e,t){return r0(e,t)}function e0(e){if(e===".skillsignore")return"control_file";let t=e.split("/");if(t.some(i=>H4.has(i.toLocaleLowerCase("en-US"))))return"default_exclusion";let n=t.at(-1).toLocaleLowerCase("en-US"),r=/^\.env(?:\.[a-z0-9_-]+)*\.(?:dist|example|sample|template)$/u.test(n);return/^\.env(?:\.|$)/u.test(n)&&!r||/^(?:credentials?|id_rsa|id_ed25519)(?:\.|$)/u.test(n)||/\.(?:key|p12|pfx|pem)$/u.test(n)||n===".ds_store"||n==="thumbs.db"?"default_exclusion":null}function t0(e){if(Buffer.byteLength(e,"utf8")>32*1024)throw new Error(".skillsignore exceeds 32 KiB.");let t=e.split(/\r?\n/gu).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#"));if(t.length>256)throw new Error(".skillsignore contains too many patterns.");let n=t.map(r=>{if(r.startsWith("!"))throw new Error(".skillsignore negation is not supported by the secure intake policy.");if(r.length>240||r.includes("\0")||r.includes("\\")||r.includes(".."))throw new Error(".skillsignore contains an unsafe pattern.");let i=r.startsWith("/"),o=r.replace(/^\/+|\/+$/gu,""),s=o.replace(/[.+^${}()|[\]\\]/gu,"\\$&").replace(/\*\*/gu,"\0").replace(/\*/gu,"[^/]*").replace(/\?/gu,"[^/]").replace(/\u0000/gu,".*");return new RegExp(`${i||o.includes("/")?"^":"(?:^|/)"}${s}(?:/.*)?$`,"u")});return r=>n.some(i=>i.test(r.normalize("NFC")))}var n0=new Map([[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"]]),X4=new Set([".md",".markdown",".txt",".json",".jsonl",".yaml",".yml",".toml",".xml",".csv",".tsv",".js",".mjs",".cjs",".ts",".tsx",".jsx",".py",".rb",".go",".rs",".java",".sh",".css",".html",".svg"]),Q4=new Map([[".webp","image/webp"],[".wav","audio/wav"],[".ttf","font/ttf"],[".otf","font/otf"]]);function r0(e,t){let n=Ty(e);return n0.has(n)?t.maxRasterBytes:n===".pdf"?t.maxPdfBytes:n===".webp"||n===".wav"?t.maxRasterBytes:n===".ttf"||n===".otf"?Math.min(t.maxRasterBytes,2*1024*1024):t.maxFileBytes}function eV(e,t){let n=Ty(e.path),r=e.file.mediaType?.trim().toLowerCase(),i=e.path.toLowerCase().endsWith(".tar.gz")?"application/gzip":Q4.get(n);if(i){if(r&&r!==i){Ye(t,"media_type_mismatch",e,"Binary media type does not match its inspection profile extension.");return}let s=e.bytes;(i==="application/gzip"?s.length>=18&&s[0]===31&&s[1]===139&&s[2]===8&&s[3]===0:n===".webp"?s.length>=20&&Wn(s,0,4)==="RIFF"&&Wn(s,8,4)==="WEBP"&&XE(s,4)===s.length-8:n===".wav"?s.length>=12&&Wn(s,0,4)==="RIFF"&&Wn(s,8,4)==="WAVE"&&XE(s,4)===s.length-8:n===".ttf"?s.length>=12&&jd(s,0)===65536:s.length>=12&&Wn(s,0,4)==="OTTO")||Ye(t,"binary_transport_signature_invalid",e,"Binary signature is not valid for the requested inspection profile.");return}let o=n0.get(n);if(o){if(r&&r!==o){Ye(t,"media_type_mismatch",e,"Raster media type does not match its approved extension.");return}tV(e,o,t);return}if(n===".pdf"){if(r&&r!=="application/pdf"){Ye(t,"media_type_mismatch",e,"PDF media type does not match its extension.");return}rV(e,t);return}if(n===".svg"){r&&r!=="image/svg+xml"&&r!=="text/plain"&&Ye(t,"media_type_mismatch",e,"SVG media type is invalid."),YE(e,t);let s=e.file.content??new TextDecoder().decode(e.bytes);/<script\b|\bon[a-z]+\s*=|\b(?:href|src)\s*=\s*["'](?:https?:|data:|\/\/)|<foreignObject\b/iu.test(s)&&Ye(t,"svg_active_content",e,"SVG contains active or externally loaded content.");return}if(sV(e.bytes)||e.file.contentBase64&&!X4.has(n)){Ye(t,"unsupported_binary_type",e,"Archive, executable, or unknown binary content is not eligible for automatic publication.");return}YE(e,t)}function YE(e,t){if(e.file.content?.includes("\0")){Ye(t,"binary_content",e,"Bundle file is not bounded UTF-8 text.");return}try{new TextDecoder("utf-8",{fatal:!0}).decode(e.bytes)}catch{Ye(t,"invalid_utf8",e,"Text bundle file is not valid UTF-8.")}}function tV(e,t,n){let r=e.bytes,i=0,o=0;if(t==="image/png"){let a=[137,80,78,71,13,10,26,10];if(r.length<33||!a.every((l,c)=>r[c]===l)||Wn(r,12,4)!=="IHDR"){Ye(n,"raster_malformed",e,"PNG header is malformed or truncated.");return}if(i=jd(r,16),o=jd(r,20),!nV(r)){Ye(n,"raster_malformed",e,"PNG chunk structure is malformed or truncated.");return}(ds(r,"eXIf")||ds(r,"tEXt")||ds(r,"zTXt")||ds(r,"iTXt"))&&Ye(n,"sensitive_image_metadata",e,"Raster metadata requires manual review.")}else if(t==="image/gif"){if(r.length<14||Wn(r,0,6)!=="GIF87a"&&Wn(r,0,6)!=="GIF89a"||r.at(-1)!==59){Ye(n,"raster_malformed",e,"GIF is malformed or truncated.");return}i=r[7]<<8|r[6],o=r[9]<<8|r[8]}else{let a=iV(r);if(!a){Ye(n,"raster_malformed",e,"JPEG is malformed or truncated.");return}({width:i,height:o}=a),oV(r)&&Ye(n,"sensitive_image_metadata",e,"Raster metadata requires manual review.")}let s=i*o;(i<1||o<1||i>16384||o>16384||s>1e8||s>Math.max(1,r.byteLength)*500)&&Ye(n,"raster_decompression_risk",e,"Raster dimensions or compression ratio exceed the safe policy.")}function nV(e){let t=8,n=0,r=!1;for(;t+12<=e.length;){let i=jd(e,t),o=Wn(e,t+4,4),s=t+12+i;if(!Number.isSafeInteger(s)||s>e.length||n===0&&(o!=="IHDR"||i!==13))return!1;if(o==="IDAT"&&(r=!0),o==="IEND")return i===0&&r&&s===e.length;t=s,n+=1}return!1}function rV(e,t){let n=e.bytes;if(n.length<12||Wn(n,0,5)!=="%PDF-"||!ds(n.subarray(Math.max(0,n.length-1024)),"%%EOF")){Ye(t,"pdf_malformed",e,"PDF structure is malformed or truncated.");return}let r=new TextDecoder("latin1").decode(n);/\/(?:JavaScript|JS|Launch|EmbeddedFile|Encrypt|AcroForm)\b/u.test(r)&&Ye(t,"pdf_active_content",e,"PDF contains active, encrypted, embedded, or form content.");let i=r.match(/\/Type\s*\/Page\b/gu)?.length??0,o=r.match(/\b\d+\s+\d+\s+obj\b/gu)?.length??0;(i>500||o>1e4)&&Ye(t,"pdf_structure_limit_exceeded",e,"PDF page or object count exceeds the safe policy.")}function iV(e){if(e.length<4||e[0]!==255||e[1]!==216||e.at(-2)!==255||e.at(-1)!==217)return null;for(let t=2;t+8<e.length;){if(e[t]!==255)return null;let n=e[t+1];if(n===217||n===218)break;let r=e[t+2]<<8|e[t+3];if(r<2||t+2+r>e.length)return null;if(n>=192&&n<=195)return{height:e[t+5]<<8|e[t+6],width:e[t+7]<<8|e[t+8]};t+=2+r}return null}function oV(e){return ds(e,"Exif\0\0")}function sV(e){let t=["PK","MZ","\x7FELF","Rar!","7z\xBC\xAF'"],n=new TextDecoder("latin1").decode(e.subarray(0,8));return t.some(r=>n.startsWith(r))}function Ye(e,t,n,r){e.push({severity:"error",code:t,path:n.originalPath,message:r})}function Ty(e){let t=e.split("/").at(-1).toLowerCase(),n=t.lastIndexOf(".");return n<=0?"":t.slice(n)}function XE(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!0)}function Wn(e,t,n){return new TextDecoder("latin1").decode(e.subarray(t,t+n))}function ds(e,t){return new TextDecoder("latin1").decode(e).includes(t)}function jd(e,t){return e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]>>>0}function aV(e,t,n){for(let r of J4)r.pattern.test(t)&&n.push({severity:"error",code:r.code,path:e,message:"Bundle content matched a protected-data rule."});lV(t)&&n.push({severity:"error",code:"secret_assignment",path:e,message:"Bundle content matched a protected-data rule."}),i0(e,t)&&n.push({severity:"error",code:"pii_email",path:e,message:"Bundle content contains an email address."}),mV(e,t)&&n.push({severity:"error",code:"pii_phone",path:e,message:"Bundle content contains a phone number."})}function lV(e){JE.lastIndex=0;for(let t of e.matchAll(JE)){let n=t.groups.value;if(/^(?:process|import\.meta)\.env\.[A-Za-z_][A-Za-z0-9_]*$/u.test(n)||uV(n))continue;let r=t[0].lastIndexOf(n),i=t.index+r+n.length;if(/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)+$/u.test(n)){let o=e.slice(i,i+256);if(/^(?:\s*<[A-Za-z_$][A-Za-z0-9_$.]*(?:\s*,\s*[A-Za-z_$][A-Za-z0-9_$.]*)*>)?\s*\(/u.test(o))continue}return!0}return!1}function i0(e,t){WE.lastIndex=0;for(let n of t.matchAll(WE)){let r=n.groups.local.toLowerCase(),i=n.groups.domain.toLowerCase(),o=t.lastIndexOf(`
702
702
  `,n.index-1)+1,s=t.indexOf(`
703
703
  `,n.index),a=t.slice(o,s<0?t.length:s);if(!(W4.has(i)||Z4.has(r)||dV(r,i)||pV(t,n.index,n[0].length,r)||cV(e,t,a,o)||fV(r,i,a)))return!0}return!1}function cV(e,t,n,r){if(!/(?:^|\/)(?:[^/]*[-_])?OFL\.txt$/iu.test(e)||r>=2048||t.slice(0,r).split(`
704
704
  `).length>16)return!1;let i=/SIL OPEN FONT LICENSE[ \t]+Version[ \t]+1\.1/iu.exec(t);return!i||r>=i.index||!/^PREAMBLE\s*$/mu.test(t)||!/^PERMISSION & CONDITIONS\s*$/mu.test(t)?!1:/^Copyright[ \t]+(?:\(c\)[ \t]*)?\d{4}(?:-\d{4})?[^@\r\n()]*\([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\)(?:,?(?:[ \t]+with Reserved Font Name[ \t]+"[^"@\r\n]{1,128}"\.)?)?[ \t]*\r?$/iu.test(n)}function uV(e){return/^(?:your|replace|insert|example|sample|dummy|fake)[_-](?:actual[_-])?(?:api[_-]?key|client[_-]?secret|password|private[_-]?token|secret|token)(?:[_-](?:here|value))?$/iu.test(e)||/^(?:(?:my|sk)[_-])?hardcoded[_-](?:api[_-]?key|client[_-]?secret|password|private[_-]?token|secret|token)$/iu.test(e)}function dV(e,t){return t==="users.noreply.github.com"||/^(?:noreply|no-reply|web-flow)$/u.test(e)}function pV(e,t,n,r){return r!=="git"?!1:/^:[^\s`'"]+\.git\b/iu.test(e.slice(t+n))}function fV(e,t,n){return t==="test.com"&&/^(?:test|user)$/u.test(e)&&/\b(?:agent-browser|example|fill|fixture)\b/iu.test(n)||/\.emails\s*\([^)]*\).*return\s+terms\s+like/iu.test(n)||/^\s*\|\s*`?#Email`?\s*\|.*\|\s*$/iu.test(n)||/^\s*(?:(?:\*|\/\/|#)\s*)?(?:@author\b|(?:\(c\)|©)\s+)[^\r\n]*<*[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}>*\s*$/iu.test(n)||/^\s*[-*]\s*(?:check\s+if\s+email\s+is\s+professional\b|use\s+format\s*:|avoid\s*:)/iu.test(n)&&(/\b(?:custom\s+domain|email|format|ideal|professional)\b/iu.test(n)||/^\s*[-*]\s*avoid\s*:/iu.test(n)&&/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}.*[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/iu.test(n))||/["']selector["']\s*:\s*["']#email["']/iu.test(n)&&/["']text["']\s*:\s*["'][A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}["']/iu.test(n)?!0:/\{[^}\n]*\bEmail\b[^}\n]*\}\s*$/u.test(n)&&/\bemail\b/iu.test(n)}function mV(e,t){ZE.lastIndex=0;for(let n of t.matchAll(ZE)){let r=n.groups.phone,i=n[0].indexOf(r),o=n.index+i;if(gV(t,o,r))continue;let s=t[o-1]??"",a=t[o-2]??"",l=t[o+r.length]??"",c=t[o+r.length+1]??"",u=t.lastIndexOf(`
705
705
  `,o-1)+1,d=t.indexOf(`
706
- `,o),p=t.slice(u,d<0?t.length:d),m=t.slice(u,o),h=/(?:^|[^\p{L}\p{N}_-])X-RateLimit-Reset\s*:\s*$/iu.test(m),g=$V(t,o),y=hV(e,p,r,o-u),v=/^\d+(?:-\d+)*$/u.test(r)&&(s==="-"&&/[\p{L}\p{N}_]/u.test(a)||l==="-"&&/[\p{L}\p{N}_]/u.test(c));if((r.startsWith("+")||/[()]/u.test(r)||/^\d{2,4}(?:[-. ]\d{2,4}){2,4}$/u.test(r)||/^(?:1\d{10}|44\d{10})$/u.test(r)||/\b(?:\w*phone|call|contact|fax|mobile|sms|tel|telephone|whatsapp)\b/iu.test(p))&&!v&&!h&&!g&&!y)return!0}return!1}function gV(e,t,n){if(!/^[\d.\s]+$/u.test(n))return!1;let r=Math.max(0,t-32),i=e.slice(r,t+n.length+32),o=/(?:^|[^\d.])(?<network>(?<address>\d{1,3}(?:\.\d{1,3}){3})(?:\/(?<prefix>\d{1,2}))?)(?=$|[^\d.])/gu,s=[];for(let a of i.matchAll(o)){if(!s0(a.groups.address)||a.groups.prefix!==void 0&&Number(a.groups.prefix)>32)continue;let l=r+a.index+a[0].indexOf(a.groups.network);s.push({start:l,end:l+a.groups.network.length})}for(let a=0;a<n.length;a++)if(/\d/u.test(n[a])&&!s.some(l=>t+a>=l.start&&t+a<l.end))return!1;return!0}function hV(e,t,n,r){let i=r+n.length;return yV(n)||_V(t,n,r)||SV(t,r,i)||xV(t,r,i)||CV(t,n,r,i)||IV(t,r,i)||PV(e,t,n,r)||ze(t,r,i,/(?<![\d.])\d+\.\d+(?![\d.])/gu)||ze(t,r,i,/\b\d{4}-\d{2}-\d{2}(?:[ T]\d{2}(?::\d{2}){0,2}(?:[,.]\d+)?(?:Z|\s+[+-]\d{2}(?::?\d{2})?)?)?\b/gu)?!0:n.startsWith("+")||/[()]/u.test(n)||/\b(?:call|contact|fax|mobile|phone|sms|tel|telephone|whatsapp)\b/iu.test(t)?!1:vV(t,r,i)||kV(t,r,i)||wV(t,r,i)||bV(t,n,r,i)||AV(t,r,i)||s0(n)||RV(t,r,i)||ze(t,r,i,/\bhresult\s+-eq\s+-?\d+\b/giu)||ze(t,r,i,/\bst_mtime_ns\s*\/\/\s*[0-9_]+/giu)||/^\s*index\s+[0-9a-f]{7,40}\.\.[0-9a-f]{7,40}\s+\d{6}\s*$/iu.test(t)||ze(t,r,i,/\bprs?\s+(?:\d+\s+){2,}\d+\b/giu)||ze(t,r,i,/\bv?\d+(?:\.\d+)*\s+\d{4}\.\d{2}\.\d{2}\s+\d{2}:\d{2}\b/giu)||ze(t,r,i,/\brun\s+`\d{9,15}`(?=[^\r\n]{0,100}\btook\b[^\r\n]{0,30}\bminutes?\b)/giu)||ze(t,r,i,/\d+\s+的\s+\d+\s+号评论/gu)||/\b(?:returnCode|unique\s+(?:code|identifier)|唯一编码)\b/iu.test(t)&&ze(t,r,i,/\b[A-Za-z][A-Za-z0-9_]*(?:_[A-Za-z0-9]+)+\/\d{9,15}\b/gu)||ze(t,r,i,/\b[A-Z][A-Z0-9_]*_BYTES\s*=\s*\d+\b/gu)||/^\s*(?:[-+]?\d+\.\d+\s+){3,}[-+]?\d+\.\d+\s*$/u.test(t)||/^\s*\[\s*[-+]?\d+(?:\.\d+)?\s*,\s*[-+]?\d+(?:\.\d+)?\s*,\s*[-+]?\d+(?:\.\d+)?\s*,\s*[-+]?\d+(?:\.\d+)?\s*\]\s*,?\s*$/u.test(t)&&/[-+]?\d+\.\d+/u.test(t)?!0:EV(e,t,r,i)}function yV(e){if(!/^\d{9,15}$/u.test(e))return!1;let t=[...e].map(Number),n=t.slice(1).every((i,o)=>i===(t[o]+1)%10),r=t.slice(1).every((i,o)=>i===(t[o]+9)%10);return n||r}function vV(e,t,n){let r=/["']?(?:created_time|enterpriseValue|exclusiveMaximum|exclusiveMinimum|expiration|expirationDate|expirationDates|expirations|fetchedAt|maximum|minimum|publishedAt|trade_date|updated_time|volume|z-index)["']?\s*[:=]\s*/giu;for(let i of e.matchAll(r)){let o=i.index+i[0].length;if(e[o]==="["){let l=e.indexOf("]",o+1);if(l<0)continue;let c=e.slice(o,l+1);if(/^\[\s*\d+(?:\s*,\s*\d+)*\s*\]$/u.test(c)&&t>=o+1&&n<=l)return!0;continue}let s=[",",")","}","]",";","|"].map(l=>e.indexOf(l,o)).filter(l=>l>=0),a=s.length>0?Math.min(...s):e.length;if(t>=o&&n<=a&&/^\s*\d+(?:\.\d+)?\s*$/u.test(e.slice(o,a)))return!0}return!1}function kV(e,t,n){for(let r of e.matchAll(/\{[^{}\r\n]*\}/gu))if(!(t<r.index||n>r.index+r[0].length))try{let i=JSON.parse(r[0]);if(typeof i.timestamp!="number"||!o0(i.timestamp))continue;let o=t-r.index;if(ze(r[0],o,n-r.index,/"timestamp"\s*:\s*(?:\d{10}|\d{13})(?=\s*[,}])/gu))return!0}catch{}return!1}function wV(e,t,n){let r=/(?:^|[\\/])\.superpowers[\\/]brainstorm[\\/][1-9]\d{0,6}-(?<epoch>\d{10})[\\/](?:content|state)(?=$|[\\/\s"'`,}])/gu;for(let i of e.matchAll(r))if(t>=i.index&&n<=i.index+i[0].length&&o0(Number(i.groups.epoch)))return!0;return!1}function o0(e){let t=e>=1e12?e/1e3:e;return t>=946684800&&t<=4102444800}function bV(e,t,n,r){let i=t.replace(/\s/gu,"");return/^\d+(?:\.\d+){1,}(?:[-~]\d+(?:\.\d+){1,})?$/u.test(i)?Number(i.split(/[.~-]/u,1)[0])<=99&&/\b(?:codex(?:\s+store)?|css(?:\s+modules?)?|owl\s+runtime|renderer|selector|windowsapps)\b/iu.test(e)||ze(e,n,r,/(?:\b(?:chromium|codex|mac|macos|release|runtime|versions?|win|windows)\b|版本(?:号)?)\s*[:=`'"(\[]*\s*\d+(?:\.\d+){1,}(?:[-~]\d+(?:\.\d+){1,})?/giu)?!0:ze(e,n,r,/["']?version["']?\s*[:=]\s*["']?\d+(?:\.\d+){1,}(?:[-~]\d+(?:\.\d+){1,})?["']?/giu):!1}function _V(e,t,n){let r=t.replace(/\D/gu,""),i=/^(?:1)?\d{3}55501\d{2}$/u.test(r),o=/^(?:1)?555\d{7}$/u.test(r);if((i||o)&&(/\.phoneNumbers\s*\([^)]*\).*return\s+terms\s+like/iu.test(e)||/^\s*\|\s*`?#PhoneNumber`?\s*\|.*\|\s*$/iu.test(e))||/^\s*[*-].*\b(?:no\s+fake|fake-perfect|avoid\s+predictable)\b.*\b(?:numbers?|phone)\b.*\b(?:organic|messy)\b/iu.test(e))return!0;let s=Math.max(e.lastIndexOf(";",n-1),e.lastIndexOf(".",n-1),e.lastIndexOf("!",n-1),e.lastIndexOf("?",n-1))+1,a=e.slice(s,n);return/\b(?:fake|placeholder|predictable|example|format|organic|messy)\b/iu.test(a)&&/\b(?:phone|numbers?)\b/iu.test(e)&&!/\b(?:actual|customer|owner|contact|call|mobile|telephone|whatsapp)\b/iu.test(a)}function SV(e,t,n){return ze(e,t,n,/https?:\/\/[^\s<>"']+/giu)}function xV(e,t,n){return ze(e,t,n,/\barXiv\s*:\s*\d{4}\.\d{4,5}(?:\s*\(\d{4}-\d{2}\))?/giu)||ze(e,t,n,/\b10\.\d{4,9}\/[A-Z0-9][A-Z0-9._()/:+-]*/giu)||ze(e,t,n,/\b(?:Academic\s+Year|学年度)[^.;\r\n]{0,24}\d{2,4}\s*\(\d{4}-\d{2,4}\)/giu)||/\b(?:activity|date|month|recent|timeline)\b|动态|最近|月份?/iu.test(e)&&ze(e,t,n,/\b\d{4}[.-]\d{1,2}\s*[-–—~]\s*\d{4}[.-]\d{1,2}\b/gu)}function CV(e,t,n,r){let i=Math.max(e.lastIndexOf(";",n-1),e.lastIndexOf("\uFF1B",n-1))+1,o=[e.indexOf(";",r),e.indexOf("\uFF1B",r)].filter(c=>c>=0),s=o.length>0?Math.min(...o):e.length,a=e.slice(i,s),l=t.replace(/[\s()]/gu,"");return/(?:[A-Z0-9_]*application_number\b|\bapplication[ -]number\b|\bnormalize_application_number\b|\bapplication_number_for_[A-Z0-9_]+\b|\bpatent(?:[_ -]?number)?\b|申请号|专利号|用户常输入)/iu.test(a)&&/^\d{9,15}(?:\.\d)?$/u.test(l)?!0:ze(e,n,r,/\b(?:application[_ -]?number|patent(?:[_ -]?number)?)\b[^;\r\n]{0,80}?(?:CN)?\d{9,15}(?:\.\d)?(?:[A-Z]\d?)?/giu)||ze(e,n,r,/申请号[^;;\r\n]{0,160}/gu)}function IV(e,t,n){return ze(e,t,n,/@id\s*=\s*\d{9,15}/giu)}function PV(e,t,n,r){if(!/\.min\.js$/iu.test(e)||!/^\d{9,16}$/u.test(n))return!1;let i=t.slice(Math.max(0,r-40),r);return/\b(?:call|contact|fax|mobile|owner|phone|sms|tel|telephone|whatsapp)\s*[:=]\s*["']?\s*$/iu.test(i)?!1:/(?:!function|=>|\bfunction\b|\bvar\b|\blet\b|\bconst\b)/u.test(t)}function AV(e,t,n){let r=/<(?:origin|joint|link)\b[^>]*\b(?:rpy|xyz)\s*=\s*(["'])(?<value>[-+\d.eE,\s]+)\1/giu;for(let i of e.matchAll(r)){let o=i.groups.value,s=i.index+i[0].indexOf(o);if(t>=s&&n<=s+o.length)return!0}return!1}function s0(e){let n=e.replace(/\s/gu,"").split(".");return n.length===4&&n.every(r=>/^\d{1,3}$/u.test(r)&&Number(r)<=255)}function RV(e,t,n){let r=e.lastIndexOf("`",t);if(r<0)return!1;let i=e.indexOf("`",r+1);if(i<0)return!1;let o=e.slice(r+1,i);return/^\s*\d+(?:\s+\d+){15,}\s*$/u.test(o)}function ze(e,t,n,r){for(let i of e.matchAll(r)){let o=i.index;if(t>=o&&n<=o+i[0].length)return!0}return!1}function EV(e,t,n,r){let i=[.../\.svg$/iu.test(e)?[/\b(?:height|viewBox|width|x|y)\s*=\s*(["'])(?<value>[-+\d.eE,\s]+)\1/giu]:[],.../data:image\/svg\+xml/iu.test(t)?[/<feColorMatrix\b[^>]*\bvalues\s*=\s*(["'])(?<value>[-+\d.eE,\s]+)\1/giu]:[]];for(let o of i)for(let s of t.matchAll(o)){let a=s.groups.value,l=s.index+s[0].indexOf(a);if(n>=l&&r<=l+a.length)return!0}return!1}function $V(e,t){let n=e.lastIndexOf("<path",t);if(n<0||e.indexOf(">",n)<t)return!1;let i=e.slice(n,t),o=/\bd\s*=\s*(["'])(?<value>[\s\S]*)$/iu.exec(i);return!!(o&&!o.groups.value.includes(o[1]))}function DV(e){return`sha256:${QE("sha256").update(e).digest("hex")}`}function TV(e){let t=QE("sha256");return e.forEach((n,r)=>{t.update(n.path),t.update("\0"),t.update(ve(n)),r<e.length-1&&t.update("\0")}),`sha256:${t.digest("hex")}`}import{createHash as OV}from"node:crypto";var LV=new Set(["evals","tests","test","fixtures","examples","golden","goldens","snapshots","__snapshots__",".github",".circleci","coverage"]),jV=new Set([".gitlab-ci.yml","azure-pipelines.yml"]),NV=[".eval.json",".eval.yaml"],FV=[".golden.",".snapshot."],a0=".skills-layer/skill.yaml",BV=new Set([".git",".hg",".svn"]),MV=new Set([".cache",".creator-tmp",".skills-layer-tmp",".tmp","node_modules"]),UV=Buffer.from([46,68,83,95,83,116,111,114,101]).toString("ascii"),zV=new Set([UV,"Thumbs.db"]);function Dn(e,t){let n=jy(e),r=c0(t),i=Oy(n,r),[o]=i.split("/");return i===a0?{path:n,relativePath:i,root:r,type:"control",reasonCode:"root_control_manifest"}:n.endsWith(`/${a0}`)?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"misplaced_control_manifest"}:i.startsWith(".skills-layer/")?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"unsupported_control_material"}:o&&BV.has(o)?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"excluded_repository_metadata"}:o&&(MV.has(o)||zV.has(o)||o.endsWith("~")||o.endsWith(".swp")||o.endsWith(".tmp"))?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"excluded_cache_or_temporary"}:o&&LV.has(o)?{path:n,relativePath:i,root:r,type:"evidence",reasonCode:"top_level_evidence_folder"}:GV(i)?{path:n,relativePath:i,root:r,type:"evidence",reasonCode:"evidence_test_or_spec_file"}:HV(i)?{path:n,relativePath:i,root:r,type:"evidence",reasonCode:"top_level_evidence_file"}:{path:n,relativePath:i,root:r,type:"runtime",reasonCode:"runtime_material"}}function l0(e){return e.map(t=>Dn(t.path,e))}function Ly(e){return qV(e,"runtime")}function qV(e,t){let n=c0(e);return e.map(r=>({...r,path:jy(r.path)})).filter(r=>Dn(r.path,e).type===t).sort((r,i)=>KV(r.path,i.path,n))}function ct(e){return VV(Ly(e))}function VV(e){let t=OV("sha256");for(let n of e)t.update(n.path),t.update("\0"),t.update(ve(n)),t.update("\0");return`sha256:${t.digest("hex")}`}function GV(e){let t=e.split("/"),n=t[t.length-1].toLocaleLowerCase("en-US");return/(?:^|\.)(?:test|spec)\.[^.]+$/u.test(n)}function HV(e){return e.includes("/")?!1:jV.has(e)||NV.some(t=>e.endsWith(t))||FV.some(t=>e.includes(t))}function c0(e){let t=e.map(n=>jy(n.path)).find(n=>n==="SKILL.md"||n.endsWith("/SKILL.md"));return!t||t==="SKILL.md"?"":t.slice(0,-9)}function Oy(e,t){return t?e===t?"":e.startsWith(`${t}/`)?e.slice(t.length+1):e:e}function KV(e,t,n){let r=Oy(e,n),i=Oy(t,n);return r==="SKILL.md"?i==="SKILL.md"?0:-1:i==="SKILL.md"?1:e.localeCompare(t)}function jy(e){return e.replaceAll("\\","/").split("/").filter(t=>t.length>0&&t!==".").join("/")}function u0(e){let t=new TextEncoder,n=[],r=[],i=0;for(let c of e){let u=t.encode(c.path),d=ve(c),p=WV(d),m=new Uint8Array(30+u.length+d.length),h=new DataView(m.buffer);h.setUint32(0,67324752,!0),h.setUint16(4,20,!0),h.setUint16(6,2048,!0),h.setUint16(8,0,!0),h.setUint16(10,0,!0),h.setUint16(12,0,!0),h.setUint32(14,p,!0),h.setUint32(18,d.byteLength,!0),h.setUint32(22,d.byteLength,!0),h.setUint16(26,u.length,!0),h.setUint16(28,0,!0),m.set(u,30),m.set(d,30+u.length),n.push(m);let g=new Uint8Array(46+u.length),y=new DataView(g.buffer);y.setUint32(0,33639248,!0),y.setUint16(4,20,!0),y.setUint16(6,20,!0),y.setUint16(8,2048,!0),y.setUint16(10,0,!0),y.setUint16(12,0,!0),y.setUint16(14,0,!0),y.setUint32(16,p,!0),y.setUint32(20,d.byteLength,!0),y.setUint32(24,d.byteLength,!0),y.setUint16(28,u.length,!0),y.setUint16(30,0,!0),y.setUint16(32,0,!0),y.setUint16(34,0,!0),y.setUint16(36,0,!0),y.setUint32(38,0,!0),y.setUint32(42,i,!0),g.set(u,46),r.push(g),i+=m.byteLength}let o=Ny(r),s=Ny(n),a=new Uint8Array(22),l=new DataView(a.buffer);return l.setUint32(0,101010256,!0),l.setUint16(4,0,!0),l.setUint16(6,0,!0),l.setUint16(8,e.length,!0),l.setUint16(10,e.length,!0),l.setUint32(12,o.byteLength,!0),l.setUint32(16,s.byteLength,!0),l.setUint16(20,0,!0),Ny([s,o,a])}function WV(e){let t=4294967295;for(let n of e){t^=n;for(let r=0;r<8;r+=1)t=(t&1)===1?t>>>1^3988292384:t>>>1}return(t^4294967295)>>>0}function Ny(e){let t=e.reduce((i,o)=>i+o.byteLength,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.byteLength;return n}function d0(e,t){if(!(e instanceof Uint8Array)||e.byteLength>t.maxArchiveBytes)throw new Error("Artifact v1 ZIP exceeds its archive limit.");if(e.byteLength<22)throw new Error("Artifact v1 ZIP is incomplete.");let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=e.byteLength-22;if(n.getUint32(r,!0)!==101010256)throw new Error("Artifact v1 ZIP end record is missing or trailing bytes are present.");let i=n.getUint16(r+4,!0),o=n.getUint16(r+6,!0),s=n.getUint16(r+8,!0),a=n.getUint16(r+10,!0),l=n.getUint32(r+12,!0),c=n.getUint32(r+16,!0),u=n.getUint16(r+20,!0);if(i!==0||o!==0||s!==a||a===65535||l===4294967295||c===4294967295||u!==0||a===0||a>t.maxFiles||c+l!==r)throw new Error("Artifact v1 ZIP end record is invalid.");let d=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),p=[],m=new Set,h=c,g=0,y=0;for(let v=0;v<a;v+=1){if(h+46>r||n.getUint32(h,!0)!==33639248)throw new Error("Artifact v1 ZIP central directory is truncated.");let b=n.getUint16(h+4,!0),w=n.getUint16(h+6,!0),_=n.getUint16(h+8,!0),C=n.getUint16(h+10,!0),P=n.getUint16(h+12,!0),N=n.getUint16(h+14,!0),O=n.getUint32(h+16,!0),X=n.getUint32(h+20,!0),G=n.getUint32(h+24,!0),ee=n.getUint16(h+28,!0),te=n.getUint16(h+30,!0),Q=n.getUint16(h+32,!0),Ie=n.getUint16(h+34,!0),fn=n.getUint16(h+36,!0),el=n.getUint32(h+38,!0),ht=n.getUint32(h+42,!0),$A=h+46+ee+te+Q;if(b!==20||w!==20||_!==2048||C!==0||P!==0||N!==0||X!==G||X===4294967295||ee===0||ee>t.maxPathBytes||te!==0||Q!==0||Ie!==0||fn!==0||el!==0||ht!==g||$A>r||G>t.maxFileBytes)throw new Error("Artifact v1 ZIP central entry is invalid.");if(y+=G,y>t.maxTotalFileBytes)throw new Error("Artifact v1 ZIP exceeds its total file-byte limit.");let Uh=e.slice(h+46,h+46+ee),od;try{od=d.decode(Uh)}catch{throw new Error("Artifact v1 ZIP path is not valid UTF-8.")}if(m.has(od))throw new Error("Artifact v1 ZIP path uniqueness is invalid.");if(m.add(od),ht+30>c||n.getUint32(ht,!0)!==67324752)throw new Error("Artifact v1 ZIP local entry is missing.");let Lz=n.getUint16(ht+4,!0),jz=n.getUint16(ht+6,!0),Nz=n.getUint16(ht+8,!0),Fz=n.getUint16(ht+10,!0),Bz=n.getUint16(ht+12,!0),Mz=n.getUint32(ht+14,!0),DA=n.getUint32(ht+18,!0),Uz=n.getUint32(ht+22,!0),zh=n.getUint16(ht+26,!0),TA=n.getUint16(ht+28,!0),OA=ht+30+zh+TA,qh=OA+DA;if(Lz!==w||jz!==_||Nz!==C||Fz!==P||Bz!==N||Mz!==O||DA!==X||Uz!==G||zh!==ee||TA!==0||qh>c||!JV(e.subarray(ht+30,ht+30+zh),Uh))throw new Error("Artifact v1 ZIP local and central entries do not match.");let Vh=e.slice(OA,qh);if(ZV(Vh)!==O)throw new Error("Artifact v1 ZIP entry CRC-32 mismatch.");let Gh;try{Gh=d.decode(Vh)}catch{Gh=void 0}p.push({path:od,pathBytes:Uh,content:Gh,contentBytes:Vh}),g=qh,h=$A}if(h!==r||g!==c)throw new Error("Artifact v1 ZIP directory boundaries are invalid.");return p}function ZV(e){let t=4294967295;for(let n of e){t^=n;for(let r=0;r<8;r+=1)t=(t&1)===1?t>>>1^3988292384:t>>>1}return(t^4294967295)>>>0}function JV(e,t){for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}var Fd="skills-layer-artifact",QV="skills-layer-review-package",e5="skills-layer-package-binding",Cl="skills-layer-length-delimited-manifest-v1",ut=Object.freeze({id:"skills-layer-stored-zip-parser-v1",version:1,archiveFormat:"zip-stored",manifestEncoding:Cl,pathNormalization:"NFC",pathOrdering:"utf8-bytewise",caseCollisionPolicy:"unicode-lowercase-en-US",maxFiles:wt.maxFiles,maxDepth:wt.maxDepth,maxPathBytes:wt.maxPathBytes,maxFileBytes:wt.maxFileBytes,maxTotalFileBytes:20*1024*1024,maxArchiveBytes:20*1024*1024+wt.maxFiles*(76+2*wt.maxPathBytes)+22}),t5=Object.freeze({...ut,maxTotalFileBytes:2*1024*1024,maxArchiveBytes:2*1024*1024+wt.maxFiles*(76+2*wt.maxPathBytes)+22}),Fy=/^sha256:[a-f0-9]{64}$/u,n5=/^(?:(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?|external-[a-f0-9]{8,64})$/u,r5=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,i5=/(?:^|\/)SKILL\.md$/u,o5=new TextEncoder().encode("SKILLS-LAYER-MANIFEST-V1\0"),s5=["archiveSha256","archiveDigest","manifestSha256","manifestDigest","packageBindingDigest","reviewPackageDigest","runtimePackageDigest"];function y0(e){g5(e),w0(e.generation,"Artifact generation identity is invalid");let n=[...Yr({files:e.reviewPackageFiles}).files].sort((h,g)=>zd(h.path,g.path)),r=new Map(n.map(h=>[h.path,h])),i=g0(e.runtimeAllowlist,r,"Runtime allowlist");if(i.length===0)throw new Error("Runtime allowlist must contain at least one exact path.");let o=g0(e.deliberateRuntimeReviewMaterial??[],r,"Deliberate runtime review material"),s=new Set(i),a=new Set(o);for(let h of o){if(!s.has(h))throw new Error("Deliberate runtime review material must also be in the runtime allowlist.");if(!h0(h,n))throw new Error("Deliberate runtime review material path is not review-only material.")}for(let h of i)if(h0(h,n)&&!a.has(h))throw new Error(`Runtime path ${h} is review-only material and requires deliberate runtime approval.`);let l=n.filter(h=>s.has(h.path));if(l.filter(h=>i5.test(h.path)).length!==1)throw new Error("Runtime deliverable must contain exactly one SKILL.md.");let c=p0(Fd,e.generation,l),u=p0(QV,e.generation,n),d=a5({generation:e.generation,reviewPackage:u,runtimePackage:c,runtimePaths:i,deliberateReviewPaths:o}),p=y5({format:Fd,formatVersion:1,generation:e.generation,archive:c.envelope.archive,manifest:c.envelope.manifest,parserPolicy:ut}),m=Object.freeze(n.filter(h=>!s.has(h.path)).map(h=>h.path));return{archiveBytes:c.archiveBytes,manifestBytes:c.manifestBytes,envelope:p,reviewPackage:Object.freeze({archiveBytes:Uint8Array.from(u.archiveBytes),manifestBytes:Uint8Array.from(u.manifestBytes),envelope:u.envelope}),packageBinding:d,reviewOnlyPaths:m}}function p0(e,t,n){let r=n.map(m5),i=k0(r),o=u0([...n]),s=My({format:e,formatVersion:1,generation:t,archive:{sha256:hn(o),sizeBytes:o.byteLength},manifest:{encoding:Cl,sha256:hn(i),fileCount:r.length,totalFileBytes:r.reduce((a,l)=>a+l.sizeBytes,0),files:r},parserPolicy:ut});return{archiveBytes:o,manifestBytes:i,envelope:s}}function a5(e){return l5({generation:e.generation,parserPolicy:e.runtimePackage.envelope.parserPolicy,reviewPackage:f0(e.reviewPackage),runtimePackage:f0(e.runtimePackage),runtimePaths:e.runtimePaths,deliberateReviewPaths:e.deliberateReviewPaths})}function l5(e){let t={format:e5,formatVersion:1,generation:b0(e.generation),parserPolicySha256:hn(Bd(JSON.stringify(e.parserPolicy))),reviewPackage:e.reviewPackage,runtimePackage:e.runtimePackage,runtimeAllowlist:m0(e.runtimePaths),deliberateRuntimeReviewMaterial:m0(e.deliberateReviewPaths)};return Object.freeze({...t,packageBindingDigest:hn(Bd(JSON.stringify(t)))})}function f0(e){return Object.freeze({archiveSha256:hn(e.archiveBytes),archiveSizeBytes:e.archiveBytes.byteLength,manifestSha256:hn(e.manifestBytes),envelopeSha256:hn(Bd(JSON.stringify(e.envelope)))})}function m0(e){let t=Object.freeze([...e]);return Object.freeze({sha256:hn(c5(t)),paths:t})}function c5(e){let t=[Md(e.length)];for(let n of e){let r=Bd(n);t.push(Md(r.byteLength),r)}return S0(t)}function Ud(e){return v0(e,Fd,"Artifact").envelope}function Il(e){return u5(e,Fd,"Artifact")}function u5(e,t,n){let r=v0(e,t,n),i=d0(r.archiveBytes,r.envelope.parserPolicy),o=i.map(c=>({path:c.path,...tn(c.contentBytes)})),s;try{let c=Yr({files:o,runDlp:!1,limits:{maxTotalBytes:r.envelope.parserPolicy.maxTotalFileBytes}});if(c.excluded.length>0)throw new Error("excluded path");s=[...c.files].sort((u,d)=>zd(u.path,d.path))}catch{throw new Error("Artifact archive entries do not satisfy the verified canonical manifest.")}let a=new Map(i.map(c=>[c.path,c])),l=s.map(c=>{let u=a.get(c.path);return{path:u.path,sizeBytes:u.contentBytes.byteLength,sha256:hn(u.contentBytes)}});if(!v5(l,r.envelope.manifest.files))throw new Error("Artifact archive entries do not match the verified manifest.");return s}function v0(e,t,n){if(!(e.archiveBytes instanceof Uint8Array))throw new Error(`${n} archive bytes are invalid.`);let r=d5(e.envelope,t,n);if(e.archiveBytes.byteLength>ut.maxArchiveBytes)throw new Error(`${n} archive exceeds the v1 parser policy.`);let i=Uint8Array.from(e.archiveBytes),o=hn(i);if(!_0(o,r.archive.sha256))throw new Error(`${n} archive SHA-256 mismatch.`);if(i.byteLength!==r.archive.sizeBytes)throw new Error(`${n} archive size mismatch.`);return{archiveBytes:i,envelope:r}}function d5(e,t,n){if(!ps(e)||e.format!==t||e.formatVersion!==1)throw new Error(`${n} envelope format is invalid.`);w0(e.generation,`${n} envelope generation identity is invalid`);let r=h5(e.parserPolicy);if(!r)throw new Error("Artifact envelope parser policy is invalid.");if(!ps(e.archive)||typeof e.archive.sha256!="string"||!Fy.test(e.archive.sha256)||!Nd(e.archive.sizeBytes)||e.archive.sizeBytes>r.maxArchiveBytes)throw new Error("Artifact envelope archive metadata is invalid.");if(!ps(e.manifest)||e.manifest.encoding!==Cl||typeof e.manifest.sha256!="string"||!Fy.test(e.manifest.sha256)||!Nd(e.manifest.fileCount)||e.manifest.fileCount===0||!Nd(e.manifest.totalFileBytes)||e.manifest.totalFileBytes>r.maxTotalFileBytes||!Array.isArray(e.manifest.files)||e.manifest.fileCount!==e.manifest.files.length)throw new Error("Artifact envelope manifest metadata is invalid.");let i=e.manifest.files.map(a=>p5(a));if(f5(i),i.reduce((a,l)=>a+l.sizeBytes,0)!==e.manifest.totalFileBytes)throw new Error("Artifact manifest totals do not match its entries.");let s=k0(i);if(!_0(hn(s),e.manifest.sha256))throw new Error("Artifact manifest SHA-256 mismatch.");return My({format:t,formatVersion:1,generation:e.generation,archive:{sha256:e.archive.sha256,sizeBytes:e.archive.sizeBytes},manifest:{encoding:Cl,sha256:e.manifest.sha256,fileCount:e.manifest.fileCount,totalFileBytes:e.manifest.totalFileBytes,files:i},parserPolicy:r})}function p5(e){if(!ps(e)||typeof e.path!="string"||!Nd(e.sizeBytes)||e.sizeBytes>ut.maxFileBytes||typeof e.sha256!="string"||!Fy.test(e.sha256))throw new Error("Artifact envelope manifest entry is invalid.");return{path:e.path,sizeBytes:e.sizeBytes,sha256:e.sha256}}function f5(e){let t;try{let n=Yr({files:e.map(r=>({path:r.path,content:""})),limits:{maxFiles:ut.maxFiles,maxDepth:ut.maxDepth,maxPathBytes:ut.maxPathBytes,maxFileBytes:ut.maxFileBytes,maxTotalBytes:ut.maxTotalFileBytes},runDlp:!1,contentPolicy:"paths_only"});if(n.excluded.length>0||n.files.length!==e.length)throw new Error("excluded path");t=n.files.map(r=>r.path).sort(zd)}catch{throw new Error("Artifact manifest paths are not canonical.")}if(e.some((n,r)=>n.path!==t[r]))throw new Error("Artifact manifest paths are not canonical.")}function m5(e){let t=ve(e);return{path:e.path,sizeBytes:t.byteLength,sha256:hn(t)}}function k0(e){let t=[o5,Md(e.length)];for(let n of e){let r=new TextEncoder().encode(n.path);t.push(Md(r.byteLength),r,k5(n.sizeBytes),By(n.sha256))}return S0(t)}function g0(e,t,n){if(!Array.isArray(e))throw new Error(`${n} must be an array of exact paths.`);let r=[],i=new Set;for(let o of e){if(typeof o!="string")throw new Error(`${n} must contain only exact string paths.`);let s=o.normalize("NFC"),a=s.toLocaleLowerCase("en-US");if(i.has(a))throw new Error(`${n} contains a duplicate or portable-path collision.`);if(i.add(a),!t.has(s))throw new Error(`${n} references a file outside the canonical review package.`);r.push(s)}return r.sort(zd)}function h0(e,t){return Dn(e,t).type==="evidence"}function g5(e){for(let t of s5)if(Object.prototype.hasOwnProperty.call(e,t))throw new Error("Caller-supplied artifact digests are forbidden; the server hashes the final ZIP bytes.")}function w0(e,t){if(!ps(e)||typeof e.skillSlug!="string"||!WA(e.skillSlug)||typeof e.semanticVersion!="string"||!n5.test(e.semanticVersion)||typeof e.generationId!="string"||!r5.test(e.generationId))throw new Error(`${t}.`)}function h5(e){if(!ps(e)||Object.keys(e).length!==Object.keys(ut).length)return null;for(let t of[ut,t5])if(Object.entries(t).every(([n,r])=>e[n]===r))return t;return null}function My(e){let t=Object.freeze(e.manifest.files.map(o=>Object.freeze({path:o.path,sizeBytes:o.sizeBytes,sha256:o.sha256}))),n=b0(e.generation),r=Object.freeze({sha256:e.archive.sha256,sizeBytes:e.archive.sizeBytes}),i=Object.freeze({encoding:Cl,sha256:e.manifest.sha256,fileCount:e.manifest.fileCount,totalFileBytes:e.manifest.totalFileBytes,files:t});return Object.freeze({format:e.format,formatVersion:1,generation:n,archive:r,manifest:i,parserPolicy:e.parserPolicy})}function y5(e){return My(e)}function b0(e){return Object.freeze({skillSlug:e.skillSlug,semanticVersion:e.semanticVersion,generationId:e.generationId})}function v5(e,t){return e.length===t.length&&e.every((n,r)=>n.path===t[r]?.path&&n.sizeBytes===t[r]?.sizeBytes&&n.sha256===t[r]?.sha256)}function zd(e,t){return Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}function Bd(e){return new TextEncoder().encode(e)}function hn(e){return`sha256:${YV("sha256").update(e).digest("hex")}`}function _0(e,t){return XV(By(e),By(t))}function By(e){return Buffer.from(e.slice(7),"hex")}function Md(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function k5(e){let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function S0(e){let t=new Uint8Array(e.reduce((r,i)=>r+i.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}function Nd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ps(e){return typeof e=="object"&&e!==null}var Uy=["productivity","coding","review","testing","devops","data","documents","media","research","planning","design","security","business","education","automation","communication","email","customer-support","sales","marketing","finance","legal","operations","project-management","writing","translation","knowledge-management","hr","ai","ecommerce"],w5="productivity",b5=new Set(Uy),_5={ci:"devops","ci-cd":"devops",compliance:"security",content:"documents",crm:"customer-support",docs:"documents",frontend:"coding","customer-service":"customer-support","customer-success":"customer-support","e-commerce":"ecommerce",genai:"ai",legal:"legal",llm:"ai",ops:"operations",pm:"project-management",reporting:"business",reports:"business","team-ops":"operations",ui:"design",ux:"design","web-development":"coding"},S5={productivity:["productivity","todo","task","tasks","calendar","meeting","notes","workflow","focus"],coding:["code","coding","developer","frontend","backend","repository","typescript","javascript","react","vite","html","css","component","bundle","artifact"],review:["review","reviews","critique","audit","feedback","pr","pull","quality"],testing:["test","tests","testing","qa","coverage","regression","playwright","vitest"],devops:["deploy","approval","ci","cd","pipeline","infra","infrastructure","docker","cloudflare","wrangler"],data:["data","dataset","sql","database","analytics","metrics","spreadsheet","csv","json"],documents:["document","documents","doc","docs","pdf","report","reports","contract","proposal","writing"],media:["media","image","video","audio","transcript","youtube","asset","thumbnail"],research:["research","search","sources","citation","citations","summarize","summaries","literature"],planning:["plan","planning","project","roadmap","milestone","sprint","delivery","schedule"],design:["design","ui","ux","layout","wireframe","prototype","figma","tailwind","shadcn"],security:["security","threat","secret","secrets","vulnerability","vulnerabilities","risk","policy"],business:["business","strategy","customer","market","stakeholder","commercial","pricing"],education:["education","teach","teaching","learn","learning","lesson","course","tutorial"],automation:["automation","automate","workflow","script","scripts","bot","trigger","orchestration"],communication:["communication","slack","message","messages","chat","reply","announcement","conversation"],email:["email","emails","gmail","googleemail","googlemail","outlook","inbox","mail","newsletter"],"customer-support":["support","ticket","tickets","helpdesk","customer","service","csat","escalation"],sales:["sales","lead","leads","prospect","pipeline","deal","deals","crm","account"],marketing:["marketing","campaign","brand","seo","content","social","audience","copy"],finance:["finance","financial","invoice","invoices","budget","forecast","accounting","revenue","tax"],legal:["legal","contract","contracts","clause","clauses","compliance","policy","terms","privacy"],operations:["operations","ops","runbook","process","sop","incident","queue","handoff"],"project-management":["project","projects","backlog","dependency","dependencies","kanban","scrum","pm"],writing:["writing","write","draft","edit","editing","blog","article","copywriting"],translation:["translation","translate","localization","locale","language","languages","i18n"],"knowledge-management":["knowledge","wiki","kb","retrieval","archive","taxonomy","knowledgebase"],hr:["hr","hiring","recruiting","interview","onboarding","employee","people","performance"],ai:["ai","llm","prompt","prompts","model","models","agent","agents","rag","embedding"],ecommerce:["ecommerce","commerce","shop","store","checkout","cart","order","orders","product"]};function zy(e){if(typeof e!="string")return null;let t=I0(e);return b5.has(t)?t:_5[t]??null}function x0(e){let t=e.trim().toLowerCase().replace(/[_\s]+/gu,"-"),n={ai:"AI",hr:"HR",ecommerce:"E-commerce","e-commerce":"E-commerce"};return n[t]?n[t]:e.split(/[-_\s]+/u).filter(Boolean).map(r=>`${r.slice(0,1).toUpperCase()}${r.slice(1)}`).join(" ")}function C0(e){let t=[{value:e.slug??"",weight:3,signal:"slug"},{value:e.name??"",weight:3,signal:"name"},{value:e.description??"",weight:2,signal:"description"},{value:e.skillType??"",weight:1,signal:"skill_type"},{value:e.compatibility??"",weight:1,signal:"compatibility"},{value:(e.tags??[]).join(" "),weight:4,signal:"tags"},{value:e.body??"",weight:1,signal:"body"}].filter(o=>o.value.trim().length>0),n=new Map;for(let o of t){let s=C5(o.value);for(let[a,l]of Object.entries(S5)){if(!l.some(d=>s.has(d)))continue;let u=n.get(a)??{score:0,signals:new Set};u.score+=o.weight,u.signals.add(o.signal),n.set(a,u)}}let i=[...n.entries()].sort((o,s)=>s[1].score-o[1].score||Uy.indexOf(o[0])-Uy.indexOf(s[0]))[0];return!i||i[1].score<2?{category:x5(e),confidence:"fallback",matchedSignals:[]}:{category:i[0],confidence:i[1].score>=5?"high":i[1].score>=3?"medium":"low",matchedSignals:[...i[1].signals].sort()}}function x5(e){let t=I0(e.skillType??"");return t.includes("automation")?"automation":t.includes("mcp")?"ai":w5}function I0(e){return e.trim().toLowerCase().replace(/[_\s]+/gu,"-")}function C5(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/u).map(t=>t.trim()).filter(t=>t.length>=2).flatMap(I5))}function I5(e){let t=[e];return e.endsWith("ing")&&e.length>5&&t.push(e.slice(0,-3)),e.endsWith("s")&&e.length>4&&t.push(e.slice(0,-1)),t}var Ik=mn(Qi(),1);import{createHash as e9}from"node:crypto";var Sk=["LICENSE","LICENCE","LICENSE.md","LICENCE.md","LICENSE.txt","COPYING","COPYING.txt"];var jpe=256*1024;var t9=`MIT License
706
+ `,o),p=t.slice(u,d<0?t.length:d),m=t.slice(u,o),h=/(?:^|[^\p{L}\p{N}_-])X-RateLimit-Reset\s*:\s*$/iu.test(m),g=$V(t,o),y=hV(e,p,r,o-u),v=/^\d+(?:-\d+)*$/u.test(r)&&(s==="-"&&/[\p{L}\p{N}_]/u.test(a)||l==="-"&&/[\p{L}\p{N}_]/u.test(c));if((r.startsWith("+")||/[()]/u.test(r)||/^\d{2,4}(?:[-. ]\d{2,4}){2,4}$/u.test(r)||/^(?:1\d{10}|44\d{10})$/u.test(r)||/\b(?:\w*phone|call|contact|fax|mobile|sms|tel|telephone|whatsapp)\b/iu.test(p))&&!v&&!h&&!g&&!y)return!0}return!1}function gV(e,t,n){if(!/^[\d.\s]+$/u.test(n))return!1;let r=Math.max(0,t-32),i=e.slice(r,t+n.length+32),o=/(?:^|[^\d.])(?<network>(?<address>\d{1,3}(?:\.\d{1,3}){3})(?:\/(?<prefix>\d{1,2}))?)(?=$|[^\d.])/gu,s=[];for(let a of i.matchAll(o)){if(!s0(a.groups.address)||a.groups.prefix!==void 0&&Number(a.groups.prefix)>32)continue;let l=r+a.index+a[0].indexOf(a.groups.network);s.push({start:l,end:l+a.groups.network.length})}for(let a=0;a<n.length;a++)if(/\d/u.test(n[a])&&!s.some(l=>t+a>=l.start&&t+a<l.end))return!1;return!0}function hV(e,t,n,r){let i=r+n.length;return yV(n)||_V(t,n,r)||SV(t,r,i)||xV(t,r,i)||CV(t,n,r,i)||IV(t,r,i)||PV(e,t,n,r)||ze(t,r,i,/(?<![\d.])\d+\.\d+(?![\d.])/gu)||ze(t,r,i,/\b\d{4}-\d{2}-\d{2}(?:[ T]\d{2}(?::\d{2}){0,2}(?:[,.]\d+)?(?:Z|\s+[+-]\d{2}(?::?\d{2})?)?)?\b/gu)?!0:n.startsWith("+")||/[()]/u.test(n)||/\b(?:call|contact|fax|mobile|phone|sms|tel|telephone|whatsapp)\b/iu.test(t)?!1:vV(t,r,i)||kV(t,r,i)||wV(t,r,i)||bV(t,n,r,i)||AV(t,r,i)||s0(n)||RV(t,r,i)||ze(t,r,i,/\bhresult\s+-eq\s+-?\d+\b/giu)||ze(t,r,i,/\bst_mtime_ns\s*\/\/\s*[0-9_]+/giu)||/^\s*index\s+[0-9a-f]{7,40}\.\.[0-9a-f]{7,40}\s+\d{6}\s*$/iu.test(t)||ze(t,r,i,/\bprs?\s+(?:\d+\s+){2,}\d+\b/giu)||ze(t,r,i,/\bv?\d+(?:\.\d+)*\s+\d{4}\.\d{2}\.\d{2}\s+\d{2}:\d{2}\b/giu)||ze(t,r,i,/\brun\s+`\d{9,15}`(?=[^\r\n]{0,100}\btook\b[^\r\n]{0,30}\bminutes?\b)/giu)||ze(t,r,i,/\d+\s+的\s+\d+\s+号评论/gu)||/\b(?:returnCode|unique\s+(?:code|identifier)|唯一编码)\b/iu.test(t)&&ze(t,r,i,/\b[A-Za-z][A-Za-z0-9_]*(?:_[A-Za-z0-9]+)+\/\d{9,15}\b/gu)||ze(t,r,i,/\b[A-Z][A-Z0-9_]*_BYTES\s*=\s*\d+\b/gu)||/^\s*(?:[-+]?\d+\.\d+\s+){3,}[-+]?\d+\.\d+\s*$/u.test(t)||/^\s*\[\s*[-+]?\d+(?:\.\d+)?\s*,\s*[-+]?\d+(?:\.\d+)?\s*,\s*[-+]?\d+(?:\.\d+)?\s*,\s*[-+]?\d+(?:\.\d+)?\s*\]\s*,?\s*$/u.test(t)&&/[-+]?\d+\.\d+/u.test(t)?!0:EV(e,t,r,i)}function yV(e){if(!/^\d{9,15}$/u.test(e))return!1;let t=[...e].map(Number),n=t.slice(1).every((i,o)=>i===(t[o]+1)%10),r=t.slice(1).every((i,o)=>i===(t[o]+9)%10);return n||r}function vV(e,t,n){let r=/["']?(?:created_time|enterpriseValue|exclusiveMaximum|exclusiveMinimum|expiration|expirationDate|expirationDates|expirations|fetchedAt|maximum|minimum|publishedAt|trade_date|updated_time|volume|z-index)["']?\s*[:=]\s*/giu;for(let i of e.matchAll(r)){let o=i.index+i[0].length;if(e[o]==="["){let l=e.indexOf("]",o+1);if(l<0)continue;let c=e.slice(o,l+1);if(/^\[\s*\d+(?:\s*,\s*\d+)*\s*\]$/u.test(c)&&t>=o+1&&n<=l)return!0;continue}let s=[",",")","}","]",";","|"].map(l=>e.indexOf(l,o)).filter(l=>l>=0),a=s.length>0?Math.min(...s):e.length;if(t>=o&&n<=a&&/^\s*\d+(?:\.\d+)?\s*$/u.test(e.slice(o,a)))return!0}return!1}function kV(e,t,n){for(let r of e.matchAll(/\{[^{}\r\n]*\}/gu))if(!(t<r.index||n>r.index+r[0].length))try{let i=JSON.parse(r[0]);if(typeof i.timestamp!="number"||!o0(i.timestamp))continue;let o=t-r.index;if(ze(r[0],o,n-r.index,/"timestamp"\s*:\s*(?:\d{10}|\d{13})(?=\s*[,}])/gu))return!0}catch{}return!1}function wV(e,t,n){let r=/(?:^|[\\/])\.superpowers[\\/]brainstorm[\\/][1-9]\d{0,6}-(?<epoch>\d{10})[\\/](?:content|state)(?=$|[\\/\s"'`,}])/gu;for(let i of e.matchAll(r))if(t>=i.index&&n<=i.index+i[0].length&&o0(Number(i.groups.epoch)))return!0;return!1}function o0(e){let t=e>=1e12?e/1e3:e;return t>=946684800&&t<=4102444800}function bV(e,t,n,r){let i=t.replace(/\s/gu,"");return/^\d+(?:\.\d+){1,}(?:[-~]\d+(?:\.\d+){1,})?$/u.test(i)?Number(i.split(/[.~-]/u,1)[0])<=99&&/\b(?:codex(?:\s+store)?|css(?:\s+modules?)?|owl\s+runtime|renderer|selector|windowsapps)\b/iu.test(e)||ze(e,n,r,/(?:\b(?:chromium|codex|mac|macos|release|runtime|versions?|win|windows)\b|版本(?:号)?)\s*[:=`'"(\[]*\s*\d+(?:\.\d+){1,}(?:[-~]\d+(?:\.\d+){1,})?/giu)?!0:ze(e,n,r,/["']?version["']?\s*[:=]\s*["']?\d+(?:\.\d+){1,}(?:[-~]\d+(?:\.\d+){1,})?["']?/giu):!1}function _V(e,t,n){let r=t.replace(/\D/gu,""),i=/^(?:1)?\d{3}55501\d{2}$/u.test(r),o=/^(?:1)?555\d{7}$/u.test(r);if((i||o)&&(/\.phoneNumbers\s*\([^)]*\).*return\s+terms\s+like/iu.test(e)||/^\s*\|\s*`?#PhoneNumber`?\s*\|.*\|\s*$/iu.test(e))||/^\s*[*-].*\b(?:no\s+fake|fake-perfect|avoid\s+predictable)\b.*\b(?:numbers?|phone)\b.*\b(?:organic|messy)\b/iu.test(e))return!0;let s=Math.max(e.lastIndexOf(";",n-1),e.lastIndexOf(".",n-1),e.lastIndexOf("!",n-1),e.lastIndexOf("?",n-1))+1,a=e.slice(s,n);return/\b(?:fake|placeholder|predictable|example|format|organic|messy)\b/iu.test(a)&&/\b(?:phone|numbers?)\b/iu.test(e)&&!/\b(?:actual|customer|owner|contact|call|mobile|telephone|whatsapp)\b/iu.test(a)}function SV(e,t,n){return ze(e,t,n,/https?:\/\/[^\s<>"']+/giu)}function xV(e,t,n){return ze(e,t,n,/\barXiv\s*:\s*\d{4}\.\d{4,5}(?:\s*\(\d{4}-\d{2}\))?/giu)||ze(e,t,n,/\b10\.\d{4,9}\/[A-Z0-9][A-Z0-9._()/:+-]*/giu)||ze(e,t,n,/\b(?:Academic\s+Year|学年度)[^.;\r\n]{0,24}\d{2,4}\s*\(\d{4}-\d{2,4}\)/giu)||/\b(?:activity|date|month|recent|timeline)\b|动态|最近|月份?/iu.test(e)&&ze(e,t,n,/\b\d{4}[.-]\d{1,2}\s*[-–—~]\s*\d{4}[.-]\d{1,2}\b/gu)}function CV(e,t,n,r){let i=Math.max(e.lastIndexOf(";",n-1),e.lastIndexOf("\uFF1B",n-1))+1,o=[e.indexOf(";",r),e.indexOf("\uFF1B",r)].filter(c=>c>=0),s=o.length>0?Math.min(...o):e.length,a=e.slice(i,s),l=t.replace(/[\s()]/gu,"");return/(?:[A-Z0-9_]*application_number\b|\bapplication[ -]number\b|\bnormalize_application_number\b|\bapplication_number_for_[A-Z0-9_]+\b|\bpatent(?:[_ -]?number)?\b|申请号|专利号|用户常输入)/iu.test(a)&&/^\d{9,15}(?:\.\d)?$/u.test(l)?!0:ze(e,n,r,/\b(?:application[_ -]?number|patent(?:[_ -]?number)?)\b[^;\r\n]{0,80}?(?:CN)?\d{9,15}(?:\.\d)?(?:[A-Z]\d?)?/giu)||ze(e,n,r,/申请号[^;;\r\n]{0,160}/gu)}function IV(e,t,n){return ze(e,t,n,/@id\s*=\s*\d{9,15}/giu)}function PV(e,t,n,r){if(!/\.min\.js$/iu.test(e)||!/^\d{9,16}$/u.test(n))return!1;let i=t.slice(Math.max(0,r-40),r);return/\b(?:call|contact|fax|mobile|owner|phone|sms|tel|telephone|whatsapp)\s*[:=]\s*["']?\s*$/iu.test(i)?!1:/(?:!function|=>|\bfunction\b|\bvar\b|\blet\b|\bconst\b)/u.test(t)}function AV(e,t,n){let r=/<(?:origin|joint|link)\b[^>]*\b(?:rpy|xyz)\s*=\s*(["'])(?<value>[-+\d.eE,\s]+)\1/giu;for(let i of e.matchAll(r)){let o=i.groups.value,s=i.index+i[0].indexOf(o);if(t>=s&&n<=s+o.length)return!0}return!1}function s0(e){let n=e.replace(/\s/gu,"").split(".");return n.length===4&&n.every(r=>/^\d{1,3}$/u.test(r)&&Number(r)<=255)}function RV(e,t,n){let r=e.lastIndexOf("`",t);if(r<0)return!1;let i=e.indexOf("`",r+1);if(i<0)return!1;let o=e.slice(r+1,i);return/^\s*\d+(?:\s+\d+){15,}\s*$/u.test(o)}function ze(e,t,n,r){for(let i of e.matchAll(r)){let o=i.index;if(t>=o&&n<=o+i[0].length)return!0}return!1}function EV(e,t,n,r){let i=[.../\.svg$/iu.test(e)?[/\b(?:height|viewBox|width|x|y)\s*=\s*(["'])(?<value>[-+\d.eE,\s]+)\1/giu]:[],.../data:image\/svg\+xml/iu.test(t)?[/<feColorMatrix\b[^>]*\bvalues\s*=\s*(["'])(?<value>[-+\d.eE,\s]+)\1/giu]:[]];for(let o of i)for(let s of t.matchAll(o)){let a=s.groups.value,l=s.index+s[0].indexOf(a);if(n>=l&&r<=l+a.length)return!0}return!1}function $V(e,t){let n=e.lastIndexOf("<path",t);if(n<0||e.indexOf(">",n)<t)return!1;let i=e.slice(n,t),o=/\bd\s*=\s*(["'])(?<value>[\s\S]*)$/iu.exec(i);return!!(o&&!o.groups.value.includes(o[1]))}function DV(e){return`sha256:${QE("sha256").update(e).digest("hex")}`}function TV(e){let t=QE("sha256");return e.forEach((n,r)=>{t.update(n.path),t.update("\0"),t.update(ve(n)),r<e.length-1&&t.update("\0")}),`sha256:${t.digest("hex")}`}import{createHash as OV}from"node:crypto";var LV=new Set(["evals","tests","test","fixtures","examples","golden","goldens","snapshots","__snapshots__",".github",".circleci","coverage"]),jV=new Set([".gitlab-ci.yml","azure-pipelines.yml"]),NV=[".eval.json",".eval.yaml"],FV=[".golden.",".snapshot."],a0=".skills-layer/skill.yaml",BV=new Set([".git",".hg",".svn"]),MV=new Set([".cache",".creator-tmp",".skills-layer-tmp",".tmp","node_modules"]),UV=Buffer.from([46,68,83,95,83,116,111,114,101]).toString("ascii"),zV=new Set([UV,"Thumbs.db"]);function Dn(e,t){let n=jy(e),r=c0(t),i=Oy(n,r),[o]=i.split("/");return i===a0?{path:n,relativePath:i,root:r,type:"control",reasonCode:"root_control_manifest"}:n.endsWith(`/${a0}`)?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"misplaced_control_manifest"}:i.startsWith(".skills-layer/")?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"unsupported_control_material"}:o&&BV.has(o)?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"excluded_repository_metadata"}:o&&(MV.has(o)||zV.has(o)||o.endsWith("~")||o.endsWith(".swp")||o.endsWith(".tmp"))?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"excluded_cache_or_temporary"}:o&&LV.has(o)?{path:n,relativePath:i,root:r,type:"evidence",reasonCode:"top_level_evidence_folder"}:GV(i)?{path:n,relativePath:i,root:r,type:"evidence",reasonCode:"evidence_test_or_spec_file"}:HV(i)?{path:n,relativePath:i,root:r,type:"evidence",reasonCode:"top_level_evidence_file"}:{path:n,relativePath:i,root:r,type:"runtime",reasonCode:"runtime_material"}}function l0(e){return e.map(t=>Dn(t.path,e))}function Ly(e){return qV(e,"runtime")}function qV(e,t){let n=c0(e);return e.map(r=>({...r,path:jy(r.path)})).filter(r=>Dn(r.path,e).type===t).sort((r,i)=>KV(r.path,i.path,n))}function ct(e){return VV(Ly(e))}function VV(e){let t=OV("sha256");for(let n of e)t.update(n.path),t.update("\0"),t.update(ve(n)),t.update("\0");return`sha256:${t.digest("hex")}`}function GV(e){let t=e.split("/"),n=t[t.length-1].toLocaleLowerCase("en-US");return/(?:^|\.)(?:test|spec)\.[^.]+$/u.test(n)}function HV(e){return e.includes("/")?!1:jV.has(e)||NV.some(t=>e.endsWith(t))||FV.some(t=>e.includes(t))}function c0(e){let t=e.map(n=>jy(n.path)).find(n=>n==="SKILL.md"||n.endsWith("/SKILL.md"));return!t||t==="SKILL.md"?"":t.slice(0,-9)}function Oy(e,t){return t?e===t?"":e.startsWith(`${t}/`)?e.slice(t.length+1):e:e}function KV(e,t,n){let r=Oy(e,n),i=Oy(t,n);return r==="SKILL.md"?i==="SKILL.md"?0:-1:i==="SKILL.md"?1:e.localeCompare(t)}function jy(e){return e.replaceAll("\\","/").split("/").filter(t=>t.length>0&&t!==".").join("/")}function u0(e){let t=new TextEncoder,n=[],r=[],i=0;for(let c of e){let u=t.encode(c.path),d=ve(c),p=WV(d),m=new Uint8Array(30+u.length+d.length),h=new DataView(m.buffer);h.setUint32(0,67324752,!0),h.setUint16(4,20,!0),h.setUint16(6,2048,!0),h.setUint16(8,0,!0),h.setUint16(10,0,!0),h.setUint16(12,0,!0),h.setUint32(14,p,!0),h.setUint32(18,d.byteLength,!0),h.setUint32(22,d.byteLength,!0),h.setUint16(26,u.length,!0),h.setUint16(28,0,!0),m.set(u,30),m.set(d,30+u.length),n.push(m);let g=new Uint8Array(46+u.length),y=new DataView(g.buffer);y.setUint32(0,33639248,!0),y.setUint16(4,20,!0),y.setUint16(6,20,!0),y.setUint16(8,2048,!0),y.setUint16(10,0,!0),y.setUint16(12,0,!0),y.setUint16(14,0,!0),y.setUint32(16,p,!0),y.setUint32(20,d.byteLength,!0),y.setUint32(24,d.byteLength,!0),y.setUint16(28,u.length,!0),y.setUint16(30,0,!0),y.setUint16(32,0,!0),y.setUint16(34,0,!0),y.setUint16(36,0,!0),y.setUint32(38,0,!0),y.setUint32(42,i,!0),g.set(u,46),r.push(g),i+=m.byteLength}let o=Ny(r),s=Ny(n),a=new Uint8Array(22),l=new DataView(a.buffer);return l.setUint32(0,101010256,!0),l.setUint16(4,0,!0),l.setUint16(6,0,!0),l.setUint16(8,e.length,!0),l.setUint16(10,e.length,!0),l.setUint32(12,o.byteLength,!0),l.setUint32(16,s.byteLength,!0),l.setUint16(20,0,!0),Ny([s,o,a])}function WV(e){let t=4294967295;for(let n of e){t^=n;for(let r=0;r<8;r+=1)t=(t&1)===1?t>>>1^3988292384:t>>>1}return(t^4294967295)>>>0}function Ny(e){let t=e.reduce((i,o)=>i+o.byteLength,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.byteLength;return n}function d0(e,t){if(!(e instanceof Uint8Array)||e.byteLength>t.maxArchiveBytes)throw new Error("Artifact v1 ZIP exceeds its archive limit.");if(e.byteLength<22)throw new Error("Artifact v1 ZIP is incomplete.");let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=e.byteLength-22;if(n.getUint32(r,!0)!==101010256)throw new Error("Artifact v1 ZIP end record is missing or trailing bytes are present.");let i=n.getUint16(r+4,!0),o=n.getUint16(r+6,!0),s=n.getUint16(r+8,!0),a=n.getUint16(r+10,!0),l=n.getUint32(r+12,!0),c=n.getUint32(r+16,!0),u=n.getUint16(r+20,!0);if(i!==0||o!==0||s!==a||a===65535||l===4294967295||c===4294967295||u!==0||a===0||a>t.maxFiles||c+l!==r)throw new Error("Artifact v1 ZIP end record is invalid.");let d=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),p=[],m=new Set,h=c,g=0,y=0;for(let v=0;v<a;v+=1){if(h+46>r||n.getUint32(h,!0)!==33639248)throw new Error("Artifact v1 ZIP central directory is truncated.");let b=n.getUint16(h+4,!0),w=n.getUint16(h+6,!0),_=n.getUint16(h+8,!0),C=n.getUint16(h+10,!0),A=n.getUint16(h+12,!0),N=n.getUint16(h+14,!0),O=n.getUint32(h+16,!0),X=n.getUint32(h+20,!0),G=n.getUint32(h+24,!0),ee=n.getUint16(h+28,!0),te=n.getUint16(h+30,!0),Q=n.getUint16(h+32,!0),Ie=n.getUint16(h+34,!0),fn=n.getUint16(h+36,!0),el=n.getUint32(h+38,!0),ht=n.getUint32(h+42,!0),$A=h+46+ee+te+Q;if(b!==20||w!==20||_!==2048||C!==0||A!==0||N!==0||X!==G||X===4294967295||ee===0||ee>t.maxPathBytes||te!==0||Q!==0||Ie!==0||fn!==0||el!==0||ht!==g||$A>r||G>t.maxFileBytes)throw new Error("Artifact v1 ZIP central entry is invalid.");if(y+=G,y>t.maxTotalFileBytes)throw new Error("Artifact v1 ZIP exceeds its total file-byte limit.");let Uh=e.slice(h+46,h+46+ee),od;try{od=d.decode(Uh)}catch{throw new Error("Artifact v1 ZIP path is not valid UTF-8.")}if(m.has(od))throw new Error("Artifact v1 ZIP path uniqueness is invalid.");if(m.add(od),ht+30>c||n.getUint32(ht,!0)!==67324752)throw new Error("Artifact v1 ZIP local entry is missing.");let Lz=n.getUint16(ht+4,!0),jz=n.getUint16(ht+6,!0),Nz=n.getUint16(ht+8,!0),Fz=n.getUint16(ht+10,!0),Bz=n.getUint16(ht+12,!0),Mz=n.getUint32(ht+14,!0),DA=n.getUint32(ht+18,!0),Uz=n.getUint32(ht+22,!0),zh=n.getUint16(ht+26,!0),TA=n.getUint16(ht+28,!0),OA=ht+30+zh+TA,qh=OA+DA;if(Lz!==w||jz!==_||Nz!==C||Fz!==A||Bz!==N||Mz!==O||DA!==X||Uz!==G||zh!==ee||TA!==0||qh>c||!JV(e.subarray(ht+30,ht+30+zh),Uh))throw new Error("Artifact v1 ZIP local and central entries do not match.");let Vh=e.slice(OA,qh);if(ZV(Vh)!==O)throw new Error("Artifact v1 ZIP entry CRC-32 mismatch.");let Gh;try{Gh=d.decode(Vh)}catch{Gh=void 0}p.push({path:od,pathBytes:Uh,content:Gh,contentBytes:Vh}),g=qh,h=$A}if(h!==r||g!==c)throw new Error("Artifact v1 ZIP directory boundaries are invalid.");return p}function ZV(e){let t=4294967295;for(let n of e){t^=n;for(let r=0;r<8;r+=1)t=(t&1)===1?t>>>1^3988292384:t>>>1}return(t^4294967295)>>>0}function JV(e,t){for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}var Fd="skills-layer-artifact",QV="skills-layer-review-package",e5="skills-layer-package-binding",Cl="skills-layer-length-delimited-manifest-v1",ut=Object.freeze({id:"skills-layer-stored-zip-parser-v1",version:1,archiveFormat:"zip-stored",manifestEncoding:Cl,pathNormalization:"NFC",pathOrdering:"utf8-bytewise",caseCollisionPolicy:"unicode-lowercase-en-US",maxFiles:wt.maxFiles,maxDepth:wt.maxDepth,maxPathBytes:wt.maxPathBytes,maxFileBytes:wt.maxFileBytes,maxTotalFileBytes:20*1024*1024,maxArchiveBytes:20*1024*1024+wt.maxFiles*(76+2*wt.maxPathBytes)+22}),t5=Object.freeze({...ut,maxTotalFileBytes:2*1024*1024,maxArchiveBytes:2*1024*1024+wt.maxFiles*(76+2*wt.maxPathBytes)+22}),Fy=/^sha256:[a-f0-9]{64}$/u,n5=/^(?:(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?|external-[a-f0-9]{8,64})$/u,r5=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,i5=/(?:^|\/)SKILL\.md$/u,o5=new TextEncoder().encode("SKILLS-LAYER-MANIFEST-V1\0"),s5=["archiveSha256","archiveDigest","manifestSha256","manifestDigest","packageBindingDigest","reviewPackageDigest","runtimePackageDigest"];function y0(e){g5(e),w0(e.generation,"Artifact generation identity is invalid");let n=[...Yr({files:e.reviewPackageFiles}).files].sort((h,g)=>zd(h.path,g.path)),r=new Map(n.map(h=>[h.path,h])),i=g0(e.runtimeAllowlist,r,"Runtime allowlist");if(i.length===0)throw new Error("Runtime allowlist must contain at least one exact path.");let o=g0(e.deliberateRuntimeReviewMaterial??[],r,"Deliberate runtime review material"),s=new Set(i),a=new Set(o);for(let h of o){if(!s.has(h))throw new Error("Deliberate runtime review material must also be in the runtime allowlist.");if(!h0(h,n))throw new Error("Deliberate runtime review material path is not review-only material.")}for(let h of i)if(h0(h,n)&&!a.has(h))throw new Error(`Runtime path ${h} is review-only material and requires deliberate runtime approval.`);let l=n.filter(h=>s.has(h.path));if(l.filter(h=>i5.test(h.path)).length!==1)throw new Error("Runtime deliverable must contain exactly one SKILL.md.");let c=p0(Fd,e.generation,l),u=p0(QV,e.generation,n),d=a5({generation:e.generation,reviewPackage:u,runtimePackage:c,runtimePaths:i,deliberateReviewPaths:o}),p=y5({format:Fd,formatVersion:1,generation:e.generation,archive:c.envelope.archive,manifest:c.envelope.manifest,parserPolicy:ut}),m=Object.freeze(n.filter(h=>!s.has(h.path)).map(h=>h.path));return{archiveBytes:c.archiveBytes,manifestBytes:c.manifestBytes,envelope:p,reviewPackage:Object.freeze({archiveBytes:Uint8Array.from(u.archiveBytes),manifestBytes:Uint8Array.from(u.manifestBytes),envelope:u.envelope}),packageBinding:d,reviewOnlyPaths:m}}function p0(e,t,n){let r=n.map(m5),i=k0(r),o=u0([...n]),s=My({format:e,formatVersion:1,generation:t,archive:{sha256:hn(o),sizeBytes:o.byteLength},manifest:{encoding:Cl,sha256:hn(i),fileCount:r.length,totalFileBytes:r.reduce((a,l)=>a+l.sizeBytes,0),files:r},parserPolicy:ut});return{archiveBytes:o,manifestBytes:i,envelope:s}}function a5(e){return l5({generation:e.generation,parserPolicy:e.runtimePackage.envelope.parserPolicy,reviewPackage:f0(e.reviewPackage),runtimePackage:f0(e.runtimePackage),runtimePaths:e.runtimePaths,deliberateReviewPaths:e.deliberateReviewPaths})}function l5(e){let t={format:e5,formatVersion:1,generation:b0(e.generation),parserPolicySha256:hn(Bd(JSON.stringify(e.parserPolicy))),reviewPackage:e.reviewPackage,runtimePackage:e.runtimePackage,runtimeAllowlist:m0(e.runtimePaths),deliberateRuntimeReviewMaterial:m0(e.deliberateReviewPaths)};return Object.freeze({...t,packageBindingDigest:hn(Bd(JSON.stringify(t)))})}function f0(e){return Object.freeze({archiveSha256:hn(e.archiveBytes),archiveSizeBytes:e.archiveBytes.byteLength,manifestSha256:hn(e.manifestBytes),envelopeSha256:hn(Bd(JSON.stringify(e.envelope)))})}function m0(e){let t=Object.freeze([...e]);return Object.freeze({sha256:hn(c5(t)),paths:t})}function c5(e){let t=[Md(e.length)];for(let n of e){let r=Bd(n);t.push(Md(r.byteLength),r)}return S0(t)}function Ud(e){return v0(e,Fd,"Artifact").envelope}function Il(e){return u5(e,Fd,"Artifact")}function u5(e,t,n){let r=v0(e,t,n),i=d0(r.archiveBytes,r.envelope.parserPolicy),o=i.map(c=>({path:c.path,...tn(c.contentBytes)})),s;try{let c=Yr({files:o,runDlp:!1,limits:{maxTotalBytes:r.envelope.parserPolicy.maxTotalFileBytes}});if(c.excluded.length>0)throw new Error("excluded path");s=[...c.files].sort((u,d)=>zd(u.path,d.path))}catch{throw new Error("Artifact archive entries do not satisfy the verified canonical manifest.")}let a=new Map(i.map(c=>[c.path,c])),l=s.map(c=>{let u=a.get(c.path);return{path:u.path,sizeBytes:u.contentBytes.byteLength,sha256:hn(u.contentBytes)}});if(!v5(l,r.envelope.manifest.files))throw new Error("Artifact archive entries do not match the verified manifest.");return s}function v0(e,t,n){if(!(e.archiveBytes instanceof Uint8Array))throw new Error(`${n} archive bytes are invalid.`);let r=d5(e.envelope,t,n);if(e.archiveBytes.byteLength>ut.maxArchiveBytes)throw new Error(`${n} archive exceeds the v1 parser policy.`);let i=Uint8Array.from(e.archiveBytes),o=hn(i);if(!_0(o,r.archive.sha256))throw new Error(`${n} archive SHA-256 mismatch.`);if(i.byteLength!==r.archive.sizeBytes)throw new Error(`${n} archive size mismatch.`);return{archiveBytes:i,envelope:r}}function d5(e,t,n){if(!ps(e)||e.format!==t||e.formatVersion!==1)throw new Error(`${n} envelope format is invalid.`);w0(e.generation,`${n} envelope generation identity is invalid`);let r=h5(e.parserPolicy);if(!r)throw new Error("Artifact envelope parser policy is invalid.");if(!ps(e.archive)||typeof e.archive.sha256!="string"||!Fy.test(e.archive.sha256)||!Nd(e.archive.sizeBytes)||e.archive.sizeBytes>r.maxArchiveBytes)throw new Error("Artifact envelope archive metadata is invalid.");if(!ps(e.manifest)||e.manifest.encoding!==Cl||typeof e.manifest.sha256!="string"||!Fy.test(e.manifest.sha256)||!Nd(e.manifest.fileCount)||e.manifest.fileCount===0||!Nd(e.manifest.totalFileBytes)||e.manifest.totalFileBytes>r.maxTotalFileBytes||!Array.isArray(e.manifest.files)||e.manifest.fileCount!==e.manifest.files.length)throw new Error("Artifact envelope manifest metadata is invalid.");let i=e.manifest.files.map(a=>p5(a));if(f5(i),i.reduce((a,l)=>a+l.sizeBytes,0)!==e.manifest.totalFileBytes)throw new Error("Artifact manifest totals do not match its entries.");let s=k0(i);if(!_0(hn(s),e.manifest.sha256))throw new Error("Artifact manifest SHA-256 mismatch.");return My({format:t,formatVersion:1,generation:e.generation,archive:{sha256:e.archive.sha256,sizeBytes:e.archive.sizeBytes},manifest:{encoding:Cl,sha256:e.manifest.sha256,fileCount:e.manifest.fileCount,totalFileBytes:e.manifest.totalFileBytes,files:i},parserPolicy:r})}function p5(e){if(!ps(e)||typeof e.path!="string"||!Nd(e.sizeBytes)||e.sizeBytes>ut.maxFileBytes||typeof e.sha256!="string"||!Fy.test(e.sha256))throw new Error("Artifact envelope manifest entry is invalid.");return{path:e.path,sizeBytes:e.sizeBytes,sha256:e.sha256}}function f5(e){let t;try{let n=Yr({files:e.map(r=>({path:r.path,content:""})),limits:{maxFiles:ut.maxFiles,maxDepth:ut.maxDepth,maxPathBytes:ut.maxPathBytes,maxFileBytes:ut.maxFileBytes,maxTotalBytes:ut.maxTotalFileBytes},runDlp:!1,contentPolicy:"paths_only"});if(n.excluded.length>0||n.files.length!==e.length)throw new Error("excluded path");t=n.files.map(r=>r.path).sort(zd)}catch{throw new Error("Artifact manifest paths are not canonical.")}if(e.some((n,r)=>n.path!==t[r]))throw new Error("Artifact manifest paths are not canonical.")}function m5(e){let t=ve(e);return{path:e.path,sizeBytes:t.byteLength,sha256:hn(t)}}function k0(e){let t=[o5,Md(e.length)];for(let n of e){let r=new TextEncoder().encode(n.path);t.push(Md(r.byteLength),r,k5(n.sizeBytes),By(n.sha256))}return S0(t)}function g0(e,t,n){if(!Array.isArray(e))throw new Error(`${n} must be an array of exact paths.`);let r=[],i=new Set;for(let o of e){if(typeof o!="string")throw new Error(`${n} must contain only exact string paths.`);let s=o.normalize("NFC"),a=s.toLocaleLowerCase("en-US");if(i.has(a))throw new Error(`${n} contains a duplicate or portable-path collision.`);if(i.add(a),!t.has(s))throw new Error(`${n} references a file outside the canonical review package.`);r.push(s)}return r.sort(zd)}function h0(e,t){return Dn(e,t).type==="evidence"}function g5(e){for(let t of s5)if(Object.prototype.hasOwnProperty.call(e,t))throw new Error("Caller-supplied artifact digests are forbidden; the server hashes the final ZIP bytes.")}function w0(e,t){if(!ps(e)||typeof e.skillSlug!="string"||!WA(e.skillSlug)||typeof e.semanticVersion!="string"||!n5.test(e.semanticVersion)||typeof e.generationId!="string"||!r5.test(e.generationId))throw new Error(`${t}.`)}function h5(e){if(!ps(e)||Object.keys(e).length!==Object.keys(ut).length)return null;for(let t of[ut,t5])if(Object.entries(t).every(([n,r])=>e[n]===r))return t;return null}function My(e){let t=Object.freeze(e.manifest.files.map(o=>Object.freeze({path:o.path,sizeBytes:o.sizeBytes,sha256:o.sha256}))),n=b0(e.generation),r=Object.freeze({sha256:e.archive.sha256,sizeBytes:e.archive.sizeBytes}),i=Object.freeze({encoding:Cl,sha256:e.manifest.sha256,fileCount:e.manifest.fileCount,totalFileBytes:e.manifest.totalFileBytes,files:t});return Object.freeze({format:e.format,formatVersion:1,generation:n,archive:r,manifest:i,parserPolicy:e.parserPolicy})}function y5(e){return My(e)}function b0(e){return Object.freeze({skillSlug:e.skillSlug,semanticVersion:e.semanticVersion,generationId:e.generationId})}function v5(e,t){return e.length===t.length&&e.every((n,r)=>n.path===t[r]?.path&&n.sizeBytes===t[r]?.sizeBytes&&n.sha256===t[r]?.sha256)}function zd(e,t){return Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}function Bd(e){return new TextEncoder().encode(e)}function hn(e){return`sha256:${YV("sha256").update(e).digest("hex")}`}function _0(e,t){return XV(By(e),By(t))}function By(e){return Buffer.from(e.slice(7),"hex")}function Md(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function k5(e){let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function S0(e){let t=new Uint8Array(e.reduce((r,i)=>r+i.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}function Nd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ps(e){return typeof e=="object"&&e!==null}var Uy=["productivity","coding","review","testing","devops","data","documents","media","research","planning","design","security","business","education","automation","communication","email","customer-support","sales","marketing","finance","legal","operations","project-management","writing","translation","knowledge-management","hr","ai","ecommerce"],w5="productivity",b5=new Set(Uy),_5={ci:"devops","ci-cd":"devops",compliance:"security",content:"documents",crm:"customer-support",docs:"documents",frontend:"coding","customer-service":"customer-support","customer-success":"customer-support","e-commerce":"ecommerce",genai:"ai",legal:"legal",llm:"ai",ops:"operations",pm:"project-management",reporting:"business",reports:"business","team-ops":"operations",ui:"design",ux:"design","web-development":"coding"},S5={productivity:["productivity","todo","task","tasks","calendar","meeting","notes","workflow","focus"],coding:["code","coding","developer","frontend","backend","repository","typescript","javascript","react","vite","html","css","component","bundle","artifact"],review:["review","reviews","critique","audit","feedback","pr","pull","quality"],testing:["test","tests","testing","qa","coverage","regression","playwright","vitest"],devops:["deploy","approval","ci","cd","pipeline","infra","infrastructure","docker","cloudflare","wrangler"],data:["data","dataset","sql","database","analytics","metrics","spreadsheet","csv","json"],documents:["document","documents","doc","docs","pdf","report","reports","contract","proposal","writing"],media:["media","image","video","audio","transcript","youtube","asset","thumbnail"],research:["research","search","sources","citation","citations","summarize","summaries","literature"],planning:["plan","planning","project","roadmap","milestone","sprint","delivery","schedule"],design:["design","ui","ux","layout","wireframe","prototype","figma","tailwind","shadcn"],security:["security","threat","secret","secrets","vulnerability","vulnerabilities","risk","policy"],business:["business","strategy","customer","market","stakeholder","commercial","pricing"],education:["education","teach","teaching","learn","learning","lesson","course","tutorial"],automation:["automation","automate","workflow","script","scripts","bot","trigger","orchestration"],communication:["communication","slack","message","messages","chat","reply","announcement","conversation"],email:["email","emails","gmail","googleemail","googlemail","outlook","inbox","mail","newsletter"],"customer-support":["support","ticket","tickets","helpdesk","customer","service","csat","escalation"],sales:["sales","lead","leads","prospect","pipeline","deal","deals","crm","account"],marketing:["marketing","campaign","brand","seo","content","social","audience","copy"],finance:["finance","financial","invoice","invoices","budget","forecast","accounting","revenue","tax"],legal:["legal","contract","contracts","clause","clauses","compliance","policy","terms","privacy"],operations:["operations","ops","runbook","process","sop","incident","queue","handoff"],"project-management":["project","projects","backlog","dependency","dependencies","kanban","scrum","pm"],writing:["writing","write","draft","edit","editing","blog","article","copywriting"],translation:["translation","translate","localization","locale","language","languages","i18n"],"knowledge-management":["knowledge","wiki","kb","retrieval","archive","taxonomy","knowledgebase"],hr:["hr","hiring","recruiting","interview","onboarding","employee","people","performance"],ai:["ai","llm","prompt","prompts","model","models","agent","agents","rag","embedding"],ecommerce:["ecommerce","commerce","shop","store","checkout","cart","order","orders","product"]};function zy(e){if(typeof e!="string")return null;let t=I0(e);return b5.has(t)?t:_5[t]??null}function x0(e){let t=e.trim().toLowerCase().replace(/[_\s]+/gu,"-"),n={ai:"AI",hr:"HR",ecommerce:"E-commerce","e-commerce":"E-commerce"};return n[t]?n[t]:e.split(/[-_\s]+/u).filter(Boolean).map(r=>`${r.slice(0,1).toUpperCase()}${r.slice(1)}`).join(" ")}function C0(e){let t=[{value:e.slug??"",weight:3,signal:"slug"},{value:e.name??"",weight:3,signal:"name"},{value:e.description??"",weight:2,signal:"description"},{value:e.skillType??"",weight:1,signal:"skill_type"},{value:e.compatibility??"",weight:1,signal:"compatibility"},{value:(e.tags??[]).join(" "),weight:4,signal:"tags"},{value:e.body??"",weight:1,signal:"body"}].filter(o=>o.value.trim().length>0),n=new Map;for(let o of t){let s=C5(o.value);for(let[a,l]of Object.entries(S5)){if(!l.some(d=>s.has(d)))continue;let u=n.get(a)??{score:0,signals:new Set};u.score+=o.weight,u.signals.add(o.signal),n.set(a,u)}}let i=[...n.entries()].sort((o,s)=>s[1].score-o[1].score||Uy.indexOf(o[0])-Uy.indexOf(s[0]))[0];return!i||i[1].score<2?{category:x5(e),confidence:"fallback",matchedSignals:[]}:{category:i[0],confidence:i[1].score>=5?"high":i[1].score>=3?"medium":"low",matchedSignals:[...i[1].signals].sort()}}function x5(e){let t=I0(e.skillType??"");return t.includes("automation")?"automation":t.includes("mcp")?"ai":w5}function I0(e){return e.trim().toLowerCase().replace(/[_\s]+/gu,"-")}function C5(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/u).map(t=>t.trim()).filter(t=>t.length>=2).flatMap(I5))}function I5(e){let t=[e];return e.endsWith("ing")&&e.length>5&&t.push(e.slice(0,-3)),e.endsWith("s")&&e.length>4&&t.push(e.slice(0,-1)),t}var Ik=mn(Qi(),1);import{createHash as e9}from"node:crypto";var Sk=["LICENSE","LICENCE","LICENSE.md","LICENCE.md","LICENSE.txt","COPYING","COPYING.txt"];var jpe=256*1024;var t9=`MIT License
707
707
 
708
708
  Copyright (c) <year> <copyright holders>
709
709
 
@@ -2029,7 +2029,7 @@ Next:
2029
2029
  `).trimStart().split(/\n\s*\n/u)[0].split(/\r?\n/u).map(o=>o.trim()).filter(Boolean)}function See(e){return[...new Set([...e.matchAll(/--[a-z0-9][a-z0-9-]*/giu)].map(t=>t[0]).sort())]}var xee=Object.freeze(["--ascii","--api-key","--base-url","--color","--detail","--help","--json","--motion","--no-color","--no-interactive","--no-motion","--output-format","--screen-reader","--ui"]),Cee=Object.freeze({"auth mfa recovery-codes":Object.freeze(["--code","--mfa-code"])}),Iee=Object.freeze(jg.map(e=>{let t=e.split(" "),n=xo(t[0],t.slice(1));if(!n)throw new Error(`Public command manifest could not resolve focused help for ${e}.`);let r=$ee(e,n.usage),o=!jg.some(s=>s!==e&&s.startsWith(`${e} `))&&r.length>0?"command":"help_topic";return Object.freeze({path:e,kind:o,pathSegments:Object.freeze(t),aliases:Object.freeze(Ree(e)),usage:r.join(`
2030
2030
  `)||n.usage,positionals:Object.freeze(Eee(r.join(`
2031
2031
  `)||n.usage)),options:Object.freeze([...new Set([...o==="command"?Dee(r.join(`
2032
- `)):n.options,...Cee[e]??[],"--json"])]),inheritedOptions:xee,outputModes:Object.freeze(["human","json","stream-json"]),mutability:Tee(n.sideEffects),humanInLoop:Oee(n),fixturePrerequisites:Object.freeze([...n.requiresLogin?["authenticated_account"]:[],...n.requiresNetwork?["reachable_backend"]:[]]),examples:Object.freeze(n.examples),availability:"public"})})),Pee=new Map(Iee.map(e=>[e.path,e]));function bN(e){let t=e.map(n=>n.trim().toLowerCase()).filter(Boolean);for(let n=t.length;n>=1;n-=1){let r=Pee.get(t.slice(0,n).join(" "));if(r)return r}return null}function Aee(e,t){let n=new Set([...e.options,...e.inheritedOptions]),r=t.indexOf("--"),i=r===-1?t:t.slice(0,r);for(let o of i){if(!o.startsWith("--"))continue;let s=o.split("=",1)[0];if(!n.has(s))return s.slice(2)}return null}var _N=Aee;function Ree(e){return e==="find"?["search"]:e==="workspaces"?["workspace"]:[]}function Eee(e){return[...new Set([...e.matchAll(/<([^>]+)>/gu)].map(t=>t[1]))]}function $ee(e,t){let n=`skills-layer ${e}`;return t.split(/\r?\n/u).map(r=>r.trim()).filter(r=>r===n||r.startsWith(`${n} `))}function Dee(e){return[...new Set([...e.matchAll(/--[a-z][a-z0-9-]*/gu)].map(t=>t[0]))]}function Tee(e){let t=e.some(r=>r.includes("local")||r.includes("credential")),n=e.some(r=>r.includes("cloud_write")||r.includes("payment"));return t&&n?"mixed":n?"cloud_write":t?"local_write":"read_only"}function Oee(e){return e.sideEffects.includes("payment_mutation")?"financial":e.mayOpenBrowser?"browser":e.mayPrompt?"prompt":"none"}import{posix as Lee,win32 as jee}from"node:path";function SN(e,t){let n=t==="win32"?jee:Lee;if(t==="win32"){let o=oI(e.APPDATA,e.USERPROFILE,e.HOME);if(!o)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(o,"skills-layer")}let r=oI(e.XDG_CONFIG_HOME);if(r)return n.join(r,"skills-layer");let i=oI(e.HOME);if(!i)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(i,".skills-layer")}function oI(...e){return e.map(t=>t?.trim()).find(t=>!!t)}var Nee=/^[\u00a0\u2007\u202f\ufeff]+|[\u00a0\u2007\u202f\ufeff]+$/gu,Fee=/^\[(https?:\/\/[^\]\r\n]+)\]\((https?:\/\/[^)\r\n]+)\)$/u;function xN(e){let t=e.indexOf("--");return e.map((n,r)=>{if(t!==-1&&r>t)return n;let i=n.replace(Nee,""),o=Fee.exec(i);return o&&o[1]===o[2]?o[1]:i})}var CN={creator_eval_live_network_unsupported:A("policy_blocked","blocked",!1,!0,"The controlled evaluator does not support live external network access.",[4]),payout_settlement_pending:A("conflict","conflict",!0,!0,"Converted payout funds are not yet available",[4]),payout_settlement_mismatch:A("operation_not_allowed","operation_not_allowed",!1,!0,"Payout settlement requires administrator review",[4]),payout_recovery_pending:A("verification_pending","verification_pending",!1,!0,"Returned payout funds require reconciliation",[4]),platform_balance_insufficient:A("conflict","conflict",!0,!0,"Platform funds are temporarily insufficient; retry later",[4]),connected_balance_insufficient:A("conflict","conflict",!0,!0,"Connected account funds cannot cover this bank payout; review settlement and account balance",[4]),platform_balance_unavailable:A("backend_unreachable","unavailable",!0,!0,"Platform funds could not be checked; retry later",[5]),payout_provider_refused:A("operation_not_allowed","error",!1,!0,"The payment provider refused the payout; check payout configuration before retrying",[4]),payout_outcome_unknown:A("verification_pending","hold",!1,!0,"Payout outcome needs reconciliation before retrying",[5]),enterprise_member_already_active:A("conflict","conflict",!1,!1,"This person is already an active Enterprise member.",[4]),local_cleanup_incomplete:A("human_action_required","error",!0,!0,"Unlock the OS credential store and retry logout to finish local cleanup.",[4,5]),admin_step_up_invalid:A("security_verification_failed","error",!1,!0,"Verify your administrator step-up key in the private operator checkout.",[4]),verification_code_locked:A("rate_limited","rate_limited",!0,!0,"This code is locked. Request a new code after the retry time.",[4]),conflicting_flags:A("invalid_input","error",!1,!0,"Choose a value or its clear flag, not both.",[4]),flag_value_missing:A("invalid_input","error",!1,!0,"Supply a value for the flag.",[4]),rights_attestation_required:A("precondition_required","error",!1,!0,"Public and unlisted releases require confirmation of distribution rights.",[4]),rights_attestation_invalid:A("invalid_input","error",!1,!0,"Supply a supported rights basis and public distribution scope.",[4]),catalogue_artifact_unavailable:A("backend_unreachable","error",!0,!0,"The catalogue artifact could not be downloaded; retry export.",[4]),admin_mfa_required:A("human_action_required","human_action_required",!1,!0,"Enable MFA with skills-layer auth mfa setup, then retry.",[4]),admin_mfa_unavailable:A("backend_unreachable","unavailable",!0,!0,"Administrator MFA is unavailable; contact the deployment operator.",[5]),source_read_unavailable:A("backend_unreachable","source_unavailable",!1,!0,"The source could not be read completely. Its package has not been assessed.",[5]),command_failed:A("internal_error","error",!1,!1,"The command could not be completed.",[5]),resource_not_found:A("not_found","not_found",!1,!0,"The requested resource was not found.",[4]),permission_denied:A("permission_denied","error",!1,!1,"This credential cannot perform the requested operation.",[4]),login_required:A("login_required","login_required",!1,!0,"Sign in is required.",[4]),unauthorized:A("login_required","login_required",!1,!0,"Sign in is required.",[4]),api_key_invalid_or_expired:A("login_required","login_required",!1,!0,"The saved API key is no longer valid. Sign in again to use account features.",[4]),confirmation_required:A("confirmation_required","human_action_required",!1,!0,"Human confirmation is required.",[4]),mfa_setup_required:A("human_action_required","human_action_required",!1,!0,"MFA setup is required.",[4]),login_mfa_required:A("human_action_required","human_action_required",!1,!0,"A second authentication factor is required.",[4]),login_mfa_input_invalid:A("invalid_input","error",!1,!0,"Provide exactly one supported MFA proof.",[4]),login_mfa_invalid:A("security_verification_failed","error",!1,!0,"The MFA proof was invalid or already used.",[4]),login_security_unavailable:A("security_verification_failed","security_unavailable",!0,!0,"Login security is unavailable.",[5]),mfa_challenge_locked:A("rate_limited","rate_limited",!0,!0,"The MFA challenge is temporarily locked.",[4]),social_secure_continuation_unavailable:A("security_verification_failed","security_unavailable",!1,!0,"Secure social continuation is unavailable.",[4,5]),social_continuation_terminal:A("security_verification_failed","error",!1,!0,"The social continuation ended without authorization.",[4]),verification_code_expired:A("human_action_required","error",!1,!0,"The verification code expired.",[4]),payout_human_confirmation_required:A("human_action_required","human_action_required",!1,!0,"Human payout confirmation is required.",[4]),security_report_requires_action:A("policy_blocked","blocked",!1,!0,"The security report requires action.",[4]),trust_report_not_actionable:A("policy_blocked","blocked",!1,!0,"The trust report does not permit this transition.",[4]),trust_report_authority_mismatch:A("security_verification_failed","blocked",!1,!0,"Trust evidence does not match the exact artifact generation.",[4,5]),trust_report_required_evidence_unavailable:A("verification_pending","action_required",!0,!0,"Required trust evidence is unavailable or incomplete.",[2,4,5]),sarif_source_mapping_required:A("precondition_required","error",!1,!0,"Repository SARIF requires verified repository-relative source locations.",[4]),sarif_security_evidence_required:A("precondition_required","error",!1,!0,"Runtime-audit SARIF requires typed security evidence.",[4]),sarif_rule_mapping_required:A("precondition_required","error",!1,!0,"Runtime-audit SARIF requires an explicit reviewed rule mapping for every actionable event.",[4]),sarif_profile_unsupported:A("invalid_input","error",!1,!0,"The requested SARIF profile is not available for this report audience.",[4]),cloud_trust_ledger_mismatch:A("security_verification_failed","blocked",!1,!0,"This exact public skill generation is temporarily unavailable because its Cloud Trust Ledger attestation does not match. A Skills Layer operator must re-attest the exact generation before install.",[4]),api_key_active_limit_reached:A("quota_exceeded","conflict",!1,!0,"The active API-key limit has been reached.",[4]),rate_limited:A("rate_limited","rate_limited",!0,!0,"The request rate limit was reached.",[4]),source_connection_already_canceled:A("unchanged","unchanged",!1,!1,"The source connection was already canceled.",[2,4]),source_connection_completed:A("conflict","conflict",!1,!1,"A completed source connection cannot be canceled.",[4]),source_connection_revoked:A("unchanged","unchanged",!1,!1,"The authorized source connection was revoked.",[0]),source_connection_already_revoked:A("unchanged","unchanged",!1,!1,"The source connection was already revoked.",[0]),source_connection_not_authorized:A("conflict","conflict",!1,!1,"Only an authorized source connection can be revoked.",[4]),reupload_required:A("precondition_required","reupload_required",!1,!0,"The stored artifact is unavailable; upload the bundle again.",[4]),artifact_finalization_failed:A("processing_action_required","partial_success",!0,!1,"The version exists but artifact finalisation is incomplete.",[0]),publication_moderation_failed:A("processing_action_required","partial_success",!1,!1,"The version exists but its moderation transition needs operator inspection.",[0]),source_connection_completion_unverified:A("verification_pending","verification_warning",!0,!0,"Source connection completion could not be verified.",[4,5]),admin_mcp_verification_warning:A("verification_pending","verification_warning",!0,!0,"Administrator MCP verification is pending.",[2,4,5]),admin_mcp_verification_rejected:A("security_verification_failed","rejected",!1,!0,"Administrator MCP verification was rejected.",[4]),authoritative_security_report_pending:A("processing_action_required","already_processing",!0,!0,"The authoritative security report is still processing.",[4]),publication_continuation_scheduled:A("processing_action_required","already_processing",!0,!1,"Publication is continuing through the durable exact-generation workflow.",[2,4]),binary_inspection_pending:A("processing_action_required","already_processing",!0,!0,"Binary asset security inspection is still processing.",[2,4]),binary_inspection_unavailable:A("verification_pending","hold",!0,!0,"Required binary asset security inspection is currently unavailable.",[2,4,5]),binary_asset_blocked:A("policy_blocked","blocked",!1,!0,"A binary asset did not satisfy the platform security policy.",[2,4]),binary_profile_suspended:A("policy_blocked","hold",!0,!0,"The required binary format profile is temporarily suspended.",[2,4]),security_adjudication_pending:A("processing_action_required","already_processing",!0,!0,"Contextual security evidence is still being evaluated.",[2,4]),content_adjudication_insufficient_evidence:A("verification_pending","hold",!0,!0,"The available evidence is insufficient to resolve the security finding.",[2,4]),content_adjudication_confirmed_risk:A("policy_blocked","blocked",!1,!0,"The exact content contains a confirmed security risk.",[2,4]),content_adjudication_source_remediation_required:A("policy_blocked","blocked",!1,!0,"The source must be changed before security review can continue.",[2,4]),content_adjudication_execution_failed:A("verification_pending","hold",!0,!0,"Content security adjudication could not complete and remains held.",[2,4,5]),content_probe_runner_unavailable:A("verification_pending","hold",!0,!0,"The isolated content security evaluator is currently unavailable.",[2,4,5]),binary_inspection_authority_invalid:A("security_verification_failed","hold",!0,!0,"Binary security evidence could not be authenticated.",[2,4,5]),managed_security_pack_stale:A("security_verification_failed","hold",!0,!0,"A required managed security definition pack is not current.",[2,4,5]),workflow_dependency_incomplete:A("precondition_required","waiting_for_dependency",!0,!0,"A required upstream workflow is incomplete.",[4]),creator_processing_sla_breached:A("processing_action_required","action_required",!1,!0,"Creator processing exceeded its platform SLA.",[4,5]),invalid_global_option:A("invalid_input","error",!1,!0,"A global CLI option is invalid.",[4]),invalid_numeric_input:A("invalid_input","error",!1,!0,"A numeric option is invalid.",[4]),unknown_flag:A("invalid_input","error",!1,!0,"The option is not supported.",[4]),unknown_command:A("invalid_input","error",!1,!0,"The command is not supported.",[4]),unknown_subcommand:A("invalid_input","error",!1,!0,"The command is not supported.",[4]),missing_required_argument:A("invalid_input","error",!1,!0,"Required information is missing.",[4]),invalid_json:A("invalid_input","error",!1,!0,"The JSON value is invalid.",[4]),canonical_bundle_rejected:A("invalid_input","error",!1,!0,"The bundle failed canonical validation.",[4]),recovery_code_invalid_or_expired:A("human_action_required","error",!1,!0,"The recovery code is invalid or expired.",[4]),social_provider_not_configured:A("precondition_required","error",!1,!0,"The selected social provider is not configured.",[4,5]),search_selection_not_found:A("not_found","not_found",!1,!0,"The selected skill is not present in these search results.",[4]),best_effort:A("unchanged","low_confidence",!1,!0,"Best-effort candidates need a more specific task for higher confidence.",[2]),unsafe_task:A("policy_blocked","policy_blocked",!1,!0,"This task is outside the recommendation safety policy.",[2]),no_confident_recommendation:A("unchanged","no_confident_recommendation",!1,!0,"No skill met the calibrated recommendation confidence policy.",[2]),clarification_required:A("human_action_required","clarification_required",!1,!0,"One public task constraint is required before a skill can be recommended.",[2]),workspace_required:A("precondition_required","error",!1,!0,"A workspace id is required for this install.",[4]),unsupported_skill_type:A("invalid_input","error",!1,!0,"The requested skill type is unsupported.",[4]),creator_resource_not_found:A("not_found","not_found",!1,!0,"The creator resource was not found.",[4]),creator_access_required:A("permission_denied","access_required",!1,!0,"Creator management access is required for this public skill.",[4]),library_access_required:A("permission_denied","access_required",!1,!0,"Library access is required to inspect issues for this public skill.",[4]),issue_not_found:A("not_found","not_found",!1,!0,"The issue was not found in the managed skill.",[4]),review_not_found:A("not_found","not_found",!1,!0,"The review was not found in the managed skill.",[4]),api_key_not_found:A("not_found","not_found",!1,!0,"The API key was not found.",[4]),approval_request_not_found:A("not_found","not_found",!1,!0,"The approval request was not found.",[4]),available:A("unchanged","available",!1,!1,"The requested capability is available.",[2]),catalog_acquisition_ready:A("unchanged","ready",!1,!1,"The catalog acquisition is ready.",[2]),catalog_artifact_unavailable:A("precondition_required","error",!0,!0,"The exact catalog artifact is temporarily unavailable.",[4,5]),compare_missing_skills:A("not_found","not_found",!1,!0,"One or more skills requested for comparison were not found.",[4]),conflicting_export_output:A("conflict","conflict",!1,!0,"The requested export output options conflict.",[4]),conflicting_mcp_client_selection:A("conflict","conflict",!1,!0,"The MCP client selection is ambiguous.",[4]),conflicting_mcp_migration_mode:A("conflict","conflict",!1,!0,"Choose either a legacy MCP migration preview or an apply operation.",[4]),needs_mcp_client_choice:A("human_action_required","needs_mcp_client_choice",!1,!0,"Choose a verified MCP host before setup can continue.",[4]),mcp_config_symlink_rejected:A("human_action_required","mcp_setup_blocked",!1,!0,"Replace the MCP config symlink with a regular user-owned config file before retrying.",[4]),mcp_registration_ownership_ambiguous:A("human_action_required","mcp_setup_blocked",!1,!0,"Review or rename the existing unowned Skills Layer MCP entry before retrying.",[4]),mcp_client_scope_required:A("human_action_required","needs_mcp_client_scope",!1,!0,"Choose one configured MCP host or explicitly select all hosts.",[4]),mcp_client_inventory_missing:A("precondition_required","mcp_needs_repair",!1,!0,"The local MCP configuration has no canonical host inventory.",[4]),mcp_legacy_project_path_required:A("precondition_required","error",!1,!0,"Choose the exact project root to inspect for legacy MCP registration.",[4]),mcp_multi_client_verify_failed:A("verification_pending","mcp_needs_repair",!0,!0,"One or more configured MCP hosts failed verification.",[4,5]),unknown_mcp_client:A("unsupported_client","error",!1,!0,"The requested MCP host is unsupported.",[4]),creator_listing_not_found_or_not_owned:A("not_found","not_found",!1,!0,"The creator listing is unavailable to this account.",[4]),creator_submission_not_found:A("not_found","not_found",!1,!0,"The creator submission was not found.",[4]),enterprise_resource_not_found:A("not_found","not_found",!1,!0,"The Enterprise resource was not found.",[4]),enterprise_checkout_completion_pending:A("processing_action_required","completion_pending",!0,!0,"Enterprise checkout completion is still being reconciled.",[2,5]),guardian_enabled:A("unchanged","enabled",!1,!1,"Guardian enforcement is enabled.",[2]),feature_already_configured:A("unchanged","unchanged",!1,!1,"The requested feature state is already configured.",[2]),guardian_exact_version_required:A("precondition_required","error",!1,!0,"Guardian requires one exact skill version.",[4]),guardian_unmanaged_atomic_execution_required:A("precondition_required","blocked",!1,!0,"Unmanaged execution cannot be authorized by a diagnostic Guardian check.",[4]),guardian_plan_resolution_failed:A("internal_error","error",!0,!0,"Guardian could not resolve a safe execution plan.",[4,5]),guardian_version_not_current:A("conflict","conflict",!1,!0,"The selected Guardian version is not current.",[4]),human_handoff_required:A("human_action_required","human_action_required",!1,!0,"A human must complete this handoff.",[2,4]),invalid_amount_cents:A("invalid_input","error",!1,!0,"The amount must be a valid non-negative number of cents.",[4]),invalid_enterprise_role:A("invalid_input","error",!1,!0,"The Enterprise role is invalid.",[4]),invalid_expiry:A("invalid_input","error",!1,!0,"The expiry value is invalid.",[4]),invalid_incident_path:A("invalid_input","error",!1,!0,"The incident path is invalid.",[4]),invalid_issue_status:A("invalid_input","error",!1,!0,"The issue status is invalid.",[4]),invalid_price_cents:A("invalid_input","error",!1,!0,"The price must be a valid non-negative number of cents.",[4]),invalid_review_status:A("invalid_input","error",!1,!0,"The review status is invalid.",[4]),invalid_scope:A("invalid_input","error",!1,!0,"The requested scope is invalid.",[4]),invalid_search_filter:A("invalid_input","error",!1,!0,"The search filter is invalid.",[4]),invalid_seats:A("invalid_input","error",!1,!0,"The Enterprise seat count is invalid.",[4]),invalid_sort:A("invalid_input","error",!1,!0,"The requested sort mode is invalid.",[4]),invalid_source:A("invalid_input","error",!1,!0,"The requested source is invalid.",[4]),invalid_version:A("invalid_input","error",!1,!0,"The semantic version is invalid.",[4]),local_install_not_found:A("not_found","not_found",!1,!0,"The local installation was not found.",[4]),local_source_requires_client_files:A("precondition_required","error",!1,!0,"This local source requires client-provided files.",[4]),ownership_claim_not_found:A("not_found","not_found",!1,!0,"The ownership claim was not found.",[4]),ownership_dispute_open:A("human_action_required","manual_review_required",!1,!0,"An ownership dispute requires human resolution.",[2,4]),ownership_already_configured:A("unchanged","unchanged",!1,!1,"The requested ownership assignments are already configured.",[2]),org_dependency_audit_incomplete:A("precondition_required","hold",!0,!0,"The organization dependency audit is incomplete.",[2,4]),purchase_not_found:A("not_found","not_found",!1,!0,"The purchase was not found.",[4]),restore_record_not_found:A("not_found","not_found",!1,!0,"No restorable installation record was found.",[4]),scaffold_overwrite_confirmation_required:A("confirmation_required","human_action_required",!1,!0,"Overwriting the scaffold requires confirmation.",[4]),security_report_requires_review:A("policy_blocked","manual_review_required",!1,!0,"The security report requires human review.",[2,4]),security_report_missing:A("not_found","not_found",!1,!0,"The security report was not found.",[4]),platform_score_subject_missing:A("not_found","not_found",!1,!0,"The exact Platform Score skill generation was not found.",[4]),security_evidence_operation_not_found:A("not_found","not_found",!1,!0,"The security evidence operation was not found.",[4]),skill_not_found:A("not_found","not_found",!1,!0,"The skill was not found.",[4]),social_browser_confirmation_required:A("human_action_required","human_action_required",!1,!0,"Social sign-in requires browser confirmation.",[4]),source_connection_not_found:A("not_found","not_found",!1,!0,"The source connection was not found.",[4]),source_not_verifiable:A("policy_blocked","manual_review_required",!1,!0,"The source cannot be verified automatically.",[2,4]),source_path_not_found:A("not_found","not_found",!1,!0,"The source path was not found.",[4]),source_reference_not_found:A("not_found","not_found",!1,!0,"The source reference was not found.",[4]),submission_not_found:A("not_found","not_found",!1,!0,"The submission was not found.",[2,4]),trust_report_not_found:A("not_found","not_found",!1,!0,"The Platform Score report was not found.",[4]),unknown_agent:A("unsupported_client","error",!1,!0,"The requested agent is unsupported.",[4]),verification_code_invalid:A("human_action_required","error",!1,!0,"The verification code is invalid or expired.",[4]),workspace_not_found_or_forbidden:A("not_found","not_found",!1,!0,"The workspace is unavailable to this account.",[4]),workspace_skill_approval_not_found:A("not_found","not_found",!1,!0,"The workspace skill approval was not found.",[4]),workspace_working_mode_not_found:A("not_found","not_found",!1,!0,"The selected workspace was not found.",[4])};function Bee(e){let t=CN[e];return t?{reasonCode:e,...t}:null}function Fg(e,t={}){if(!e)return t.httpStatus===404?Pa("resource_not_found"):t.httpStatus===401?Pa("login_required"):t.httpStatus===403?Pa("permission_denied"):t.httpStatus===409?gt("conflict","conflict"):t.httpStatus===429?Pa("rate_limited"):(t.httpStatus&&t.httpStatus>=500,Pa("command_failed"));let n=Bee(e);return n||(e.includes("not_found")||e==="missing_record"?gt(e,"not_found","not_found"):e.includes("rate_limit")?gt(e,"rate_limited","rate_limited",!0):e.includes("quota")||e.includes("_limit_reached")||e.includes("_limit_exhausted")?gt(e,"quota_exceeded","conflict"):e.includes("human")||e.includes("mfa")||e.includes("browser_confirmation")?gt(e,"human_action_required","human_action_required"):e.includes("already_canceled")||e.includes("unchanged")||e.includes("already_complete")?gt(e,"unchanged","unchanged"):e.includes("dependency")||e.includes("precondition")||e.includes("required")?gt(e,"precondition_required","error"):e.includes("processing")||e.includes("pending")||e.includes("already_processing")?gt(e,"processing_action_required","already_processing",!0):e.includes("conflict")||e.includes("already_final")||e.includes("completed")?gt(e,"conflict","conflict"):e.includes("payment")||e.includes("checkout")||e.includes("purchase")?gt(e,"payment_required","human_action_required"):e.includes("source")?gt(e,"source_required","error"):e.includes("backend")||e.includes("unreachable")||e.includes("network")?gt(e,"backend_unreachable","error",!0):e.includes("agent")||e.includes("client")||e.includes("unsupported")?gt(e,"unsupported_client","error"):e.includes("blocked")||e.includes("policy")||e.includes("guardian")?gt(e,"policy_blocked","blocked"):e.includes("forbidden")||e.includes("permission_denied")?gt(e,"permission_denied","error"):e.includes("not_allowed")||e.includes("invalid_transition")?gt(e,"operation_not_allowed","error"):gt(e,"invalid_input","error"))}function A(e,t,n,r,i,o){return{family:e,defaultStatus:t,retryable:n,nextActionRequired:r,safeSummary:i,allowedHttpStatusClasses:o}}function Pa(e){return{reasonCode:e,...CN[e]}}function gt(e,t,n="error",r=!1){return{reasonCode:e,family:t,defaultStatus:n,retryable:r,nextActionRequired:!1,safeSummary:"The command could not be completed.",allowedHttpStatusClasses:[4,5]}}var IN=[["help","account"],["help","use"],["help","creator"],["help","teams"],["help","security"],["help","mcp"],["help","automation"],["help","troubleshoot"],["help","full"]],PN=[["help"],["help","topic"],["login"],["logout"],["register"],["setup"],["whoami"],["profile"],["profile","update"],["auth"],["auth","status"],["auth","repair"],["auth","verify"],["auth","recover"],["auth","recover","complete"],["auth","connect"],["auth","mfa"],["auth","mfa","status"],["auth","mfa","setup"],["auth","mfa","verify"],["auth","mfa","recovery-codes"],["auth","mfa","disable"],["api-key"],["api-key","create"],["api-key","list"],["api-key","revoke"],["mcp"],["mcp","setup"],["mcp","status"],["mcp","verify"],["mcp","repair"],["mcp","migrate"],["mcp","disconnect"],["backend"],["backend","status"],["backend","cloud"],["backend","local"],["status"],["doctor"],["search"],["find"],["featured"],["trending"],["show"],["trust"],["recommend"],["categories"],["compare"],["install"],["install","status"],["installed"],["owned"],["export"],["add-review"],["show-reviews"],["add-issue"],["show-issues"],["purchases"],["purchases","list"],["purchases","invoice"],["purchases","status"],["purchases","refund-quote"],["purchases","refund"],["purchases","spending"],["validate"],["preview-trigger"],["creator"],["creator","init"],["creator","create"],["creator","sessions"],["creator","resume"],["creator","inspect"],["creator","answer"],["creator","resources"],["creator","resource-decide"],["creator","tool-contract"],["creator","draft"],["creator","validate"],["creator","eval"],["creator","improve"],["creator","revise"],["creator","materialize"],["creator","finalize"],["creator","rules"],["creator","submissions"],["creator","spaces"],["creator","spaces","buy"],["creator","status"],["creator","source"],["creator","source","prepare"],["creator","source","publish-request"],["creator","source","release-status"],["creator","submit"],["creator","submit-version"],["creator","check-slug"],["creator","rename"],["creator","pricing"],["creator","delist"],["creator","relist"],["creator","update-listing"],["creator","visibility"],["creator","security-report"],["creator","rescan-security"],["creator","provenance"],["creator","claim"],["creator","verify"],["creator","dispute"],["creator","issues"],["creator","update-issue"],["creator","reviews"],["creator","moderate-review"],["creator","analytics"],["creator","earnings"],["creator","payout-profile"],["creator","payout-link"],["creator","payouts"],["creator","withdraw"],["source"],["source","connection"],["source","connection","start"],["source","connection","status"],["source","connection","complete"],["source","connection","cancel"],["source","connection","revoke"],["source","reference"],["source","reference","resolve"],["approval"],["approval","request"],["approval","request","status"],["approval","request","complete"],["enterprise"],["enterprise","accept-invite"],["enterprise","checkout"],["enterprise","install-authorize"],["enterprise","list"],["enterprise","member"],["enterprise","member","remove"],["enterprise","member","role"],["enterprise","members"],["enterprise","rename"],["enterprise","primary-admin"],["enterprise","primary-admin","transfer"],["enterprise","primary-admin","status"],["enterprise","primary-admin","accept"],["enterprise","primary-admin","cancel"],["enterprise","seats"],["enterprise","seats","add"],["enterprise","invite"],["enterprise","invites"],["enterprise","revoke-invite"],["enterprise","resend-invite"],["enterprise","workspace-member"],["enterprise","workspace-member","list"],["enterprise","workspace-member","add"],["enterprise","workspace-member","remove"],["enterprise","workspace"],["enterprise","workspace","create"],["enterprise","workspace","rename"],["enterprise","workspace","update"],["enterprise","workspace","archive"],["enterprise","workspaces"],["enterprise","skill"],["enterprise","skill","entitlements"],["enterprise","skill","quote"],["enterprise","skill","buy"],["workspace"],["workspace","list"],["workspace","current"],["workspace","select"],["workspace","request"],["workspace","approve"],["workspace","reject"],["workspace","skills"],["workspace","guide"],["workspaces"],["guardian"],["guardian","check"],["guardian","incident"],["guardian","enable"],["guardian","disable"],["guardian","enable-warnings-only"],["guardian","status"],["guardian","hook"],["guardian","hook","install"],["guardian","hook","status"],["guardian","launch"],["guardian","exec"],["agents"],["agents","list"],["import"],["sync"],["restore"],["check"],["update"],["remove"],["identity"],["identity","providers"],["identity","start"],["identity","continue"],["identity","status"],["identity","complete"],["identity","list"],["identity","unlink"],["library"],["buy"]],Mee=1+IN.length+PN.length;var Co="0.2.25";var Uee="skills-layer-cli-event-v1";function RN(e){let t=0,n=e.now??(()=>new Date().toISOString());return(r,i)=>{let o=Di(i.summary,"summary",512),s=i.redactedDetail===void 0?void 0:Di(i.redactedDetail,"redacted detail",2048),a=i.next?.map(u=>({id:Di(u.id,"next-action ID",128),kind:u.kind,label:Di(u.label,"next-action label",512),...u.command===void 0?{}:{command:{executable:u.command.executable,args:u.command.args.map(d=>Di(d,"next-action argument",1024))}},...u.url===void 0?{}:{url:AN(u.url)},safeToAutoRun:u.safeToAutoRun,requiresHuman:u.requiresHuman,...u.rationale===void 0?{}:{rationale:Di(u.rationale,"next-action rationale",1024)},safety:u.safety})),l=i.links?.map(u=>{let d=AN(u.url);return{label:Di(u.label,"link label",512),url:d}}),c=i.data===void 0?void 0:sI(i.data);return t+=1,{schemaVersion:Uee,operationId:H(e.operationId),sequence:t,timestamp:n(),type:r,command:{name:H(e.command.name)},...i,summary:o,...s===void 0?{}:{redactedDetail:s},...a===void 0?{}:{next:a},...l===void 0?{}:{links:l},...c===void 0?{}:{data:c}}}}function AN(e){let t=Di(e,"link URL",2048);if(!/^https?:\/\//u.test(t))throw new Error("CLI event links must use http or https URLs.");return t}function Di(e,t,n){let r=H(e);if(r.length>n)throw new Error(`CLI event ${t} exceeds ${n} characters.`);return r}function sI(e,t=""){return/^(?:accessToken|apiKey|authorization|clientSecret|handoffCode|password|refreshToken|secret)$/iu.test(t)?"[redacted-secret]":typeof e=="string"?H(e):Array.isArray(e)?e.map(n=>sI(n)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,sI(r,n)])):e}var zee=["human","json","stream-json"],EN=["auto","always","never"],qee=["auto","modern","classic"],Vee=["concise","standard","full"];function $N(e){let t=[],n={},r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(r){t.push(o);continue}if(o==="--"){r=!0,t.push(o);continue}let[s,a]=Gee(o);if(s==="--output-format"){let[l,c]=wu(s,a,e[i+1],zee);n.outputFormat=l,i+=c}else if(s==="--color"){let[l,c]=wu(s,a,e[i+1],EN);n.color=l,i+=c}else if(s==="--motion"){let[l,c]=wu(s,a,e[i+1],EN);n.motion=l,i+=c}else if(s==="--ui"){let[l,c]=wu(s,a,e[i+1],qee);n.ui=l,i+=c}else if(s==="--detail"){let[l,c]=wu(s,a,e[i+1],Vee);n.detail=l,i+=c}else o==="--no-color"?n.color="never":o==="--no-motion"?n.motion="never":o==="--screen-reader"?n.screenReader=!0:o==="--no-interactive"?n.interactive=!1:o==="--ascii"?n.unicode=!1:t.push(o)}return{args:t,options:n}}function DN(e,t,n){let r=e.outputFormat??"human",i=e.screenReader===!0,o=Bg(t.CI),s=t.TERM==="dumb",a=n.stdinIsTty&&n.stdoutIsTty&&n.stderrIsTty,l=e.ui!=="classic",c=e.ui==="classic",u=e.detail??(r==="human"?"concise":"standard"),d=a&&!o&&!s&&l&&!i&&e.interactive!==!1,p=d&&e.motion!=="never",m=d&&p,h=!i&&e.color!=="never"&&(e.color==="always"||!Bg(t.NO_COLOR)&&!c&&(Bg(t.FORCE_COLOR)||!o&&!s&&n.stdoutIsTty)),g=e.unicode!==!1&&!Bg(t.NO_UNICODE)&&!s;return r==="json"?{kind:"json-final",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:r==="stream-json"?{kind:"json-stream",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:{kind:m?"human-interactive":"human-static",color:h,motion:p,interactive:m,unicode:g,screenReader:i,classic:c,detail:u}}function Gee(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function wu(e,t,n,r){let i=t??n;if(i===void 0||i.startsWith("--")||!r.includes(i))throw new Error(`${e} expects one of: ${r.join(", ")}.`);return[i,t===void 0?1:0]}function Bg(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}var TN=()=>null;var Io=88,Hee=/(?:^|_)(?:blocked|cancelled|canceled|rejected|denied|expired|invalid|not_found|conflict|missing_required_argument)(?:$|_)/u,Kee=/(?:^|_)(?:required|requires_action|warning|unverified|completion_pending)(?:$|_)/u,Wee=/(?:^|_)(?:argument|field|input|parameter|protocol|value)_required(?:$|_)/u,Zee=/(?:^|_)(?:failed|failure|internal_error|network_error|service_unavailable|timed_out|timeout)(?:$|_)/u,Jee=/\b(?:required information is missing|unknown (?:command|option|flag)|invalid|already used|not found|blocked|cancelled|canceled|rejected|denied|expired|missing|not supported|could not be read|cannot write)\b/iu,Yee=/\b(?:action|approval|authentication|checkout|confirmation|consent|human action|login|mfa|payment|purchase|registration|second factor|secure account connection|sign in|source connection|verification|workspace approval)\b[^.\n]*\b(?:required|needed|must be completed)\b|\b(?:complete|confirm|continue)\b[^.\n]*\b(?:browser|cli|terminal)\b/iu,Xee=/\b(?:failed|failure|service unavailable|server error|network error|timed out|timeout|could not complete)\b/iu;function LN(e){let t=ON(e.status),n=ON(e.reasonCode),r=[t,n].filter(Boolean);return r.some(i=>Hee.test(i))?"stopped":r.some(i=>Kee.test(i)&&!Wee.test(i))?"required":r.some(i=>Zee.test(i))||e.summary&&aI(e.summary)==="failed"?"failed":e.exitCode!==void 0&&e.exitCode!==0?"stopped":"completed"}function aI(e){let t=Qee(e);return Jee.test(t)?"stopped":Yee.test(t)?"required":Xee.test(t)?"failed":"stopped"}function bu(e,t){let n=t?"\u2014":"-",r=e.slice(0,1).toUpperCase()+e.slice(1);return`Skills Layer ${n} Action ${r}`}function ON(e){return H(e??"").trim().toLowerCase().replace(/[^a-z0-9]+/gu,"_")}function Qee(e){return H(e).split(/\n(?:Unchanged|Why|Next|Reference)(?:\s|$)/u,1)[0]}function Po(e){return UN(Mn(e)).reduce((t,n)=>t+zN(n),0)}function jN(e,t){return e.split(`
2032
+ `)):n.options,...Cee[e]??[],"--json"])]),inheritedOptions:xee,outputModes:Object.freeze(["human","json","stream-json"]),mutability:Tee(n.sideEffects),humanInLoop:Oee(n),fixturePrerequisites:Object.freeze([...n.requiresLogin?["authenticated_account"]:[],...n.requiresNetwork?["reachable_backend"]:[]]),examples:Object.freeze(n.examples),availability:"public"})})),Pee=new Map(Iee.map(e=>[e.path,e]));function bN(e){let t=e.map(n=>n.trim().toLowerCase()).filter(Boolean);for(let n=t.length;n>=1;n-=1){let r=Pee.get(t.slice(0,n).join(" "));if(r)return r}return null}function Aee(e,t){let n=new Set([...e.options,...e.inheritedOptions]),r=t.indexOf("--"),i=r===-1?t:t.slice(0,r);for(let o of i){if(!o.startsWith("--"))continue;let s=o.split("=",1)[0];if(!n.has(s))return s.slice(2)}return null}var _N=Aee;function Ree(e){return e==="find"?["search"]:e==="workspaces"?["workspace"]:[]}function Eee(e){return[...new Set([...e.matchAll(/<([^>]+)>/gu)].map(t=>t[1]))]}function $ee(e,t){let n=`skills-layer ${e}`;return t.split(/\r?\n/u).map(r=>r.trim()).filter(r=>r===n||r.startsWith(`${n} `))}function Dee(e){return[...new Set([...e.matchAll(/--[a-z][a-z0-9-]*/gu)].map(t=>t[0]))]}function Tee(e){let t=e.some(r=>r.includes("local")||r.includes("credential")),n=e.some(r=>r.includes("cloud_write")||r.includes("payment"));return t&&n?"mixed":n?"cloud_write":t?"local_write":"read_only"}function Oee(e){return e.sideEffects.includes("payment_mutation")?"financial":e.mayOpenBrowser?"browser":e.mayPrompt?"prompt":"none"}import{posix as Lee,win32 as jee}from"node:path";function SN(e,t){let n=t==="win32"?jee:Lee;if(t==="win32"){let o=oI(e.APPDATA,e.USERPROFILE,e.HOME);if(!o)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(o,"skills-layer")}let r=oI(e.XDG_CONFIG_HOME);if(r)return n.join(r,"skills-layer");let i=oI(e.HOME);if(!i)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(i,".skills-layer")}function oI(...e){return e.map(t=>t?.trim()).find(t=>!!t)}var Nee=/^[\u00a0\u2007\u202f\ufeff]+|[\u00a0\u2007\u202f\ufeff]+$/gu,Fee=/^\[(https?:\/\/[^\]\r\n]+)\]\((https?:\/\/[^)\r\n]+)\)$/u;function xN(e){let t=e.indexOf("--");return e.map((n,r)=>{if(t!==-1&&r>t)return n;let i=n.replace(Nee,""),o=Fee.exec(i);return o&&o[1]===o[2]?o[1]:i})}var CN={creator_self_review:P("policy_blocked","blocked",!1,!1,"Skill creators, owners and maintainers cannot review their own skill.",[4]),creator_self_issue:P("policy_blocked","blocked",!1,!1,"Skill creators, owners and maintainers cannot file customer issues on their own skill.",[4]),creator_self_purchase_limit:P("policy_blocked","blocked",!1,!1,"Creators may acquire their own skill once for life, including after a refund.",[4]),creator_eval_live_network_unsupported:P("policy_blocked","blocked",!1,!0,"The controlled evaluator does not support live external network access.",[4]),payout_settlement_pending:P("conflict","conflict",!0,!0,"Converted payout funds are not yet available",[4]),payout_settlement_mismatch:P("operation_not_allowed","operation_not_allowed",!1,!0,"Payout settlement requires administrator review",[4]),payout_recovery_pending:P("verification_pending","verification_pending",!1,!0,"Returned payout funds require reconciliation",[4]),platform_balance_insufficient:P("conflict","conflict",!0,!0,"Platform funds are temporarily insufficient; retry later",[4]),connected_balance_insufficient:P("conflict","conflict",!0,!0,"Connected account funds cannot cover this bank payout; review settlement and account balance",[4]),platform_balance_unavailable:P("backend_unreachable","unavailable",!0,!0,"Platform funds could not be checked; retry later",[5]),payout_provider_refused:P("operation_not_allowed","error",!1,!0,"The payment provider refused the payout; check payout configuration before retrying",[4]),payout_outcome_unknown:P("verification_pending","hold",!1,!0,"Payout outcome needs reconciliation before retrying",[5]),enterprise_member_already_active:P("conflict","conflict",!1,!1,"This person is already an active Enterprise member.",[4]),local_cleanup_incomplete:P("human_action_required","error",!0,!0,"Unlock the OS credential store and retry logout to finish local cleanup.",[4,5]),admin_step_up_invalid:P("security_verification_failed","error",!1,!0,"Verify your administrator step-up key in the private operator checkout.",[4]),verification_code_locked:P("rate_limited","rate_limited",!0,!0,"This code is locked. Request a new code after the retry time.",[4]),conflicting_flags:P("invalid_input","error",!1,!0,"Choose a value or its clear flag, not both.",[4]),flag_value_missing:P("invalid_input","error",!1,!0,"Supply a value for the flag.",[4]),rights_attestation_required:P("precondition_required","error",!1,!0,"Public and unlisted releases require confirmation of distribution rights.",[4]),rights_attestation_invalid:P("invalid_input","error",!1,!0,"Supply a supported rights basis and public distribution scope.",[4]),catalogue_artifact_unavailable:P("backend_unreachable","error",!0,!0,"The catalogue artifact could not be downloaded; retry export.",[4]),admin_mfa_required:P("human_action_required","human_action_required",!1,!0,"Enable MFA with skills-layer auth mfa setup, then retry.",[4]),admin_mfa_unavailable:P("backend_unreachable","unavailable",!0,!0,"Administrator MFA is unavailable; contact the deployment operator.",[5]),source_read_unavailable:P("backend_unreachable","source_unavailable",!1,!0,"The source could not be read completely. Its package has not been assessed.",[5]),command_failed:P("internal_error","error",!1,!1,"The command could not be completed.",[5]),resource_not_found:P("not_found","not_found",!1,!0,"The requested resource was not found.",[4]),permission_denied:P("permission_denied","error",!1,!1,"This credential cannot perform the requested operation.",[4]),login_required:P("login_required","login_required",!1,!0,"Sign in is required.",[4]),unauthorized:P("login_required","login_required",!1,!0,"Sign in is required.",[4]),api_key_invalid_or_expired:P("login_required","login_required",!1,!0,"The saved API key is no longer valid. Sign in again to use account features.",[4]),confirmation_required:P("confirmation_required","human_action_required",!1,!0,"Human confirmation is required.",[4]),mfa_setup_required:P("human_action_required","human_action_required",!1,!0,"MFA setup is required.",[4]),login_mfa_required:P("human_action_required","human_action_required",!1,!0,"A second authentication factor is required.",[4]),login_mfa_input_invalid:P("invalid_input","error",!1,!0,"Provide exactly one supported MFA proof.",[4]),login_mfa_invalid:P("security_verification_failed","error",!1,!0,"The MFA proof was invalid or already used.",[4]),login_security_unavailable:P("security_verification_failed","security_unavailable",!0,!0,"Login security is unavailable.",[5]),mfa_challenge_locked:P("rate_limited","rate_limited",!0,!0,"The MFA challenge is temporarily locked.",[4]),social_secure_continuation_unavailable:P("security_verification_failed","security_unavailable",!1,!0,"Secure social continuation is unavailable.",[4,5]),social_continuation_terminal:P("security_verification_failed","error",!1,!0,"The social continuation ended without authorization.",[4]),verification_code_expired:P("human_action_required","error",!1,!0,"The verification code expired.",[4]),payout_human_confirmation_required:P("human_action_required","human_action_required",!1,!0,"Human payout confirmation is required.",[4]),security_report_requires_action:P("policy_blocked","blocked",!1,!0,"The security report requires action.",[4]),trust_report_not_actionable:P("policy_blocked","blocked",!1,!0,"The trust report does not permit this transition.",[4]),trust_report_authority_mismatch:P("security_verification_failed","blocked",!1,!0,"Trust evidence does not match the exact artifact generation.",[4,5]),trust_report_required_evidence_unavailable:P("verification_pending","action_required",!0,!0,"Required trust evidence is unavailable or incomplete.",[2,4,5]),sarif_source_mapping_required:P("precondition_required","error",!1,!0,"Repository SARIF requires verified repository-relative source locations.",[4]),sarif_security_evidence_required:P("precondition_required","error",!1,!0,"Runtime-audit SARIF requires typed security evidence.",[4]),sarif_rule_mapping_required:P("precondition_required","error",!1,!0,"Runtime-audit SARIF requires an explicit reviewed rule mapping for every actionable event.",[4]),sarif_profile_unsupported:P("invalid_input","error",!1,!0,"The requested SARIF profile is not available for this report audience.",[4]),cloud_trust_ledger_mismatch:P("security_verification_failed","blocked",!1,!0,"This exact public skill generation is temporarily unavailable because its Cloud Trust Ledger attestation does not match. A Skills Layer operator must re-attest the exact generation before install.",[4]),api_key_active_limit_reached:P("quota_exceeded","conflict",!1,!0,"The active API-key limit has been reached.",[4]),rate_limited:P("rate_limited","rate_limited",!0,!0,"The request rate limit was reached.",[4]),source_connection_already_canceled:P("unchanged","unchanged",!1,!1,"The source connection was already canceled.",[2,4]),source_connection_completed:P("conflict","conflict",!1,!1,"A completed source connection cannot be canceled.",[4]),source_connection_revoked:P("unchanged","unchanged",!1,!1,"The authorized source connection was revoked.",[0]),source_connection_already_revoked:P("unchanged","unchanged",!1,!1,"The source connection was already revoked.",[0]),source_connection_not_authorized:P("conflict","conflict",!1,!1,"Only an authorized source connection can be revoked.",[4]),reupload_required:P("precondition_required","reupload_required",!1,!0,"The stored artifact is unavailable; upload the bundle again.",[4]),artifact_finalization_failed:P("processing_action_required","partial_success",!0,!1,"The version exists but artifact finalisation is incomplete.",[0]),publication_moderation_failed:P("processing_action_required","partial_success",!1,!1,"The version exists but its moderation transition needs operator inspection.",[0]),source_connection_completion_unverified:P("verification_pending","verification_warning",!0,!0,"Source connection completion could not be verified.",[4,5]),admin_mcp_verification_warning:P("verification_pending","verification_warning",!0,!0,"Administrator MCP verification is pending.",[2,4,5]),admin_mcp_verification_rejected:P("security_verification_failed","rejected",!1,!0,"Administrator MCP verification was rejected.",[4]),authoritative_security_report_pending:P("processing_action_required","already_processing",!0,!0,"The authoritative security report is still processing.",[4]),publication_continuation_scheduled:P("processing_action_required","already_processing",!0,!1,"Publication is continuing through the durable exact-generation workflow.",[2,4]),binary_inspection_pending:P("processing_action_required","already_processing",!0,!0,"Binary asset security inspection is still processing.",[2,4]),binary_inspection_unavailable:P("verification_pending","hold",!0,!0,"Required binary asset security inspection is currently unavailable.",[2,4,5]),binary_asset_blocked:P("policy_blocked","blocked",!1,!0,"A binary asset did not satisfy the platform security policy.",[2,4]),binary_profile_suspended:P("policy_blocked","hold",!0,!0,"The required binary format profile is temporarily suspended.",[2,4]),security_adjudication_pending:P("processing_action_required","already_processing",!0,!0,"Contextual security evidence is still being evaluated.",[2,4]),content_adjudication_insufficient_evidence:P("verification_pending","hold",!0,!0,"The available evidence is insufficient to resolve the security finding.",[2,4]),content_adjudication_confirmed_risk:P("policy_blocked","blocked",!1,!0,"The exact content contains a confirmed security risk.",[2,4]),content_adjudication_source_remediation_required:P("policy_blocked","blocked",!1,!0,"The source must be changed before security review can continue.",[2,4]),content_adjudication_execution_failed:P("verification_pending","hold",!0,!0,"Content security adjudication could not complete and remains held.",[2,4,5]),content_probe_runner_unavailable:P("verification_pending","hold",!0,!0,"The isolated content security evaluator is currently unavailable.",[2,4,5]),binary_inspection_authority_invalid:P("security_verification_failed","hold",!0,!0,"Binary security evidence could not be authenticated.",[2,4,5]),managed_security_pack_stale:P("security_verification_failed","hold",!0,!0,"A required managed security definition pack is not current.",[2,4,5]),workflow_dependency_incomplete:P("precondition_required","waiting_for_dependency",!0,!0,"A required upstream workflow is incomplete.",[4]),creator_processing_sla_breached:P("processing_action_required","action_required",!1,!0,"Creator processing exceeded its platform SLA.",[4,5]),invalid_global_option:P("invalid_input","error",!1,!0,"A global CLI option is invalid.",[4]),invalid_numeric_input:P("invalid_input","error",!1,!0,"A numeric option is invalid.",[4]),unknown_flag:P("invalid_input","error",!1,!0,"The option is not supported.",[4]),unknown_command:P("invalid_input","error",!1,!0,"The command is not supported.",[4]),unknown_subcommand:P("invalid_input","error",!1,!0,"The command is not supported.",[4]),missing_required_argument:P("invalid_input","error",!1,!0,"Required information is missing.",[4]),invalid_json:P("invalid_input","error",!1,!0,"The JSON value is invalid.",[4]),canonical_bundle_rejected:P("invalid_input","error",!1,!0,"The bundle failed canonical validation.",[4]),recovery_code_invalid_or_expired:P("human_action_required","error",!1,!0,"The recovery code is invalid or expired.",[4]),social_provider_not_configured:P("precondition_required","error",!1,!0,"The selected social provider is not configured.",[4,5]),search_selection_not_found:P("not_found","not_found",!1,!0,"The selected skill is not present in these search results.",[4]),best_effort:P("unchanged","low_confidence",!1,!0,"Best-effort candidates need a more specific task for higher confidence.",[2]),unsafe_task:P("policy_blocked","policy_blocked",!1,!0,"This task is outside the recommendation safety policy.",[2]),no_confident_recommendation:P("unchanged","no_confident_recommendation",!1,!0,"No skill met the calibrated recommendation confidence policy.",[2]),clarification_required:P("human_action_required","clarification_required",!1,!0,"One public task constraint is required before a skill can be recommended.",[2]),workspace_required:P("precondition_required","error",!1,!0,"A workspace id is required for this install.",[4]),unsupported_skill_type:P("invalid_input","error",!1,!0,"The requested skill type is unsupported.",[4]),creator_resource_not_found:P("not_found","not_found",!1,!0,"The creator resource was not found.",[4]),creator_access_required:P("permission_denied","access_required",!1,!0,"Creator management access is required for this public skill.",[4]),library_access_required:P("permission_denied","access_required",!1,!0,"Library access is required to inspect issues for this public skill.",[4]),issue_not_found:P("not_found","not_found",!1,!0,"The issue was not found in the managed skill.",[4]),review_not_found:P("not_found","not_found",!1,!0,"The review was not found in the managed skill.",[4]),api_key_not_found:P("not_found","not_found",!1,!0,"The API key was not found.",[4]),approval_request_not_found:P("not_found","not_found",!1,!0,"The approval request was not found.",[4]),available:P("unchanged","available",!1,!1,"The requested capability is available.",[2]),catalog_acquisition_ready:P("unchanged","ready",!1,!1,"The catalog acquisition is ready.",[2]),catalog_artifact_unavailable:P("precondition_required","error",!0,!0,"The exact catalog artifact is temporarily unavailable.",[4,5]),compare_missing_skills:P("not_found","not_found",!1,!0,"One or more skills requested for comparison were not found.",[4]),conflicting_export_output:P("conflict","conflict",!1,!0,"The requested export output options conflict.",[4]),conflicting_mcp_client_selection:P("conflict","conflict",!1,!0,"The MCP client selection is ambiguous.",[4]),conflicting_mcp_migration_mode:P("conflict","conflict",!1,!0,"Choose either a legacy MCP migration preview or an apply operation.",[4]),needs_mcp_client_choice:P("human_action_required","needs_mcp_client_choice",!1,!0,"Choose a verified MCP host before setup can continue.",[4]),mcp_config_symlink_rejected:P("human_action_required","mcp_setup_blocked",!1,!0,"Replace the MCP config symlink with a regular user-owned config file before retrying.",[4]),mcp_registration_ownership_ambiguous:P("human_action_required","mcp_setup_blocked",!1,!0,"Review or rename the existing unowned Skills Layer MCP entry before retrying.",[4]),mcp_client_scope_required:P("human_action_required","needs_mcp_client_scope",!1,!0,"Choose one configured MCP host or explicitly select all hosts.",[4]),mcp_client_inventory_missing:P("precondition_required","mcp_needs_repair",!1,!0,"The local MCP configuration has no canonical host inventory.",[4]),mcp_legacy_project_path_required:P("precondition_required","error",!1,!0,"Choose the exact project root to inspect for legacy MCP registration.",[4]),mcp_multi_client_verify_failed:P("verification_pending","mcp_needs_repair",!0,!0,"One or more configured MCP hosts failed verification.",[4,5]),unknown_mcp_client:P("unsupported_client","error",!1,!0,"The requested MCP host is unsupported.",[4]),creator_listing_not_found_or_not_owned:P("not_found","not_found",!1,!0,"The creator listing is unavailable to this account.",[4]),creator_submission_not_found:P("not_found","not_found",!1,!0,"The creator submission was not found.",[4]),enterprise_resource_not_found:P("not_found","not_found",!1,!0,"The Enterprise resource was not found.",[4]),enterprise_checkout_completion_pending:P("processing_action_required","completion_pending",!0,!0,"Enterprise checkout completion is still being reconciled.",[2,5]),guardian_enabled:P("unchanged","enabled",!1,!1,"Guardian enforcement is enabled.",[2]),feature_already_configured:P("unchanged","unchanged",!1,!1,"The requested feature state is already configured.",[2]),guardian_exact_version_required:P("precondition_required","error",!1,!0,"Guardian requires one exact skill version.",[4]),guardian_unmanaged_atomic_execution_required:P("precondition_required","blocked",!1,!0,"Unmanaged execution cannot be authorized by a diagnostic Guardian check.",[4]),guardian_plan_resolution_failed:P("internal_error","error",!0,!0,"Guardian could not resolve a safe execution plan.",[4,5]),guardian_version_not_current:P("conflict","conflict",!1,!0,"The selected Guardian version is not current.",[4]),human_handoff_required:P("human_action_required","human_action_required",!1,!0,"A human must complete this handoff.",[2,4]),invalid_amount_cents:P("invalid_input","error",!1,!0,"The amount must be a valid non-negative number of cents.",[4]),invalid_enterprise_role:P("invalid_input","error",!1,!0,"The Enterprise role is invalid.",[4]),invalid_expiry:P("invalid_input","error",!1,!0,"The expiry value is invalid.",[4]),invalid_incident_path:P("invalid_input","error",!1,!0,"The incident path is invalid.",[4]),invalid_issue_status:P("invalid_input","error",!1,!0,"The issue status is invalid.",[4]),invalid_price_cents:P("invalid_input","error",!1,!0,"The price must be a valid non-negative number of cents.",[4]),invalid_review_status:P("invalid_input","error",!1,!0,"The review status is invalid.",[4]),invalid_scope:P("invalid_input","error",!1,!0,"The requested scope is invalid.",[4]),invalid_search_filter:P("invalid_input","error",!1,!0,"The search filter is invalid.",[4]),invalid_seats:P("invalid_input","error",!1,!0,"The Enterprise seat count is invalid.",[4]),invalid_sort:P("invalid_input","error",!1,!0,"The requested sort mode is invalid.",[4]),invalid_source:P("invalid_input","error",!1,!0,"The requested source is invalid.",[4]),invalid_version:P("invalid_input","error",!1,!0,"The semantic version is invalid.",[4]),local_install_not_found:P("not_found","not_found",!1,!0,"The local installation was not found.",[4]),local_source_requires_client_files:P("precondition_required","error",!1,!0,"This local source requires client-provided files.",[4]),ownership_claim_not_found:P("not_found","not_found",!1,!0,"The ownership claim was not found.",[4]),ownership_dispute_open:P("human_action_required","manual_review_required",!1,!0,"An ownership dispute requires human resolution.",[2,4]),ownership_already_configured:P("unchanged","unchanged",!1,!1,"The requested ownership assignments are already configured.",[2]),org_dependency_audit_incomplete:P("precondition_required","hold",!0,!0,"The organization dependency audit is incomplete.",[2,4]),purchase_not_found:P("not_found","not_found",!1,!0,"The purchase was not found.",[4]),restore_record_not_found:P("not_found","not_found",!1,!0,"No restorable installation record was found.",[4]),scaffold_overwrite_confirmation_required:P("confirmation_required","human_action_required",!1,!0,"Overwriting the scaffold requires confirmation.",[4]),security_report_requires_review:P("policy_blocked","manual_review_required",!1,!0,"The security report requires human review.",[2,4]),security_report_missing:P("not_found","not_found",!1,!0,"The security report was not found.",[4]),platform_score_subject_missing:P("not_found","not_found",!1,!0,"The exact Platform Score skill generation was not found.",[4]),security_evidence_operation_not_found:P("not_found","not_found",!1,!0,"The security evidence operation was not found.",[4]),skill_not_found:P("not_found","not_found",!1,!0,"The skill was not found.",[4]),social_browser_confirmation_required:P("human_action_required","human_action_required",!1,!0,"Social sign-in requires browser confirmation.",[4]),source_connection_not_found:P("not_found","not_found",!1,!0,"The source connection was not found.",[4]),source_not_verifiable:P("policy_blocked","manual_review_required",!1,!0,"The source cannot be verified automatically.",[2,4]),source_path_not_found:P("not_found","not_found",!1,!0,"The source path was not found.",[4]),source_reference_not_found:P("not_found","not_found",!1,!0,"The source reference was not found.",[4]),submission_not_found:P("not_found","not_found",!1,!0,"The submission was not found.",[2,4]),trust_report_not_found:P("not_found","not_found",!1,!0,"The Platform Score report was not found.",[4]),unknown_agent:P("unsupported_client","error",!1,!0,"The requested agent is unsupported.",[4]),verification_code_invalid:P("human_action_required","error",!1,!0,"The verification code is invalid or expired.",[4]),workspace_not_found_or_forbidden:P("not_found","not_found",!1,!0,"The workspace is unavailable to this account.",[4]),workspace_skill_approval_not_found:P("not_found","not_found",!1,!0,"The workspace skill approval was not found.",[4]),workspace_working_mode_not_found:P("not_found","not_found",!1,!0,"The selected workspace was not found.",[4])};function Bee(e){let t=CN[e];return t?{reasonCode:e,...t}:null}function Fg(e,t={}){if(!e)return t.httpStatus===404?Pa("resource_not_found"):t.httpStatus===401?Pa("login_required"):t.httpStatus===403?Pa("permission_denied"):t.httpStatus===409?gt("conflict","conflict"):t.httpStatus===429?Pa("rate_limited"):(t.httpStatus&&t.httpStatus>=500,Pa("command_failed"));let n=Bee(e);return n||(e.includes("not_found")||e==="missing_record"?gt(e,"not_found","not_found"):e.includes("rate_limit")?gt(e,"rate_limited","rate_limited",!0):e.includes("quota")||e.includes("_limit_reached")||e.includes("_limit_exhausted")?gt(e,"quota_exceeded","conflict"):e.includes("human")||e.includes("mfa")||e.includes("browser_confirmation")?gt(e,"human_action_required","human_action_required"):e.includes("already_canceled")||e.includes("unchanged")||e.includes("already_complete")?gt(e,"unchanged","unchanged"):e.includes("dependency")||e.includes("precondition")||e.includes("required")?gt(e,"precondition_required","error"):e.includes("processing")||e.includes("pending")||e.includes("already_processing")?gt(e,"processing_action_required","already_processing",!0):e.includes("conflict")||e.includes("already_final")||e.includes("completed")?gt(e,"conflict","conflict"):e.includes("payment")||e.includes("checkout")||e.includes("purchase")?gt(e,"payment_required","human_action_required"):e.includes("source")?gt(e,"source_required","error"):e.includes("backend")||e.includes("unreachable")||e.includes("network")?gt(e,"backend_unreachable","error",!0):e.includes("agent")||e.includes("client")||e.includes("unsupported")?gt(e,"unsupported_client","error"):e.includes("blocked")||e.includes("policy")||e.includes("guardian")?gt(e,"policy_blocked","blocked"):e.includes("forbidden")||e.includes("permission_denied")?gt(e,"permission_denied","error"):e.includes("not_allowed")||e.includes("invalid_transition")?gt(e,"operation_not_allowed","error"):gt(e,"invalid_input","error"))}function P(e,t,n,r,i,o){return{family:e,defaultStatus:t,retryable:n,nextActionRequired:r,safeSummary:i,allowedHttpStatusClasses:o}}function Pa(e){return{reasonCode:e,...CN[e]}}function gt(e,t,n="error",r=!1){return{reasonCode:e,family:t,defaultStatus:n,retryable:r,nextActionRequired:!1,safeSummary:"The command could not be completed.",allowedHttpStatusClasses:[4,5]}}var IN=[["help","account"],["help","use"],["help","creator"],["help","teams"],["help","security"],["help","mcp"],["help","automation"],["help","troubleshoot"],["help","full"]],PN=[["help"],["help","topic"],["login"],["logout"],["register"],["setup"],["whoami"],["profile"],["profile","update"],["auth"],["auth","status"],["auth","repair"],["auth","verify"],["auth","recover"],["auth","recover","complete"],["auth","connect"],["auth","mfa"],["auth","mfa","status"],["auth","mfa","setup"],["auth","mfa","verify"],["auth","mfa","recovery-codes"],["auth","mfa","disable"],["api-key"],["api-key","create"],["api-key","list"],["api-key","revoke"],["mcp"],["mcp","setup"],["mcp","status"],["mcp","verify"],["mcp","repair"],["mcp","migrate"],["mcp","disconnect"],["backend"],["backend","status"],["backend","cloud"],["backend","local"],["status"],["doctor"],["search"],["find"],["featured"],["trending"],["show"],["trust"],["recommend"],["categories"],["compare"],["install"],["install","status"],["installed"],["owned"],["export"],["add-review"],["show-reviews"],["add-issue"],["show-issues"],["purchases"],["purchases","list"],["purchases","invoice"],["purchases","status"],["purchases","refund-quote"],["purchases","refund"],["purchases","spending"],["validate"],["preview-trigger"],["creator"],["creator","init"],["creator","create"],["creator","sessions"],["creator","resume"],["creator","inspect"],["creator","answer"],["creator","resources"],["creator","resource-decide"],["creator","tool-contract"],["creator","draft"],["creator","validate"],["creator","eval"],["creator","improve"],["creator","revise"],["creator","materialize"],["creator","finalize"],["creator","rules"],["creator","submissions"],["creator","spaces"],["creator","spaces","buy"],["creator","status"],["creator","source"],["creator","source","prepare"],["creator","source","publish-request"],["creator","source","release-status"],["creator","submit"],["creator","submit-version"],["creator","check-slug"],["creator","rename"],["creator","pricing"],["creator","delist"],["creator","relist"],["creator","update-listing"],["creator","visibility"],["creator","security-report"],["creator","rescan-security"],["creator","provenance"],["creator","claim"],["creator","verify"],["creator","dispute"],["creator","issues"],["creator","update-issue"],["creator","reviews"],["creator","moderate-review"],["creator","analytics"],["creator","earnings"],["creator","payout-profile"],["creator","payout-link"],["creator","payouts"],["creator","withdraw"],["source"],["source","connection"],["source","connection","start"],["source","connection","status"],["source","connection","complete"],["source","connection","cancel"],["source","connection","revoke"],["source","reference"],["source","reference","resolve"],["approval"],["approval","request"],["approval","request","status"],["approval","request","complete"],["enterprise"],["enterprise","accept-invite"],["enterprise","checkout"],["enterprise","install-authorize"],["enterprise","list"],["enterprise","member"],["enterprise","member","remove"],["enterprise","member","role"],["enterprise","members"],["enterprise","rename"],["enterprise","primary-admin"],["enterprise","primary-admin","transfer"],["enterprise","primary-admin","status"],["enterprise","primary-admin","accept"],["enterprise","primary-admin","cancel"],["enterprise","seats"],["enterprise","seats","add"],["enterprise","invite"],["enterprise","invites"],["enterprise","revoke-invite"],["enterprise","resend-invite"],["enterprise","workspace-member"],["enterprise","workspace-member","list"],["enterprise","workspace-member","add"],["enterprise","workspace-member","remove"],["enterprise","workspace"],["enterprise","workspace","create"],["enterprise","workspace","rename"],["enterprise","workspace","update"],["enterprise","workspace","archive"],["enterprise","workspaces"],["enterprise","skill"],["enterprise","skill","entitlements"],["enterprise","skill","quote"],["enterprise","skill","buy"],["workspace"],["workspace","list"],["workspace","current"],["workspace","select"],["workspace","request"],["workspace","approve"],["workspace","reject"],["workspace","skills"],["workspace","guide"],["workspaces"],["guardian"],["guardian","check"],["guardian","incident"],["guardian","enable"],["guardian","disable"],["guardian","enable-warnings-only"],["guardian","status"],["guardian","hook"],["guardian","hook","install"],["guardian","hook","status"],["guardian","launch"],["guardian","exec"],["agents"],["agents","list"],["import"],["sync"],["restore"],["check"],["update"],["remove"],["identity"],["identity","providers"],["identity","start"],["identity","continue"],["identity","status"],["identity","complete"],["identity","list"],["identity","unlink"],["library"],["buy"]],Mee=1+IN.length+PN.length;var Co="0.2.26";var Uee="skills-layer-cli-event-v1";function RN(e){let t=0,n=e.now??(()=>new Date().toISOString());return(r,i)=>{let o=Di(i.summary,"summary",512),s=i.redactedDetail===void 0?void 0:Di(i.redactedDetail,"redacted detail",2048),a=i.next?.map(u=>({id:Di(u.id,"next-action ID",128),kind:u.kind,label:Di(u.label,"next-action label",512),...u.command===void 0?{}:{command:{executable:u.command.executable,args:u.command.args.map(d=>Di(d,"next-action argument",1024))}},...u.url===void 0?{}:{url:AN(u.url)},safeToAutoRun:u.safeToAutoRun,requiresHuman:u.requiresHuman,...u.rationale===void 0?{}:{rationale:Di(u.rationale,"next-action rationale",1024)},safety:u.safety})),l=i.links?.map(u=>{let d=AN(u.url);return{label:Di(u.label,"link label",512),url:d}}),c=i.data===void 0?void 0:sI(i.data);return t+=1,{schemaVersion:Uee,operationId:H(e.operationId),sequence:t,timestamp:n(),type:r,command:{name:H(e.command.name)},...i,summary:o,...s===void 0?{}:{redactedDetail:s},...a===void 0?{}:{next:a},...l===void 0?{}:{links:l},...c===void 0?{}:{data:c}}}}function AN(e){let t=Di(e,"link URL",2048);if(!/^https?:\/\//u.test(t))throw new Error("CLI event links must use http or https URLs.");return t}function Di(e,t,n){let r=H(e);if(r.length>n)throw new Error(`CLI event ${t} exceeds ${n} characters.`);return r}function sI(e,t=""){return/^(?:accessToken|apiKey|authorization|clientSecret|handoffCode|password|refreshToken|secret)$/iu.test(t)?"[redacted-secret]":typeof e=="string"?H(e):Array.isArray(e)?e.map(n=>sI(n)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,sI(r,n)])):e}var zee=["human","json","stream-json"],EN=["auto","always","never"],qee=["auto","modern","classic"],Vee=["concise","standard","full"];function $N(e){let t=[],n={},r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(r){t.push(o);continue}if(o==="--"){r=!0,t.push(o);continue}let[s,a]=Gee(o);if(s==="--output-format"){let[l,c]=wu(s,a,e[i+1],zee);n.outputFormat=l,i+=c}else if(s==="--color"){let[l,c]=wu(s,a,e[i+1],EN);n.color=l,i+=c}else if(s==="--motion"){let[l,c]=wu(s,a,e[i+1],EN);n.motion=l,i+=c}else if(s==="--ui"){let[l,c]=wu(s,a,e[i+1],qee);n.ui=l,i+=c}else if(s==="--detail"){let[l,c]=wu(s,a,e[i+1],Vee);n.detail=l,i+=c}else o==="--no-color"?n.color="never":o==="--no-motion"?n.motion="never":o==="--screen-reader"?n.screenReader=!0:o==="--no-interactive"?n.interactive=!1:o==="--ascii"?n.unicode=!1:t.push(o)}return{args:t,options:n}}function DN(e,t,n){let r=e.outputFormat??"human",i=e.screenReader===!0,o=Bg(t.CI),s=t.TERM==="dumb",a=n.stdinIsTty&&n.stdoutIsTty&&n.stderrIsTty,l=e.ui!=="classic",c=e.ui==="classic",u=e.detail??(r==="human"?"concise":"standard"),d=a&&!o&&!s&&l&&!i&&e.interactive!==!1,p=d&&e.motion!=="never",m=d&&p,h=!i&&e.color!=="never"&&(e.color==="always"||!Bg(t.NO_COLOR)&&!c&&(Bg(t.FORCE_COLOR)||!o&&!s&&n.stdoutIsTty)),g=e.unicode!==!1&&!Bg(t.NO_UNICODE)&&!s;return r==="json"?{kind:"json-final",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:r==="stream-json"?{kind:"json-stream",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:{kind:m?"human-interactive":"human-static",color:h,motion:p,interactive:m,unicode:g,screenReader:i,classic:c,detail:u}}function Gee(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function wu(e,t,n,r){let i=t??n;if(i===void 0||i.startsWith("--")||!r.includes(i))throw new Error(`${e} expects one of: ${r.join(", ")}.`);return[i,t===void 0?1:0]}function Bg(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}var TN=()=>null;var Io=88,Hee=/(?:^|_)(?:blocked|cancelled|canceled|rejected|denied|expired|invalid|not_found|conflict|missing_required_argument)(?:$|_)/u,Kee=/(?:^|_)(?:required|requires_action|warning|unverified|completion_pending)(?:$|_)/u,Wee=/(?:^|_)(?:argument|field|input|parameter|protocol|value)_required(?:$|_)/u,Zee=/(?:^|_)(?:failed|failure|internal_error|network_error|service_unavailable|timed_out|timeout)(?:$|_)/u,Jee=/\b(?:required information is missing|unknown (?:command|option|flag)|invalid|already used|not found|blocked|cancelled|canceled|rejected|denied|expired|missing|not supported|could not be read|cannot write)\b/iu,Yee=/\b(?:action|approval|authentication|checkout|confirmation|consent|human action|login|mfa|payment|purchase|registration|second factor|secure account connection|sign in|source connection|verification|workspace approval)\b[^.\n]*\b(?:required|needed|must be completed)\b|\b(?:complete|confirm|continue)\b[^.\n]*\b(?:browser|cli|terminal)\b/iu,Xee=/\b(?:failed|failure|service unavailable|server error|network error|timed out|timeout|could not complete)\b/iu;function LN(e){let t=ON(e.status),n=ON(e.reasonCode),r=[t,n].filter(Boolean);return r.some(i=>Hee.test(i))?"stopped":r.some(i=>Kee.test(i)&&!Wee.test(i))?"required":r.some(i=>Zee.test(i))||e.summary&&aI(e.summary)==="failed"?"failed":e.exitCode!==void 0&&e.exitCode!==0?"stopped":"completed"}function aI(e){let t=Qee(e);return Jee.test(t)?"stopped":Yee.test(t)?"required":Xee.test(t)?"failed":"stopped"}function bu(e,t){let n=t?"\u2014":"-",r=e.slice(0,1).toUpperCase()+e.slice(1);return`Skills Layer ${n} Action ${r}`}function ON(e){return H(e??"").trim().toLowerCase().replace(/[^a-z0-9]+/gu,"_")}function Qee(e){return H(e).split(/\n(?:Unchanged|Why|Next|Reference)(?:\s|$)/u,1)[0]}function Po(e){return UN(Mn(e)).reduce((t,n)=>t+zN(n),0)}function jN(e,t){return e.split(`
2033
2033
  `).flatMap(n=>tte(n,t))}function Mg(e,t,n){let r=H(e),i=H(t),o=n.width-2;if(n.width<12||Po(r)+4>o)return i;let s=n.unicode?{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502"}:{topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|"},a=`${s.horizontal} ${r} `,l=n.border??(m=>m),c=l(`${s.topLeft}${a}${s.horizontal.repeat(o-Po(a))}${s.topRight}`),u=o-2,d=jN(i,u).map(m=>`${l(s.vertical)} ${cI(m,u)} ${l(s.vertical)}`),p=l(`${s.bottomLeft}${s.horizontal.repeat(o)}${s.bottomRight}`);return[c,...d,p].join(`
2034
2034
  `)}function Ke(e,t){return`${H(e)}
2035
2035
  ${H(t)}`}function Ug(e,t){let n=t?"\u2022":"-";return e.map(r=>`${n} ${H(r)}`).join(`
@@ -2058,8 +2058,8 @@ ${H(t)}`}function Ug(e,t){let n=t?"\u2022":"-";return e.map(r=>`${n} ${H(r)}`).j
2058
2058
  `).pop()??"",Ru=class{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(t){this.rl=t,this.cursorPos=t.getCursorPos()}write(t){this.rl.output.unmute(),this.rl.output.write(t),this.rl.output.mute()}render(t,n=""){let r=une(t),i=cne(r),o=i;this.rl.line.length>0&&(o=o.slice(0,-this.rl.line.length)),this.rl.setPrompt(o),this.cursorPos=this.rl.getCursorPos();let s=Xg();t=Au(t,s),n=Au(n,s),i.length%s===0&&(t+=`
2059
2059
  `);let a=t+(n?`
2060
2060
  `+n:""),c=Math.floor(i.length/s)-this.cursorPos.rows+(n?VF(n):0);c>0&&(a+=BI(c)),a+=UI(this.cursorPos.cols),this.write(MI(this.extraLinesUnderPrompt)+zI(this.height)+a),this.extraLinesUnderPrompt=c,this.height=VF(a)}checkCursorPos(){let t=this.rl.getCursorPos();t.cols!==this.cursorPos.cols&&(this.write(UI(t.cols)),this.cursorPos=t)}done({clearContent:t}){this.rl.setPrompt("");let n=MI(this.extraLinesUnderPrompt);n+=t?zI(this.height):`
2061
- `,n+=qF,this.write(n),this.rl.close()}};var nh=class extends Promise{static withResolver(){let t,n;return{promise:new Promise((i,o)=>{t=i,n=o}),resolve:t,reject:n}}};function pne(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(n,r)=>{let i=r.slice(1);return t=i,i},new Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function qI(e){let t=pne();return(r,i={})=>{let{input:o=process.stdin,signal:s}=i,a=new Set,l=new HF.default;l.pipe(i.output??process.stdout);let c=GF.createInterface({terminal:!0,input:o,output:l}),u=new Ru(c),{promise:d,resolve:p,reject:m}=nh.withResolver(),h=()=>m(new Kg);if(s){let v=()=>m(new Hg({cause:s.reason}));if(s.aborted)return v(),Object.assign(d,{cancel:h});s.addEventListener("abort",v),a.add(()=>s.removeEventListener("abort",v))}a.add(th((v,b)=>{m(new Su(`User force closed the prompt with ${v} ${b}`))}));let g=()=>m(new Su("User force closed the prompt with SIGINT"));c.on("SIGINT",g),a.add(()=>c.removeListener("SIGINT",g));let y=()=>u.checkCursorPos();return c.input.on("keypress",y),a.add(()=>c.input.removeListener("keypress",y)),tF(c,v=>{let b=dne.bind(()=>Eo.clearAll());return c.on("close",b),a.add(()=>c.removeListener("close",b)),v(()=>{try{let w=e(r,P=>{setImmediate(()=>p(P))});if(w===void 0){let P=t[1]?.getFileName();throw new Error(`Prompt functions must return a string.
2062
- at ${P}`)}let[_,C]=typeof w=="string"?[w]:w;u.render(_,C),Eo.run()}catch(w){m(w)}}),Object.assign(d.then(w=>(Eo.clearAll(),w),w=>{throw Eo.clearAll(),w}).finally(()=>{a.forEach(w=>w()),u.done({clearContent:!!i.clearPromptOnDone}),l.end()}).then(()=>d),{cancel:h})})}}var KF=mn(Zg(),1);var lr=class{separator=KF.default.dim(Array.from({length:15}).join(Da.line));type="separator";constructor(t){t&&(this.separator=t)}static isSeparator(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="separator")}};var Na=mn(Zg(),1);var fne={icon:{cursor:Da.pointer},style:{disabled:e=>Na.default.dim(`- ${e}`),description:e=>Na.default.cyan(e),keysHelpTip:e=>e.map(([t,n])=>`${Na.default.bold(t)} ${Na.default.dim(n)}`).join(Na.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function ja(e){return!lr.isSeparator(e)&&!e.disabled}function mne(e){return e.map(t=>{if(lr.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let n=t.name??String(t.value),r={value:t.value,name:n,short:t.short??n,disabled:t.disabled??!1};return t.description&&(r.description=t.description),r})}var WF=qI((e,t)=>{let{loop:n=!0,pageSize:r=7}=e,i=xu(fne,e.theme),{keybindings:o}=i,[s,a]=Nr("idle"),l=bI({status:s,theme:i}),c=Do(),u=!o.includes("vim"),d=Cu(()=>mne(e.choices),[e.choices]),p=Cu(()=>{let N=d.findIndex(ja),O=d.findLastIndex(ja);if(N===-1)throw new Ea("[select prompt] No selectable choices. All choices are disabled.");return{first:N,last:O}},[d]),m=Cu(()=>"default"in e?d.findIndex(N=>ja(N)&&N.value===e.default):-1,[e.default,d]),[h,g]=Nr(m===-1?p.first:m),y=d[h];_I((N,O)=>{if(clearTimeout(c.current),vI(N))a("done"),t(y.value);else if(_u(N,o)||Gg(N,o)){if(O.clearLine(0),n||_u(N,o)&&h!==p.first||Gg(N,o)&&h!==p.last){let X=_u(N,o)?-1:1,G=h;do G=(G+X+d.length)%d.length;while(!ja(d[G]));g(G)}}else if(yI(N)&&!Number.isNaN(Number(O.line))){let X=Number(O.line)-1,G=-1,ee=d.findIndex(Q=>lr.isSeparator(Q)?!1:(G++,G===X)),te=d[ee];te!=null&&ja(te)&&g(ee),c.current=setTimeout(()=>{O.clearLine(0)},700)}else if(hI(N))O.clearLine(0);else if(u){let X=O.line.toLowerCase(),G=d.findIndex(ee=>lr.isSeparator(ee)||!ja(ee)?!1:ee.name.toLowerCase().startsWith(X));G!==-1&&g(G),c.current=setTimeout(()=>{O.clearLine(0)},700)}}),$o(()=>()=>{clearTimeout(c.current)},[]);let v=i.style.message(e.message,s),b;if(i.helpMode!=="never")if(e.instructions){let{pager:N,navigation:O}=e.instructions;b=i.style.help(d.length>r?N:O)}else b=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let w=0,_=$I({items:d,active:h,renderItem({item:N,isActive:O,index:X}){if(lr.isSeparator(N))return w++,` ${N.separator}`;let G=i.indexMode==="number"?`${X+1-w}. `:"";if(N.disabled){let Q=typeof N.disabled=="string"?N.disabled:"(disabled)";return i.style.disabled(`${G}${N.name} ${Q}`)}let ee=O?i.style.highlight:Q=>Q,te=O?i.icon.cursor:" ";return ee(`${te} ${G}${N.name}`)},pageSize:r,loop:n});if(s==="done")return[l,v,i.style.answer(y.short)].filter(Boolean).join(" ");let{description:C}=y;return`${[[l,v].filter(Boolean).join(" "),_," ",C?i.style.description(C):"",b].filter(Boolean).join(`
2061
+ `,n+=qF,this.write(n),this.rl.close()}};var nh=class extends Promise{static withResolver(){let t,n;return{promise:new Promise((i,o)=>{t=i,n=o}),resolve:t,reject:n}}};function pne(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(n,r)=>{let i=r.slice(1);return t=i,i},new Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function qI(e){let t=pne();return(r,i={})=>{let{input:o=process.stdin,signal:s}=i,a=new Set,l=new HF.default;l.pipe(i.output??process.stdout);let c=GF.createInterface({terminal:!0,input:o,output:l}),u=new Ru(c),{promise:d,resolve:p,reject:m}=nh.withResolver(),h=()=>m(new Kg);if(s){let v=()=>m(new Hg({cause:s.reason}));if(s.aborted)return v(),Object.assign(d,{cancel:h});s.addEventListener("abort",v),a.add(()=>s.removeEventListener("abort",v))}a.add(th((v,b)=>{m(new Su(`User force closed the prompt with ${v} ${b}`))}));let g=()=>m(new Su("User force closed the prompt with SIGINT"));c.on("SIGINT",g),a.add(()=>c.removeListener("SIGINT",g));let y=()=>u.checkCursorPos();return c.input.on("keypress",y),a.add(()=>c.input.removeListener("keypress",y)),tF(c,v=>{let b=dne.bind(()=>Eo.clearAll());return c.on("close",b),a.add(()=>c.removeListener("close",b)),v(()=>{try{let w=e(r,A=>{setImmediate(()=>p(A))});if(w===void 0){let A=t[1]?.getFileName();throw new Error(`Prompt functions must return a string.
2062
+ at ${A}`)}let[_,C]=typeof w=="string"?[w]:w;u.render(_,C),Eo.run()}catch(w){m(w)}}),Object.assign(d.then(w=>(Eo.clearAll(),w),w=>{throw Eo.clearAll(),w}).finally(()=>{a.forEach(w=>w()),u.done({clearContent:!!i.clearPromptOnDone}),l.end()}).then(()=>d),{cancel:h})})}}var KF=mn(Zg(),1);var lr=class{separator=KF.default.dim(Array.from({length:15}).join(Da.line));type="separator";constructor(t){t&&(this.separator=t)}static isSeparator(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="separator")}};var Na=mn(Zg(),1);var fne={icon:{cursor:Da.pointer},style:{disabled:e=>Na.default.dim(`- ${e}`),description:e=>Na.default.cyan(e),keysHelpTip:e=>e.map(([t,n])=>`${Na.default.bold(t)} ${Na.default.dim(n)}`).join(Na.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function ja(e){return!lr.isSeparator(e)&&!e.disabled}function mne(e){return e.map(t=>{if(lr.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let n=t.name??String(t.value),r={value:t.value,name:n,short:t.short??n,disabled:t.disabled??!1};return t.description&&(r.description=t.description),r})}var WF=qI((e,t)=>{let{loop:n=!0,pageSize:r=7}=e,i=xu(fne,e.theme),{keybindings:o}=i,[s,a]=Nr("idle"),l=bI({status:s,theme:i}),c=Do(),u=!o.includes("vim"),d=Cu(()=>mne(e.choices),[e.choices]),p=Cu(()=>{let N=d.findIndex(ja),O=d.findLastIndex(ja);if(N===-1)throw new Ea("[select prompt] No selectable choices. All choices are disabled.");return{first:N,last:O}},[d]),m=Cu(()=>"default"in e?d.findIndex(N=>ja(N)&&N.value===e.default):-1,[e.default,d]),[h,g]=Nr(m===-1?p.first:m),y=d[h];_I((N,O)=>{if(clearTimeout(c.current),vI(N))a("done"),t(y.value);else if(_u(N,o)||Gg(N,o)){if(O.clearLine(0),n||_u(N,o)&&h!==p.first||Gg(N,o)&&h!==p.last){let X=_u(N,o)?-1:1,G=h;do G=(G+X+d.length)%d.length;while(!ja(d[G]));g(G)}}else if(yI(N)&&!Number.isNaN(Number(O.line))){let X=Number(O.line)-1,G=-1,ee=d.findIndex(Q=>lr.isSeparator(Q)?!1:(G++,G===X)),te=d[ee];te!=null&&ja(te)&&g(ee),c.current=setTimeout(()=>{O.clearLine(0)},700)}else if(hI(N))O.clearLine(0);else if(u){let X=O.line.toLowerCase(),G=d.findIndex(ee=>lr.isSeparator(ee)||!ja(ee)?!1:ee.name.toLowerCase().startsWith(X));G!==-1&&g(G),c.current=setTimeout(()=>{O.clearLine(0)},700)}}),$o(()=>()=>{clearTimeout(c.current)},[]);let v=i.style.message(e.message,s),b;if(i.helpMode!=="never")if(e.instructions){let{pager:N,navigation:O}=e.instructions;b=i.style.help(d.length>r?N:O)}else b=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let w=0,_=$I({items:d,active:h,renderItem({item:N,isActive:O,index:X}){if(lr.isSeparator(N))return w++,` ${N.separator}`;let G=i.indexMode==="number"?`${X+1-w}. `:"";if(N.disabled){let Q=typeof N.disabled=="string"?N.disabled:"(disabled)";return i.style.disabled(`${G}${N.name} ${Q}`)}let ee=O?i.style.highlight:Q=>Q,te=O?i.icon.cursor:" ";return ee(`${te} ${G}${N.name}`)},pageSize:r,loop:n});if(s==="done")return[l,v,i.style.answer(y.short)].filter(Boolean).join(" ");let{description:C}=y;return`${[[l,v].filter(Boolean).join(" "),_," ",C?i.style.description(C):"",b].filter(Boolean).join(`
2063
2063
  `).trimEnd()}${zF}`});function rh(e,t){return async(...n)=>{t.start?.();try{return await e(...n)}finally{t.end?.()}}}async function ZF(e,t,n={},r=WF){if(t.length===0)throw new Error("Interactive selection has no available options.");return r({message:e,choices:t.map(i=>({value:i.value,name:i.label,...i.description===void 0?{}:{description:i.description}})),loop:!0,pageSize:Math.min(12,Math.max(7,t.length)),instructions:{navigation:"Use arrow keys or type a number",pager:"Use page keys for more choices"}},n)}var Fa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},Et=(e,t="Unavailable")=>typeof e=="string"&&e.trim()?H(e.trim()):t,VI=e=>{let t=Et(e).replaceAll("_"," ");return t.charAt(0).toUpperCase()+t.slice(1)},JF=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=100?`${e}/100`:"Unavailable";function YF(e,t,n=88){let r=Fa(e.sourceDisclosure),i=Fa(e.platformScore),o=Fa(i.dimensions),s=Fa(e.securityPosture),a=Fa(e.price),l=i.availability==="available",c=[["Name",Et(e.name)],["Slug",Et(e.slug)],["Version",Et(e.currentVersion)],["Category",Et(e.category)],["Source",Et(r.sourceRepository)],["Licence",Et(r.identifier,Et(r.label))],["Price",Et(a.display)]];typeof e.catalogPublishedAt=="string"&&e.catalogPublishedAt.trim()?c.push(["Catalog published",Et(e.catalogPublishedAt)]):typeof e.platformPublishedAt=="string"&&e.platformPublishedAt.trim()&&c.push(["Platform published",Et(e.platformPublishedAt)]),t.detail==="full"&&c.push(["Source commit",Et(r.sourceCommitSha)]);let u=[["Platform score",l?JF(i.score):"Unavailable"],["Assessment",VI(l?i.decision:i.availability)]];if(l)for(let[y,v]of[["security_safety","Security and safety"],["runtime_access_control","Runtime access control"],["effectiveness_outcomes","Effectiveness and outcomes"],["trust_integrity","Trust and integrity"]])u.push([v,JF(o[y])]);let d=[["Runtime risk",VI(s.runtimeRisk)],["Security recommendation",VI(s.recommendation)]],p=typeof e.slug=="string"&&/^[a-z0-9][a-z0-9._-]*$/iu.test(e.slug)?e.slug:"<skill-slug>",m=t.detail==="full"?Et(e.fullDescription,Et(e.shortDescription,"No description available.")):Et(e.shortDescription,"No description available."),h=[Ke("Description",m),Ke("Skill",Aa(c,n)),Ke("Assessment",Aa(u,n)),Ke("Security",Aa(d,n)),...fI({effectiveness:{assessmentCoverage:Fa(e.effectiveness).assessmentCoverage}},ln(t)),Ke("Next",`Review security: skills-layer trust ${p}
2064
2064
  Preview installation: skills-layer install ${p} --dry-run`)],g=St(h.join(`
2065
2065
 
@@ -2148,7 +2148,7 @@ Run:
2148
2148
  `)}function die(e,t){let n=Ae(t),r=T(e,"entitlement"),i=r?f(r,"enterpriseId"):void 0,o=r?f(r,"skillSlug"):void 0,s=[`${n.ok("OK")} Enterprise skill is ready for workspace approval.`,"",n.section("Entitlement")];return s.push(` ${n.label("Skill")}: ${r?f(r,"skillName")??o??"unknown":"unknown"}`),o&&s.push(` ${n.label("Slug")}: ${o}`),r&&s.push(` ${n.label("Version")}: ${f(r,"version")??"latest"}`),i&&s.push(` ${n.label("Enterprise ID")}: ${i}`),s.push("",n.section("Next")),i&&s.push(` ${n.arrow} skills-layer enterprise skill entitlements ${i}`),o&&s.push(` ${n.arrow} skills-layer workspace approve <workspace-id> ${o}`),s.join(`
2149
2149
  `)}function pie(e,t){let n=Ae(t),r=T(e,"enterprise"),i=J(e,"addedSeats"),o=r?J(r,"seatCapacity"):void 0,s=r?J(r,"usedSeats"):void 0,a=r?J(r,"availableSeats"):void 0,l=[`${n.ok("OK")} ${i??"Additional"} Enterprise seat${i===1?"":"s"} added.`,"",n.section("Enterprise")];return l.push(` ${n.label("Name")}: ${r?f(r,"name")??"unknown":"unknown"}`),l.push(` ${n.label("ID")}: ${r?f(r,"enterpriseId")??"unknown":"unknown"}`),o!==void 0&&s!==void 0&&a!==void 0&&l.push(` ${n.label("Seats")}: ${s} used, ${a} available of ${o}`),l.push("",n.section("Next"),` ${n.arrow} skills-layer enterprise seats`),l.join(`
2150
2150
  `)}function fie(e,t){let n=e==="canceled"||e==="cancelled",r=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat checkout":"Enterprise skill checkout",i=t==="enterprise"?"No Enterprise, workspace, or seats were created.":t==="enterprise_seats"?"No seats were added and the Enterprise capacity is unchanged.":"No Enterprise skill entitlement was created and no workspace access changed.",o=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat purchase":"Enterprise skill purchase";return n?`${r} was cancelled. ${i} Rerun the ${o} command when you are ready.`:e==="expired"?`${r} expired. ${i} Start a new ${o} when you are ready.`:`${r} failed${e?` (${e})`:""}. ${i} Retry the ${o} command or contact support if payment was charged.`}function mie(e,t,n){let r=Ae(n),i=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat checkout":"Enterprise skill checkout";return[`${r.muted("!")} ${i} payment or provisioning may already be in progress.`,"",r.section("Status"),` ${r.label("Checkout ID")}: ${f(e,"checkoutId")??"unknown"}`,` ${r.label("State")}: Completion pending`,"",r.section("Next"),` ${r.arrow} ${f(e,"nextStep")??"Check the same checkout status again. Do not start a second checkout."}`].join(`
2151
- `)}function jt(e){if(e==="workspace_approved_only")return"Workspace-approved only";let t=e.replace(/[_-]+/gu," ").trim().toLowerCase();return t.length>0?t[0].toUpperCase()+t.slice(1):"Unknown"}function un(e,t,n,r,i){return r?R(e,n,!0,i):{exitCode:0,stdout:t,stderr:""}}function Ot(e){let t=rl(e);return t.status==="unknown"?null:t.hostId}function gie(e){return Ot(e)!==null}function iU(e){return Qt.includes(e)}function lP(e,t){return x({status:"error",reasonCode:"unknown_mcp_client",requestedClient:e,nextAction:"mcp.status",nextStep:"Run `skills-layer mcp setup --all --dry-run` to see verified MCP host ids."},`Unknown MCP client "${e}". MCP hosts are separate from skill-install agents; run \`skills-layer mcp setup --all --dry-run\` to inspect them.`,t.json,"unknown_mcp_client")}function fh(e){let t=e.target.instructions,n=Array.isArray(t)&&typeof t[0]=="string"?t[0]:`Install skills with \`skills-layer install <skill> --agent ${e.clientId}\`.`;return{...e,status:"skills_only",configured:!1,nextCommand:null,nextAction:"install.skills",nextStep:n}}async function nA(e,t){let n=k(e.environment)??Dt(t.baseUrl),r=[...H2],i=`${t.baseUrl}/mcp`,o=ts({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:"codex",environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath}),s=await hie(e,t,o);if(s.clientIds.length===0)return x({status:"needs_mcp_client_choice",reasonCode:"needs_mcp_client_choice",configured:!1,detectedClientIds:s.detectedClientIds,supportedClientIds:o.targets.filter(C=>C.status==="automatic").map(C=>C.agentId),nextAction:"mcp.setup.select_client",nextStep:"Run `skills-layer mcp setup --client <host-id>` or `skills-layer mcp setup --all`."},"No verified Tier 1 MCP host was detected, so no client was selected. Choose a host explicitly or use --all.",e.json,"needs_mcp_client_choice");let a=s.clientIds[0],l=ts({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:a,environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath});if(e.dryRun){let C=l.targets.filter(P=>P.status==="automatic"&&s.clientIds.includes(Ot(P.agentId)));return{status:"mcp_setup_preview",evidenceStale:l.evidenceStale,warnings:l.warnings,dryRun:!0,configured:!1,unchanged:!0,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,plannedWrites:C.map(P=>({clientId:P.agentId,scope:"user_global",configPath:P.configPath})),skippedClients:l.targets.filter(P=>P.status!=="automatic").map(P=>({clientId:P.agentId,reason:P.reason})),bridgePath:l.bridgePath,brokerPath:l.brokerPath,nextAction:"mcp.setup"}}let c=l.targets.filter(C=>C.status==="automatic"&&s.clientIds.includes(Ot(C.agentId)));try{for(let C of c)await C.preflight?.()}catch(C){let P=C instanceof Error&&C.message.startsWith("mcp_config_symlink_rejected")?"mcp_config_symlink_rejected":"mcp_registration_ownership_ambiguous";return x({status:"mcp_setup_blocked",configured:!1,unchanged:!0,reasonCode:P,clientIds:s.clientIds,nextAction:"mcp.config.review",nextStep:"Review the existing user-global MCP entry. Skills Layer did not mint a credential or overwrite it."},C instanceof Error?C.message:"MCP host configuration preflight failed.",e.json,P)}if(Cg(t.baseUrl)&&!t.credentialStore)return x({status:"security_unavailable",reasonCode:"mcp_secure_storage_required",configured:!1,unchanged:!0,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup --client <host-id>` on a machine with supported OS-secure credential storage."},"Skills Layer Cloud MCP setup requires supported OS-secure credential storage. No MCP credential was created.",e.json,"mcp_secure_storage_required");let u=Ko(),d=await D(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({clientId:ny,linkedClientIds:s.clientIds,environment:n,scopes:r,handoffCodeHash:u.authorizationCodeHash,handoffCodeChallenge:u.codeChallenge})});if(f(d,"credentialHandoff")!=="ready")return E("MCP setup did not prepare a secure credential handoff.",e.json);let p=await D(t,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({authorizationCode:u.authorizationCode,codeVerifier:u.codeVerifier})}),m=f(p,"apiKey");if(!m)return E("MCP token credential exchange failed closed.",e.json);let h;try{h=await yie(t,{token:m,clientId:ny,environment:n})}catch(C){if(!(C instanceof xa))throw C;let P=f(p,"id"),N=!1;if(P)try{await D(t,"/api/v1/me/session/revoke",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:[P]})}),N=!0}catch{t.config?.userId&&await AA(t,{baseUrl:t.baseUrl,userId:t.config.userId,humanKeyIds:[],mcpKeyIds:[P],revokeAllMcp:!1,revokeAdminMcp:!1,createdAt:t.now()})}return E(N?"OS-secure credential storage failed, so the new MCP credential was revoked and no local MCP setup was written.":"OS-secure credential storage failed. No local MCP setup was written; server revocation is pending or requires prompt retry.",e.json)}let g={...h,shared:!0,keyId:f(p,"id")??null,tokenPrefix:f(p,"keyPrefix")??null,scopes:Array.isArray(p.scopes)?p.scopes:[]},y=await be(t.paths.mcpConfigPath),v=`${t.paths.stateDir}/mcp-credential-refs.json`,b=await be(v),w=[...Ua(b??{},je),...Ua(y??{},je),...Ua(g,je)];if(await Ve(v,{tokens:Object.fromEntries(w.map(C=>[C.tokenRef,{tokenRef:C.tokenRef,credentialService:C.service,credentialStorage:"macos_keychain"}]))}),await Ve(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:i,clientId:a,clientIds:s.clientIds,environment:n,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,...g,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,brokerLockPath:l.brokerLockPath,brokerIntegrityProfile:"standard_v1",brokerChecksum:l.brokerChecksum,savedAt:t.now()}),t.credentialStore){let C=new Set(Ua(g,je).map(P=>`${P.service}:${P.tokenRef}`));for(let P of w)C.has(`${P.service}:${P.tokenRef}`)||await t.credentialStore.delete(P.service,P.tokenRef);await Ve(v,{tokens:Object.fromEntries(w.filter(P=>C.has(`${P.service}:${P.tokenRef}`)).map(P=>[P.tokenRef,{tokenRef:P.tokenRef,credentialService:P.service,credentialStorage:"macos_keychain"}]))})}let _=c;for(let C of _)await C.apply?.();return await Ze(t.paths.mcpPreferencePath,{force:!0}),{...Nt(p),status:"mcp_configured",evidenceStale:l.evidenceStale,warnings:l.warnings,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,environment:n,mcpUrl:i,bridgePath:l.bridgePath,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,nodePath:l.nodePath,bridgeChecksum:l.bridgeChecksum,brokerChecksum:l.brokerChecksum,saved:!0,readiness:{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${a}`,nextStep:"Open a fresh agent session so the host can load the updated MCP configuration. Run verify or repair if Skills Layer tools are still not visible."},registrations:{status:"mcp_registration_plan",automaticCount:l.automaticCount,manualCount:l.manualCount,skillsOnlyCount:l.skillsOnlyCount,unsupportedCount:l.unsupportedCount,appliedCount:_.length,appliedClients:_.map(C=>C.agentId),targets:l.targets.map(C=>({agentId:C.agentId,displayName:C.displayName,tier:C.tier,status:C.status,transport:C.transport,configPath:C.configPath,bridgePath:C.bridgePath,restartRequired:C.restartRequired,reason:C.reason,instructions:C.instructions}))}}}async function hie(e,t,n){let r=k(e.client),i=n.targets.filter(l=>l.status==="automatic").flatMap(l=>{let c=Ot(l.agentId);return c?[c]:[]});if(r){let l=Ot(r);return{clientIds:l?[l]:[],detectedClientIds:[],selectionSource:"explicit"}}if(e.all)return{clientIds:i,detectedClientIds:i,selectionSource:"all"};let o=await uR({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:t.pathExists}),s=new Set(i),a=o.map(l=>l.hostId).filter(l=>s.has(l));if(a.length>0)return{clientIds:a,detectedClientIds:a,selectionSource:"detected"};if(t.stdoutIsTty&&!e.json)try{let l=await t.promptSelect("Choose the MCP host to configure globally:",n.targets.filter(u=>u.status==="automatic").map(u=>({value:String(u.agentId),label:u.displayName,description:`User-global config: ${u.configPath}`}))),c=Ot(l);if(c)return{clientIds:[c],detectedClientIds:[],selectionSource:"explicit"}}catch{}return{clientIds:[],detectedClientIds:[],selectionSource:"choice_required"}}async function yie(e,t){if(!e.credentialStore){if(Cg(e.baseUrl))throw new xa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}let n=vie({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment,stateDir:e.paths.stateDir});try{return await e.credentialStore.set(je,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:je,tokenStorage:"macos_keychain"}}catch{if(Cg(e.baseUrl))throw new xa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function PP(e,t){let n=`${t.paths.stateDir}/mcp-credential-refs.json`,r=await be(n),i=[...Ua(e??{},je),...Ua(r??{},je)];if(!t.credentialStore){if(i.length)throw new Error("OS credential storage is unavailable; retry cleanup on this profile's original machine.");return}if((await Promise.allSettled(i.map(s=>t.credentialStore.delete(s.service,s.tokenRef)))).some(s=>s.status==="rejected"))throw new Error("MCP credential cleanup is incomplete; retry logout.");await Ze(n,{force:!0})}function Ua(e,t){let n=new Map;KB(e,t,n);let r=e.tokens;if(j(r))for(let i of Object.values(r))j(i)&&KB(i,t,n);return[...n.values()]}function KB(e,t,n){let r=f(e,"tokenRef");if(!r||f(e,"credentialStorage")!=="macos_keychain")return;let i=f(e,"credentialService")??t;n.set(`${i}:${r}`,{service:i,tokenRef:r})}function vie(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
2151
+ `)}function jt(e){if(e==="workspace_approved_only")return"Workspace-approved only";let t=e.replace(/[_-]+/gu," ").trim().toLowerCase();return t.length>0?t[0].toUpperCase()+t.slice(1):"Unknown"}function un(e,t,n,r,i){return r?R(e,n,!0,i):{exitCode:0,stdout:t,stderr:""}}function Ot(e){let t=rl(e);return t.status==="unknown"?null:t.hostId}function gie(e){return Ot(e)!==null}function iU(e){return Qt.includes(e)}function lP(e,t){return x({status:"error",reasonCode:"unknown_mcp_client",requestedClient:e,nextAction:"mcp.status",nextStep:"Run `skills-layer mcp setup --all --dry-run` to see verified MCP host ids."},`Unknown MCP client "${e}". MCP hosts are separate from skill-install agents; run \`skills-layer mcp setup --all --dry-run\` to inspect them.`,t.json,"unknown_mcp_client")}function fh(e){let t=e.target.instructions,n=Array.isArray(t)&&typeof t[0]=="string"?t[0]:`Install skills with \`skills-layer install <skill> --agent ${e.clientId}\`.`;return{...e,status:"skills_only",configured:!1,nextCommand:null,nextAction:"install.skills",nextStep:n}}async function nA(e,t){let n=k(e.environment)??Dt(t.baseUrl),r=[...H2],i=`${t.baseUrl}/mcp`,o=ts({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:"codex",environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath}),s=await hie(e,t,o);if(s.clientIds.length===0)return x({status:"needs_mcp_client_choice",reasonCode:"needs_mcp_client_choice",configured:!1,detectedClientIds:s.detectedClientIds,supportedClientIds:o.targets.filter(C=>C.status==="automatic").map(C=>C.agentId),nextAction:"mcp.setup.select_client",nextStep:"Run `skills-layer mcp setup --client <host-id>` or `skills-layer mcp setup --all`."},"No verified Tier 1 MCP host was detected, so no client was selected. Choose a host explicitly or use --all.",e.json,"needs_mcp_client_choice");let a=s.clientIds[0],l=ts({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:a,environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath});if(e.dryRun){let C=l.targets.filter(A=>A.status==="automatic"&&s.clientIds.includes(Ot(A.agentId)));return{status:"mcp_setup_preview",evidenceStale:l.evidenceStale,warnings:l.warnings,dryRun:!0,configured:!1,unchanged:!0,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,plannedWrites:C.map(A=>({clientId:A.agentId,scope:"user_global",configPath:A.configPath})),skippedClients:l.targets.filter(A=>A.status!=="automatic").map(A=>({clientId:A.agentId,reason:A.reason})),bridgePath:l.bridgePath,brokerPath:l.brokerPath,nextAction:"mcp.setup"}}let c=l.targets.filter(C=>C.status==="automatic"&&s.clientIds.includes(Ot(C.agentId)));try{for(let C of c)await C.preflight?.()}catch(C){let A=C instanceof Error&&C.message.startsWith("mcp_config_symlink_rejected")?"mcp_config_symlink_rejected":"mcp_registration_ownership_ambiguous";return x({status:"mcp_setup_blocked",configured:!1,unchanged:!0,reasonCode:A,clientIds:s.clientIds,nextAction:"mcp.config.review",nextStep:"Review the existing user-global MCP entry. Skills Layer did not mint a credential or overwrite it."},C instanceof Error?C.message:"MCP host configuration preflight failed.",e.json,A)}if(Cg(t.baseUrl)&&!t.credentialStore)return x({status:"security_unavailable",reasonCode:"mcp_secure_storage_required",configured:!1,unchanged:!0,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup --client <host-id>` on a machine with supported OS-secure credential storage."},"Skills Layer Cloud MCP setup requires supported OS-secure credential storage. No MCP credential was created.",e.json,"mcp_secure_storage_required");let u=Ko(),d=await D(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({clientId:ny,linkedClientIds:s.clientIds,environment:n,scopes:r,handoffCodeHash:u.authorizationCodeHash,handoffCodeChallenge:u.codeChallenge})});if(f(d,"credentialHandoff")!=="ready")return E("MCP setup did not prepare a secure credential handoff.",e.json);let p=await D(t,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({authorizationCode:u.authorizationCode,codeVerifier:u.codeVerifier})}),m=f(p,"apiKey");if(!m)return E("MCP token credential exchange failed closed.",e.json);let h;try{h=await yie(t,{token:m,clientId:ny,environment:n})}catch(C){if(!(C instanceof xa))throw C;let A=f(p,"id"),N=!1;if(A)try{await D(t,"/api/v1/me/session/revoke",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:[A]})}),N=!0}catch{t.config?.userId&&await AA(t,{baseUrl:t.baseUrl,userId:t.config.userId,humanKeyIds:[],mcpKeyIds:[A],revokeAllMcp:!1,revokeAdminMcp:!1,createdAt:t.now()})}return E(N?"OS-secure credential storage failed, so the new MCP credential was revoked and no local MCP setup was written.":"OS-secure credential storage failed. No local MCP setup was written; server revocation is pending or requires prompt retry.",e.json)}let g={...h,shared:!0,keyId:f(p,"id")??null,tokenPrefix:f(p,"keyPrefix")??null,scopes:Array.isArray(p.scopes)?p.scopes:[]},y=await be(t.paths.mcpConfigPath),v=`${t.paths.stateDir}/mcp-credential-refs.json`,b=await be(v),w=[...Ua(b??{},je),...Ua(y??{},je),...Ua(g,je)];if(await Ve(v,{tokens:Object.fromEntries(w.map(C=>[C.tokenRef,{tokenRef:C.tokenRef,credentialService:C.service,credentialStorage:"macos_keychain"}]))}),await Ve(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:i,clientId:a,clientIds:s.clientIds,environment:n,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,...g,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,brokerLockPath:l.brokerLockPath,brokerIntegrityProfile:"standard_v1",brokerChecksum:l.brokerChecksum,savedAt:t.now()}),t.credentialStore){let C=new Set(Ua(g,je).map(A=>`${A.service}:${A.tokenRef}`));for(let A of w)C.has(`${A.service}:${A.tokenRef}`)||await t.credentialStore.delete(A.service,A.tokenRef);await Ve(v,{tokens:Object.fromEntries(w.filter(A=>C.has(`${A.service}:${A.tokenRef}`)).map(A=>[A.tokenRef,{tokenRef:A.tokenRef,credentialService:A.service,credentialStorage:"macos_keychain"}]))})}let _=c;for(let C of _)await C.apply?.();return await Ze(t.paths.mcpPreferencePath,{force:!0}),{...Nt(p),status:"mcp_configured",evidenceStale:l.evidenceStale,warnings:l.warnings,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,environment:n,mcpUrl:i,bridgePath:l.bridgePath,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,nodePath:l.nodePath,bridgeChecksum:l.bridgeChecksum,brokerChecksum:l.brokerChecksum,saved:!0,readiness:{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${a}`,nextStep:"Open a fresh agent session so the host can load the updated MCP configuration. Run verify or repair if Skills Layer tools are still not visible."},registrations:{status:"mcp_registration_plan",automaticCount:l.automaticCount,manualCount:l.manualCount,skillsOnlyCount:l.skillsOnlyCount,unsupportedCount:l.unsupportedCount,appliedCount:_.length,appliedClients:_.map(C=>C.agentId),targets:l.targets.map(C=>({agentId:C.agentId,displayName:C.displayName,tier:C.tier,status:C.status,transport:C.transport,configPath:C.configPath,bridgePath:C.bridgePath,restartRequired:C.restartRequired,reason:C.reason,instructions:C.instructions}))}}}async function hie(e,t,n){let r=k(e.client),i=n.targets.filter(l=>l.status==="automatic").flatMap(l=>{let c=Ot(l.agentId);return c?[c]:[]});if(r){let l=Ot(r);return{clientIds:l?[l]:[],detectedClientIds:[],selectionSource:"explicit"}}if(e.all)return{clientIds:i,detectedClientIds:i,selectionSource:"all"};let o=await uR({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:t.pathExists}),s=new Set(i),a=o.map(l=>l.hostId).filter(l=>s.has(l));if(a.length>0)return{clientIds:a,detectedClientIds:a,selectionSource:"detected"};if(t.stdoutIsTty&&!e.json)try{let l=await t.promptSelect("Choose the MCP host to configure globally:",n.targets.filter(u=>u.status==="automatic").map(u=>({value:String(u.agentId),label:u.displayName,description:`User-global config: ${u.configPath}`}))),c=Ot(l);if(c)return{clientIds:[c],detectedClientIds:[],selectionSource:"explicit"}}catch{}return{clientIds:[],detectedClientIds:[],selectionSource:"choice_required"}}async function yie(e,t){if(!e.credentialStore){if(Cg(e.baseUrl))throw new xa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}let n=vie({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment,stateDir:e.paths.stateDir});try{return await e.credentialStore.set(je,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:je,tokenStorage:"macos_keychain"}}catch{if(Cg(e.baseUrl))throw new xa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function PP(e,t){let n=`${t.paths.stateDir}/mcp-credential-refs.json`,r=await be(n),i=[...Ua(e??{},je),...Ua(r??{},je)];if(!t.credentialStore){if(i.length)throw new Error("OS credential storage is unavailable; retry cleanup on this profile's original machine.");return}if((await Promise.allSettled(i.map(s=>t.credentialStore.delete(s.service,s.tokenRef)))).some(s=>s.status==="rejected"))throw new Error("MCP credential cleanup is incomplete; retry logout.");await Ze(n,{force:!0})}function Ua(e,t){let n=new Map;KB(e,t,n);let r=e.tokens;if(j(r))for(let i of Object.values(r))j(i)&&KB(i,t,n);return[...n.values()]}function KB(e,t,n){let r=f(e,"tokenRef");if(!r||f(e,"credentialStorage")!=="macos_keychain")return;let i=f(e,"credentialService")??t;n.set(`${i}:${r}`,{service:i,tokenRef:r})}function vie(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
2152
2152
  `);return`skills-layer-cli:mcp-token:${Ue("sha256").update(t).digest("base64url").slice(0,32)}`}async function AP(e,t){if(e.noMcp)return{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."};let n=await be(t.paths.mcpConfigPath),r=n?f(n,"baseUrl"):void 0,i=n?f(n,"clientId"):null;if(!e.withMcp&&r===t.baseUrl&&i)return{data:{status:"mcp_already_configured",configured:!0,clientId:i,mcpUrl:n?f(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};let o=e.withMcp===!0;if(!o&&!e.json)try{let a=await t.promptSelect("Set up Skills Layer MCP for your AI tools on this machine?",[{value:"yes",label:"Yes, set up MCP",description:"Mint a scoped token and write local MCP configuration"},{value:"no",label:"Not now",description:"You can run skills-layer mcp setup later"}]);if(o=a==="yes",a==="no")return await Ze(t.paths.mcpPreferencePath,{force:!0}),{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."}}catch{return{}}if(!o)return{};let s=await nA(e,t);return fe(s)?{data:kie(s),message:"Login completed, but MCP was not configured. Choose a verified host with `skills-layer mcp setup --client <host-id>` or use `--all`."}:{data:s,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}function kie(e){let t="mcp_setup_failed";try{let n=JSON.parse(e.stderr);t=f(n,"reasonCode")??t}catch{e.stderr.includes("OS-secure credential storage")&&(t="mcp_secure_storage_required")}return{status:"mcp_not_configured",configured:!1,reasonCode:t,nextAction:"mcp.setup",nextCommand:"skills-layer mcp setup --client <host-id>",nextStep:"Run `skills-layer mcp setup --client <host-id>` after resolving the reported MCP prerequisite, or use `--all`."}}function RP(e,t){return t?t.status==="mcp_skipped"?{...e,nextAction:"whoami",nextStep:"Run `skills-layer whoami` to check your account."}:t.configured!==!1?{...e,nextAction:"mcp.verify",nextStep:"Open a fresh agent session so it can load Skills Layer, then run `skills-layer mcp verify` if the tools are not visible."}:t.configured===!1||t.status==="mcp_skipped"?{...e,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup` when you want Skills Layer available to your AI tools."}:e:e}async function _h(e,t){if(t.config?.edition==="community")return{};let n;try{n=await D(t,"/api/v1/me/working-modes",{headers:ne(t.apiKey,t.authBlockedMessage)})}catch{return{}}await Bi(t,n);let r=Array.isArray(n.modes)?n.modes.filter(j):[],i=f(n,"selectedModeId");if(!r.some(u=>f(u,"type")==="enterprise_workspace")){let u=r.find(p=>f(p,"modeId")===i),d=u?f(u,"label")??i:i;return i?{data:{status:"working_mode_selected",selectedModeId:i,...u?{mode:u}:{}},message:`Selected workspace: ${d}.`}:{}}let s=wie(r,i);if(s.length===0)return{};if(e.json)return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:i??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",!0,"working_mode_selection_required");let a;try{a=await t.promptSelect("Select your Skills Layer workspace:",s)}catch{return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:f(n,"selectedModeId")??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",e.json,"working_mode_selection_required")}let l=await D(t,"/api/v1/me/working-mode",{method:"PUT",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({modeId:a})});await Bi(t,l);let c=s.find(u=>u.value===a)?.label??a;return{data:l,message:`Selected workspace: ${c}.`}}function wie(e,t){let n=new Map;for(let o of e){let s=f(o,"modeId"),a=f(o,"type");!s||a!=="personal"&&a!=="enterprise_workspace"||n.has(s)||n.set(s,o)}let r=[...n.values()],i=new Map;for(let o of r){let s=f(o,"modeId"),l=(f(o,"label")??s).trim().toLocaleLowerCase();i.set(l,[...i.get(l)??[],o])}return r.map(o=>{let s=f(o,"modeId"),a=f(o,"type"),l=f(o,"label")??s;if(a==="personal")return{value:s,label:l,description:s===t?"Currently selected \u2014 your personal library and public catalog":"Your personal library and public catalog"};let c=i.get(l.trim().toLocaleLowerCase())??[];if(c.length===1)return{value:s,label:l,...s===t?{description:"Currently selected"}:{}};let u=new Set(c.map(h=>f(h,"enterpriseId")).filter(Boolean)),d=u.size>1?f(o,"enterpriseId"):f(o,"workspaceId"),p=u.size>1?"Enterprise":"Workspace",m=bie(d??s);return{value:s,label:`${l} (${p} ${m})`,...s===t?{description:"Currently selected"}:{}}})}function bie(e){return e.replace(/^(?:enterprise|workspace)_/u,"").slice(0,8)}function _ie(e){if(!e)return null;let t=e.mode??e.workingMode,n=j(t)?t:e,r=f(n,"modeId")??f(e,"selectedModeId"),i=f(n,"type");return!r||i!=="personal"&&i!=="enterprise_workspace"?null:{workingModeId:r,workingModeType:i,workingModeEnterpriseId:f(n,"enterpriseId"),workingModeWorkspaceId:f(n,"workspaceId"),workingModeGuardianPolicy:n.guardianPolicy==="standard"?"standard":"strict",workingModeRole:f(n,"role"),workingModeLabel:f(n,"label")}}async function Bi(e,t){let n=_ie(t);if(!n||!e.config)return e.config;let r={...e.config,...n,workingModeSavedAt:e.now()};return await RA(e.paths.configPath,r,e),e.config=r,r}async function WB(e,t,n){let r=[...new Set(t.map(i=>i.trim()).filter(Boolean))];for(let i of r){let o=await rA(e,i,n);if(o)return o}return null}async function rA(e,t,n){if(!e.apiKey)return null;let r=e.config?.workingModeType;if(r!=="personal"&&r!=="enterprise_workspace"){let i;try{i=await D(e,"/api/v1/me/install-policy",{headers:ne(e.apiKey,e.authBlockedMessage)})}catch(o){if(o instanceof Z&&(o.status===403||o.status===409))return cP(o.details??{error:o.message},t,n.json);throw o}if(await Bi(e,i),i.requiresWorkingModeSelection===!0)return x({status:"working_mode_selection_required",skillSlug:t,reasonCode:"working_mode_selection_required",nextAction:f(i,"nextAction")??"select_working_mode",nextStep:f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."},`Install blocked for ${t}. ${f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."}`,n.json,"working_mode_selection_required");r=e.config?.workingModeType}if(r!=="enterprise_workspace")return null;try{let i=await D(e,`/api/v1/skills/${encodeURIComponent(t)}/install-authorize`,{method:"POST",headers:V(e.apiKey,e.authBlockedMessage),body:JSON.stringify({})});return await Bi(e,i),f(i,"status")==="authorized"?null:cP(i,t,n.json)}catch(i){if(i instanceof Z&&(i.status===403||i.status===409))return cP(i.details??{error:i.message},t,n.json);throw i}}function cP(e,t,n){let r=j(e.data)?e.data:e,i=f(e,"reasonCode")??f(r,"reasonCode"),o=f(e,"nextAction")??f(r,"nextAction"),s=f(e,"nextStep")??f(r,"nextStep"),a=f(r,"status")??"blocked";return x({...r,status:a,skillSlug:t,...i?{reasonCode:i}:{},...o?{nextAction:o}:{},...s?{nextStep:s}:{}},`Install blocked for ${t}${i?` (${i})`:""}.${s?` ${s}`:""}`,n,i)}function Sie(e){let t=k(e);if(t)return t.split(",").map(n=>n.trim()).filter(Boolean)}async function xie(e,t,n){let r=e.join(" ").trim()||k(t.search)||"",i=new URLSearchParams;r&&i.set("query",r);let o=k(t.runtimeRisk);if(o&&!ZB.includes(o))return dP("runtime-risk",o,ZB,t);let s=k(t.agent);if(s&&!iU(s))return x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:s,acceptedValues:Qt,nextAction:"search",nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown search --agent "${s}". Run \`skills-layer agents list\` to inspect supported agents.`,t.json,"unknown_agent");let a=k(t.trust);if(a&&!JB.includes(a))return dP("trust",a,JB,t);let l=k(t.securityCapability),c=Nie(l);if(l&&!c)return dP("security-capability",l,oU,t);let u=Oz(i,t);if(typeof u=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},u,t.json,"invalid_limit");We(i,"agent",t.agent),We(i,"capability",t.capability),We(i,"trust",a),We(i,"runtime-risk",o),We(i,"security-capability",c);let d=await D(n,`/api/v1/search${Qe(i)}`);if(t.install!==void 0){let p=k(t.install);if(!p){if(t.json)return E("search --install requires an explicit skill slug in the public CLI package.",!0);let h=ur(d);if(h.length===0)return E("Search results do not include any installable skills. Run search again with a broader query.",!1);if(h.length===1)p=h[0].value;else try{p=await n.promptSelect("Select a search result to install:",h)}catch{return E("No search result was selected for install.",!1)}}let m=Rce(d);return m.includes(p)?await Za([p],t,n,{origin:"search_result",fallbackPolicy:"eligible_public"}):E(m.length===0?`Search results do not include "${p}". Run search again with a matching query first.`:`Search results do not include "${p}". Run search again with a matching query or choose one of: ${m.join(", ")}.`,t.json)}return R({...d,...u.length?{warnings:[...Array.isArray(d.warnings)?d.warnings:[],...u]}:{}},"Search complete.",t.json,n)}var ZB=VA,JB=tl,oU=["filesystem_read","filesystem_write","network_access","api_access","browser_access","device_control","generated_code_execution","secret_handling","model_context","shell_access"],Cie={network:"network_access",filesystem:"filesystem_read",files:"filesystem_read",file_read:"filesystem_read",file_write:"filesystem_write",shell:"shell_access",browser:"browser_access",device:"device_control",api:"api_access",secrets:"secret_handling",model:"model_context"},uP=["local","project","global","workspace"],ju=["private","public","unlisted"],qa=["private","public","unlisted"],YB=["github","gitlab","local","generic_git","domain"],Iie=["owner","maintainer"],Pie=["open","acknowledged","fixed","closed","rejected","abusive","reopened","resolved"],Aie=["visible","flagged","hidden"],Rie=["bug","quality","safety","other"],Eie=["approved","denied"],$ie=["email","google","github","gitlab","microsoft"],Die=["email","google","github","gitlab","microsoft"],XB=["catalog:read","library:read","creator:read","creator:submit","source:read","source:write","guardian:check","guardian:incident","workspace:read","workspace:write","workspace:approve","mcp:use"],QB=["automation","mcp","agent"],eM=["active","expired","revoked","all"],tM=["created-desc","created-asc","expires-desc","expires-asc","name-asc","name-desc","last-used-desc","last-used-asc"];var sU=["json","sarif","report","passport","markdown"],mh=[...GA,"score"],Tie=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u,Oie=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Lie=/^[a-f0-9]{6,64}$/iu;function jie(e,t,n,r){let i=k(t);if(!i)return{};if(!/^\d+$/u.test(i))return{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be a whole number from 1 to ${n}.`,r.json,"invalid_limit")};let o=Number.parseInt(i,10);return!Number.isInteger(o)||o<1||o>n?{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be between 1 and ${n}.`,r.json,"invalid_limit")}:{value:String(o)}}function dP(e,t,n,r){return x({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":e==="limit"?"Use --limit with a whole number from 1 to 20.":`Use --${e} with one of: ${n.join(", ")}.`},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:e==="limit"?`Invalid search limit "${t}". Use a whole number from 1 to 20.`:`Invalid search --${e} "${t}". Use one of: ${n.join(", ")}.`,r.json,"invalid_search_filter")}function Nie(e){if(e)return oU.includes(e)?e:Cie[e]}function Fr(e,t,n,r,i,o,s=t){return x({status:"error",reasonCode:o,[t]:n,acceptedValues:r,nextAction:e,nextStep:`Use --${s} with one of: ${r.join(", ")}.`},`Invalid ${e} --${s} "${n}". Use one of: ${r.join(", ")}.`,i.json,o)}function pr(e,t,n,r,i,o,s=t){let a=k(n);if(!(!a||r.includes(a)))return Fr(e,t,a,r,i,o,s)}function Ni(e,t){let n=k(t.version);return n&&!Lh(n)?iA(e,n,t):void 0}function Fie(e,t,n){return x({status:"error",reasonCode:"invalid_slug",value:t,acceptedFormat:"lowercase words separated by hyphens",nextAction:e,nextStep:"Use a lowercase skill slug such as project-planner or year9-history-study-guide."},`Invalid skill slug "${t}". Use lowercase letters, numbers, and single hyphens.`,n.json,"invalid_slug")}function aU(e,t,n){return t&&!Oie.test(t)?Fie(e,t,n):void 0}function Bie(e,t,n){return x({status:"error",reasonCode:"invalid_format",format:t,acceptedValues:sU,nextAction:e,nextStep:"Use --format json, sarif, report, passport, or markdown."},`Invalid ${e} --format "${t}". Use json, sarif, report, passport, or markdown.`,n.json,"invalid_format")}function lU(e,t){let n=k(t.format);return n&&!sU.includes(n.toLowerCase())?Bie(e,n,t):void 0}function Mie(e,t,n){return x({status:"error",reasonCode:"invalid_commit_sha",commitSha:t,nextAction:e,nextStep:"Use --commit-sha with a 6 to 64 character hexadecimal commit SHA."},`Invalid --commit-sha "${t}". Use a hexadecimal commit SHA.`,n.json,"invalid_commit_sha")}function Uie(e,t){let n=k(t.commitSha);return n&&!Lie.test(n)?Mie(e,n,t):void 0}function zie(e,t){return x({status:"error",reasonCode:"invalid_base_url",baseUrl:e,nextAction:"backend",nextStep:"Use --base-url with HTTPS, or HTTP for loopback development only."},`Invalid backend base URL "${e}". Use HTTPS, or HTTP for loopback development only.`,t.json,"invalid_base_url")}function qie(e,t){try{nl(e);return}catch{return zie(e,t)}}function nM(e,t,n){return x({status:"error",reasonCode:"unexpected_argument",command:e,argument:t,nextAction:e,nextStep:`Run \`skills-layer ${e} --help\` to see supported arguments for this command.`},`Unexpected argument "${t}" for ${e}.`,n.json,"unexpected_argument")}function ed(e,t){let n=k(t.scope);if(n&&!uP.includes(n))return{failure:x({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:uP,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${uP.join(", ")}.`,t.json,"invalid_install_filter")};let r=k(t.agent);return r&&!(e==="install"&&r==="all")&&!iU(r)?{failure:x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:r,acceptedValues:Qt,nextAction:e,nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown ${e} --agent "${r}". Run \`skills-layer agents\` to inspect supported agents.`,t.json,"unknown_agent")}:{scope:n,agent:r}}function cU(e,t){let n=ed(e,t);if(n.failure)return n.failure;let r=k(t.version);if(e==="install"&&r&&!Lh(r))return iA("install",r,t)}function iA(e,t,n){return x({status:"error",reasonCode:"invalid_version",command:e,version:t,nextAction:e,nextStep:"Use a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --version "${t}". Use a semver version or an external-<digest> version.`,n.json,"invalid_version")}function Vie(e,t,n){return x({status:"error",reasonCode:"invalid_expiry",command:e,expiresIn:t,acceptedFormat:"<positive whole number>d",maxDays:365,nextAction:e,nextStep:"Use --expires from 1d to 365d. Omit it for the 90-day default."},`Invalid --expires "${t}". Use a day duration from 1d to 365d. Omit it for the 90-day default.`,n.json,"invalid_expiry")}function Gie(e,t,n){let r=k(t);if(r&&JA(r)===null)return Vie(e,r,n)}function Mi(e,t,n,r,i,o){let s=k(e);if(!s)return{};if(!/^\d+$/u.test(s))return{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)};let a=Number(s);return!Number.isSafeInteger(a)||a<o.minimum?{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)}:{value:a}}function rM(e,t,n,r,i,o){let s=Mi(e,t,n,`invalid_${n.replace(/[A-Z]/gu,a=>`_${a.toLowerCase()}`)}`,i,o);return s.failure?s.failure:s.value===void 0?E(`${r} requires ${t} <count>.`,i.json):s.value}function Hie(e){let t=k(e.paymentMethod)??"card";return Tie.test(t)?{value:t}:{failure:x({status:"error",reasonCode:"invalid_payment_method",paymentMethod:t,acceptedValues:["card","card_<test-card>","pm_<provider-method-id>"],nextAction:"buy",nextStep:"Use --payment-method card or a provider token such as pm_<id>."},`Invalid payment method "${t}". Use card or a provider token such as pm_<id>.`,e.json,"invalid_payment_method")}}async function Kie(e,t,n){let r=new URLSearchParams,i=Oz(r,t);if(typeof i=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},i,t.json,"invalid_limit");let o=k(t.sort);if(o&&!mh.includes(o))return x({status:"error",reasonCode:"invalid_sort",sort:o,acceptedValues:mh,nextAction:e,nextStep:`Use --sort with one of: ${mh.join(", ")}.`},`${e} --sort must be one of: ${mh.join(", ")}.`,t.json,"invalid_sort");We(r,"search",t.search),We(r,"sort",o);let s=await D(n,`/api/v1/${e}${Qe(r)}`);return e==="trending"&&!t.json?{exitCode:0,stdout:LA({...s,warnings:[...Array.isArray(s.warnings)?s.warnings:[],...i]},r,n.baseUrl),stderr:""}:R({...s,...i.length?{warnings:[...Array.isArray(s.warnings)?s.warnings:[],...i]}:{}},e==="trending"&&typeof s.basis=="string"?sd(s.basis):`${Mh(e)} skills loaded.`,t.json,n)}async function Wie(e,t,n){let r=e.join(" ").trim();if(!r)return E("recommend requires a task.",t.json);let i=jie("recommend",t.limit,20,t);if(i.failure)return i.failure;let o=new URLSearchParams({task:r});We(o,"limit",i.value);let s=await D(n,`/api/v1/recommend?${o.toString()}`,{headers:Zo(n.apiKey)});return R(s,f(s,"summary")??"Recommendations loaded.",t.json,n)}async function Zie(e,t,n){if(e.length<2)return E("compare requires two or more skill slugs.",t.json);if(e.length>5)return x({status:"error",reasonCode:"too_many_compare_slugs",requestedCount:e.length,maxItems:5,nextAction:"compare",nextStep:"Compare up to 5 skills at a time."},"compare supports up to 5 skill slugs at a time.",t.json,"too_many_compare_slugs");let r=new URLSearchParams({slugs:e.join(",")}),i=await D(n,`/api/v1/skills/compare?${r.toString()}`),o=Array.isArray(i.missing)?i.missing.filter(s=>typeof s=="string"):[];return o.length>0?x({...i,status:"not_found",reasonCode:"compare_missing_skills",missing:o,nextAction:"search",nextStep:`Run \`skills-layer search ${o[0]}\` to find the correct slug, then retry compare.`},`Comparison could not find: ${o.join(", ")}.`,t.json,"compare_missing_skills"):t.json?R(i,"Comparison loaded.",!0,n):{exitCode:0,stdout:Fle(i,"Comparison loaded.",Ae(n),t.verbose),stderr:""}}async function Jie(e,t,n){let r=L(e[0],"show requires a skill slug."),i=await D(n,`/api/v1/skills/${encodeURIComponent(r)}`);return R(Kh(i),"Skill loaded.",t.json,n)}async function Yie(e,t,n){let r=L(e[0],"trust requires a skill slug."),i=lU("trust",t);if(i)return i;let o=new URLSearchParams;We(o,"format",t.format),We(o,"version",t.version),We(o,"versionId",t.versionId);let s=await D(n,`/api/v1/skills/${encodeURIComponent(r)}/platform-score${Qe(o)}`);return k(t.format)?.toLowerCase()==="sarif"?{exitCode:0,stdout:JSON.stringify(s,null,2),stderr:""}:!t.json&&oC(s)?{exitCode:0,stdout:H(nj(s)),stderr:""}:R(s,"Platform Score loaded.",t.json,n)}async function Xie(e,t,n){e.length===0&&n.renderMode.detail==="full"&&(e=["full"]);let r=e[0];if(t.json||n.renderMode.kind==="json-final"){if(r==="full")return R(vN(),"Help loaded.",!0,n);let a=e.length===1?Tg(r,So):null;if(a)return R({status:"ok",kind:"goal_help",goal:a},"Help loaded.",!0,n);let l=r==="topic"?xo(e[1]):xo(r,e.slice(1));if(l)return R(l,"Help loaded.",!0,n);if(r!=="topic"&&!yre.has(r??""))return EP(e,!0)}if(!r){if(n.renderMode.kind==="json-stream"||!n.helpInteractive)return{exitCode:0,stdout:jo(n.renderMode),stderr:""};let a;try{a=await n.promptSelect("What do you want to do?",fN(So))}catch{a=void 0}if(!a)return{exitCode:0,stdout:jo(n.renderMode),stderr:""};if(a==="full")return Ma(jo(n.renderMode,!0),"full",t,n);let l=Tg(a,So);return l?Ma(eI(l),l.id,t,n):{exitCode:0,stdout:jo(n.renderMode),stderr:""}}if(r==="full")return Ma(jo(n.renderMode,!0),"full",t,n);let o=e.length===1?Tg(r,So):null;if(o)return Ma(eI(o),o.id,t,n);let s=ku(e[0],e.slice(1));if(s)return Ma(s,e.filter(Boolean).join(" "),t,n);if(r==="topic"){let a=ku(e[1]);if(a)return Ma(a,e[1]??"overview",t,n);let l=new URLSearchParams;return e[1]&&l.set("topic",e[1]),await he(`/api/v1/help${Qe(l)}`,t,n,"Help topic loaded.")}if(r==="standards")return await he("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let a=await D(n,"/api/v1/marketplace/status");return t.json?R(a,"Marketplace status loaded.",!0,n):R(Vle(a),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let a=await D(n,"/api/v1/capabilities");return R(Hle(a),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return E("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let a=L(t.text,"help optimize-tokens requires --text."),l=Kle(t.maxCharacters,t.json);if(fe(l))return l;let c=await D(n,"/api/v1/optimize-tokens",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({text:a,...l?{maxCharacters:l}:{}})});return R(c,"Token optimization complete.",t.json,n)}return E(`Unknown help command "${r}".`,t.json)}function Ma(e,t,n,r){return n.json?R({status:"ok",topic:t,content:e},"Help topic loaded.",!0,r):{exitCode:0,stdout:e,stderr:""}}function EP(e,t){let n=e.filter(Boolean).join(" ").trim()||"help";return x({status:"not_found",reasonCode:"help_topic_not_found",topic:n,nextAction:"help",nextStep:"Run `skills-layer --help`, `skills-layer help full`, or `skills-layer <command> --help` for a supported command."},`Help topic not found: ${n}.`,t,"help_topic_not_found")}async function Qie(e,t,n){let r=L(e[0]??t.path,"validate requires a file or directory."),i=Tt(n.cwd,r);if(!await fr(i))return BU("validate",r,t,n);let o=(await ga({cwd:n.cwd,sourcePath:r,limits:ko})).files;o=await eoe({files:o,resolvedTarget:i,flags:t,backend:n});let s=nt(o),a={files:o,sourceIntakeContext:k(t.sourceIntakeContext),publicationStatus:k(t.publicationStatus),dependencyAuditStatus:k(t.dependencyAuditStatus),category:k(t.category),discloseSource:!!t.discloseSource},l;try{l=await D(n,"/api/v1/validation/preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(a))})}catch(d){if(d instanceof Z&&d.status===422&&d.details)l=Dce(d.details);else throw d}let c=toe({...l,license:s.license,licenseIssues:s.issues.filter(d=>d.code.startsWith("license_"))},o),u=c.valid===!1||T(c,"validation")?.valid===!1;return t.json?u?x({...Sz(c,n.renderMode.detail,"validate"),nextAction:"validate",nextStep:"Fix the listed issues, then run validate again."},"Validation failed.",!0,"bundle_invalid"):R(c,"Validation complete.",!0,n,"validate"):{exitCode:u?1:0,stdout:Wle(c,r,n),stderr:""}}async function eoe(e){if(nt(e.files).license?.status==="verified"||e.flags.json||!e.backend.stdoutIsTty)return e.files;let n=await zk({cwd:e.backend.cwd,files:e.files,skip:!1,interactive:!0,prompt:uU(e.backend)});if(n.selection.mode==="skip"||await e.backend.promptSelect("Apply this licence change to the local bundle?",[{value:"apply",label:"Apply the reviewed change"},{value:"cancel",label:"Cancel without changing files"}])!=="apply")return e.files;let o=(await Ya(e.resolvedTarget)).isDirectory()?e.resolvedTarget:Me(e.resolvedTarget);return await ef({targetDir:o,files:Q1(e.files,n.selection),confirmed:!0}),(await ga({cwd:e.backend.cwd,sourcePath:o})).files}function toe(e,t){return{...e,evalReadiness:Wk(t)}}function noe(e,t){let n=roe(e);return $s({status:n?"not_run":"generated_only",skillSlug:t.skillSlug,version:t.version,artifactDigest:ct(e),...n?{evalPackDigest:n}:{},generatedAt:t.generatedAt,runnerVersion:Co,counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})}function roe(e){let t=e.find(n=>{let r=Dn(n.path,e);return r.type==="evidence"&&typeof n.content=="string"&&(r.relativePath.startsWith("evals/")||r.relativePath.endsWith(".eval.json")||r.relativePath.endsWith(".eval.yaml"))});if(t?.content)try{return Es(JSON.parse(t.content))}catch{return}}async function ioe(e,t,n){let r=L(e[0]??t.path,"preview-trigger requires a file or directory."),i=Tt(n.cwd,r);if(!await fr(i))return BU("preview-trigger",r,t,n);let o=(await ga({cwd:n.cwd,sourcePath:r,limits:ko})).files,s=await D(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({files:o,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?R(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:Zle(s,r,n),stderr:""}}async function ooe(e,t,n){let r=e[0];if(["create","sessions","resume","inspect","answer","resources","resource-decide","tool-contract","draft","validate","eval","improve","revise","materialize","finalize"].includes(r??""))return await oM(r,e.slice(1),t,n);if(r==="init")return t.quick?await oM("create",e.slice(1),{...t,mode:"quick"},n):await aoe(e.slice(1),t,n);if(r==="rules")return await he("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(r==="submissions")return await he("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(r==="status"){let i=L(e[1],"creator status requires a skill slug.");try{let o=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/status`,{headers:ne(n.apiKey,n.authBlockedMessage)}),s=T(o,"processing");!f(o,"nextStep")&&s&&["queued","running"].includes(String(s.status))&&(o.nextAction="creator.status",o.nextStep="Check creator status in 30 seconds; evaluation is still in progress.");let a=T(T(o,"submission")??{},"latestFailure"),l=[...Array.isArray(o.warnings)?o.warnings:[],...s?[`Processing stage: ${f(s,"stage")}; status: ${f(s,"status")}.`]:[],...a?[`Latest attempt ${f(a,"version")}: ${f(a,"reasonCode")}.`]:[]];return R({...o,...l.length?{warnings:l}:{}},f(o,"summary")??"Submission status loaded.",t.json,n)}catch(o){if(o instanceof Z&&o.status===404)return hoe(i,t);throw o}}if(r==="charge-status"){let i=L(e[1],"creator charge-status requires a charge id.");return await he(`/api/v1/me/private-skill-charges/${encodeURIComponent(i)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(r==="spaces")return await uoe(e.slice(1),t,n);if(r==="submit")return await DP(e.slice(1),t,n,!1);if(r==="submit-version")return await DP(e.slice(1),t,n,!0);if(r==="check-slug"){let i=L(e[1],"creator check-slug requires a slug.");return await moe(i,t,n)}if(r==="rename"){let i=L(e[1],"creator rename requires the current slug."),o=L(e[2],"creator rename requires the new slug."),s=aU("creator.rename",o,t);return s||await Fi(`/api/v1/me/submissions/${encodeURIComponent(i)}/slug`,{nextSkillSlug:o},t,n,"Skill renamed.")}if(r==="pricing")return await voe(e,t,n);if(r==="update-listing"){let i=L(e[1],"creator update-listing requires a skill slug.");return await koe(i,t,n)}if(r==="visibility"){let i=L(e[1],"creator visibility requires a skill slug."),o=Ni("creator.visibility",t);if(o)return o;let s=k(t.visibility)??e[2],a=dc(s);if(!a||!ju.includes(a))return x({status:"error",reasonCode:"invalid_visibility",skillSlug:i,visibility:s??null,acceptedValues:ju,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${ju.join(", ")}.`,t.json,"invalid_visibility");let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/visibility`,{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(ie({visibility:a,dryRun:t.dryRun}))});return _se(l)?x(l,Sse(l,i),t.json,f(l,"reasonCode")??f(l,"status")):R(l,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(r==="security-report"){let i=L(e[1],"creator security-report requires a skill slug."),o=lU("creator.security-report",t);if(o)return o;let s=Ni("creator.security-report",t);if(s)return s;let a=new URLSearchParams;We(a,"format",t.format),We(a,"version",t.version),We(a,"versionId",t.versionId);let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security-report${Qe(a)}`,{headers:ne(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?R(l,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:dce(l,i,n),stderr:""}}if(r==="rescan-security"){let i=L(e[1],"creator rescan-security requires a skill slug."),o=Ni("creator.rescan-security",t);if(o)return o;let s=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security/rescan`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(Ft(t,["version","versionId"])))});return t.json?R(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:pce(s,i,n),stderr:""}}if(r==="provenance"){let i=L(e[1],"creator provenance requires a skill slug.");return await he(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership`,t,n,"Provenance loaded.",{authenticated:!0})}if(r==="claim"||r==="verify"||r==="dispute")return await woe(r,e,t,n);if(r==="issues"||r==="reviews"||r==="update-issue"||r==="moderate-review")return await Ioe(r,e,t,n);if(r==="analytics"){let i=L(e[1],"creator analytics requires a skill slug.");return await boe(i,t,n)}if(r==="delist"||r==="relist"){let i=L(e[1],`creator ${r} requires a skill slug.`),o=k(t.reason)??(r==="relist"?"Creator relisted skill":"");return o.trim().length<3?E("creator delist requires --reason (at least 3 characters).",t.json):await Fi(`/api/v1/me/submissions/${encodeURIComponent(i)}`,{lifecycle:r==="delist"?"delisted":"active",reason:o},t,n,`${i} ${r==="delist"?"delisted":"relisted"}; existing buyers keep access.`)}if(r==="earnings")return await he("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(r==="payout-profile")return k(t.country)?await dM(t,n):await _oe(t,n);if(r==="payout-link")return await dM(t,n);if(r==="payouts")return await he("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(r==="withdraw"){if(!k(t.amountCents))return E("creator withdraw requires --amount-cents.",t.json);let i=Mi(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});if(i.failure)return i.failure;let o=k(t.idempotencyKey)??ple(),s=t.json?await D(n,"/api/v1/me/payout-profile",{headers:ne(n.apiKey,n.authBlockedMessage)}).then(h=>({payoutCurrency:h.profile.currency,payoutDisclosure:jA(h.profile.currency)})):{};if(t.json&&!k(t.mfaCode))return x({...s,status:"blocked",reasonCode:"mfa_step_up_required",nextStep:"Run skills-layer creator withdraw --amount-cents <amount> in a human terminal to enter MFA and confirm the withdrawal."},"A fresh authenticator code is required.",!0,"mfa_step_up_required");if(t.json||!n.stdoutIsTty)return x({status:"blocked",...s,reasonCode:"payout_human_confirmation_required",nextAction:"creator.withdraw",nextStep:"Use an interactive terminal. MCP returns a browser handoff, and automation credentials cannot withdraw."},"Creator withdrawal requires an interactive human confirmation. Use an interactive terminal; MCP returns a browser handoff and automation credentials cannot withdraw.",t.json,"payout_human_confirmation_required");let a=mU(t,n),l=ie({amountCents:i.value,reason:k(t.reason)}),c={...V(n.apiKey),"idempotency-key":o},u=await a("/api/v1/me/payouts",{method:"POST",headers:c,body:JSON.stringify(l)});if(u.status==="requested")return R(u,"Withdrawal requested.",!1,n);if(u.status!=="confirmation_required"||typeof u.confirmationId!="string"||typeof u.confirmationToken!="string"||typeof u.confirmationPhrase!="string")throw new Error("The payout service did not return a valid action-bound confirmation challenge.");let d=u.impact&&typeof u.impact=="object"?u.impact:{};if(await n.promptText(`Withdrawal impact: ${me(Number(d.amountCents??i.value),String(d.currency??"usd"))}, remaining withdrawable balance ${typeof d.withdrawableAfterCents=="number"?me(d.withdrawableAfterCents,"usd"):"unknown"}.
2153
2153
  `+(typeof d.payoutDisclosure=="string"?`${d.payoutDisclosure}
2154
2154
  `:"")+`Type exactly "${u.confirmationPhrase}" to confirm: `)!==u.confirmationPhrase)return E("Withdrawal cancelled; the confirmation phrase did not match.",!1);let m=await a("/api/v1/me/payouts",{method:"POST",headers:c,body:JSON.stringify({...l,confirmationId:u.confirmationId,confirmationToken:u.confirmationToken,confirmationPhrase:u.confirmationPhrase})});return R(m,"Withdrawal requested.",!1,n)}return r==="source"?await Roe(e.slice(1),t,n):E(`Unknown creator command "${r??""}".`,t.json)}var iM="\0derived";function $P(e,t){return`${e}-${Ue("sha256").update(JSON.stringify(t)).digest("hex").slice(0,32)}`}async function oM(e,t,n,r){let i=k(n.idempotencyKey)??(e==="create"?`creator-${Ge(12).toString("hex")}`:iM),o=k(n.sessionId)??t[0],s=k(n.expectedRevision),a=s===void 0?void 0:Number(s);if(s!==void 0&&(!Number.isInteger(a)||Number(a)<1))return E("--expected-revision must be a positive integer.",n.json);let l=g=>{if(!o)throw new Error(`creator ${g} requires a session id.`);if(a===void 0)throw new Error(`creator ${g} requires --expected-revision.`);return{sessionId:o,expectedRevision:a,idempotencyKey:i}},c,u="POST",d;if(e==="create"){let g=k(n.skill)??t[0],y=k(n.outcome)??k(n.description),v=k(n.mode)??"guided";v==="guided"&&!n.json&&r.stdoutIsTty&&(g||(g=(await r.promptText(`Choose a unique kebab-case skill name:
@@ -2163,9 +2163,9 @@ Suggested answer: ${i.currentQuestion.suggestedAnswer}`:"",a=r?`Previous answer
2163
2163
  `:"",l;try{l=await t.promptText(`${o}${a}[${i.progress.questionNumber}/${i.progress.maximumQuestions}] ${i.currentQuestion.prompt}${s}
2164
2164
  Why: ${i.currentQuestion.whyAsked}
2165
2165
  > `)}catch(u){throw pP(u,n)}let c;try{c=Hp(i.currentQuestion.id,l)}catch(u){r=ke(u);continue}try{n=await D(t,`/api/v1/creator/sessions/${encodeURIComponent(String(n.sessionId))}/turn-answers`,{method:"POST",headers:V(t.apiKey),body:JSON.stringify({expectedRevision:n.revision,idempotencyKey:$P("creator-turn",{sessionId:n.sessionId,revision:n.revision,questionId:i.currentQuestion.id,answer:c}),questionId:i.currentQuestion.id,answer:c})}),r=null}catch(u){if(u instanceof Z&&u.status===422){r=ke(u);continue}throw pP(u,n)}}}async function sM(e,t,n){await Ve(K(t.paths.stateDir,"creator-resume.json"),{version:1,baseUrl:t.baseUrl,sessionId:String(e.sessionId),skillSlug:Va(e,!1)?.skillSlug??null,revision:e.revision,completed:n,savedAt:t.now()})}function pP(e,t){let n=Va(t,!1)?.skillSlug||String(t.sessionId),r=e instanceof Z&&e.status===409?" The server revision is authoritative; reload it before answering again.":"";return new Error(`${ke(e)}${r} Resume with skills-layer creator resume ${n}.`)}function Va(e,t=!0){let n=e.data,r=n&&typeof n=="object"&&!Array.isArray(n)?n.turn:null;if(!r||typeof r!="object"||Array.isArray(r)){if(t)throw new Error("Creator response did not include the canonical interview turn");return null}return r}async function aoe(e,t,n){let r=k(t.skill)??e[0]??"my-skill",i=aU("creator.init",r,t);if(i)return i;let o=k(t.dir)?Tt(n.cwd,k(t.dir)):K(n.paths.stateDir,"authoring",r),s;try{s=v1(k(t.type))}catch(y){return E(ke(y),t.json)}let a=k(t.category),l=await G1(o),c=await zk({cwd:n.cwd,files:l.files,explicitIdentifier:k(t.license),explicitLicenseFile:k(t.licenseFile),skip:!!t.skipLicense,interactive:!t.json&&n.stdoutIsTty,prompt:uU(n)}),u=k1({skillSlug:r,description:k(t.description)??`Helps with ${r.replaceAll("-"," ")}.`,skillType:s,category:a,licenseSelection:c.selection}),d=await ef({targetDir:o,files:u,confirmed:t.confirmed});if(d.status==="confirmation_required"){let y={status:"confirmation_required",reasonCode:"scaffold_overwrite_confirmation_required",targetDir:d.plan.targetDir,changes:d.plan.changes,preservedEntryCount:d.plan.preservedEntryCount,nextAction:"creator.init",nextStep:"Review the reported create/replace diff, then rerun with --confirm only if every replacement is intended."};return x(y,dU(d.plan),t.json,"scaffold_overwrite_confirmation_required")}let p=nt(u),m=Wk(u),h=K(d.plan.targetDir,"SKILL.md"),g=ie({status:d.status,path:h,skillSlug:r,skillType:s,category:a,targetDir:d.plan.targetDir,files:u.map(y=>y.path),fileCount:u.length,licenseStatus:p.license?.status??"unspecified",licenseIdentifier:p.license?.identifier??void 0,licenseSource:c.source,evaluationStatus:m.status,evalReadiness:m,warnings:[...p.issues.filter(y=>y.severity==="warning"),...m.status==="attention_needed"?[{severity:"warning",code:"evaluation_readiness_limited",message:"The scaffold is structurally valid, but its evaluation readiness needs attention before submission."}]:[]],validation:p});return t.json?R(g,`Created ${h}.`,!0,n):{exitCode:0,stdout:nce(g,d.plan.targetDir,h,n),stderr:""}}function uU(e){return{select:(t,n)=>e.promptSelect(t,n),text:t=>e.promptText(t)}}function dU(e){let t=e.changes.map(n=>`- ${n.action} ${n.path} (${n.previousBytes??0} -> ${n.nextBytes} bytes)`);return[`Creator init target already contains files at ${e.targetDir}.`,...t,"Re-run with --confirm only after reviewing every replacement."].join(`
2166
- `)}async function fr(e){try{return await JM(e),!0}catch{return!1}}function pU(e){return e.attestRights?{attestRights:!0,rightsBasis:k(e.rightsBasis)??"self_authored",distributionScope:k(e.distributionScope)??"commercial_distribution",rightsDeclarationVersion:Qj}:{}}async function DP(e,t,n,r){let i=k(t.visibility);if(i){let P=dc(i);if(!P||!ju.includes(P))return Fr(r?"creator.submit-version":"creator.submit","visibility",i,ju,t,"invalid_visibility")}let o=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let s=k(t.spacePack),a=s===void 0?void 0:sc(s);if(a===null)return Fr(r?"creator.submit-version":"creator.submit","spacePack",s,["5","10","20","50"],t,"invalid_private_skill_space_pack","space-pack");let l=k(t.creatorSessionId);if(l){let P=r?L(k(t.skill)??e[0],"creator submit-version with --creator-session-id requires a skill slug."):null,N=r?{creatorSessionId:l,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",...t.dryRun?{dryRun:!0}:{}}:{creatorSessionId:l,...t.dryRun?{dryRun:!0}:{},...a?{privateSkillSpacePack:a}:{}},O=r?`/api/v1/me/submissions/${encodeURIComponent(P)}/versions`:"/api/v1/me/submissions",X=await D(n,O,{method:"POST",headers:aM(n,t.dryRun?null:{path:O,creatorSessionId:l}),body:JSON.stringify(N)});return lM(X,t,n)??R(X,t.dryRun?qM(X):X.status==="submission_incomplete"?`Creator session submission is incomplete. ${f(X,"nextStep")??"Retry this session submission to complete finalization."}`:"Finalized Creator session submitted.",t.json,n)}let c=r?L(k(t.skill)??e[0],"creator submit-version requires a skill slug."):k(t.skill),u=L(k(t.source)??(r?e[1]:e[0])??t.path,`creator ${r?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),d=await Ku(u,n.cwd);if(t.list)return await doe(u,d,c,t,n);let p=Ni(r?"creator.submit-version":"creator.submit",t);if(p)return p;if(!d&&!qu(u)&&(Dz(u)||/^(?:github|gitlab):/iu.test(u)))return poe(u,t);let m=d?.files??(await ga({cwd:n.cwd,sourcePath:u,limits:ko})).files;if(!r&&!t.dryRun){let P=await foe(m,t,n);if(P)return P}if(t.dryRun&&gg(m))return loe(m,{slug:c,flags:t,backend:n});let h=gg(m)?await IC({baseUrl:n.baseUrl,apiKey:n.apiKey,fetchFn:n.fetchFn,files:m}):null,g=ie({...h?{hydrationManifestId:h.manifestId}:{files:m},version:k(t.version),dryRun:t.dryRun,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",evalSummary:noe(m,{skillSlug:c??oA(m)??"unknown",version:k(t.version)??"0.0.0",generatedAt:n.now()}),replaceUnpublished:r&&t.replaceUnpublished===!0?!0:void 0,priceCents:o.value,privateSkillSpacePack:a,...pU(t),...d?{sourceMetadata:d.sourceMetadata}:{},...Ft(t,["displayName","skillType","category","visibility","source","skill"])}),y=r&&c?`/api/v1/me/submissions/${encodeURIComponent(c)}/versions`:"/api/v1/me/submissions",v=await D(n,y,{method:"POST",headers:aM(n,t.dryRun?null:{path:y,request:g,files:m}),body:JSON.stringify(g)});if(t.json||t.noOpen||v.status!=="checkout_required"||typeof v.checkoutUrl!="string"||typeof v.chargeId!="string")return lM(v,t,n)??R(v,t.dryRun?qM(v):r?"Version submitted.":"Submission uploaded.",t.json,n);let b=T(v,"spacePack"),w=b?sc(b.code):null;n.emitInfo(w?`No private skill space is left. Opening checkout for ${qp(w).label} (${qp(w).displayPrice}); other packs: --space-pack 5|10|20|50. Complete the payment in your browser, then come back here.`:"Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(v.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${v.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let C=await ale(v.chargeId,n);return fe(C)?C:C.status!=="submitted"?R({...v,chargeStatus:C.status},`Payment is still ${C.status}. You can rerun \`skills-layer creator charge-status ${v.chargeId}\` to continue tracking it.`,t.json,n):R(C,r?"Version submitted.":"Submission uploaded.",t.json,n)}function aM(e,t){let n=V(e.apiKey);if(!t)return n;let{hydrationManifestId:r,files:i,evalSummary:o,...s}=t.request??{},a=t.files?Ue("sha256").update(JSON.stringify(t.files.map(c=>[c.path,c.content??null,c.contentBase64??null]))).digest("hex"):null,l=Ue("sha256").update(JSON.stringify({path:t.path,creatorSessionId:t.creatorSessionId??null,request:s,bundleDigest:a})).digest("hex");return{...n,"idempotency-key":`cli-submit-${l.slice(0,48)}`}}function lM(e,t,n){if(e.status!=="checkout_required"||typeof e.checkoutUrl!="string"||typeof e.chargeId!="string")return null;let r=`Open ${e.checkoutUrl} to complete payment, then run \`skills-layer creator charge-status ${e.chargeId}\` to confirm the submission.`;return R({...e,paymentRequired:!0,checkoutUrl:e.checkoutUrl,chargeId:e.chargeId,nextAction:"creator.charge-status",nextStep:r},`Payment required to finish: ${r}`,t.json,n)}function loe(e,t){let n="creator.submit",r=nt(e),i=e.reduce((l,c)=>l+us(c),0),o=t.slug??oA(e),s=["skill_name_availability","security_review","moderation","pricing_and_checkout","eval_evidence"],a=ie({status:r.valid?"ready":"blocked",reasonCode:r.valid?"local_preview_only":"invalid_bundle",dryRun:!0,previewMode:"local",operation:n,uploaded:!1,skillSlug:o,version:k(t.flags.version),bundle:{fileCount:e.length,totalBytes:i,transport:"source_hydration",artifactDigest:ct(e)},localChecks:[{check:"bundle_size",status:"passed"},{check:"paths",status:"passed"},{check:"secrets",status:"passed"},{check:"manifest",status:r.valid?"passed":"failed"}],serverChecks:{status:"not_run",checks:s},why:"The bundle exceeds the 2 MiB inline request limit, so the dry run previewed it locally and uploaded nothing.",validation:r,nextAction:r.valid?n:"validate",nextStep:r.valid?`Re-run without --dry-run to upload and submit. Server-only checks (${s.join(", ")}) run during the real submit.`:"Fix the bundle issues before submitting again."});return R(a,r.valid?`Local submission preview ready (${e.length} files, ${i} bytes; nothing uploaded). Server-only checks run on the real submit: ${s.join(", ")}.`:"Local submission preview blocked: the bundle does not satisfy the creator validation rules. Nothing was uploaded.",t.flags.json,t.backend)}var coe="Use `skills-layer creator spaces` or `skills-layer creator spaces buy --pack 5|10|20|50`.";function cM(e){if(e.status==="community_unlimited")return"Community edition supports unlimited private skills.";let t=n=>typeof e[n]=="number"?e[n]:0;return`Private skill spaces: ${t("availablePrivateSkillSpaces")} available of ${t("totalPrivateSkillSpaces")} (${t("activePrivateSkills")} active private skills; free ${t("freePrivateSkillSpacesUsed")} used, ${t("freePrivateSkillSpacesRemaining")} left; purchased ${t("purchasedPrivateSkillSpaces")}, ${t("purchasedPrivateSkillSpacesUsed")} used). Buy more with \`skills-layer creator spaces buy --pack 5|10|20|50\`: ${ac}.`}async function uoe(e,t,n){let r=e[0];if(r===void 0||r==="status"){let u=await D(n,"/api/v1/me/private-skill-spaces",{headers:ne(n.apiKey,n.authBlockedMessage)});return R(u,cM(u),t.json,n)}if(r!=="buy")return E(`Unknown creator spaces action "${r}". ${coe}`,t.json);let i=k(t.pack)??e[1],o=i===void 0?void 0:sc(i);if(o===null)return Fr("creator.spaces.buy","pack",i,["5","10","20","50"],t,"invalid_private_skill_space_pack","pack");let s=await D(n,"/api/v1/me/private-skill-spaces/checkout",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(o?{privateSkillSpacePack:o}:{})});if(s.status!=="checkout_required"||typeof s.checkoutUrl!="string")return R(s,cM(s),t.json,n);let a=qp(sc(T(s,"spacePack")?.code)??"spaces_5"),l=`Checkout for ${a.label} (${a.displayPrice}) is ready. Complete the payment in your browser, then run \`skills-layer creator spaces\` to see the credited spaces.`;return t.json||t.noOpen?R(s,`${l} Checkout URL: ${s.checkoutUrl}`,t.json,n):(await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),R(s,l,t.json,n))}async function doe(e,t,n,r,i){if(t)return R(uM(dA(e,t,n)),"Source skills loaded.",r.json,i);let o=await DU(i,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},r);return o.kind==="failure"?o.result:R(uM(o.inspection),"Source skills loaded.",r.json,i)}function uM(e){return{...e,sourceSubmissionSupported:!0}}function poe(e,t){let r=`skills-layer source connection start --provider ${LU(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return x({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:r},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${r}\`.`,t.json,"source_connection_required")}async function foe(e,t,n){let r=k(t.skill)??oA(e);if(!r)return null;let i;try{i=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(r)}`,{headers:ne(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof Z&&o.status===404)return fU(r,t);throw o}if(i.available===!1||f(i,"reasonCode")==="unavailable"||f(i,"reasonCode")==="reserved"){let o=f(i,"assignedSlug"),s=ie({status:"duplicate_candidate",reasonCode:f(i,"reasonCode")??"slug_unavailable",requestedSlug:r,assignedSlug:o,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${r}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return x(s,`A public skill slug "${r}" already exists or is not available. Run \`skills-layer creator status ${r}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,f(s,"reasonCode"))}return null}async function moe(e,t,n){try{let r=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:ne(n.apiKey,n.authBlockedMessage)});return R(goe(r),"Slug status loaded.",t.json,n)}catch(r){if(r instanceof Z&&r.status===404)return fU(e,t);throw r}}function fU(e,t){let n={status:"slug_check_unavailable",reasonCode:"slug_check_route_unavailable",requestedSlug:e,nextAction:"creator.status",nextStep:`Slug availability could not be checked on the selected backend. Run \`skills-layer creator submissions\`, \`skills-layer creator status ${e}\`, or retry after selecting a compatible Skills Layer backend.`};return x(n,`Slug availability could not be checked for ${e} on the selected backend. Run \`skills-layer creator submissions\` or retry after selecting a compatible Skills Layer backend.`,t.json,"slug_check_route_unavailable")}function goe(e){let t=e.available===!0,n=f(e,"assignedSlug");if(t)return ie({requestedSlug:f(e,"requestedSlug"),available:!0,reasonCode:f(e,"reasonCode")??"available",assignedSlug:n});let r=T(e,"slugAssignment"),i=Array.isArray(r?.candidateSlugs)?r.candidateSlugs.filter(o=>typeof o=="string").slice(0,3):void 0;return ie({...e,...r?{slugAssignment:{...r,...i?{candidateSlugs:i}:{}}}:{},...i?{candidateSlugs:i}:{}})}function hoe(e,t){return x({status:"not_submitted",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submit",nextStep:"Run `skills-layer creator submit <path> --dry-run` to validate a local skill before submitting it, or run `skills-layer creator submissions` to see your existing submissions."},`No creator submission was found for ${e}. Run \`skills-layer creator submit <path> --dry-run\` before checking status.`,t.json,"creator_submission_not_found")}function oA(e){let t=e.find(r=>r.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(r=>r.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(r=>!!r);return yoe(n??ot(Me(t.path)))}function yoe(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function voe(e,t,n){let r=L(e[1],"creator pricing requires a skill slug."),i=Ni("creator.pricing",t);if(i)return i;let o=new URLSearchParams;if(We(o,"version",t.version),!t.priceCents)return await he(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let a=s.value??0;if(t.dryRun){o.set("dryRun","true"),o.set("priceCents",String(a));let d=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:ne(n.apiKey,n.authBlockedMessage)});return d.dryRun!==!0||d.status!=="preview"?E("This backend does not support read-only pricing previews. Upgrade the backend before retrying.",t.json):R(d,"Pricing preview; the live price is unchanged.",t.json,n)}let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:ne(n.apiKey,n.authBlockedMessage)}),c=J(l,"priceCents")??0,u=J(l,"revision");if(!u||!Number.isSafeInteger(u)||u<1)return E("Pricing authority did not return a valid revision.",t.json);if(a>c&&!t.confirmed){let d=ie({status:"pending_approval",reasonCode:"price_increase_confirmation_required",skillSlug:r,version:f(l,"version"),currentPriceCents:c,requestedPriceCents:a,currency:f(l,"currency")??"usd",nextStep:"Review the old and new USD prices, then rerun with --yes."});return R(d,"Pricing change requires explicit confirmation.",t.json,n)}return await Fi(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing`,{priceCents:a,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),expectedRevision:u,idempotencyKey:k(t.idempotencyKey)?.trim()||`pricing-${Ge(12).toString("hex")}`,reason:"Creator changed the version list price through CLI.",...pU(t)},t,n,"Pricing updated.")}async function koe(e,t,n){try{return await Fi(`/api/v1/me/submissions/${encodeURIComponent(e)}`,Ft(t,["displayName","summary","description","category","skillType","license"]),t,n,"Listing updated.")}catch(r){if(r instanceof Z&&r.status===404){let i={status:"listing_not_found_or_not_editable",reasonCode:"creator_listing_not_found_or_not_owned",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see editable listings, or \`skills-layer show ${e}\` to inspect the public catalog entry.`};return x(i,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw r}}async function woe(e,t,n,r){let i=L(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let o=pr("creator.claim","requestedRole",n.requestedRole,Iie,n,"invalid_requested_role","requested-role");if(o)return o}try{if(e==="claim")return await Le(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/claim`,Ft(n,["requestedRole","message"]),n,r,"Ownership claim submitted.");if(e==="verify"){let o=L(n.claimId,"creator verify requires --claim-id.");return await Le(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/verify`,{claimId:o},n,r,"Ownership claim verified.")}return L(n.message,"creator dispute requires --message."),await Le(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/dispute`,Ft(n,["message"]),n,r,"Ownership dispute submitted.")}catch(o){if(o instanceof Z&&o.status===404){let s={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:i,requestedRole:k(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${i}\`, \`skills-layer show ${i}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${i}\` to start a new claim if the skill is claimable.`};return x(s,e==="claim"?`No claimable skill was found for ${i}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${i}. Start a new claim if the skill is claimable.`,n.json,f(s,"reasonCode")??"ownership_action_unavailable")}throw o}}async function boe(e,t,n){try{return await he(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(r){if(r instanceof Z&&r.status===404){let i={status:"no_creator_submission",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see skills you own, \`skills-layer show ${e}\` to inspect the catalog listing, or \`skills-layer creator claim ${e}\` if it is a claimable public-source skill.`};return x(i,`No creator-owned analytics submission was found for ${e}. Run \`skills-layer creator submissions\`, \`skills-layer show ${e}\`, or \`skills-layer creator claim ${e}\` if you should manage it.`,t.json,"creator_submission_not_found")}throw r}}async function _oe(e,t){let n=await D(t,"/api/v1/me/payout-profile",{headers:ne(t.apiKey,t.authBlockedMessage)});return R(n,"Creator payout profile loaded.",e.json,t)}function mU(e,t){let n={};return(r,i)=>UA({session:n,code:k(e.mfaCode),interactive:!e.json&&!t.nonInteractive&&t.stdoutIsTty,promptSecret:t.promptSecret,verify:async o=>{let s=await D(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({purpose:"creator_payout",code:o})});return L(s.stepUpGrant,"MFA verification did not return a step-up grant.")},request:o=>{let s=new Headers(i.headers);return o&&s.set("x-mfa-step-up-grant",o),D(t,r,{...i,headers:s})}})}async function dM(e,t){let n=Soe(k(e.mode));if(e.mode&&n===null)return E("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let r;try{r=await mU(e,t)("/api/v1/me/payout-profile/link",{method:"POST",headers:V(t.apiKey),body:JSON.stringify(ie({...n?{mode:n}:{},country:k(e.country)}))})}catch(o){if(o instanceof Z&&Coe(o))return x({status:"payout_setup_already_submitted",reasonCode:"payout_update_link_unavailable",nextAction:"creator.payout-profile",nextStep:"Run `skills-layer creator payout-profile` to confirm readiness, then use `skills-layer creator earnings` or `skills-layer creator withdraw --amount-cents <amount>`."},"The bank-update link could not be opened. Run `skills-layer creator payout-link --mode account_onboarding` to change your bank account.",e.json,"payout_update_link_unavailable");throw o}let i=mz(r);return i&&xoe(e)&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(i)||t.emitInfo(`Open this payout setup URL manually to continue: ${i}`)),R(r,"Payout setup link created.",e.json,t)}function Soe(e){if(!e)return null;let t=e.trim().toLowerCase();return t==="account_onboarding"||t==="onboarding"?"account_onboarding":t==="account_update"||t==="update"?"account_update":null}function xoe(e){return!e.json&&!e.noOpen}function Coe(e){let t=`${e.message} ${f(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function Ioe(e,t,n,r){let i=L(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await he(`/api/v1/me/skills/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await he(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let l=L(n.issueId,"creator update-issue requires --issue-id."),c=L(n.status,"creator update-issue requires --status."),u=pr("creator.update-issue","status",c,Pie,n,"invalid_issue_status");if(u)return u;let d=Ni("creator.update-issue",{...n,version:n.fixedVersion});if(d)return d;try{return await Fi(`/api/v1/me/skills/${encodeURIComponent(i)}/issues/${encodeURIComponent(l)}`,Ft(n,["status","fixedVersion","note"]),n,r,"Issue updated.")}catch(p){if(p instanceof Z&&p.status===404)return Poe(i,l,n);throw p}}let o=L(n.reviewId,"creator moderate-review requires --review-id."),s=L(n.status,"creator moderate-review requires --status."),a=pr("creator.moderate-review","status",s,Aie,n,"invalid_review_status");if(a)return a;try{return await Le(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews/${encodeURIComponent(o)}/moderate`,Ft(n,["status","reason"]),n,r,"Review updated.")}catch(l){if(l instanceof Z&&l.status===404)return Aoe(i,o,n);throw l}}function Poe(e,t,n){return x({status:"not_found",reasonCode:"issue_not_found",skillSlug:e,issueId:t,nextAction:"creator.issues",nextStep:`Run \`skills-layer creator issues ${e}\` to inspect open issues before updating one.`},`Issue ${t} was not found for ${e}. Run \`skills-layer creator issues ${e}\` first.`,n.json,"issue_not_found")}function Aoe(e,t,n){return x({status:"not_found",reasonCode:"review_not_found",skillSlug:e,reviewId:t,nextAction:"creator.reviews",nextStep:`Run \`skills-layer creator reviews ${e}\` to inspect review ids before moderating one.`},`Review ${t} was not found for ${e}. Run \`skills-layer creator reviews ${e}\` first.`,n.json,"review_not_found")}async function Roe(e,t,n){let r=e[0],i=L(e[1],`creator source ${r??""} requires a source connection id.`),o=k(t.skill)??e[2];if(r==="prepare"){let s=Ni("creator.source.prepare",t);if(s)return s;let a=pr("creator.source.prepare","visibility",t.visibility,qa,t,"invalid_visibility");if(a)return a;let l=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=k(t.source)??e[2],u=c?await Ku(c,n.cwd):void 0;return await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/prepare`,ie({...Ft(t,["skill","source","version","displayName","skillType","category","visibility"]),...l.value!==void 0?{priceCents:l.value}:{},source:c,...u?{files:u.files}:{}}),t,n,"Source release prepared.")}if(r==="publish-request"){let s=Ni("creator.source.publish-request",t);if(s)return s;let a=pr("creator.source.publish-request","visibility",t.visibility,qa,t,"invalid_visibility");if(a)return a;let l=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=t.approvalRequestId.length>0?t.approvalRequestId:k(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/publish-request`,ie({skillSlug:o,approvalRequestIds:c,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),...Ft(t,["visibility","license","discloseSource"]),...l.value!==void 0?{priceCents:l.value}:{}}),t,n,"Source publish requested.")}if(r==="release-status"){let s=new URLSearchParams;return o&&s.set("skill",o),await he(`/api/v1/me/source-connections/${encodeURIComponent(i)}/release-status${Qe(s)}`,t,n,"Source release status loaded.",{authenticated:!0})}return E(`Unknown creator source command "${r??""}".`,t.json)}function TP(e){return!e.list&&!e.dryRun}async function pM(e){if(!TP(e.flags)||k(e.flags.visibility)==="private"||k(e.flags.scope)==="workspace")return null;if(e.flags.all&&Array.isArray(e.inspection.catalogueDecisions)){let p=[];for(let m of ur(e.inspection)){let h=await Za([],{...e.flags,all:!1,json:!0,source:f(e.inspection,"catalogueSourceInput")??e.source,skill:m.value},e.backend);if(h.exitCode!==0){let g=JSON.parse(h.stderr||h.stdout);return x({status:"source_install_batch_partial",reasonCode:g.reasonCode??"source_install_child_failed",failedSkill:m.value,results:p,failure:g.data},"Source installation stopped; earlier results are retained.",e.flags.json,g.reasonCode??"source_install_child_failed")}p.push(JSON.parse(h.stdout).data)}return R({status:"source_install_batch",results:p},"Source installation results loaded.",e.flags.json,e.backend)}let t=T(e.inspection,"catalogueMatch");if(!t&&e.selectedSkillSlug&&typeof e.inspection.catalogueSourceInput=="string"){let p=await MP(e.backend,e.source,{source:e.inspection.catalogueSourceInput,skillSlug:e.selectedSkillSlug,preferCatalogue:!0,listOnly:!0},e.flags);if(p.kind==="failure")return p.result;t=T(p.inspection,"catalogueMatch"),t&&(e.inspection=p.inspection)}if(!t)return null;let n=ir(e.source),r=f(t,"skillSlug"),i=f(t,"version"),o=f(t,"generationId"),s=n.kind==="github"?n.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,l=(Array.isArray(e.inspection.results)?e.inspection.results:[]).find(p=>j(p)&&p.skillSlug===e.selectedSkillSlug),c=j(l)?f(l,"relativeSkillRoot"):void 0,u=c&&s&&c!=="."?s==="."||c===s||c.startsWith(`${s}/`)?c:`${s}/${c}`:void 0,d=typeof t.sourceRoot=="string"&&(t.sourceRoot==="."||!t.sourceRoot.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)));return n.kind!=="github"||t.schemaVersion!=="skills-layer.source-catalogue-match.v1"||typeof t.repository!="string"||t.repository.toLowerCase()!==`${n.owner}/${n.repo}`.toLowerCase()||!d||t.sourceRoot!==s&&t.sourceRoot!==u||typeof t.commitSha!="string"||!/^[a-f0-9]{40}$/u.test(t.commitSha)||/^[a-f0-9]{40}$/iu.test(n.ref)&&n.ref.toLowerCase()!==t.commitSha||!r||!/^[a-z0-9][a-z0-9-]{0,255}$/u.test(r)||!i||!o||e.selectedSkillSlug&&e.selectedSkillSlug!==t.requestedSkillSlug?x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e.source,nextStep:"Retry after the exact source-to-catalogue identity is refreshed. No raw-source fallback was activated."},"The catalogue match did not identify this exact GitHub skill and revision.",e.flags.json,"source_catalogue_identity_invalid"):Za([r],{...e.flags,source:void 0,skill:void 0,version:i},e.backend,{...gU,expectedSourceGeneration:{generationId:o,version:i}})}var gU={origin:"direct",fallbackPolicy:"eligible_public"};function Eoe(e){return{origin:"update_existing",fallbackPolicy:f(e??{},"acquisitionMode")==="authenticated_account"?"account_required":"eligible_public"}}async function Za(e,t,n,r=gU){if(e[0]==="status"&&e[1])return he(`/api/v1/install-receipts/${encodeURIComponent(e[1])}`,t,n,"Install progress loaded.",{authenticated:!!n.apiKey});let i=cU("install",t);if(i)return i;if(t.localOnly&&(t.visibility!==void 0||k(t.scope)==="workspace"||n.config?.workingModeType==="enterprise_workspace"))return x({status:"local_only_intent_conflict",reasonCode:"local_only_intent_conflict"},"Local-only installation requires a personal local target and cannot request platform visibility or workspace authority.",t.json,"local_only_intent_conflict");let o=k(t.source);if(o){let h=k(t.skill),g=yM(o,h,t);if(g)return g;let y=await Ku(o,n.cwd);if(y)return await mM(o,y,h,t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let v=vM(o,t);if(v)return v;let b=t.list||t.dryRun||!h&&!t.all,w=await MP(n,o,{source:o,skillSlug:h,listOnly:b,...t.all?{all:!0}:{},preferCatalogue:TP(t),visibility:k(t.visibility)},t);if(w.kind==="failure")return w.result;let _=w.inspection;if(t.list)return R(_,"Source skills loaded.",t.json,n);let C=Ah(o,_,t);if(C)return C;let P=await Nu({source:o,inspection:_,requestedSkillSlug:h,mode:"install",flags:t,backend:n});if(P.kind==="failure")return P.result;if(t.dryRun)return R(BP(o,_,P.skillSlug,t),"Source install preview ready.",t.json,n);let N=t.all?ur(_).map(Q=>Q.value):[P.skillSlug??ur(_)[0]?.value??ot(o)],O=await pM({inspection:_,source:o,selectedSkillSlug:P.skillSlug,flags:t,backend:n});if(O)return O;let X=await WB(n,N,t);if(X)return X;let G=f(_,"catalogueSourceInput")??o,ee=await gM({backend:n,flags:t,source:G,skillSlug:P.skillSlug,defaultAcceptUnverifiedSource:ji(o,t,n,w.sourceAccess)==="public"});if(fe(ee))return ee;let te;try{te=await wM({source:G,skillSlug:P.skillSlug,flags:t,backend:n,sourceAccess:w.sourceAccess})}catch(Q){if(ee)return await SM({backend:n,flags:t,source:G,sourceAccess:w.sourceAccess,skillSlug:P.skillSlug??N[0],unverifiedMaterialization:ee,error:Q});if(Q instanceof Z)return _M(o,Q,t);throw Q}return await zu({backend:n,result:te,fallbackSlug:P.skillSlug??f(te,"skillSlug")??o,source:G,sourceAccess:w.sourceAccess,flags:t,requestedVisibility:ji(o,t,n,w.sourceAccess),...ee?{unverifiedMaterialization:ee}:{}})}let s=L(e[0]??t.install,"install requires a skill slug or --source.");if(Dz(s)){let h=yM(s,k(t.skill),t);if(h)return h;let g=await Ku(s,n.cwd);if(g)return await mM(s,g,k(t.skill),t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let y=vM(s,t);if(y)return y;let v=k(t.skill),b,w="unknown",_=async Q=>{if(b)return null;let Ie=await MP(n,s,{source:s,skillSlug:v,listOnly:Q,...t.all?{all:!0}:{},preferCatalogue:TP(t),visibility:k(t.visibility)},t);return Ie.kind==="failure"?Ie.result:(b=Ie.inspection,w=Ie.sourceAccess,null)};if(t.list){let Q=await _(!0);return Q||R(b,"Source skills loaded.",t.json,n)}if(!v&&!t.all){let Q=await _(!0);if(Q)return Q;let Ie=b,fn=Ah(s,Ie,t);if(fn)return fn;let el=await Nu({source:s,inspection:Ie,requestedSkillSlug:v,mode:"install",flags:t,backend:n});if(el.kind==="failure")return el.result;v=el.skillSlug}if(t.dryRun){let Q=await _(!0);if(Q)return Q;let Ie=b,fn=await Nu({source:s,inspection:Ie,requestedSkillSlug:v,mode:"install",flags:t,backend:n});return fn.kind==="failure"?fn.result:(v=fn.skillSlug,R(BP(s,Ie,v,t),"Source install preview ready.",t.json,n))}let C=await _(!1);if(C)return C;let P=b,N=t.all?ur(P).map(Q=>Q.value):[v??ur(P)[0]?.value??ot(s)],O=await pM({inspection:P,source:s,selectedSkillSlug:v,flags:t,backend:n});if(O)return O;let X=await WB(n,N,t);if(X)return X;let G=f(P,"catalogueSourceInput")??s,ee=await gM({backend:n,flags:t,source:G,skillSlug:v,defaultAcceptUnverifiedSource:ji(s,t,n,w)==="public"});if(fe(ee))return ee;let te;try{te=await wM({source:G,skillSlug:v,flags:t,backend:n,sourceAccess:w})}catch(Q){if(ee)return await SM({backend:n,flags:t,source:G,sourceAccess:w,skillSlug:v??N[0],unverifiedMaterialization:ee,error:Q});if(Q instanceof Z)return _M(s,Q,t);throw Q}return await zu({backend:n,result:te,fallbackSlug:v??f(te,"skillSlug")??ot(s),source:G,sourceAccess:w,flags:t,requestedVisibility:ji(s,t,n,w),...ee?{unverifiedMaterialization:ee}:{}})}if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");if(k(t.scope)==="workspace"){let h=L(t.workspace,"workspace installs require --workspace <workspace-id>."),g=await hU(n,`/api/v1/workspaces/${encodeURIComponent(h)}/skills/${encodeURIComponent(s)}/approve`,{dryRun:t.dryRun},t);return fe(g)?g:t.dryRun?await ase(g,"Workspace approval preview ready.",t,n):R(g,"Workspace approval requested.",t.json,n)}if(!n.apiKey&&r.fallbackPolicy==="eligible_public")return await fP({target:s,flags:t,backend:n,catalogContext:r});if(!t.dryRun){let h;try{h=await rA(n,s,t)}catch(g){if(OP(r,g))return await fP({target:s,flags:t,backend:n,catalogContext:r});throw g}if(h)return h}let a=await vU(s,t,n);if("result"in a)return a.result;let l=a.flags,c=ie({skillSlug:s,version:k(l.version),scope:k(l.scope),agent:k(l.agent),dryRun:t.dryRun}),u;try{u=await sA(n,c,t)}catch(h){if(OP(r,h))return await fP({target:s,flags:t,backend:n,catalogContext:r,effectiveFlags:l});throw h}if(fe(u))return u;let d=u;if(d.status==="purchase_required")return MU(d,s,t,n);if(await Bi(n,d),t.dryRun)return await jU(d,l,n);let p=await aA(n,d,s,l,{expectedSourceGeneration:r.expectedSourceGeneration});if(fe(p))return p;let m=await uA(n,{...p,acquisitionMode:"authenticated_account",acquisitionOrigin:r.origin},s,l);return await Ka(n,m,s),Ga(m,Array.isArray(m.materializedWrites)&&m.materializedWrites.length>0?"Skill installed.":l.agent?"Recorded; choose --scope project|global to install files.":"Recorded; no agent selected \u2014 rerun with --agent <id> to write the skill files.",t.json,n,k(l.agent))}async function fP(e){let t=e.backend.apiKey?{...e.backend,apiKey:void 0,authBlockedMessage:void 0}:e.backend,n=e.effectiveFlags;if(!n){let o=await vU(e.target,e.flags,e.backend);if("result"in o)return o.result;n=o.flags}let r=k(n.version),i={status:"anonymous_public",skillSlug:e.target,...r?{version:r}:{},scope:k(n.scope),agent:k(n.agent),acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin};if(e.flags.dryRun)try{let o=await Sh(t,i,e.target,r,{exportMode:"public"});return await jU({...i,...Ch(o)},e.flags,t)}catch(o){if(o instanceof Z)return Ho(o,e.flags.json);throw o}try{let o=await aA(t,i,e.target,n,{exportMode:"public",expectedSourceGeneration:e.catalogContext.expectedSourceGeneration});if(fe(o))return o;let s=await uA(t,{...o,acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin},e.target,n);return await Ka(t,s,e.target),Ga(s,"Public skill installed locally without an account.",e.flags.json,t)}catch(o){if(o instanceof Z)return Ho(o,e.flags.json);throw o}}function OP(e,t){return e.fallbackPolicy==="eligible_public"&&t instanceof Z&&t.status===401&&f(t.details??{},"reasonCode")==="api_key_invalid_or_expired"}async function hU(e,t,n,r){let i=o=>D(e,t,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(n)}catch(o){let s=yU(o);if(!s)throw o;return r.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before workspace approval. Interactive acknowledgement is unavailable in this mode.",r.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}).`),await e.promptSelect("Approve this exact warned generation for the workspace?",[{value:"cancel",label:"Cancel approval",description:"Do not approve or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind approval to this warning revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Workspace approval cancelled without granting value.",r.json,"distribution_warning_declined"):i({...n,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}async function sA(e,t,n,r="/api/v1/install"){let i=o=>D(e,r,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(t)}catch(o){let s=yU(o);if(!s)throw o;return n.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before install. Interactive acknowledgement is unavailable in this mode.",n.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}). Next action: ${s.posture.nextAction}.`),await e.promptSelect("Continue with this exact warned skill generation?",[{value:"cancel",label:"Cancel install",description:"Do not grant or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind consent to this warning and authority revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Install cancelled without granting value.",n.json,"distribution_warning_declined"):await i({...t,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}function yU(e){if(!(e instanceof Z)||e.status!==409||!e.details)return null;let t=j(e.details.data)?e.details.data:e.details,n=j(t.distributionPosture)?t.distributionPosture:null,r=n?.contractVersion,i=n?.warningDigest,o=n?.authorityRevision;return!n||r!=="skills-layer.distribution.v1"||typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i)||typeof o!="number"||!Number.isSafeInteger(o)||o<1?null:{reasonCode:typeof t.reasonCode=="string"?t.reasonCode:"warning_acknowledgement_required",posture:{contractVersion:r,warningDigest:i,authorityRevision:o,effectiveDistributionStatus:typeof n.effectiveDistributionStatus=="string"?n.effectiveDistributionStatus:"published_with_warning",reasonCode:typeof n.reasonCode=="string"?n.reasonCode:"guardian_incident_warning",nextAction:typeof n.nextAction=="string"?n.nextAction:"review_warning_before_install"}}}async function vU(e,t,n){let r=k(t.scope),i=k(t.agent);if(t.json||t.dryRun||!n.stdoutIsTty||r==="workspace"||r==="local"||r!==void 0&&i!==void 0)return{flags:t};let o=et(n.env,n.platform,n.cwd),s=$oe(n),a=await Doe(n.paths.installTargetPreferencePath),l=a?.workingModeId===s,c=l&&a?.agent?o.find(w=>w.id===a.agent):void 0,u=c&&a?.scope?a.scope==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath:void 0;if(i===void 0&&r===void 0&&a?.policy==="recheck_every_5"&&l&&c!==void 0&&(a.scope==="project"||a.scope==="global")&&u!==void 0&&a.usesSinceConfirmation>0&&a.usesSinceConfirmation<4)return await Ve(n.paths.installTargetPreferencePath,{...a,usesSinceConfirmation:a.usesSinceConfirmation+1,savedAt:n.now()}),{flags:{...t,agent:c.id,scope:a.scope}};let p=await tR({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:fr}),m=p.filter(w=>w.detectionSources.includes("project")),h=i??Ee(n.env.SKILLS_LAYER_AGENT),g=h?o.find(w=>w.id===h):void 0;if(h&&!g)return{result:E(`Unsupported agent "${h}". Run \`skills-layer agents list\` to choose a supported install target.`,t.json)};if(!g&&m.length===1&&(g=m[0]),!g){let w=Ee(n.config?.lastSelectedAgent);g=w?p.find(_=>_.id===w)??o.find(_=>_.id===w):void 0}if(!g&&p.length===1&&(g=p[0]),!g&&p.length>1){let w=await n.promptSelect("Multiple supported agents were detected. Select one to install for:",p.map(_=>({value:_.id,label:`${_.displayName} (${_.detectionSources.join(", ")})`})));g=p.find(_=>_.id===w)}if(!g)return{result:E("No supported local agent was detected. Run `skills-layer agents list`, then retry with --agent <agent> and --scope <project|global>.",t.json)};let y=r;if(!y){let w=[{value:"project",label:"Project (this folder)"}];g.targets.globalSkillsPath&&w.push({value:"global",label:"Global (all projects)"}),y=w.length===1?w[0].value:await n.promptSelect(`Install ${e} for ${g.displayName} where?`,w)}let v=i!==void 0||r!==void 0,b=a?.policy==="ask_every_time"&&l;if(!v&&!b&&(y==="project"||y==="global")){let w=y==="project"?"Project":"Global",C=await n.promptSelect(`Remember ${g.displayName} / ${w} for future installs?`,[{value:"recheck_every_5",label:"Yes - recheck on every 5th install"},{value:"ask_every_time",label:"No - ask every time"}])==="recheck_every_5"?{version:1,policy:"recheck_every_5",agent:g.id,scope:y,usesSinceConfirmation:1,workingModeId:s,savedAt:n.now()}:{version:1,policy:"ask_every_time",usesSinceConfirmation:0,workingModeId:s,savedAt:n.now()};await Ve(n.paths.installTargetPreferencePath,C)}return{flags:{...t,agent:g.id,scope:y}}}function $oe(e){return e.apiKey?Ee(e.config?.workingModeId)??"personal":"anonymous"}async function Doe(e){let t=await be(e);return!j(t)||t.version!==1||t.policy!=="recheck_every_5"&&t.policy!=="ask_every_time"||typeof t.workingModeId!="string"||typeof t.savedAt!="string"||typeof t.usesSinceConfirmation!="number"||!Number.isInteger(t.usesSinceConfirmation)||t.usesSinceConfirmation<0||t.agent!==void 0&&typeof t.agent!="string"||t.scope!==void 0&&t.scope!=="project"&&t.scope!=="global"?null:t}async function aA(e,t,n,r,i={}){if(k(r.agent)==="all")return await Toe(e,t,n,r,i);let o=lA(e,t,n,r);if(o.status==="skip")return t;if(o.status==="cache_only"){let h=await Sh(e,t,o.skillSlug,o.version,i),g=await Ih({backend:e,exportResult:h,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(g))return g;let v=(e.platform==="win32"?st:Lt).join(e.paths.bundlesDir,o.skillSlug,g.envelope.generation.semanticVersion,encodeURIComponent(g.envelope.generation.generationId),"bundle.zip");return await EA(v,g.bytes),{...t,...Ch(h),version:g.envelope.generation.semanticVersion,scope:"local",archiveSha256:g.archiveSha256,archiveHashFormat:g.archiveHashFormat,manifestSha256:g.envelope.manifest.sha256,generationId:g.envelope.generation.generationId,sourceContentDigest:ct(g.files),verificationStatus:"verified",cachedArtifact:{state:"verified",bundlePath:v,generation:g.envelope.generation,archiveSha256:g.archiveSha256,manifestSha256:g.envelope.manifest.sha256,savedAt:e.now()}}}if(o.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:o.skillSlug,nextStep:o.nextStep},o.message,r.json,"materialization_target_invalid");let s=await Xa({backend:e,skillSlug:o.skillSlug,agentId:o.agent.id,scope:o.scope,flags:r});if(s)return s;let a=await Sh(e,t,o.skillSlug,o.version,i),l=await Ih({backend:e,exportResult:a,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(l))return l;let c=(await lt(e)).installs[o.skillSlug],u=Vn(c,{scope:o.scope,installedPath:(e.platform==="win32"?st:Lt).join(o.skillsPath,zr(o.skillSlug)),platform:e.platform})[0]?.record,d=u?f(u,"sourceContentDigest"):void 0,p=ct(l.files);if(u?.verificationStatus==="unverified"&&!r.replaceUnverifiedSource&&(await Tr({targetDir:(e.platform==="win32"?st:Lt).join(o.skillsPath,zr(o.skillSlug)),generation:l.envelope.generation,archiveSha256:l.archiveSha256,manifestSha256:l.envelope.manifest.sha256,files:l.envelope.manifest.files})).status!=="verified")return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:o.skillSlug,installedArchiveSha256:u.archiveSha256,approvedArchiveSha256:l.archiveSha256,installedContentDigest:d,approvedContentDigest:p,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and retry with --replace-unverified-source to replace them with the approved catalogue generation."},"The approved catalogue artifact differs from the installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let m=await cA({backend:e,skillSlug:o.skillSlug,scope:o.scope,agent:o.agent,skillsPath:o.skillsPath,bytes:l.bytes,files:l.files,envelope:l.envelope,approval:l.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});return{...t,...Ch(a),archiveSha256:l.archiveSha256,archiveHashFormat:l.archiveHashFormat,scope:o.scope,agent:o.agent.id,targetAgent:o.agent.id,materializationPlan:{scope:o.scope,agent:o.agent.id},...Uu(e),...m,...m.guardianActivationReceipt?{warnings:[...Be(t,"warnings")??[],...Be(m,"warnings")??[]]}:{}}}async function Toe(e,t,n,r,i){let o=T(t,"materializationPlan")??T(t,"installPlan"),s=k(r.scope)??f(t,"scope")??(o?f(o,"scope"):void 0),a=f(t,"skillSlug")??f(t,"slug")??n;if(s!=="project"&&s!=="global")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Use --agent all with --scope project or --scope global."},"Installing for all compatible agents requires project or global scope.",r.json,"materialization_target_invalid");let l=et(e.env,e.platform,e.cwd),c=new Map;for(let w of l){let _=s==="global"?w.targets.globalSkillsPath:w.targets.projectSkillsPath;if(!_)continue;let C=Mo(_,e.platform),P=c.get(C);P?P.agents.push(w):c.set(C,{agent:w,agents:[w],skillsPath:_})}if(c.size===0)return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Run `skills-layer agents list` and select a supported target with an available path."},`No supported agent exposes a ${s} skill path on this machine.`,r.json,"materialization_target_invalid");for(let w of c.values())for(let _ of w.agents){let C=await Xa({backend:e,skillSlug:a,agentId:_.id,scope:s,flags:r});if(C)return C}let u=f(t,"version")??f(t,"currentVersion"),d=await Sh(e,t,a,u,i),p=await Ih({backend:e,exportResult:d,flags:r,skillSlug:a,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(p))return p;let m=ct(p.files),h=(await lt(e)).installs[a],g;if(!r.replaceUnverifiedSource)for(let w of c.values()){let _=(e.platform==="win32"?st:Lt).join(w.skillsPath,zr(a)),C=Vn(h,{scope:s,installedPath:_,platform:e.platform})[0];if(C?.record.verificationStatus==="unverified"&&(await Tr({targetDir:_,generation:p.envelope.generation,archiveSha256:p.archiveSha256,manifestSha256:p.envelope.manifest.sha256,files:p.envelope.manifest.files})).status!=="verified"){g=C;break}}if(g)return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:a,materializationId:g.materializationId,installedContentDigest:f(g.record,"sourceContentDigest"),approvedContentDigest:m,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and use --replace-unverified-source to replace the unverified generation."},"The approved catalogue artifact differs from an installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let y=[];for(let w of c.values()){let _=await cA({backend:e,skillSlug:a,scope:s,agent:w.agent,skillsPath:w.skillsPath,bytes:p.bytes,files:p.files,envelope:p.envelope,approval:p.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});y.push({...t,scope:s,agent:w.agent.id,targetAgent:w.agent.id,...Uu(e),..._})}let v=y[0],b=v[Ph];return{...t,...Ch(d),archiveSha256:p.archiveSha256,archiveHashFormat:p.archiveHashFormat,scope:s,agent:"all",targetAgents:l.map(w=>w.id),materializationPlan:{scope:s,agent:"all",physicalTargetCount:y.length,agentCount:l.length},materializationResults:y,materializedWrites:y.flatMap(w=>Array.isArray(w.materializedWrites)?w.materializedWrites:[]),materializedSkillRoot:f(v,"materializedSkillRoot"),...Uu(e),...bU(b)?{[Ph]:b}:{}}}async function Xa(e){let t=e.backend.config?.workingModeType==="enterprise_workspace",n=e.enforceRequired?"enforce":await id(e.backend,e.skillSlug);if(!t&&n!=="enforce"&&n!=="enabled")return null;let r=Ee(e.backend.config?.workingModeWorkspaceId);if(t&&!r)return x({status:"blocked",reasonCode:"guardian_workspace_context_unavailable",skillSlug:e.skillSlug,agent:e.agentId,scope:e.scope,nextAction:"workspace.current",nextStep:"Refresh the selected Enterprise workspace before materializing this skill."},"Enterprise materialization requires a current workspace-bound Guardian context.",e.flags.json,"guardian_workspace_context_unavailable");let i=await qn(e.backend,e.scope),o=(Be(i,"hooks")??[]).filter(j).find(u=>f(u,"agent")===e.agentId&&f(u,"scope")===e.scope&&u.active===!0),s=br(e.agentId),a=vl({evaluationContext:"activation_eligibility",requestedMode:"enforce",workspacePolicy:t?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:s?.maximumTier==="strict_candidate",hookInstalled:!!o,strictHookVerified:o?.strictPreActionBlocking===!0&&o.evidenceCapability==="strict",exactActivationVerified:o?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"none",materializationState:"active"}),l=a.activationAllowed&&a.countedAsEnforced,c=t&&e.backend.config.workingModeGuardianPolicy==="standard"&&o!==void 0&&o.configActive!==!1;return l||c?(t&&(e.backend.guardianActivationReceipts??={},e.backend.guardianActivationReceipts[`${e.agentId}:${e.scope}`]={policy:e.backend.config.workingModeGuardianPolicy==="standard"?"standard":"strict",agent:e.agentId,scope:e.scope,tier:l?"strict_verified":"hook_unverified",observedAt:e.backend.now()}),null):x({status:"blocked",reasonCode:"guardian_enforcement_unavailable",skillSlug:e.skillSlug,workspaceId:r,agent:e.agentId,scope:e.scope,measuredProtection:{...a,evidenceCapability:o?.evidenceCapability??"unverified",evidenceReasons:o?.evidenceReasons??[s?.reasonCode??"host_has_no_supported_guardian_route"]},nextAction:"guardian.hook.install",nextStep:!o||o.configActive===!1?`Run skills-layer guardian hook install --agent ${e.agentId} --scope ${e.scope}.`:e.backend.config?.workingModeRole==="enterprise_admin"?`This host has no current strict verification. Select a qualified host or use skills-layer enterprise workspace update ${e.backend.config?.workingModeEnterpriseId??"<enterprise-id>"} ${r??"<workspace-id>"} --guardian-policy standard. Hook installation alone does not prove strict enforcement.`:"This host has no current strict verification. Ask your Enterprise Admin to select a qualified host or review the workspace Guardian policy. Hook installation alone does not prove strict enforcement."},t&&e.backend.config.workingModeGuardianPolicy==="standard"&&(!o||o.configActive===!1)?`No active Guardian hook is installed for ${e.agentId} at ${e.scope} scope.`:`${t?"Enterprise":"Guardian-enforced"} materialization was blocked because verified Guardian enforcement is unavailable.`,e.flags.json,"guardian_enforcement_unavailable")}function LP(e,t,n){let r=e.guardianActivationReceipts?.[`${t}:${n}`];return r?{guardianEnforcement:r.tier,guardianActivationReceipt:r,...r.tier==="hook_unverified"?{warnings:[`Guardian hook installed but not strict-verified on ${t}; workspace policy allows standard enforcement.`]}:{}}:{}}function Uu(e){return e.config?.workingModeType!=="enterprise_workspace"?{}:ie({workingModeType:"enterprise_workspace",enterpriseId:e.config.workingModeEnterpriseId,workspaceId:e.config.workingModeWorkspaceId,workingModeWorkspaceId:e.config.workingModeWorkspaceId})}function lA(e,t,n,r){let i=T(t,"materializationPlan")??T(t,"installPlan"),o=k(r.scope)??f(t,"scope")??(i?f(i,"scope"):void 0),s=f(t,"skillSlug")??f(t,"slug")??n;if(o==="local")return{status:"cache_only",skillSlug:s,version:f(t,"version")??f(t,"currentVersion")};if(o!=="project"&&o!=="global")return{status:"skip"};let a=k(r.agent)??f(t,"agent")??f(t,"targetAgent")??(i?f(i,"agent")??f(i,"targetAgent"):void 0)??Ee(e.config?.lastSelectedAgent)??"codex",l=et(e.env,e.platform,e.cwd).find(u=>u.id===a);if(!l)return{status:"failure",skillSlug:s,message:`Unsupported agent "${a}". Run \`skills-layer agents list\` to choose a supported local install target.`,nextStep:"Run `skills-layer agents list` and retry with a supported --agent value."};let c=o==="global"?l.targets.globalSkillsPath:l.targets.projectSkillsPath;return c?{status:"ok",scope:o,agent:l,skillsPath:c,skillSlug:s,version:f(t,"version")??f(t,"currentVersion")}:{status:"failure",skillSlug:s,message:`${l.displayName} does not expose a ${o} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function Sh(e,t,n,r,i={}){if(typeof t.downloadUrl=="string"&&j(t.artifactEnvelope)&&j(t.artifactApproval)&&j(t.platformScoreAuthority))return t;let o=new URLSearchParams;r&&o.set("version",r);let s=i.exportMode==="public"||!e.apiKey,a=s?`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`:`/api/v1/me/library/${encodeURIComponent(n)}/export${Qe(o)}`,l=await D(e,a,{headers:s?{}:ne(e.apiKey,e.authBlockedMessage)});if(!s&&!j(l.platformScoreAuthority))try{let c=await D(e,`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`,{headers:{}});return{...l,platformScoreAuthority:c.platformScoreAuthority}}catch(c){if(!(c instanceof Z)||![401,403,404].includes(c.status))throw c}return s?{...l,downloadUrl:Ooe(n,f(l,"version")??r)}:l}function Ooe(e,t){let n=new URLSearchParams;return t&&n.set("version",t),`/api/v1/skills/${encodeURIComponent(e)}/download${Qe(n)}`}function Loe(e){let t=f(e,"visibility")??f(e,"versionVisibility"),n=f(e,"publicationStatus");return kU(e)&&(t==="public"||n==="clean_publishable"||n==="publishable_with_findings")}function joe(e){return kU(e)}async function zu(e){let t=xh(e.result),n=f(t,"skillSlug")??f(t,"slug")??e.fallbackSlug,r=e.requestedVisibility??(f(t,"visibility")==="public"||f(t,"versionVisibility")==="public"||f(t,"releaseVisibility")==="public"?"public":"private");if(!joe(t)){let c=T(t,"publication"),u=f(t,"reasonCode")??(c?f(c,"reasonCode"):void 0)??"security_review_pending",d=!!e.unverifiedMaterialization,p=f(t,"version"),m=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"version")??f(e.unverifiedMaterialization,"currentVersion"):void 0,h=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"generationId"):void 0,g=c?f(c,"status")??f(t,"status")??"submitted":f(t,"status")??"submitted",y=g==="catalogue_submission_failed"||u==="source_ingestion_candidate_not_claimable",v=f(t,"workflowId"),b=f(t,"processingAttemptId"),w=f(t,"jobId"),_=f(t,"intakeReceiptId"),C=T(t,"progress")??{},P=!y&&t.continuationConfirmed!==!1&&!!(v||b||w)&&["queued","running","catalogue_processing_scheduled","held_for_moderation","source_install_pending_review","reused"].includes(g),N={status:y?"rejected":g==="reused"&&_?"reused":P?g==="reused"?"reused":"accepted":_?"accepted":"unconfirmed",reasonCode:u,continuationConfirmed:P,nextActor:f(C,"nextActor")??(P?"platform":u==="source_ingestion_candidate_not_claimable"?"operator":"requester")},O=ie({...e.unverifiedMaterialization,status:d?"installed_unverified":"install_pending_review",sourceItemStatus:f(t,"status")??"submitted",skillId:f(t,"skillId"),versionId:f(t,"versionId"),skillSlug:n,version:d?m:p,catalogueCandidateVersion:p,localProvisionalVersion:m,localGeneration:h,sourceContentDigest:e.unverifiedMaterialization?f(e.unverifiedMaterialization,"sourceContentDigest"):void 0,visibility:r,catalogueVisibilityRequested:r,requestedVisibility:r,catalogueStatus:g,publiclyDiscoverable:!1,intakeAdmission:N,assessmentStatus:f(C,"status")??(P?"pending":"unconfirmed"),publicationStatus:"not_published",distributionStatus:"verified_artifact_required",workflowId:v,processingAttemptId:b,jobId:w,intakeReceiptId:_,progress:t.progress,intakeReceiptIds:t.intakeReceiptIds,candidateIds:t.candidateIds,wakeStatus:t.wakeStatus,uploadIntent:t.uploadIntent,backgroundWorkStatus:P?"catalogue_review_continues_automatically":"retry_or_operator_action_required",publication:c?xh(c):void 0,activationStatus:d?"installed_unverified":"held",verificationStatus:d?"unverified":void 0,reasonCode:u,materializedWrites:d&&Array.isArray(e.unverifiedMaterialization?.materializedWrites)?e.unverifiedMaterialization.materializedWrites:[],materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex",activation:d?"unverified_install_request_authorized":"approved_artifact_only"},nextStep:d?`Local installation is complete as Unverified / Unscored. ${P?"The durable assessment job remains scheduled.":"Continued assessment is not confirmed; retry submission or inspect the candidate status."} Verified publication requires valid four-dimension evidence and current distribution authority. Valid poor effectiveness is a warning, not a security block.`:P?`Run skills-layer ${_?`install status ${_}`:`creator status ${n}`}, then retry when verified distribution is available.`:"Submission continuation is not confirmed. Inspect the intake status or retry submission before waiting for assessment."});return d&&await Ka(e.backend,O,n),Ga(O,d?`External source installed locally as unverified; ${P?"catalogue review continues":"catalogue continuation is unconfirmed"}.`:P?"Source submitted; installation is pending approval.":"Source installation is held; catalogue continuation is unconfirmed.",e.flags.json,e.backend)}let i=T(T(t,"progress")??{},"subject"),o=i?f(i,"generationId"):void 0,s=i?f(i,"version"):void 0;if(i&&(!o||!s||f(i,"slug")!==n))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",skillSlug:n,intakeReceiptId:t.intakeReceiptId,nextStep:"Retry after the source receipt identifies the exact approved skill, version and generation."},"The completed source receipt does not identify this exact skill and generation.",e.flags.json,"source_catalogue_identity_invalid");let a;try{a=await aA(e.backend,t,n,e.flags,{exportMode:Loe(t)?"public":"auto",...i?{expectedSourceGeneration:{generationId:o,version:s}}:{}})}catch(c){if(!(c instanceof Z)||![404,502,503,504].includes(c.status))throw c;let u=ie({...t,...e.unverifiedMaterialization,status:e.unverifiedMaterialization?"installed_unverified":"catalogue_artifact_unavailable",activationStatus:e.unverifiedMaterialization?"installed_unverified":"not_installed",sourceItemStatus:f(t,"status"),catalogueStatus:f(t,"status"),publicationStatus:"published",continuationConfirmed:!0,reasonCode:"catalogue_artifact_unavailable",serverReasonCode:c.details?f(c.details,"reasonCode"):void 0,nextStep:"The catalogue version is published, but its approved artifact could not be downloaded. Retry the install when export is available. Any existing local source install remains unverified."});return e.unverifiedMaterialization?(await Ka(e.backend,u,n),Ga(u,"Source installed locally as unverified; the published catalogue artifact is temporarily unavailable.",e.flags.json,e.backend)):x(u,"The published catalogue artifact is temporarily unavailable.",e.flags.json,"catalogue_artifact_unavailable")}if(fe(a))return a;let l=await uA(e.backend,a,n,e.flags);return await Ka(e.backend,l,n),Ga(l,tse(e.source,e.flags,e.backend,l,e.sourceAccess),e.flags.json,e.backend)}function xh(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>t==="localWrites"||t==="files"||t==="content"||t==="archiveBytes"?[]:Array.isArray(n)?[[t,n.map(r=>j(r)?xh(r):r)]]:j(n)?[[t,xh(n)]]:[[t,n]]))}function kU(e){if(wU(e.artifactApproval).status==="ok"&&e.artifactEnvelope!==void 0&&typeof e.downloadUrl=="string")return!0;let n=T(e,"publication"),r=n?f(n,"status")==="published":!1,i=f(e,"listingStatus")==="published",o=f(e,"versionStatus")==="published",s=f(e,"status");return i&&o&&(r||s==="published"||s==="reused"||s==="source_approved")}function Ch(e){return ie({version:f(e,"version"),storageKey:f(e,"storageKey"),expiresAt:f(e,"expiresAt")})}async function Ih(e){let t=wU(e.exportResult.artifactApproval);if(t.status!=="ok"){let d=t.status==="missing";return Ti(e,d?"artifact_v1_approval_missing":"artifact_v1_approval_invalid",d?`Export for ${e.skillSlug} did not include an authoritative approved Artifact Format v1 identity.`:`Export for ${e.skillSlug} included malformed Artifact Format v1 approval metadata.`)}let n=t.approval;if(e.expectedSourceGeneration&&(n.generation.generationId!==e.expectedSourceGeneration.generationId||n.generation.semanticVersion!==e.expectedSourceGeneration.version))return Ti(e,"source_catalogue_generation_mismatch","The exported artifact does not match the exact version and generation resolved for this source.");let r=Noe({backend:e.backend,exportResult:e.exportResult,approval:n,skillSlug:e.skillSlug});if(r.status!=="ok")return Ti(e,r.reasonCode,r.message);if(e.exportResult.artifactEnvelope===void 0)return Ti(e,"artifact_v1_envelope_missing",`Export for ${e.skillSlug} did not include an Artifact Format v1 envelope.`);let i=f(e.exportResult,"downloadUrl");if(!i)return x({status:"export_download_unavailable",reasonCode:"export_download_unavailable",skillSlug:e.skillSlug,nextStep:"Retry after the backend returns a signed bundle download URL."},`Export for ${e.skillSlug} did not include a signed download URL.`,e.flags.json,"export_download_unavailable");let o=await e.backend.fetchFn(Boe(e.backend.baseUrl,i));if(!o.ok)throw new Z(o.status,`Unable to download exported bundle (${o.status}).`);let s;try{s=await Moe(o)}catch(d){return Ti(e,"artifact_v1_archive_bounds_failed",`Downloaded ${e.skillSlug} exceeded Artifact Format v1 archive bounds.`,{verificationError:ke(d)})}let a,l;try{a=Ud({archiveBytes:s,envelope:e.exportResult.artifactEnvelope}),l=Il({archiveBytes:s,envelope:a})}catch(d){return Ti(e,"artifact_v1_verification_failed",`Downloaded ${e.skillSlug} failed Artifact Format v1 verification.`,{verificationError:ke(d)})}if(!Foe(n,a))return Ti(e,"artifact_v1_identity_mismatch",`Downloaded ${e.skillSlug} did not match the authoritative approved generation.`);let c=f(e.exportResult,"skillSlug"),u=f(e.exportResult,"version");return a.generation.skillSlug!==e.skillSlug||c!==void 0&&c!==a.generation.skillSlug||u!==void 0&&u!==a.generation.semanticVersion?Ti(e,"artifact_v1_target_mismatch",`Downloaded ${e.skillSlug} was approved for a different skill or version.`):{status:"ok",bytes:s,files:l,envelope:a,approval:n,archiveSha256:a.archive.sha256,archiveBytesSha256:a.archive.sha256,archiveHashFormat:"artifact_v1_zip"}}function Noe(e){let t=T(e.exportResult,"platformScoreAuthority"),n=t?.machineReport,r=t?.passport,i=t?.parityManifest,o=t?f(t,"passportPublicKey"):void 0;if(!t||!oC(n)||!o)return{status:"invalid",reasonCode:"platform_score_authority_missing",message:`Export for ${e.skillSlug} did not include a verifiable Platform Score authority.`};let s=Xc.safeParse(r),a=iC.safeParse(i);if(!s.success||!a.success)return{status:"invalid",reasonCode:"platform_score_authority_invalid",message:`Export for ${e.skillSlug} included malformed Platform Score authority metadata.`};let l=n.projection.report;if(l.subject.slug!==e.skillSlug||l.subject.version!==e.approval.generation.semanticVersion||l.subject.generationId!==e.approval.generation.generationId||l.subject.archiveSha256!==e.approval.archiveSha256||a.data.report.reportId!==l.reportId||a.data.report.revision!==l.revision||a.data.report.digest!==l.reportDigest)return{status:"invalid",reasonCode:"platform_score_authority_subject_mismatch",message:`Export for ${e.skillSlug} did not match the exact Platform Score generation.`};try{let c=sj({passport:s.data,publicKeys:{[s.data.issuer.keyId]:dre(o)},now:e.backend.now(),expectedSubject:l.subject,expectedReport:{reportId:l.reportId,revision:l.revision,digest:l.reportDigest},currentPassportId:s.data.passportId});if(!c.valid)return{status:"invalid",reasonCode:`platform_score_${c.reasonCode}`,message:`Export for ${e.skillSlug} failed signed Skill Passport verification.`}}catch{return{status:"invalid",reasonCode:"platform_score_passport_key_invalid",message:`Export for ${e.skillSlug} included an invalid Skill Passport public key.`}}return{status:"ok"}}function wU(e){return e==null?{status:"missing"}:!j(e)||e.status!=="approved"||!j(e.generation)||typeof e.generation.skillSlug!="string"||typeof e.generation.semanticVersion!="string"||typeof e.generation.generationId!="string"||typeof e.archiveSha256!="string"||typeof e.manifestSha256!="string"?{status:"invalid"}:{status:"ok",approval:{status:"approved",generation:{skillSlug:e.generation.skillSlug,semanticVersion:e.generation.semanticVersion,generationId:e.generation.generationId},archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256}}}function Foe(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archive.sha256&&e.manifestSha256===t.manifest.sha256}function Ti(e,t,n,r={}){return x({status:"download_integrity_failed",reasonCode:t,skillSlug:e.skillSlug,version:f(e.exportResult,"version"),archiveHashFormat:"artifact_v1_zip",...r,nextStep:"Retry after the catalog serving generation is refreshed, or contact Skills Layer support if this repeats."},n,e.flags.json,t)}function Boe(e,t){return/^https?:\/\//iu.test(t)?t:`${dr(e)}${t.startsWith("/")?"":"/"}${t}`}async function Moe(e){let t=e.headers.get("content-length");if(t!==null){let a=Number(t);if(!Number.isSafeInteger(a)||a<0)throw new Error("Artifact response Content-Length is invalid.");if(a>ut.maxArchiveBytes)throw new Error("Artifact response exceeds the v1 archive byte limit.")}if(!e.body)throw new Error("Artifact response body is unavailable.");let n=e.body.getReader(),r=[],i=0;try{for(;;){let a=await n.read();if(a.done)break;if(i+=a.value.byteLength,i>ut.maxArchiveBytes)throw await n.cancel("Artifact response exceeds the v1 archive byte limit."),new Error("Artifact response exceeds the v1 archive byte limit.");r.push(Uint8Array.from(a.value))}}finally{n.releaseLock()}let o=new Uint8Array(i),s=0;for(let a of r)o.set(a,s),s+=a.byteLength;return o}async function cA(e){let t=e.verificationStatus??"verified";if(t==="verified"&&!e.approval)throw new Error("Verified materialization requires platform artifact approval.");let n=e.backend.platform==="win32"?st:Lt,r=ct(e.files),i=n.join(e.backend.paths.bundlesDir,e.skillSlug,e.envelope.generation.semanticVersion,encodeURIComponent(e.envelope.generation.generationId),"bundle.zip"),o=n.join(e.skillsPath,zr(e.skillSlug)),s=et(e.backend.env,e.backend.platform,e.backend.cwd).filter(G=>{let ee=e.scope==="global"?G.targets.globalSkillsPath:G.targets.projectSkillsPath;return ee!==null&&Mo(ee,e.backend.platform)===Mo(e.skillsPath,e.backend.platform)}).map(G=>G.id).sort(),a=`activation_${Ge(16).toString("hex")}`,l={targetDir:o,generation:e.envelope.generation,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,files:e.envelope.manifest.files},c=hz({scope:e.scope,targetDir:o,platform:e.backend.platform}),u=await lt(e.backend);for(let[G,ee]of Object.entries(u.installs)){let te=[ee,...Rn(ee).map(Q=>Q.record)].flatMap(Q=>[Yt(Q)?.receipt.targetDir,f(Q,"materializedSkillRoot"),f(Q,"materializedPath")]);if(G!==e.skillSlug&&te.some(Q=>Q&&bA(o,Q,e.backend.platform)))throw new Error(`Install folder already belongs to another skill (${G}). Remove that installation or choose a different target before installing ${e.skillSlug}.`)}let d=u.installs[e.skillSlug],p=Xt(d)[c],m=JSON.stringify(p??null),h=Zu({state:"pending_activation",operationId:a,receipt:l,backend:e.backend}),g=Zu({state:"active",operationId:a,receipt:l,backend:e.backend}),y={skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,targetAgents:s.length>0?s:[e.agent.id],materializedPath:o,materializedSkillRoot:o,materializationId:c,bundlePath:i,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,...Uu(e.backend),...LP(e.backend,e.agent.id,e.scope),localLifecycle:h,savedAt:e.backend.now()};await EA(i,e.bytes);let v=e.files.find(G=>ot(G.path).toLowerCase()==="skill.md"),b=v?await Zae({backend:e.backend,skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,skillDocumentPath:n.join(o,...fM(v.path)),skillDocumentContent:v.content??""}):void 0,w,_=!1,C;try{let G={targetDir:o,...t==="verified"&&p?.verificationStatus==="unverified"&&!e.replaceUnverifiedSource?{expectedPreviousReceipt:l}:{},archiveBytes:e.bytes,envelope:e.envelope,preActivate:async({stageDir:ee})=>{let te=await zoe({backend:e.backend,stageDir:ee,envelope:e.envelope});return te.status==="passed"?(w=te.evalRun,{status:"passed",evidenceId:te.evidenceId}):{status:"failed",reasonCode:te.reasonCode}},checkpoint:async ee=>{if(ee==="after_static_eval"){await Mr(e.backend,te=>{let Q=te.installs[e.skillSlug],Ie=Xt(Q)[c];if(JSON.stringify(Ie??null)!==m)throw new Error(`Local install materialization for ${e.skillSlug} changed during atomic activation.`);te.installs[e.skillSlug]=Br({existing:Q,skillSlug:e.skillSlug,materialization:y,backend:e.backend})}),_=!0;return}ee==="after_stage_activated"&&await Mr(e.backend,te=>{let Q=te.installs[e.skillSlug],Ie=Xt(Q)[c],fn=Ie?Yt(Ie):null;if(!fn||fn.state!=="pending_activation"||fn.operationId!==a)throw new Error(`Atomic activation receipt reservation for ${e.skillSlug} was lost before commit.`);te.installs[e.skillSlug]=Br({existing:Q,skillSlug:e.skillSlug,materialization:{...y,localLifecycle:g,savedAt:e.backend.now()},backend:e.backend})})}};C=t==="verified"?await l2({...G,approval:e.approval}):await c2(G)}catch(G){throw _&&await ble({backend:e.backend,skillSlug:e.skillSlug,materializationId:c,operationId:a,baselineMaterialization:p}),G}if(!w)throw new Error("Static pre-activation Eval did not produce generation-bound evidence.");let P=await lt(e.backend),N=Xt(P.installs[e.skillSlug])[c],O=N?Yt(N):null;if(!O||O.state!=="active"||O.operationId!==a)throw new Error(`Atomic activation receipt for ${e.skillSlug} was not committed.`);let X=C.receipt.files.map(G=>({path:EU(e.backend.cwd,n.join(o,...fM(G.path))),bytes:G.sizeBytes}));return{...e.backend.config?.workingModeType==="enterprise_workspace"?{status:"installed"}:{},bundlePath:i,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,...Uu(e.backend),...LP(e.backend,e.agent.id,e.scope),materializedPath:o,materializedSkillRoot:o,materializationId:c,targetAgents:s.length>0?s:[e.agent.id],archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,materializedWrites:X,...b?{guardianRuntimeMetadata:b}:{},localLifecycle:g,atomicActivation:{status:C.status,receipt:C.receipt,generation:C.receipt.generation,archiveSha256:C.receipt.archiveSha256,manifestSha256:C.receipt.manifestSha256,staticEvaluation:C.staticEvaluation,cleanupPending:C.cleanupPending,...C.cleanupPath?{cleanupPath:C.cleanupPath}:{}},[Ph]:w}}var Ph=Symbol("skills-layer.pre-activation-eval"),Uoe=new Set(["file_exists","json_valid","schema_match","section_exists","regex_match","artifact_valid"]);async function zoe(e){let t=await _U(e.stageDir),n=ct(t),r=CU(t,n),i=l=>cT({pack:l,files:t,activationState:"inactive_staging",skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now(),runnerVersion:jP()}),o=i(r.pack);if(o.outcome!=="completed")return{status:"failed",reasonCode:o.reasonCode};let s=i(IU(t,n));if(s.outcome!=="completed")return{status:"failed",reasonCode:s.reasonCode};if(s.result.summary.status!=="passed")return{status:"failed",reasonCode:`static_eval_${s.result.summary.status}`};let a=xU({files:t,skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now()});return{status:"passed",evidenceId:`${s.result.summary.evalPackDigest??"eval-pack-unavailable"}:${s.result.summary.artifactDigest}`,evalRun:a}}async function uA(e,t,n,r){let i=f(t,"materializedSkillRoot");if(!i)return t;let o=f(t,"skillSlug")??f(t,"slug")??n,s=f(t,"version")??f(t,"currentVersion")??k(r.version)??"local";try{let a=t[Ph],l;if(bU(a))l=a;else{let u=await _U(Tt(e.cwd,i));if(u.length===0)return gh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"installed_files_unreadable"});l=xU({files:u,skillSlug:o,version:s,generatedAt:e.now()})}let c=await Yoe(e,l.summary);return c.status==="recorded"?gh({...t,...c.effectiveness?{effectiveness:c.effectiveness}:{}},r,{status:"recorded",source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,evidenceRevision:c.evidenceRevision}):gh(t,r,{status:c.status,source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,reasonCode:c.reasonCode})}catch(a){return gh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"local_eval_failed",message:ke(a)})}}function bU(e){return j(e)&&(e.source==="submitted"||e.source==="inferred"||e.source==="invalid_submitted")&&j(e.summary)&&e.summary.schemaVersion==="skills-layer.eval.summary.v1"}async function _U(e){let t=[];return await SU(e,e,t),t.sort((n,r)=>n.path.localeCompare(r.path))}async function SU(e,t,n){for(let r of await mre(t,{withFileTypes:!0})){if(qoe(r.name))continue;let i=K(t,r.name);if(r.isDirectory()){await SU(e,i,n);continue}if(!(!r.isFile()||Goe(r.name)))try{n.push({path:Mu(e,i).split("\\").join("/"),content:await Ui(i,"utf8")})}catch{continue}}}function qoe(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Voe()||e==="dist"}function Voe(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}function Goe(e){return e==="bundle.zip"||/^\.skills-layer-.*\.json$/u.test(e)}function xU(e){let t=ct(e.files),n=CU(e.files,t);if(!uf(n.pack).valid)return{source:"invalid_submitted",summary:$s({status:"runner_unavailable",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:t,evalPackDigest:Es(n.pack),generatedAt:e.generatedAt,runnerVersion:jP(),counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})};let i=Koe(n.pack).map(s=>({id:s.id,assertions:s.assertions.map(a=>Woe(a,e.files))})),o=Zoe(i);return{source:n.source,summary:$s({status:Joe(o),skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:typeof n.pack.artifactDigest=="string"?n.pack.artifactDigest:t,evalPackDigest:Es(n.pack),generatedAt:e.generatedAt,runnerVersion:jP(),counts:{cases:i.length,assertions:o.total,passed:o.passed,failed:o.failed,skipped:o.skipped}})}}function CU(e,t){let n=Hoe(e);return n?{pack:n,source:"submitted"}:{pack:IU(e,t),source:"inferred"}}function Hoe(e){for(let t of e){let n=Dn(t.path,e);if(!(n.type!=="evidence"||!t.content||!n.relativePath.toLowerCase().endsWith(".eval.json")))try{let r=JSON.parse(t.content);if(j(r))return r}catch{return{schemaVersion:"invalid",artifactDigest:ct(e),origin:"submitted",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[]}}}}function IU(e,t){let r=e.find(i=>i.path.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()==="skill.md")?.path??"SKILL.md";return{schemaVersion:"skills-layer.eval.pack.v1",artifactDigest:t,origin:"inferred",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[{id:"starter-runtime-shape",assertions:[{type:"file_exists",path:r},{type:"regex_match",path:r,pattern:"name:"},{type:"artifact_valid",artifactDigest:t}]}]}}function Koe(e){return Array.isArray(e.cases)?e.cases.flatMap(t=>!j(t)||typeof t.id!="string"||!Array.isArray(t.assertions)?[]:[{id:t.id,assertions:t.assertions.filter(j)}]):[]}function Woe(e,t){return typeof e.type=="string"&&!Uoe.has(e.type)?{status:"skipped",reasonCode:"runner_unavailable"}:lf(e,{files:t})}function Zoe(e){return e.reduce((t,n)=>{for(let r of n.assertions)t.total+=1,r.status==="passed"&&(t.passed+=1),r.status==="failed"&&(t.failed+=1),r.status==="skipped"&&(t.skipped+=1);return t},{total:0,passed:0,failed:0,skipped:0})}function Joe(e){return e.failed>0?"failed":e.passed>0?"passed":e.skipped>0?"runner_unavailable":"not_run"}function jP(){return`skills-layer-public-cli:${Co}:local-install`}async function Yoe(e,t){if(!e.apiKey)return{status:"local_only",reasonCode:"not_authenticated"};try{let n=await D(e,"/api/v1/me/evals/results",{method:"POST",headers:{"content-type":"application/json",...ne(e.apiKey,e.authBlockedMessage)},body:JSON.stringify({evalSummary:t})}),r=T(n,"evalEvidence");return{status:"recorded",effectiveness:T(n,"effectiveness"),evidenceRevision:r?J(r,"revision"):void 0}}catch(n){return{status:"submit_failed",reasonCode:n instanceof Z?`http_${n.status}`:"request_failed"}}}function gh(e,t,n){return t.json?{...e,localEval:n}:e}function fM(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(r=>r.length>0);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function mM(e,t,n,r,i){let o=k(r.visibility)??"private";if(o!=="private"&&o!=="public")return x({status:"invalid_visibility",reasonCode:"invalid_visibility",source:e,requestedVisibility:o,nextStep:`Use \`skills-layer install ${e} --visibility private\` or \`--visibility public\`.`},"Local path install visibility must be private or public.",r.json,"invalid_visibility");let s=dA(e,t,n);if(r.list)return R(s,"Local source skills loaded.",r.json,i);let a=Ah(e,s,r);if(a)return a;let l=await Nu({source:e,inspection:s,requestedSkillSlug:n,mode:"install",flags:r,backend:i});if(l.kind==="failure")return l.result;let c=l.skillSlug??ur(s)[0]?.value??RU(e),u=Xoe(t.files,c),d=Jr({files:u,limits:ko}),p={mode:r.localOnly?"local_only":o==="public"?"explicit_public":"managed_private",upload:!r.localOnly,destination:r.localOnly?null:i.baseUrl,audience:r.localOnly?"local_device":o==="public"?"public_after_governed_review":"account_private",authentication:r.localOnly?"not_required":"required",files:d.preview.files.map(y=>({path:y.path,bytes:y.bytes})),totalBytes:d.preview.totalBytes};if(r.dryRun)return R({...BP(e,s,c,r),installKind:"local_source_submission",visibility:o,publicationStatus:"preview",catalogRecord:o,activationStatus:"not_started",uploadIntent:p,nextStep:r.localOnly?"Re-run without --dry-run for unverified, unscored local activation without upload.":`Re-run without --dry-run to create or reuse the ${o} central item. Local activation remains held until the exact generation completes security review and Artifact-v1 approval.`},"Local source submission preview ready.",r.json,i);if(r.localOnly){let y=await NP({backend:i,flags:r,source:e,skillSlug:c,files:u,defaultAcceptUnverifiedSource:!0});if(fe(y))return y;let v={...y,status:"installed_unverified",activationStatus:"installed_unverified",uploadIntent:p,intakeAdmission:{status:"not_requested"},assessmentStatus:"not_requested",publicationStatus:"not_requested",distributionStatus:"unverified_local",backgroundWorkStatus:"not_requested"};return await Ka(i,v,c),Ga(v,"Local source installed as unverified and unscored. No files were uploaded.",r.json,i)}if(!i.apiKey)return x({reasonCode:"local_source_authentication_required",uploadIntent:p,nextStep:"Sign in for managed submission, or use --local-only for an unverified installation without upload."},"Managed local source submission requires authentication before uploading files.",r.json,"local_source_authentication_required");i.emitInfo(`Upload intent: ${p.files.length} selected files (${p.totalBytes} bytes) to ${i.baseUrl}; audience ${p.audience}; authenticated account required. Use --dry-run --json to inspect the file list or --local-only to avoid upload.`);let m=await rA(i,c,r);if(m)return m;let h;if(PU(r,i)){let y=await NP({backend:i,flags:r,source:e,skillSlug:c,files:u});if(fe(y))return y;h=y}let g;try{let y=gg(u)?await IC({baseUrl:i.baseUrl,apiKey:i.apiKey,fetchFn:i.fetchFn,files:u}):null;g=await D(i,"/api/v1/me/source-installs",{method:"POST",headers:{"content-type":"application/json",...ne(i.apiKey,i.authBlockedMessage)},body:JSON.stringify(ie({...y?{hydrationManifestId:y.manifestId}:{files:u},skillSlug:c,version:k(r.version),visibility:o,category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),sourceMetadata:t.sourceMetadata}))})}catch(y){return h?await zu({backend:i,flags:r,source:e,fallbackSlug:c,sourceAccess:"authenticated",requestedVisibility:o,unverifiedMaterialization:h,result:{status:"catalogue_submission_failed",skillSlug:c,uploadIntent:p,reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable"}}):x({status:"catalogue_submission_failed",uploadIntent:p,activationStatus:"not_started",intakeAdmission:{status:"rejected"},assessmentStatus:"not_requested",publicationStatus:"not_published",distributionStatus:"verified_artifact_required",reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable",skillSlug:c,nextStep:"Retry the source submission when catalogue service is available. No local files were written."},"The source was not installed because catalogue submission did not complete.",r.json,"catalogue_submission_failed")}return await zu({backend:i,result:{...g,uploadIntent:p},fallbackSlug:f(g,"skillSlug")??c,source:e,sourceAccess:"authenticated",flags:r,requestedVisibility:o,...h?{unverifiedMaterialization:h}:{}})}function Xoe(e,t){let n=pA(e).find(i=>i.skillSlug===t);if(!n||n.relativeSkillRoot===".")return e.map(i=>({...i}));let r=`${n.relativeSkillRoot.replace(/\/+$/u,"")}/`;return e.filter(i=>i.path.replaceAll("\\","/").startsWith(r)).map(i=>({...i,path:i.path.replaceAll("\\","/").slice(r.length)}))}async function gM(e){if(!e.flags.all&&!(!e.defaultAcceptUnverifiedSource&&!PU(e.flags,e.backend)))try{let t=ir(e.source),n=await Ej({source:t,cwd:e.backend.cwd,platform:e.backend.platform,fetchFn:e.backend.fetchFn,...e.skillSlug?{requestedSkillSlug:e.skillSlug}:{}}),r=e.skillSlug?n.results.find(i=>i.skillSlug===e.skillSlug):n.results.length===1?n.results[0]:void 0;return r?await NP({backend:e.backend,flags:e.flags,source:e.source,skillSlug:r.skillSlug,files:r.files,relativeSkillRoot:r.relativeSkillRoot,defaultAcceptUnverifiedSource:e.defaultAcceptUnverifiedSource}):e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,nextStep:"Use --list to inspect the source and --skill <skill-slug> to select one exact skill before retrying."},"The CLI could not resolve one immutable external skill snapshot for local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}catch(t){return e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,error:t instanceof Error?t.message.slice(0,512):"Source snapshot could not be loaded.",nextStep:"Check source access and retry the exact source after its immutable snapshot is available."},"The CLI could not load the external source snapshot for unverified local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}}async function NP(e){let t=Jr({files:e.files,limits:ko}),n=nt(e.files,{profile:"external_ingest_tolerant"}),r=x2(e.files,S2),i=[...t.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:/^(?:secret_|pii_|sensitive_)/u.test(_.code)?"privacy":"integrity",..._.path?{path:_.path}:{}})),...n.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:"package_validity"})),...r.filter(_=>_.severity==="high"||_.severity==="critical").map(_=>({code:_.ruleId,concern:"security",path:_.filePath,..._.lineNumber?{lineNumber:_.lineNumber}:{}}))],o=i.map(_=>_.code);if(o.length>0){let _=i.some(C=>C.concern==="security")?"critical_local_preflight_blocked":"source_package_invalid";return x({status:"unverified_install_blocked",reasonCode:_,skillSlug:e.skillSlug,findingCodes:[...new Set(o)].sort((C,P)=>C.localeCompare(P)),blockingFindings:i,nextStep:"Do not activate this source. Review or remove the blocking content, then retry from a new immutable generation."},"External source did not satisfy the required local package checks and was not installed.",e.flags.json,_)}if(!(e.flags.acceptUnverifiedSource===!0||e.defaultAcceptUnverifiedSource===!0||await Qoe(e)))return x({status:"unverified_install_consent_required",reasonCode:"unverified_source_consent_required",skillSlug:e.skillSlug,nextStep:"Review the source, then retry with --accept-unverified-source to install it before platform approval."},"External source was not installed because informed unverified-source consent was not provided.",e.flags.json,"unverified_source_consent_required");let a=lA(e.backend,{skillSlug:e.skillSlug,materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex"}},e.skillSlug,e.flags);if(a.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:e.skillSlug,nextStep:a.nextStep},a.message,e.flags.json,"materialization_target_invalid");if(a.status==="skip"||a.status==="cache_only")return x({status:"materialization_target_required",reasonCode:"materialization_target_required",skillSlug:e.skillSlug,nextStep:"Retry with --scope project|global and --agent <agent>."},"An explicit local target is required for an unverified external installation.",e.flags.json,"materialization_target_required");let l=await Xa({backend:e.backend,skillSlug:e.skillSlug,agentId:a.agent.id,scope:a.scope,flags:e.flags});if(l)return l;let c=ct(e.files),u=ir(e.source),d=u.kind==="github"?u.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,p=e.relativeSkillRoot,m=u.kind==="github"&&/^[a-f0-9]{40}$/u.test(u.ref)?{provider:"github",repository:`${u.owner}/${u.repo}`,commitSha:u.ref,sourceRoot:!p||p==="."?d:d==="."?p:`${d}/${p}`,sourceContentDigest:t.preview.bundleSha256}:void 0,h=c.slice(7,19),g=k(e.flags.version)??`0.0.0-external.${h}`,y=`generation_unverified_${c.slice(7,39)}`,v=e.files.filter(_=>Dn(_.path,e.files).type==="runtime").map(_=>_.path),b=y0({generation:{skillSlug:e.skillSlug,semanticVersion:g,generationId:y},reviewPackageFiles:e.files,runtimeAllowlist:v});return{...await cA({backend:e.backend,skillSlug:e.skillSlug,scope:a.scope,agent:a.agent,skillsPath:a.skillsPath,bytes:b.archiveBytes,files:Il({archiveBytes:b.archiveBytes,envelope:b.envelope}),envelope:b.envelope,verificationStatus:"unverified"}),source:e.source,sourceContentDigest:c,...m?{sourceSnapshot:{...m,runtimeDigest:c,archiveSha256:b.envelope.archive.sha256}}:{},platformScoreDecision:null,scoreAvailability:"unscored",scoreReasonCode:"unscored_local_source",localPreflight:{status:"passed",recommendation:t.issues.length+n.issues.length+r.length>0?"approved_with_notes":"approved",issueCount:t.issues.length+n.issues.length+r.length,findingCodes:[...t.issues.map(_=>_.code),...n.issues.map(_=>_.code),...r.map(_=>_.ruleId)]}}}function PU(e,t){return e.acceptUnverifiedSource===!0||!e.json&&!t.nonInteractive&&t.stdoutIsTty}async function Qoe(e){if(e.flags.json||e.backend.nonInteractive)return!1;try{return await e.backend.promptSelect(`${e.skillSlug} comes from ${e.source} and has not completed Skills Layer Security/Eval. Install this immutable generation as unverified?`,[{value:"decline",label:"Do not install",description:"Keep local agent files unchanged."},{value:"accept",label:"Install unverified",description:"Use locally now while catalogue review runs in parallel."}])==="accept"}catch{return!1}}function dA(e,t,n){let r=pA(t.files),i=n?r.find(o=>o.skillSlug===n)??null:r.length===1?r[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:i,results:r,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function pA(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=Me(t.path).replaceAll("\\","/"),r=n==="."?".":n,i=AU(t.content??"")??RU(r==="."?t.path:r),o=ese(t.content??"");return{skillSlug:i,name:i,...o?{description:o}:{},relativeSkillRoot:r,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function AU(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function ese(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function RU(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}function EU(e,t){let n=Mu(e,t);return n&&!n.startsWith("..")&&!st.isAbsolute(n)?n.split("\\").join("/"):t}function ji(e,t,n,r="unknown"){let i=k(t.visibility);return i==="public"||i==="private"?i:r==="anonymous"&&FP(e)?"public":r==="authenticated"?"private":!n.apiKey&&FP(e)?"public":"private"}function FP(e){try{let t=ir(e).kind;return t==="github"||t==="gitlab"}catch{return/^https:\/\/(?:github|gitlab)\.com\//iu.test(e.trim())}}function fA(e,t,n,r="unknown"){return ji(e,t,n,r)==="private"||k(t.visibility)==="unlisted"||r==="authenticated"?"/api/v1/me/source-installs":"/api/v1/source-imports"}function $U(e,t,n,r="unknown"){return{"content-type":"application/json",...fA(e,t,n,r)==="/api/v1/me/source-installs"?ne(n.apiKey,n.authBlockedMessage):{}}}function tse(e,t,n,r,i="unknown"){let o=r?f(r,"visibility")??f(r,"versionVisibility"):void 0,s=r?f(r,"publicationStatus"):void 0,a=r?f(r,"catalogRecord"):void 0,l=r?f(r,"status"):void 0;return o==="public"||s==="clean_publishable"||s==="publishable_with_findings"||l==="published"?"Public source install planned.":o==="private"||s==="private"||a==="private"||l==="private_source_installed"?"Private source skill installed.":ji(e,t,n,i)==="public"?"Public source install planned.":"Private source skill installed."}async function Nu(e){let t=ur(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:nse(e.source,e.requestedSkillSlug,t.map(n=>n.value),e.flags)}:{kind:"selected",skillSlug:e.requestedSkillSlug};if(e.flags.all||e.flags.json&&e.flags.dryRun)return{kind:"selected",skillSlug:e.requestedSkillSlug};if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};if(e.flags.json)return{kind:"failure",result:hM(e.source,t,e.flags)};try{return{kind:"selected",skillSlug:await e.backend.promptSelect(`${e.source} exposes multiple skills. Select one to ${e.mode}:`,t)}}catch{return{kind:"failure",result:hM(e.source,t,e.flags)}}}function hM(e,t,n){let r=t.map(i=>i.value);return x({status:"selection_required",reasonCode:"source_skill_selection_required",source:e,availableSkills:r,nextAction:"install.source.select",nextStep:`Re-run with --skill <skill-slug> using one of: ${r.join(", ")}. Use --all only if you intend to install every discovered skill.`},`Source "${e}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${r.join(", ")}.`,n.json,"source_skill_selection_required")}function yM(e,t,n){if(n.all&&t)return x({status:"error",reasonCode:"conflicting_source_selection",source:e,selectedSkillSlug:t,all:!0,nextAction:"install",nextStep:"Use either --all to install every discovered skill or --skill <skill-slug> to install one skill, not both."},"Source install cannot combine --all with --skill. Choose one selection mode before retrying.",n.json,"conflicting_source_selection")}function vM(e,t){try{if(ir(e).kind!=="local")return}catch{return}return x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:qu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source URL, or run `skills-layer install --source <source> --list` with a supported source."},qu(e)?`Install source ${e} was not found or is not readable.`:`Install source "${e}" is not a supported remote source and no local path was found.`,t.json,"invalid_source")}function nse(e,t,n,r){return x({status:"not_found",reasonCode:"source_skill_not_found",source:e,requestedSkillSlug:t,availableSkills:n,nextAction:"install.source.list",nextStep:`Run \`skills-layer install --source ${e} --list\` to inspect discovered skills, then retry with one of the listed slugs.`},`Source ${e} does not contain a discovered skill named ${t}. Run with --list to inspect available skills.`,r.json,"source_skill_not_found")}function ur(e){let t=[e.results,e.skills,e.discoveredSkills,T(e,"source")?.results,T(e,"inspection")?.results],n=new Set,r=[];for(let i of t)if(Array.isArray(i))for(let o of i){let s=rse(o);!s||n.has(s.value)||(n.add(s.value),r.push(s))}return r}function rse(e){if(!j(e))return;let t=f(e,"skillSlug")??f(e,"slug")??f(e,"name");if(!t)return;let n=f(e,"displayName")??f(e,"title")??f(e,"name"),r=n&&n!==t?`${t} - ${n}`:t,i=T(e,"parsedSkill"),o=T(e,"frontmatter")??(i?T(i,"frontmatter"):void 0),s=f(e,"shortDescription")??f(e,"summary")??f(e,"description")??(o?f(o,"description"):void 0)??f(e,"relativeSkillRoot")??f(e,"path")??f(e,"discoveryRoute")??f(e,"sourceKind");return s?{value:t,label:r,description:s}:{value:t,label:r}}function kM(e,t,n,r,i,o={}){return ie({...t,skillSlug:n,scope:k(r.scope),agent:k(r.agent),workspace:k(r.workspace),version:k(r.version),visibility:o.visibility??k(r.visibility),category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),all:r.all,acceptCapability:r.acceptCapability})}async function wM(e){let t=e.sourceAccess??"unknown",n=fA(e.source,e.flags,e.backend,t);try{return await D(e.backend,n,{method:"POST",headers:$U(e.source,e.flags,e.backend,t),body:JSON.stringify(kM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{sourceAccess:t,...n==="/api/v1/source-imports"?{visibility:"public"}:{}}))})}catch(r){if(r instanceof Z&&r.status===401&&k(e.flags.visibility)!=="private"&&t!=="authenticated"&&FP(e.source))return await D(e.backend,"/api/v1/source-imports",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(kM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{visibility:"public"}))});throw r}}function BP(e,t,n,r){return ie({status:"dry_run",source:e,selectedSkillSlug:n,all:r.all,scope:k(r.scope)??"local",agent:k(r.agent),workspace:k(r.workspace),acceptCapability:r.acceptCapability,candidates:ur(t).map(i=>({skillSlug:i.value,name:i.label,description:i.description})),nextStep:r.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function DU(e,t,n,r,i={}){try{return{kind:"ok",inspection:await D(e,"/api/v1/source-inspect",{method:"POST",headers:TU(e,i.authMode??"auto"),body:JSON.stringify(ie(n))})}}catch(o){if(o instanceof Z)return{kind:"failure",result:UP(t,o,r)};throw o}}function TU(e,t){return t==="anonymous"?{"content-type":"application/json"}:V(e.apiKey)}async function MP(e,t,n,r){try{let s=await D(e,"/api/v1/source-inspect",{method:"POST",headers:TU(e,"anonymous"),body:JSON.stringify(ie(n))}),a=bM(t,s,r);return a?{kind:"failure",result:a}:{kind:"ok",inspection:s,sourceAccess:"anonymous"}}catch(s){if(!(s instanceof Z))throw s;let a=s.details??{},l=f(a,"error")??s.message;if(!mA(s.status,l))return{kind:"failure",result:UP(t,s,r)};if(!e.apiKey)return{kind:"failure",result:UP(t,s,r)}}let i=await DU(e,t,n,r,{authMode:"authenticated"});if(i.kind==="failure")return i;let o=bM(t,i.inspection,r);return o?{kind:"failure",result:o}:{kind:"ok",inspection:i.inspection,sourceAccess:"authenticated"}}function bM(e,t,n){if(n.list||n.dryRun)return null;let r=[t.catalogueDecision,...Array.isArray(t.catalogueDecisions)?t.catalogueDecisions:[]].filter(i=>i!==void 0);for(let i of r){let o=j(i)?i.status:void 0;if(!j(i)||i.schemaVersion!=="skills-layer.source-catalogue-decision.v1"||!["approved","pending","new"].includes(String(o))){let s=["security_blocked","revoked","restricted","unavailable"].includes(String(o))?`source_catalogue_${o}`:"source_catalogue_identity_invalid";return x({status:s,reasonCode:s,source:e,catalogueDecision:i,nextStep:"Resolve the current catalogue decision before retrying this exact source."},"This source cannot be activated under its current catalogue decision.",n.json,s)}}if(t.catalogueSourceInput!==void 0){let i=ir(e),o=typeof t.catalogueSourceInput=="string"?ir(t.catalogueSourceInput):void 0,s=l=>l.replace(/(?:^|\/)SKILL\.md$/u,"")||".";if(!(i.kind==="github"&&o?.kind==="github"&&`${i.owner}/${i.repo}`.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&s(i.subpath)===s(o.subpath)&&/^[a-f0-9]{40}$/u.test(o.ref)&&(!/^[a-f0-9]{40}$/iu.test(i.ref)||i.ref.toLowerCase()===o.ref)&&r.every(l=>{let c=j(l)?T(l,"subject"):void 0,u=c?f(c,"sourceRoot"):void 0,d=s(o.subpath);return c?.commitSha===o.ref&&typeof c.repository=="string"&&c.repository.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&u&&(u==="."||!u.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)))&&(d==="."||u===d||u.startsWith(`${d}/`))})))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e},"The inspected snapshot does not identify this exact source.",n.json,"source_catalogue_identity_invalid")}return null}function Ah(e,t,n){if(ur(t).length>0)return null;let i=ise(t);return x({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:i,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},ose(e,i),n.json)}function ise(e){return(Array.isArray(e.issues)?e.issues:[]).filter(j).map(n=>({...f(n,"code")?{code:f(n,"code")}:{},...f(n,"message")?{message:f(n,"message")}:{},...f(n,"path")?{path:f(n,"path")}:{}}))}function UP(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(mA(t.status,i))return OU(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Ho(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be inspected as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}function _M(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(mA(t.status,i))return OU(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Ho(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be installed as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}async function SM(e){let t=e.error instanceof Z?e.error.details??{}:{},n=e.error instanceof Z?f(t,"reasonCode")??"catalogue_submission_failed":"catalogue_submission_unavailable";return await zu({backend:e.backend,result:{...t,status:"catalogue_submission_failed",reasonCode:n,publiclyDiscoverable:!1},fallbackSlug:e.skillSlug,source:e.source,sourceAccess:e.sourceAccess,flags:e.flags,requestedVisibility:ji(e.source,e.flags,e.backend,e.sourceAccess),unverifiedMaterialization:e.unverifiedMaterialization})}function mA(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function OU(e,t,n,r){let i=t.details??{},o=f(i,"error")??t.message,a=`skills-layer source connection start --provider ${LU(e)} --source ${e} --visibility private --provenance-intent private_source_import`,l={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:o,nextStep:a};return x(l,`Cloud could not ${r} ${e} directly. If this is a private source, start a private source connection first:
2166
+ `)}async function fr(e){try{return await JM(e),!0}catch{return!1}}function pU(e){return e.attestRights?{attestRights:!0,rightsBasis:k(e.rightsBasis)??"self_authored",distributionScope:k(e.distributionScope)??"commercial_distribution",rightsDeclarationVersion:Qj}:{}}async function DP(e,t,n,r){let i=k(t.visibility);if(i){let A=dc(i);if(!A||!ju.includes(A))return Fr(r?"creator.submit-version":"creator.submit","visibility",i,ju,t,"invalid_visibility")}let o=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let s=k(t.spacePack),a=s===void 0?void 0:sc(s);if(a===null)return Fr(r?"creator.submit-version":"creator.submit","spacePack",s,["5","10","20","50"],t,"invalid_private_skill_space_pack","space-pack");let l=k(t.creatorSessionId);if(l){let A=r?L(k(t.skill)??e[0],"creator submit-version with --creator-session-id requires a skill slug."):null,N=r?{creatorSessionId:l,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",...t.dryRun?{dryRun:!0}:{}}:{creatorSessionId:l,...t.dryRun?{dryRun:!0}:{},...a?{privateSkillSpacePack:a}:{}},O=r?`/api/v1/me/submissions/${encodeURIComponent(A)}/versions`:"/api/v1/me/submissions",X=await D(n,O,{method:"POST",headers:aM(n,t.dryRun?null:{path:O,creatorSessionId:l}),body:JSON.stringify(N)});return lM(X,t,n)??R(X,t.dryRun?qM(X):X.status==="submission_incomplete"?`Creator session submission is incomplete. ${f(X,"nextStep")??"Retry this session submission to complete finalization."}`:"Finalized Creator session submitted.",t.json,n)}let c=r?L(k(t.skill)??e[0],"creator submit-version requires a skill slug."):k(t.skill),u=L(k(t.source)??(r?e[1]:e[0])??t.path,`creator ${r?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),d=await Ku(u,n.cwd);if(t.list)return await doe(u,d,c,t,n);let p=Ni(r?"creator.submit-version":"creator.submit",t);if(p)return p;if(!d&&!qu(u)&&(Dz(u)||/^(?:github|gitlab):/iu.test(u)))return poe(u,t);let m=d?.files??(await ga({cwd:n.cwd,sourcePath:u,limits:ko})).files;if(!r&&!t.dryRun){let A=await foe(m,t,n);if(A)return A}if(t.dryRun&&gg(m))return loe(m,{slug:c,flags:t,backend:n});let h=gg(m)?await IC({baseUrl:n.baseUrl,apiKey:n.apiKey,fetchFn:n.fetchFn,files:m}):null,g=ie({...h?{hydrationManifestId:h.manifestId}:{files:m},version:k(t.version),dryRun:t.dryRun,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",evalSummary:noe(m,{skillSlug:c??oA(m)??"unknown",version:k(t.version)??"0.0.0",generatedAt:n.now()}),replaceUnpublished:r&&t.replaceUnpublished===!0?!0:void 0,priceCents:o.value,privateSkillSpacePack:a,...pU(t),...d?{sourceMetadata:d.sourceMetadata}:{},...Ft(t,["displayName","skillType","category","visibility","source","skill"])}),y=r&&c?`/api/v1/me/submissions/${encodeURIComponent(c)}/versions`:"/api/v1/me/submissions",v=await D(n,y,{method:"POST",headers:aM(n,t.dryRun?null:{path:y,request:g,files:m}),body:JSON.stringify(g)});if(t.json||t.noOpen||v.status!=="checkout_required"||typeof v.checkoutUrl!="string"||typeof v.chargeId!="string")return lM(v,t,n)??R(v,t.dryRun?qM(v):r?"Version submitted.":"Submission uploaded.",t.json,n);let b=T(v,"spacePack"),w=b?sc(b.code):null;n.emitInfo(w?`No private skill space is left. Opening checkout for ${qp(w).label} (${qp(w).displayPrice}); other packs: --space-pack 5|10|20|50. Complete the payment in your browser, then come back here.`:"Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(v.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${v.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let C=await ale(v.chargeId,n);return fe(C)?C:C.status!=="submitted"?R({...v,chargeStatus:C.status},`Payment is still ${C.status}. You can rerun \`skills-layer creator charge-status ${v.chargeId}\` to continue tracking it.`,t.json,n):R(C,r?"Version submitted.":"Submission uploaded.",t.json,n)}function aM(e,t){let n=V(e.apiKey);if(!t)return n;let{hydrationManifestId:r,files:i,evalSummary:o,...s}=t.request??{},a=t.files?Ue("sha256").update(JSON.stringify(t.files.map(c=>[c.path,c.content??null,c.contentBase64??null]))).digest("hex"):null,l=Ue("sha256").update(JSON.stringify({path:t.path,creatorSessionId:t.creatorSessionId??null,request:s,bundleDigest:a})).digest("hex");return{...n,"idempotency-key":`cli-submit-${l.slice(0,48)}`}}function lM(e,t,n){if(e.status!=="checkout_required"||typeof e.checkoutUrl!="string"||typeof e.chargeId!="string")return null;let r=`Open ${e.checkoutUrl} to complete payment, then run \`skills-layer creator charge-status ${e.chargeId}\` to confirm the submission.`;return R({...e,paymentRequired:!0,checkoutUrl:e.checkoutUrl,chargeId:e.chargeId,nextAction:"creator.charge-status",nextStep:r},`Payment required to finish: ${r}`,t.json,n)}function loe(e,t){let n="creator.submit",r=nt(e),i=e.reduce((l,c)=>l+us(c),0),o=t.slug??oA(e),s=["skill_name_availability","security_review","moderation","pricing_and_checkout","eval_evidence"],a=ie({status:r.valid?"ready":"blocked",reasonCode:r.valid?"local_preview_only":"invalid_bundle",dryRun:!0,previewMode:"local",operation:n,uploaded:!1,skillSlug:o,version:k(t.flags.version),bundle:{fileCount:e.length,totalBytes:i,transport:"source_hydration",artifactDigest:ct(e)},localChecks:[{check:"bundle_size",status:"passed"},{check:"paths",status:"passed"},{check:"secrets",status:"passed"},{check:"manifest",status:r.valid?"passed":"failed"}],serverChecks:{status:"not_run",checks:s},why:"The bundle exceeds the 2 MiB inline request limit, so the dry run previewed it locally and uploaded nothing.",validation:r,nextAction:r.valid?n:"validate",nextStep:r.valid?`Re-run without --dry-run to upload and submit. Server-only checks (${s.join(", ")}) run during the real submit.`:"Fix the bundle issues before submitting again."});return R(a,r.valid?`Local submission preview ready (${e.length} files, ${i} bytes; nothing uploaded). Server-only checks run on the real submit: ${s.join(", ")}.`:"Local submission preview blocked: the bundle does not satisfy the creator validation rules. Nothing was uploaded.",t.flags.json,t.backend)}var coe="Use `skills-layer creator spaces` or `skills-layer creator spaces buy --pack 5|10|20|50`.";function cM(e){if(e.status==="community_unlimited")return"Community edition supports unlimited private skills.";let t=n=>typeof e[n]=="number"?e[n]:0;return`Private skill spaces: ${t("availablePrivateSkillSpaces")} available of ${t("totalPrivateSkillSpaces")} (${t("activePrivateSkills")} active private skills; free ${t("freePrivateSkillSpacesUsed")} used, ${t("freePrivateSkillSpacesRemaining")} left; purchased ${t("purchasedPrivateSkillSpaces")}, ${t("purchasedPrivateSkillSpacesUsed")} used). Buy more with \`skills-layer creator spaces buy --pack 5|10|20|50\`: ${ac}.`}async function uoe(e,t,n){let r=e[0];if(r===void 0||r==="status"){let u=await D(n,"/api/v1/me/private-skill-spaces",{headers:ne(n.apiKey,n.authBlockedMessage)});return R(u,cM(u),t.json,n)}if(r!=="buy")return E(`Unknown creator spaces action "${r}". ${coe}`,t.json);let i=k(t.pack)??e[1],o=i===void 0?void 0:sc(i);if(o===null)return Fr("creator.spaces.buy","pack",i,["5","10","20","50"],t,"invalid_private_skill_space_pack","pack");let s=await D(n,"/api/v1/me/private-skill-spaces/checkout",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(o?{privateSkillSpacePack:o}:{})});if(s.status!=="checkout_required"||typeof s.checkoutUrl!="string")return R(s,cM(s),t.json,n);let a=qp(sc(T(s,"spacePack")?.code)??"spaces_5"),l=`Checkout for ${a.label} (${a.displayPrice}) is ready. Complete the payment in your browser, then run \`skills-layer creator spaces\` to see the credited spaces.`;return t.json||t.noOpen?R(s,`${l} Checkout URL: ${s.checkoutUrl}`,t.json,n):(await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),R(s,l,t.json,n))}async function doe(e,t,n,r,i){if(t)return R(uM(dA(e,t,n)),"Source skills loaded.",r.json,i);let o=await DU(i,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},r);return o.kind==="failure"?o.result:R(uM(o.inspection),"Source skills loaded.",r.json,i)}function uM(e){return{...e,sourceSubmissionSupported:!0}}function poe(e,t){let r=`skills-layer source connection start --provider ${LU(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return x({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:r},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${r}\`.`,t.json,"source_connection_required")}async function foe(e,t,n){let r=k(t.skill)??oA(e);if(!r)return null;let i;try{i=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(r)}`,{headers:ne(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof Z&&o.status===404)return fU(r,t);throw o}if(i.available===!1||f(i,"reasonCode")==="unavailable"||f(i,"reasonCode")==="reserved"){let o=f(i,"assignedSlug"),s=ie({status:"duplicate_candidate",reasonCode:f(i,"reasonCode")??"slug_unavailable",requestedSlug:r,assignedSlug:o,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${r}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return x(s,`A public skill slug "${r}" already exists or is not available. Run \`skills-layer creator status ${r}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,f(s,"reasonCode"))}return null}async function moe(e,t,n){try{let r=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:ne(n.apiKey,n.authBlockedMessage)});return R(goe(r),"Slug status loaded.",t.json,n)}catch(r){if(r instanceof Z&&r.status===404)return fU(e,t);throw r}}function fU(e,t){let n={status:"slug_check_unavailable",reasonCode:"slug_check_route_unavailable",requestedSlug:e,nextAction:"creator.status",nextStep:`Slug availability could not be checked on the selected backend. Run \`skills-layer creator submissions\`, \`skills-layer creator status ${e}\`, or retry after selecting a compatible Skills Layer backend.`};return x(n,`Slug availability could not be checked for ${e} on the selected backend. Run \`skills-layer creator submissions\` or retry after selecting a compatible Skills Layer backend.`,t.json,"slug_check_route_unavailable")}function goe(e){let t=e.available===!0,n=f(e,"assignedSlug");if(t)return ie({requestedSlug:f(e,"requestedSlug"),available:!0,reasonCode:f(e,"reasonCode")??"available",assignedSlug:n});let r=T(e,"slugAssignment"),i=Array.isArray(r?.candidateSlugs)?r.candidateSlugs.filter(o=>typeof o=="string").slice(0,3):void 0;return ie({...e,...r?{slugAssignment:{...r,...i?{candidateSlugs:i}:{}}}:{},...i?{candidateSlugs:i}:{}})}function hoe(e,t){return x({status:"not_submitted",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submit",nextStep:"Run `skills-layer creator submit <path> --dry-run` to validate a local skill before submitting it, or run `skills-layer creator submissions` to see your existing submissions."},`No creator submission was found for ${e}. Run \`skills-layer creator submit <path> --dry-run\` before checking status.`,t.json,"creator_submission_not_found")}function oA(e){let t=e.find(r=>r.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(r=>r.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(r=>!!r);return yoe(n??ot(Me(t.path)))}function yoe(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function voe(e,t,n){let r=L(e[1],"creator pricing requires a skill slug."),i=Ni("creator.pricing",t);if(i)return i;let o=new URLSearchParams;if(We(o,"version",t.version),!t.priceCents)return await he(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let a=s.value??0;if(t.dryRun){o.set("dryRun","true"),o.set("priceCents",String(a));let d=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:ne(n.apiKey,n.authBlockedMessage)});return d.dryRun!==!0||d.status!=="preview"?E("This backend does not support read-only pricing previews. Upgrade the backend before retrying.",t.json):R(d,"Pricing preview; the live price is unchanged.",t.json,n)}let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:ne(n.apiKey,n.authBlockedMessage)}),c=J(l,"priceCents")??0,u=J(l,"revision");if(!u||!Number.isSafeInteger(u)||u<1)return E("Pricing authority did not return a valid revision.",t.json);if(a>c&&!t.confirmed){let d=ie({status:"pending_approval",reasonCode:"price_increase_confirmation_required",skillSlug:r,version:f(l,"version"),currentPriceCents:c,requestedPriceCents:a,currency:f(l,"currency")??"usd",nextStep:"Review the old and new USD prices, then rerun with --yes."});return R(d,"Pricing change requires explicit confirmation.",t.json,n)}return await Fi(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing`,{priceCents:a,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),expectedRevision:u,idempotencyKey:k(t.idempotencyKey)?.trim()||`pricing-${Ge(12).toString("hex")}`,reason:"Creator changed the version list price through CLI.",...pU(t)},t,n,"Pricing updated.")}async function koe(e,t,n){try{return await Fi(`/api/v1/me/submissions/${encodeURIComponent(e)}`,Ft(t,["displayName","summary","description","category","skillType","license"]),t,n,"Listing updated.")}catch(r){if(r instanceof Z&&r.status===404){let i={status:"listing_not_found_or_not_editable",reasonCode:"creator_listing_not_found_or_not_owned",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see editable listings, or \`skills-layer show ${e}\` to inspect the public catalog entry.`};return x(i,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw r}}async function woe(e,t,n,r){let i=L(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let o=pr("creator.claim","requestedRole",n.requestedRole,Iie,n,"invalid_requested_role","requested-role");if(o)return o}try{if(e==="claim")return await Le(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/claim`,Ft(n,["requestedRole","message"]),n,r,"Ownership claim submitted.");if(e==="verify"){let o=L(n.claimId,"creator verify requires --claim-id.");return await Le(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/verify`,{claimId:o},n,r,"Ownership claim verified.")}return L(n.message,"creator dispute requires --message."),await Le(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/dispute`,Ft(n,["message"]),n,r,"Ownership dispute submitted.")}catch(o){if(o instanceof Z&&o.status===404){let s={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:i,requestedRole:k(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${i}\`, \`skills-layer show ${i}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${i}\` to start a new claim if the skill is claimable.`};return x(s,e==="claim"?`No claimable skill was found for ${i}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${i}. Start a new claim if the skill is claimable.`,n.json,f(s,"reasonCode")??"ownership_action_unavailable")}throw o}}async function boe(e,t,n){try{return await he(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(r){if(r instanceof Z&&r.status===404){let i={status:"no_creator_submission",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see skills you own, \`skills-layer show ${e}\` to inspect the catalog listing, or \`skills-layer creator claim ${e}\` if it is a claimable public-source skill.`};return x(i,`No creator-owned analytics submission was found for ${e}. Run \`skills-layer creator submissions\`, \`skills-layer show ${e}\`, or \`skills-layer creator claim ${e}\` if you should manage it.`,t.json,"creator_submission_not_found")}throw r}}async function _oe(e,t){let n=await D(t,"/api/v1/me/payout-profile",{headers:ne(t.apiKey,t.authBlockedMessage)});return R(n,"Creator payout profile loaded.",e.json,t)}function mU(e,t){let n={};return(r,i)=>UA({session:n,code:k(e.mfaCode),interactive:!e.json&&!t.nonInteractive&&t.stdoutIsTty,promptSecret:t.promptSecret,verify:async o=>{let s=await D(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({purpose:"creator_payout",code:o})});return L(s.stepUpGrant,"MFA verification did not return a step-up grant.")},request:o=>{let s=new Headers(i.headers);return o&&s.set("x-mfa-step-up-grant",o),D(t,r,{...i,headers:s})}})}async function dM(e,t){let n=Soe(k(e.mode));if(e.mode&&n===null)return E("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let r;try{r=await mU(e,t)("/api/v1/me/payout-profile/link",{method:"POST",headers:V(t.apiKey),body:JSON.stringify(ie({...n?{mode:n}:{},country:k(e.country)}))})}catch(o){if(o instanceof Z&&Coe(o))return x({status:"payout_setup_already_submitted",reasonCode:"payout_update_link_unavailable",nextAction:"creator.payout-profile",nextStep:"Run `skills-layer creator payout-profile` to confirm readiness, then use `skills-layer creator earnings` or `skills-layer creator withdraw --amount-cents <amount>`."},"The bank-update link could not be opened. Run `skills-layer creator payout-link --mode account_onboarding` to change your bank account.",e.json,"payout_update_link_unavailable");throw o}let i=mz(r);return i&&xoe(e)&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(i)||t.emitInfo(`Open this payout setup URL manually to continue: ${i}`)),R(r,"Payout setup link created.",e.json,t)}function Soe(e){if(!e)return null;let t=e.trim().toLowerCase();return t==="account_onboarding"||t==="onboarding"?"account_onboarding":t==="account_update"||t==="update"?"account_update":null}function xoe(e){return!e.json&&!e.noOpen}function Coe(e){let t=`${e.message} ${f(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function Ioe(e,t,n,r){let i=L(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await he(`/api/v1/me/skills/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await he(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let l=L(n.issueId,"creator update-issue requires --issue-id."),c=L(n.status,"creator update-issue requires --status."),u=pr("creator.update-issue","status",c,Pie,n,"invalid_issue_status");if(u)return u;let d=Ni("creator.update-issue",{...n,version:n.fixedVersion});if(d)return d;try{return await Fi(`/api/v1/me/skills/${encodeURIComponent(i)}/issues/${encodeURIComponent(l)}`,Ft(n,["status","fixedVersion","note"]),n,r,"Issue updated.")}catch(p){if(p instanceof Z&&p.status===404)return Poe(i,l,n);throw p}}let o=L(n.reviewId,"creator moderate-review requires --review-id."),s=L(n.status,"creator moderate-review requires --status."),a=pr("creator.moderate-review","status",s,Aie,n,"invalid_review_status");if(a)return a;try{return await Le(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews/${encodeURIComponent(o)}/moderate`,Ft(n,["status","reason"]),n,r,"Review updated.")}catch(l){if(l instanceof Z&&l.status===404)return Aoe(i,o,n);throw l}}function Poe(e,t,n){return x({status:"not_found",reasonCode:"issue_not_found",skillSlug:e,issueId:t,nextAction:"creator.issues",nextStep:`Run \`skills-layer creator issues ${e}\` to inspect open issues before updating one.`},`Issue ${t} was not found for ${e}. Run \`skills-layer creator issues ${e}\` first.`,n.json,"issue_not_found")}function Aoe(e,t,n){return x({status:"not_found",reasonCode:"review_not_found",skillSlug:e,reviewId:t,nextAction:"creator.reviews",nextStep:`Run \`skills-layer creator reviews ${e}\` to inspect review ids before moderating one.`},`Review ${t} was not found for ${e}. Run \`skills-layer creator reviews ${e}\` first.`,n.json,"review_not_found")}async function Roe(e,t,n){let r=e[0],i=L(e[1],`creator source ${r??""} requires a source connection id.`),o=k(t.skill)??e[2];if(r==="prepare"){let s=Ni("creator.source.prepare",t);if(s)return s;let a=pr("creator.source.prepare","visibility",t.visibility,qa,t,"invalid_visibility");if(a)return a;let l=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=k(t.source)??e[2],u=c?await Ku(c,n.cwd):void 0;return await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/prepare`,ie({...Ft(t,["skill","source","version","displayName","skillType","category","visibility"]),...l.value!==void 0?{priceCents:l.value}:{},source:c,...u?{files:u.files}:{}}),t,n,"Source release prepared.")}if(r==="publish-request"){let s=Ni("creator.source.publish-request",t);if(s)return s;let a=pr("creator.source.publish-request","visibility",t.visibility,qa,t,"invalid_visibility");if(a)return a;let l=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=t.approvalRequestId.length>0?t.approvalRequestId:k(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/publish-request`,ie({skillSlug:o,approvalRequestIds:c,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),...Ft(t,["visibility","license","discloseSource"]),...l.value!==void 0?{priceCents:l.value}:{}}),t,n,"Source publish requested.")}if(r==="release-status"){let s=new URLSearchParams;return o&&s.set("skill",o),await he(`/api/v1/me/source-connections/${encodeURIComponent(i)}/release-status${Qe(s)}`,t,n,"Source release status loaded.",{authenticated:!0})}return E(`Unknown creator source command "${r??""}".`,t.json)}function TP(e){return!e.list&&!e.dryRun}async function pM(e){if(!TP(e.flags)||k(e.flags.visibility)==="private"||k(e.flags.scope)==="workspace")return null;if(e.flags.all&&Array.isArray(e.inspection.catalogueDecisions)){let p=[];for(let m of ur(e.inspection)){let h=await Za([],{...e.flags,all:!1,json:!0,source:f(e.inspection,"catalogueSourceInput")??e.source,skill:m.value},e.backend);if(h.exitCode!==0){let g=JSON.parse(h.stderr||h.stdout);return x({status:"source_install_batch_partial",reasonCode:g.reasonCode??"source_install_child_failed",failedSkill:m.value,results:p,failure:g.data},"Source installation stopped; earlier results are retained.",e.flags.json,g.reasonCode??"source_install_child_failed")}p.push(JSON.parse(h.stdout).data)}return R({status:"source_install_batch",results:p},"Source installation results loaded.",e.flags.json,e.backend)}let t=T(e.inspection,"catalogueMatch");if(!t&&e.selectedSkillSlug&&typeof e.inspection.catalogueSourceInput=="string"){let p=await MP(e.backend,e.source,{source:e.inspection.catalogueSourceInput,skillSlug:e.selectedSkillSlug,preferCatalogue:!0,listOnly:!0},e.flags);if(p.kind==="failure")return p.result;t=T(p.inspection,"catalogueMatch"),t&&(e.inspection=p.inspection)}if(!t)return null;let n=ir(e.source),r=f(t,"skillSlug"),i=f(t,"version"),o=f(t,"generationId"),s=n.kind==="github"?n.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,l=(Array.isArray(e.inspection.results)?e.inspection.results:[]).find(p=>j(p)&&p.skillSlug===e.selectedSkillSlug),c=j(l)?f(l,"relativeSkillRoot"):void 0,u=c&&s&&c!=="."?s==="."||c===s||c.startsWith(`${s}/`)?c:`${s}/${c}`:void 0,d=typeof t.sourceRoot=="string"&&(t.sourceRoot==="."||!t.sourceRoot.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)));return n.kind!=="github"||t.schemaVersion!=="skills-layer.source-catalogue-match.v1"||typeof t.repository!="string"||t.repository.toLowerCase()!==`${n.owner}/${n.repo}`.toLowerCase()||!d||t.sourceRoot!==s&&t.sourceRoot!==u||typeof t.commitSha!="string"||!/^[a-f0-9]{40}$/u.test(t.commitSha)||/^[a-f0-9]{40}$/iu.test(n.ref)&&n.ref.toLowerCase()!==t.commitSha||!r||!/^[a-z0-9][a-z0-9-]{0,255}$/u.test(r)||!i||!o||e.selectedSkillSlug&&e.selectedSkillSlug!==t.requestedSkillSlug?x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e.source,nextStep:"Retry after the exact source-to-catalogue identity is refreshed. No raw-source fallback was activated."},"The catalogue match did not identify this exact GitHub skill and revision.",e.flags.json,"source_catalogue_identity_invalid"):Za([r],{...e.flags,source:void 0,skill:void 0,version:i},e.backend,{...gU,expectedSourceGeneration:{generationId:o,version:i}})}var gU={origin:"direct",fallbackPolicy:"eligible_public"};function Eoe(e){return{origin:"update_existing",fallbackPolicy:f(e??{},"acquisitionMode")==="authenticated_account"?"account_required":"eligible_public"}}async function Za(e,t,n,r=gU){if(e[0]==="status"&&e[1])return he(`/api/v1/install-receipts/${encodeURIComponent(e[1])}`,t,n,"Install progress loaded.",{authenticated:!!n.apiKey});let i=cU("install",t);if(i)return i;if(t.localOnly&&(t.visibility!==void 0||k(t.scope)==="workspace"||n.config?.workingModeType==="enterprise_workspace"))return x({status:"local_only_intent_conflict",reasonCode:"local_only_intent_conflict"},"Local-only installation requires a personal local target and cannot request platform visibility or workspace authority.",t.json,"local_only_intent_conflict");let o=k(t.source);if(o){let h=k(t.skill),g=yM(o,h,t);if(g)return g;let y=await Ku(o,n.cwd);if(y)return await mM(o,y,h,t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let v=vM(o,t);if(v)return v;let b=t.list||t.dryRun||!h&&!t.all,w=await MP(n,o,{source:o,skillSlug:h,listOnly:b,...t.all?{all:!0}:{},preferCatalogue:TP(t),visibility:k(t.visibility)},t);if(w.kind==="failure")return w.result;let _=w.inspection;if(t.list)return R(_,"Source skills loaded.",t.json,n);let C=Ah(o,_,t);if(C)return C;let A=await Nu({source:o,inspection:_,requestedSkillSlug:h,mode:"install",flags:t,backend:n});if(A.kind==="failure")return A.result;if(t.dryRun)return R(BP(o,_,A.skillSlug,t),"Source install preview ready.",t.json,n);let N=t.all?ur(_).map(Q=>Q.value):[A.skillSlug??ur(_)[0]?.value??ot(o)],O=await pM({inspection:_,source:o,selectedSkillSlug:A.skillSlug,flags:t,backend:n});if(O)return O;let X=await WB(n,N,t);if(X)return X;let G=f(_,"catalogueSourceInput")??o,ee=await gM({backend:n,flags:t,source:G,skillSlug:A.skillSlug,defaultAcceptUnverifiedSource:ji(o,t,n,w.sourceAccess)==="public"});if(fe(ee))return ee;let te;try{te=await wM({source:G,skillSlug:A.skillSlug,flags:t,backend:n,sourceAccess:w.sourceAccess})}catch(Q){if(ee)return await SM({backend:n,flags:t,source:G,sourceAccess:w.sourceAccess,skillSlug:A.skillSlug??N[0],unverifiedMaterialization:ee,error:Q});if(Q instanceof Z)return _M(o,Q,t);throw Q}return await zu({backend:n,result:te,fallbackSlug:A.skillSlug??f(te,"skillSlug")??o,source:G,sourceAccess:w.sourceAccess,flags:t,requestedVisibility:ji(o,t,n,w.sourceAccess),...ee?{unverifiedMaterialization:ee}:{}})}let s=L(e[0]??t.install,"install requires a skill slug or --source.");if(Dz(s)){let h=yM(s,k(t.skill),t);if(h)return h;let g=await Ku(s,n.cwd);if(g)return await mM(s,g,k(t.skill),t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let y=vM(s,t);if(y)return y;let v=k(t.skill),b,w="unknown",_=async Q=>{if(b)return null;let Ie=await MP(n,s,{source:s,skillSlug:v,listOnly:Q,...t.all?{all:!0}:{},preferCatalogue:TP(t),visibility:k(t.visibility)},t);return Ie.kind==="failure"?Ie.result:(b=Ie.inspection,w=Ie.sourceAccess,null)};if(t.list){let Q=await _(!0);return Q||R(b,"Source skills loaded.",t.json,n)}if(!v&&!t.all){let Q=await _(!0);if(Q)return Q;let Ie=b,fn=Ah(s,Ie,t);if(fn)return fn;let el=await Nu({source:s,inspection:Ie,requestedSkillSlug:v,mode:"install",flags:t,backend:n});if(el.kind==="failure")return el.result;v=el.skillSlug}if(t.dryRun){let Q=await _(!0);if(Q)return Q;let Ie=b,fn=await Nu({source:s,inspection:Ie,requestedSkillSlug:v,mode:"install",flags:t,backend:n});return fn.kind==="failure"?fn.result:(v=fn.skillSlug,R(BP(s,Ie,v,t),"Source install preview ready.",t.json,n))}let C=await _(!1);if(C)return C;let A=b,N=t.all?ur(A).map(Q=>Q.value):[v??ur(A)[0]?.value??ot(s)],O=await pM({inspection:A,source:s,selectedSkillSlug:v,flags:t,backend:n});if(O)return O;let X=await WB(n,N,t);if(X)return X;let G=f(A,"catalogueSourceInput")??s,ee=await gM({backend:n,flags:t,source:G,skillSlug:v,defaultAcceptUnverifiedSource:ji(s,t,n,w)==="public"});if(fe(ee))return ee;let te;try{te=await wM({source:G,skillSlug:v,flags:t,backend:n,sourceAccess:w})}catch(Q){if(ee)return await SM({backend:n,flags:t,source:G,sourceAccess:w,skillSlug:v??N[0],unverifiedMaterialization:ee,error:Q});if(Q instanceof Z)return _M(s,Q,t);throw Q}return await zu({backend:n,result:te,fallbackSlug:v??f(te,"skillSlug")??ot(s),source:G,sourceAccess:w,flags:t,requestedVisibility:ji(s,t,n,w),...ee?{unverifiedMaterialization:ee}:{}})}if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");if(k(t.scope)==="workspace"){let h=L(t.workspace,"workspace installs require --workspace <workspace-id>."),g=await hU(n,`/api/v1/workspaces/${encodeURIComponent(h)}/skills/${encodeURIComponent(s)}/approve`,{dryRun:t.dryRun},t);return fe(g)?g:t.dryRun?await ase(g,"Workspace approval preview ready.",t,n):R(g,"Workspace approval requested.",t.json,n)}if(!n.apiKey&&r.fallbackPolicy==="eligible_public")return await fP({target:s,flags:t,backend:n,catalogContext:r});if(!t.dryRun){let h;try{h=await rA(n,s,t)}catch(g){if(OP(r,g))return await fP({target:s,flags:t,backend:n,catalogContext:r});throw g}if(h)return h}let a=await vU(s,t,n);if("result"in a)return a.result;let l=a.flags,c=ie({skillSlug:s,version:k(l.version),scope:k(l.scope),agent:k(l.agent),dryRun:t.dryRun}),u;try{u=await sA(n,c,t)}catch(h){if(OP(r,h))return await fP({target:s,flags:t,backend:n,catalogContext:r,effectiveFlags:l});throw h}if(fe(u))return u;let d=u;if(d.status==="purchase_required")return MU(d,s,t,n);if(await Bi(n,d),t.dryRun)return await jU(d,l,n);let p=await aA(n,d,s,l,{expectedSourceGeneration:r.expectedSourceGeneration});if(fe(p))return p;let m=await uA(n,{...p,acquisitionMode:"authenticated_account",acquisitionOrigin:r.origin},s,l);return await Ka(n,m,s),Ga(m,Array.isArray(m.materializedWrites)&&m.materializedWrites.length>0?"Skill installed.":l.agent?"Recorded; choose --scope project|global to install files.":"Recorded; no agent selected \u2014 rerun with --agent <id> to write the skill files.",t.json,n,k(l.agent))}async function fP(e){let t=e.backend.apiKey?{...e.backend,apiKey:void 0,authBlockedMessage:void 0}:e.backend,n=e.effectiveFlags;if(!n){let o=await vU(e.target,e.flags,e.backend);if("result"in o)return o.result;n=o.flags}let r=k(n.version),i={status:"anonymous_public",skillSlug:e.target,...r?{version:r}:{},scope:k(n.scope),agent:k(n.agent),acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin};if(e.flags.dryRun)try{let o=await Sh(t,i,e.target,r,{exportMode:"public"});return await jU({...i,...Ch(o)},e.flags,t)}catch(o){if(o instanceof Z)return Ho(o,e.flags.json);throw o}try{let o=await aA(t,i,e.target,n,{exportMode:"public",expectedSourceGeneration:e.catalogContext.expectedSourceGeneration});if(fe(o))return o;let s=await uA(t,{...o,acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin},e.target,n);return await Ka(t,s,e.target),Ga(s,"Public skill installed locally without an account.",e.flags.json,t)}catch(o){if(o instanceof Z)return Ho(o,e.flags.json);throw o}}function OP(e,t){return e.fallbackPolicy==="eligible_public"&&t instanceof Z&&t.status===401&&f(t.details??{},"reasonCode")==="api_key_invalid_or_expired"}async function hU(e,t,n,r){let i=o=>D(e,t,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(n)}catch(o){let s=yU(o);if(!s)throw o;return r.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before workspace approval. Interactive acknowledgement is unavailable in this mode.",r.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}).`),await e.promptSelect("Approve this exact warned generation for the workspace?",[{value:"cancel",label:"Cancel approval",description:"Do not approve or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind approval to this warning revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Workspace approval cancelled without granting value.",r.json,"distribution_warning_declined"):i({...n,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}async function sA(e,t,n,r="/api/v1/install"){let i=o=>D(e,r,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(t)}catch(o){let s=yU(o);if(!s)throw o;return n.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before install. Interactive acknowledgement is unavailable in this mode.",n.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}). Next action: ${s.posture.nextAction}.`),await e.promptSelect("Continue with this exact warned skill generation?",[{value:"cancel",label:"Cancel install",description:"Do not grant or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind consent to this warning and authority revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Install cancelled without granting value.",n.json,"distribution_warning_declined"):await i({...t,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}function yU(e){if(!(e instanceof Z)||e.status!==409||!e.details)return null;let t=j(e.details.data)?e.details.data:e.details,n=j(t.distributionPosture)?t.distributionPosture:null,r=n?.contractVersion,i=n?.warningDigest,o=n?.authorityRevision;return!n||r!=="skills-layer.distribution.v1"||typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i)||typeof o!="number"||!Number.isSafeInteger(o)||o<1?null:{reasonCode:typeof t.reasonCode=="string"?t.reasonCode:"warning_acknowledgement_required",posture:{contractVersion:r,warningDigest:i,authorityRevision:o,effectiveDistributionStatus:typeof n.effectiveDistributionStatus=="string"?n.effectiveDistributionStatus:"published_with_warning",reasonCode:typeof n.reasonCode=="string"?n.reasonCode:"guardian_incident_warning",nextAction:typeof n.nextAction=="string"?n.nextAction:"review_warning_before_install"}}}async function vU(e,t,n){let r=k(t.scope),i=k(t.agent);if(t.json||t.dryRun||!n.stdoutIsTty||r==="workspace"||r==="local"||r!==void 0&&i!==void 0)return{flags:t};let o=et(n.env,n.platform,n.cwd),s=$oe(n),a=await Doe(n.paths.installTargetPreferencePath),l=a?.workingModeId===s,c=l&&a?.agent?o.find(w=>w.id===a.agent):void 0,u=c&&a?.scope?a.scope==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath:void 0;if(i===void 0&&r===void 0&&a?.policy==="recheck_every_5"&&l&&c!==void 0&&(a.scope==="project"||a.scope==="global")&&u!==void 0&&a.usesSinceConfirmation>0&&a.usesSinceConfirmation<4)return await Ve(n.paths.installTargetPreferencePath,{...a,usesSinceConfirmation:a.usesSinceConfirmation+1,savedAt:n.now()}),{flags:{...t,agent:c.id,scope:a.scope}};let p=await tR({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:fr}),m=p.filter(w=>w.detectionSources.includes("project")),h=i??Ee(n.env.SKILLS_LAYER_AGENT),g=h?o.find(w=>w.id===h):void 0;if(h&&!g)return{result:E(`Unsupported agent "${h}". Run \`skills-layer agents list\` to choose a supported install target.`,t.json)};if(!g&&m.length===1&&(g=m[0]),!g){let w=Ee(n.config?.lastSelectedAgent);g=w?p.find(_=>_.id===w)??o.find(_=>_.id===w):void 0}if(!g&&p.length===1&&(g=p[0]),!g&&p.length>1){let w=await n.promptSelect("Multiple supported agents were detected. Select one to install for:",p.map(_=>({value:_.id,label:`${_.displayName} (${_.detectionSources.join(", ")})`})));g=p.find(_=>_.id===w)}if(!g)return{result:E("No supported local agent was detected. Run `skills-layer agents list`, then retry with --agent <agent> and --scope <project|global>.",t.json)};let y=r;if(!y){let w=[{value:"project",label:"Project (this folder)"}];g.targets.globalSkillsPath&&w.push({value:"global",label:"Global (all projects)"}),y=w.length===1?w[0].value:await n.promptSelect(`Install ${e} for ${g.displayName} where?`,w)}let v=i!==void 0||r!==void 0,b=a?.policy==="ask_every_time"&&l;if(!v&&!b&&(y==="project"||y==="global")){let w=y==="project"?"Project":"Global",C=await n.promptSelect(`Remember ${g.displayName} / ${w} for future installs?`,[{value:"recheck_every_5",label:"Yes - recheck on every 5th install"},{value:"ask_every_time",label:"No - ask every time"}])==="recheck_every_5"?{version:1,policy:"recheck_every_5",agent:g.id,scope:y,usesSinceConfirmation:1,workingModeId:s,savedAt:n.now()}:{version:1,policy:"ask_every_time",usesSinceConfirmation:0,workingModeId:s,savedAt:n.now()};await Ve(n.paths.installTargetPreferencePath,C)}return{flags:{...t,agent:g.id,scope:y}}}function $oe(e){return e.apiKey?Ee(e.config?.workingModeId)??"personal":"anonymous"}async function Doe(e){let t=await be(e);return!j(t)||t.version!==1||t.policy!=="recheck_every_5"&&t.policy!=="ask_every_time"||typeof t.workingModeId!="string"||typeof t.savedAt!="string"||typeof t.usesSinceConfirmation!="number"||!Number.isInteger(t.usesSinceConfirmation)||t.usesSinceConfirmation<0||t.agent!==void 0&&typeof t.agent!="string"||t.scope!==void 0&&t.scope!=="project"&&t.scope!=="global"?null:t}async function aA(e,t,n,r,i={}){if(k(r.agent)==="all")return await Toe(e,t,n,r,i);let o=lA(e,t,n,r);if(o.status==="skip")return t;if(o.status==="cache_only"){let h=await Sh(e,t,o.skillSlug,o.version,i),g=await Ih({backend:e,exportResult:h,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(g))return g;let v=(e.platform==="win32"?st:Lt).join(e.paths.bundlesDir,o.skillSlug,g.envelope.generation.semanticVersion,encodeURIComponent(g.envelope.generation.generationId),"bundle.zip");return await EA(v,g.bytes),{...t,...Ch(h),version:g.envelope.generation.semanticVersion,scope:"local",archiveSha256:g.archiveSha256,archiveHashFormat:g.archiveHashFormat,manifestSha256:g.envelope.manifest.sha256,generationId:g.envelope.generation.generationId,sourceContentDigest:ct(g.files),verificationStatus:"verified",cachedArtifact:{state:"verified",bundlePath:v,generation:g.envelope.generation,archiveSha256:g.archiveSha256,manifestSha256:g.envelope.manifest.sha256,savedAt:e.now()}}}if(o.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:o.skillSlug,nextStep:o.nextStep},o.message,r.json,"materialization_target_invalid");let s=await Xa({backend:e,skillSlug:o.skillSlug,agentId:o.agent.id,scope:o.scope,flags:r});if(s)return s;let a=await Sh(e,t,o.skillSlug,o.version,i),l=await Ih({backend:e,exportResult:a,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(l))return l;let c=(await lt(e)).installs[o.skillSlug],u=Vn(c,{scope:o.scope,installedPath:(e.platform==="win32"?st:Lt).join(o.skillsPath,zr(o.skillSlug)),platform:e.platform})[0]?.record,d=u?f(u,"sourceContentDigest"):void 0,p=ct(l.files);if(u?.verificationStatus==="unverified"&&!r.replaceUnverifiedSource&&(await Tr({targetDir:(e.platform==="win32"?st:Lt).join(o.skillsPath,zr(o.skillSlug)),generation:l.envelope.generation,archiveSha256:l.archiveSha256,manifestSha256:l.envelope.manifest.sha256,files:l.envelope.manifest.files})).status!=="verified")return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:o.skillSlug,installedArchiveSha256:u.archiveSha256,approvedArchiveSha256:l.archiveSha256,installedContentDigest:d,approvedContentDigest:p,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and retry with --replace-unverified-source to replace them with the approved catalogue generation."},"The approved catalogue artifact differs from the installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let m=await cA({backend:e,skillSlug:o.skillSlug,scope:o.scope,agent:o.agent,skillsPath:o.skillsPath,bytes:l.bytes,files:l.files,envelope:l.envelope,approval:l.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});return{...t,...Ch(a),archiveSha256:l.archiveSha256,archiveHashFormat:l.archiveHashFormat,scope:o.scope,agent:o.agent.id,targetAgent:o.agent.id,materializationPlan:{scope:o.scope,agent:o.agent.id},...Uu(e),...m,...m.guardianActivationReceipt?{warnings:[...Be(t,"warnings")??[],...Be(m,"warnings")??[]]}:{}}}async function Toe(e,t,n,r,i){let o=T(t,"materializationPlan")??T(t,"installPlan"),s=k(r.scope)??f(t,"scope")??(o?f(o,"scope"):void 0),a=f(t,"skillSlug")??f(t,"slug")??n;if(s!=="project"&&s!=="global")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Use --agent all with --scope project or --scope global."},"Installing for all compatible agents requires project or global scope.",r.json,"materialization_target_invalid");let l=et(e.env,e.platform,e.cwd),c=new Map;for(let w of l){let _=s==="global"?w.targets.globalSkillsPath:w.targets.projectSkillsPath;if(!_)continue;let C=Mo(_,e.platform),A=c.get(C);A?A.agents.push(w):c.set(C,{agent:w,agents:[w],skillsPath:_})}if(c.size===0)return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Run `skills-layer agents list` and select a supported target with an available path."},`No supported agent exposes a ${s} skill path on this machine.`,r.json,"materialization_target_invalid");for(let w of c.values())for(let _ of w.agents){let C=await Xa({backend:e,skillSlug:a,agentId:_.id,scope:s,flags:r});if(C)return C}let u=f(t,"version")??f(t,"currentVersion"),d=await Sh(e,t,a,u,i),p=await Ih({backend:e,exportResult:d,flags:r,skillSlug:a,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(p))return p;let m=ct(p.files),h=(await lt(e)).installs[a],g;if(!r.replaceUnverifiedSource)for(let w of c.values()){let _=(e.platform==="win32"?st:Lt).join(w.skillsPath,zr(a)),C=Vn(h,{scope:s,installedPath:_,platform:e.platform})[0];if(C?.record.verificationStatus==="unverified"&&(await Tr({targetDir:_,generation:p.envelope.generation,archiveSha256:p.archiveSha256,manifestSha256:p.envelope.manifest.sha256,files:p.envelope.manifest.files})).status!=="verified"){g=C;break}}if(g)return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:a,materializationId:g.materializationId,installedContentDigest:f(g.record,"sourceContentDigest"),approvedContentDigest:m,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and use --replace-unverified-source to replace the unverified generation."},"The approved catalogue artifact differs from an installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let y=[];for(let w of c.values()){let _=await cA({backend:e,skillSlug:a,scope:s,agent:w.agent,skillsPath:w.skillsPath,bytes:p.bytes,files:p.files,envelope:p.envelope,approval:p.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});y.push({...t,scope:s,agent:w.agent.id,targetAgent:w.agent.id,...Uu(e),..._})}let v=y[0],b=v[Ph];return{...t,...Ch(d),archiveSha256:p.archiveSha256,archiveHashFormat:p.archiveHashFormat,scope:s,agent:"all",targetAgents:l.map(w=>w.id),materializationPlan:{scope:s,agent:"all",physicalTargetCount:y.length,agentCount:l.length},materializationResults:y,materializedWrites:y.flatMap(w=>Array.isArray(w.materializedWrites)?w.materializedWrites:[]),materializedSkillRoot:f(v,"materializedSkillRoot"),...Uu(e),...bU(b)?{[Ph]:b}:{}}}async function Xa(e){let t=e.backend.config?.workingModeType==="enterprise_workspace",n=e.enforceRequired?"enforce":await id(e.backend,e.skillSlug);if(!t&&n!=="enforce"&&n!=="enabled")return null;let r=Ee(e.backend.config?.workingModeWorkspaceId);if(t&&!r)return x({status:"blocked",reasonCode:"guardian_workspace_context_unavailable",skillSlug:e.skillSlug,agent:e.agentId,scope:e.scope,nextAction:"workspace.current",nextStep:"Refresh the selected Enterprise workspace before materializing this skill."},"Enterprise materialization requires a current workspace-bound Guardian context.",e.flags.json,"guardian_workspace_context_unavailable");let i=await qn(e.backend,e.scope),o=(Be(i,"hooks")??[]).filter(j).find(u=>f(u,"agent")===e.agentId&&f(u,"scope")===e.scope&&u.active===!0),s=br(e.agentId),a=vl({evaluationContext:"activation_eligibility",requestedMode:"enforce",workspacePolicy:t?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:s?.maximumTier==="strict_candidate",hookInstalled:!!o,strictHookVerified:o?.strictPreActionBlocking===!0&&o.evidenceCapability==="strict",exactActivationVerified:o?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"none",materializationState:"active"}),l=a.activationAllowed&&a.countedAsEnforced,c=t&&e.backend.config.workingModeGuardianPolicy==="standard"&&o!==void 0&&o.configActive!==!1;return l||c?(t&&(e.backend.guardianActivationReceipts??={},e.backend.guardianActivationReceipts[`${e.agentId}:${e.scope}`]={policy:e.backend.config.workingModeGuardianPolicy==="standard"?"standard":"strict",agent:e.agentId,scope:e.scope,tier:l?"strict_verified":"hook_unverified",observedAt:e.backend.now()}),null):x({status:"blocked",reasonCode:"guardian_enforcement_unavailable",skillSlug:e.skillSlug,workspaceId:r,agent:e.agentId,scope:e.scope,measuredProtection:{...a,evidenceCapability:o?.evidenceCapability??"unverified",evidenceReasons:o?.evidenceReasons??[s?.reasonCode??"host_has_no_supported_guardian_route"]},nextAction:"guardian.hook.install",nextStep:!o||o.configActive===!1?`Run skills-layer guardian hook install --agent ${e.agentId} --scope ${e.scope}.`:e.backend.config?.workingModeRole==="enterprise_admin"?`This host has no current strict verification. Select a qualified host or use skills-layer enterprise workspace update ${e.backend.config?.workingModeEnterpriseId??"<enterprise-id>"} ${r??"<workspace-id>"} --guardian-policy standard. Hook installation alone does not prove strict enforcement.`:"This host has no current strict verification. Ask your Enterprise Admin to select a qualified host or review the workspace Guardian policy. Hook installation alone does not prove strict enforcement."},t&&e.backend.config.workingModeGuardianPolicy==="standard"&&(!o||o.configActive===!1)?`No active Guardian hook is installed for ${e.agentId} at ${e.scope} scope.`:`${t?"Enterprise":"Guardian-enforced"} materialization was blocked because verified Guardian enforcement is unavailable.`,e.flags.json,"guardian_enforcement_unavailable")}function LP(e,t,n){let r=e.guardianActivationReceipts?.[`${t}:${n}`];return r?{guardianEnforcement:r.tier,guardianActivationReceipt:r,...r.tier==="hook_unverified"?{warnings:[`Guardian hook installed but not strict-verified on ${t}; workspace policy allows standard enforcement.`]}:{}}:{}}function Uu(e){return e.config?.workingModeType!=="enterprise_workspace"?{}:ie({workingModeType:"enterprise_workspace",enterpriseId:e.config.workingModeEnterpriseId,workspaceId:e.config.workingModeWorkspaceId,workingModeWorkspaceId:e.config.workingModeWorkspaceId})}function lA(e,t,n,r){let i=T(t,"materializationPlan")??T(t,"installPlan"),o=k(r.scope)??f(t,"scope")??(i?f(i,"scope"):void 0),s=f(t,"skillSlug")??f(t,"slug")??n;if(o==="local")return{status:"cache_only",skillSlug:s,version:f(t,"version")??f(t,"currentVersion")};if(o!=="project"&&o!=="global")return{status:"skip"};let a=k(r.agent)??f(t,"agent")??f(t,"targetAgent")??(i?f(i,"agent")??f(i,"targetAgent"):void 0)??Ee(e.config?.lastSelectedAgent)??"codex",l=et(e.env,e.platform,e.cwd).find(u=>u.id===a);if(!l)return{status:"failure",skillSlug:s,message:`Unsupported agent "${a}". Run \`skills-layer agents list\` to choose a supported local install target.`,nextStep:"Run `skills-layer agents list` and retry with a supported --agent value."};let c=o==="global"?l.targets.globalSkillsPath:l.targets.projectSkillsPath;return c?{status:"ok",scope:o,agent:l,skillsPath:c,skillSlug:s,version:f(t,"version")??f(t,"currentVersion")}:{status:"failure",skillSlug:s,message:`${l.displayName} does not expose a ${o} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function Sh(e,t,n,r,i={}){if(typeof t.downloadUrl=="string"&&j(t.artifactEnvelope)&&j(t.artifactApproval)&&j(t.platformScoreAuthority))return t;let o=new URLSearchParams;r&&o.set("version",r);let s=i.exportMode==="public"||!e.apiKey,a=s?`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`:`/api/v1/me/library/${encodeURIComponent(n)}/export${Qe(o)}`,l=await D(e,a,{headers:s?{}:ne(e.apiKey,e.authBlockedMessage)});if(!s&&!j(l.platformScoreAuthority))try{let c=await D(e,`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`,{headers:{}});return{...l,platformScoreAuthority:c.platformScoreAuthority}}catch(c){if(!(c instanceof Z)||![401,403,404].includes(c.status))throw c}return s?{...l,downloadUrl:Ooe(n,f(l,"version")??r)}:l}function Ooe(e,t){let n=new URLSearchParams;return t&&n.set("version",t),`/api/v1/skills/${encodeURIComponent(e)}/download${Qe(n)}`}function Loe(e){let t=f(e,"visibility")??f(e,"versionVisibility"),n=f(e,"publicationStatus");return kU(e)&&(t==="public"||n==="clean_publishable"||n==="publishable_with_findings")}function joe(e){return kU(e)}async function zu(e){let t=xh(e.result),n=f(t,"skillSlug")??f(t,"slug")??e.fallbackSlug,r=e.requestedVisibility??(f(t,"visibility")==="public"||f(t,"versionVisibility")==="public"||f(t,"releaseVisibility")==="public"?"public":"private");if(!joe(t)){let c=T(t,"publication"),u=f(t,"reasonCode")??(c?f(c,"reasonCode"):void 0)??"security_review_pending",d=!!e.unverifiedMaterialization,p=f(t,"version"),m=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"version")??f(e.unverifiedMaterialization,"currentVersion"):void 0,h=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"generationId"):void 0,g=c?f(c,"status")??f(t,"status")??"submitted":f(t,"status")??"submitted",y=g==="catalogue_submission_failed"||u==="source_ingestion_candidate_not_claimable",v=f(t,"workflowId"),b=f(t,"processingAttemptId"),w=f(t,"jobId"),_=f(t,"intakeReceiptId"),C=T(t,"progress")??{},A=!y&&t.continuationConfirmed!==!1&&!!(v||b||w)&&["queued","running","catalogue_processing_scheduled","held_for_moderation","source_install_pending_review","reused"].includes(g),N={status:y?"rejected":g==="reused"&&_?"reused":A?g==="reused"?"reused":"accepted":_?"accepted":"unconfirmed",reasonCode:u,continuationConfirmed:A,nextActor:f(C,"nextActor")??(A?"platform":u==="source_ingestion_candidate_not_claimable"?"operator":"requester")},O=ie({...e.unverifiedMaterialization,status:d?"installed_unverified":"install_pending_review",sourceItemStatus:f(t,"status")??"submitted",skillId:f(t,"skillId"),versionId:f(t,"versionId"),skillSlug:n,version:d?m:p,catalogueCandidateVersion:p,localProvisionalVersion:m,localGeneration:h,sourceContentDigest:e.unverifiedMaterialization?f(e.unverifiedMaterialization,"sourceContentDigest"):void 0,visibility:r,catalogueVisibilityRequested:r,requestedVisibility:r,catalogueStatus:g,publiclyDiscoverable:!1,intakeAdmission:N,assessmentStatus:f(C,"status")??(A?"pending":"unconfirmed"),publicationStatus:"not_published",distributionStatus:"verified_artifact_required",workflowId:v,processingAttemptId:b,jobId:w,intakeReceiptId:_,progress:t.progress,intakeReceiptIds:t.intakeReceiptIds,candidateIds:t.candidateIds,wakeStatus:t.wakeStatus,uploadIntent:t.uploadIntent,backgroundWorkStatus:A?"catalogue_review_continues_automatically":"retry_or_operator_action_required",publication:c?xh(c):void 0,activationStatus:d?"installed_unverified":"held",verificationStatus:d?"unverified":void 0,reasonCode:u,materializedWrites:d&&Array.isArray(e.unverifiedMaterialization?.materializedWrites)?e.unverifiedMaterialization.materializedWrites:[],materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex",activation:d?"unverified_install_request_authorized":"approved_artifact_only"},nextStep:d?`Local installation is complete as Unverified / Unscored. ${A?"The durable assessment job remains scheduled.":"Continued assessment is not confirmed; retry submission or inspect the candidate status."} Verified publication requires valid four-dimension evidence and current distribution authority. Valid poor effectiveness is a warning, not a security block.`:A?`Run skills-layer ${_?`install status ${_}`:`creator status ${n}`}, then retry when verified distribution is available.`:"Submission continuation is not confirmed. Inspect the intake status or retry submission before waiting for assessment."});return d&&await Ka(e.backend,O,n),Ga(O,d?`External source installed locally as unverified; ${A?"catalogue review continues":"catalogue continuation is unconfirmed"}.`:A?"Source submitted; installation is pending approval.":"Source installation is held; catalogue continuation is unconfirmed.",e.flags.json,e.backend)}let i=T(T(t,"progress")??{},"subject"),o=i?f(i,"generationId"):void 0,s=i?f(i,"version"):void 0;if(i&&(!o||!s||f(i,"slug")!==n))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",skillSlug:n,intakeReceiptId:t.intakeReceiptId,nextStep:"Retry after the source receipt identifies the exact approved skill, version and generation."},"The completed source receipt does not identify this exact skill and generation.",e.flags.json,"source_catalogue_identity_invalid");let a;try{a=await aA(e.backend,t,n,e.flags,{exportMode:Loe(t)?"public":"auto",...i?{expectedSourceGeneration:{generationId:o,version:s}}:{}})}catch(c){if(!(c instanceof Z)||![404,502,503,504].includes(c.status))throw c;let u=ie({...t,...e.unverifiedMaterialization,status:e.unverifiedMaterialization?"installed_unverified":"catalogue_artifact_unavailable",activationStatus:e.unverifiedMaterialization?"installed_unverified":"not_installed",sourceItemStatus:f(t,"status"),catalogueStatus:f(t,"status"),publicationStatus:"published",continuationConfirmed:!0,reasonCode:"catalogue_artifact_unavailable",serverReasonCode:c.details?f(c.details,"reasonCode"):void 0,nextStep:"The catalogue version is published, but its approved artifact could not be downloaded. Retry the install when export is available. Any existing local source install remains unverified."});return e.unverifiedMaterialization?(await Ka(e.backend,u,n),Ga(u,"Source installed locally as unverified; the published catalogue artifact is temporarily unavailable.",e.flags.json,e.backend)):x(u,"The published catalogue artifact is temporarily unavailable.",e.flags.json,"catalogue_artifact_unavailable")}if(fe(a))return a;let l=await uA(e.backend,a,n,e.flags);return await Ka(e.backend,l,n),Ga(l,tse(e.source,e.flags,e.backend,l,e.sourceAccess),e.flags.json,e.backend)}function xh(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>t==="localWrites"||t==="files"||t==="content"||t==="archiveBytes"?[]:Array.isArray(n)?[[t,n.map(r=>j(r)?xh(r):r)]]:j(n)?[[t,xh(n)]]:[[t,n]]))}function kU(e){if(wU(e.artifactApproval).status==="ok"&&e.artifactEnvelope!==void 0&&typeof e.downloadUrl=="string")return!0;let n=T(e,"publication"),r=n?f(n,"status")==="published":!1,i=f(e,"listingStatus")==="published",o=f(e,"versionStatus")==="published",s=f(e,"status");return i&&o&&(r||s==="published"||s==="reused"||s==="source_approved")}function Ch(e){return ie({version:f(e,"version"),storageKey:f(e,"storageKey"),expiresAt:f(e,"expiresAt")})}async function Ih(e){let t=wU(e.exportResult.artifactApproval);if(t.status!=="ok"){let d=t.status==="missing";return Ti(e,d?"artifact_v1_approval_missing":"artifact_v1_approval_invalid",d?`Export for ${e.skillSlug} did not include an authoritative approved Artifact Format v1 identity.`:`Export for ${e.skillSlug} included malformed Artifact Format v1 approval metadata.`)}let n=t.approval;if(e.expectedSourceGeneration&&(n.generation.generationId!==e.expectedSourceGeneration.generationId||n.generation.semanticVersion!==e.expectedSourceGeneration.version))return Ti(e,"source_catalogue_generation_mismatch","The exported artifact does not match the exact version and generation resolved for this source.");let r=Noe({backend:e.backend,exportResult:e.exportResult,approval:n,skillSlug:e.skillSlug});if(r.status!=="ok")return Ti(e,r.reasonCode,r.message);if(e.exportResult.artifactEnvelope===void 0)return Ti(e,"artifact_v1_envelope_missing",`Export for ${e.skillSlug} did not include an Artifact Format v1 envelope.`);let i=f(e.exportResult,"downloadUrl");if(!i)return x({status:"export_download_unavailable",reasonCode:"export_download_unavailable",skillSlug:e.skillSlug,nextStep:"Retry after the backend returns a signed bundle download URL."},`Export for ${e.skillSlug} did not include a signed download URL.`,e.flags.json,"export_download_unavailable");let o=await e.backend.fetchFn(Boe(e.backend.baseUrl,i));if(!o.ok)throw new Z(o.status,`Unable to download exported bundle (${o.status}).`);let s;try{s=await Moe(o)}catch(d){return Ti(e,"artifact_v1_archive_bounds_failed",`Downloaded ${e.skillSlug} exceeded Artifact Format v1 archive bounds.`,{verificationError:ke(d)})}let a,l;try{a=Ud({archiveBytes:s,envelope:e.exportResult.artifactEnvelope}),l=Il({archiveBytes:s,envelope:a})}catch(d){return Ti(e,"artifact_v1_verification_failed",`Downloaded ${e.skillSlug} failed Artifact Format v1 verification.`,{verificationError:ke(d)})}if(!Foe(n,a))return Ti(e,"artifact_v1_identity_mismatch",`Downloaded ${e.skillSlug} did not match the authoritative approved generation.`);let c=f(e.exportResult,"skillSlug"),u=f(e.exportResult,"version");return a.generation.skillSlug!==e.skillSlug||c!==void 0&&c!==a.generation.skillSlug||u!==void 0&&u!==a.generation.semanticVersion?Ti(e,"artifact_v1_target_mismatch",`Downloaded ${e.skillSlug} was approved for a different skill or version.`):{status:"ok",bytes:s,files:l,envelope:a,approval:n,archiveSha256:a.archive.sha256,archiveBytesSha256:a.archive.sha256,archiveHashFormat:"artifact_v1_zip"}}function Noe(e){let t=T(e.exportResult,"platformScoreAuthority"),n=t?.machineReport,r=t?.passport,i=t?.parityManifest,o=t?f(t,"passportPublicKey"):void 0;if(!t||!oC(n)||!o)return{status:"invalid",reasonCode:"platform_score_authority_missing",message:`Export for ${e.skillSlug} did not include a verifiable Platform Score authority.`};let s=Xc.safeParse(r),a=iC.safeParse(i);if(!s.success||!a.success)return{status:"invalid",reasonCode:"platform_score_authority_invalid",message:`Export for ${e.skillSlug} included malformed Platform Score authority metadata.`};let l=n.projection.report;if(l.subject.slug!==e.skillSlug||l.subject.version!==e.approval.generation.semanticVersion||l.subject.generationId!==e.approval.generation.generationId||l.subject.archiveSha256!==e.approval.archiveSha256||a.data.report.reportId!==l.reportId||a.data.report.revision!==l.revision||a.data.report.digest!==l.reportDigest)return{status:"invalid",reasonCode:"platform_score_authority_subject_mismatch",message:`Export for ${e.skillSlug} did not match the exact Platform Score generation.`};try{let c=sj({passport:s.data,publicKeys:{[s.data.issuer.keyId]:dre(o)},now:e.backend.now(),expectedSubject:l.subject,expectedReport:{reportId:l.reportId,revision:l.revision,digest:l.reportDigest},currentPassportId:s.data.passportId});if(!c.valid)return{status:"invalid",reasonCode:`platform_score_${c.reasonCode}`,message:`Export for ${e.skillSlug} failed signed Skill Passport verification.`}}catch{return{status:"invalid",reasonCode:"platform_score_passport_key_invalid",message:`Export for ${e.skillSlug} included an invalid Skill Passport public key.`}}return{status:"ok"}}function wU(e){return e==null?{status:"missing"}:!j(e)||e.status!=="approved"||!j(e.generation)||typeof e.generation.skillSlug!="string"||typeof e.generation.semanticVersion!="string"||typeof e.generation.generationId!="string"||typeof e.archiveSha256!="string"||typeof e.manifestSha256!="string"?{status:"invalid"}:{status:"ok",approval:{status:"approved",generation:{skillSlug:e.generation.skillSlug,semanticVersion:e.generation.semanticVersion,generationId:e.generation.generationId},archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256}}}function Foe(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archive.sha256&&e.manifestSha256===t.manifest.sha256}function Ti(e,t,n,r={}){return x({status:"download_integrity_failed",reasonCode:t,skillSlug:e.skillSlug,version:f(e.exportResult,"version"),archiveHashFormat:"artifact_v1_zip",...r,nextStep:"Retry after the catalog serving generation is refreshed, or contact Skills Layer support if this repeats."},n,e.flags.json,t)}function Boe(e,t){return/^https?:\/\//iu.test(t)?t:`${dr(e)}${t.startsWith("/")?"":"/"}${t}`}async function Moe(e){let t=e.headers.get("content-length");if(t!==null){let a=Number(t);if(!Number.isSafeInteger(a)||a<0)throw new Error("Artifact response Content-Length is invalid.");if(a>ut.maxArchiveBytes)throw new Error("Artifact response exceeds the v1 archive byte limit.")}if(!e.body)throw new Error("Artifact response body is unavailable.");let n=e.body.getReader(),r=[],i=0;try{for(;;){let a=await n.read();if(a.done)break;if(i+=a.value.byteLength,i>ut.maxArchiveBytes)throw await n.cancel("Artifact response exceeds the v1 archive byte limit."),new Error("Artifact response exceeds the v1 archive byte limit.");r.push(Uint8Array.from(a.value))}}finally{n.releaseLock()}let o=new Uint8Array(i),s=0;for(let a of r)o.set(a,s),s+=a.byteLength;return o}async function cA(e){let t=e.verificationStatus??"verified";if(t==="verified"&&!e.approval)throw new Error("Verified materialization requires platform artifact approval.");let n=e.backend.platform==="win32"?st:Lt,r=ct(e.files),i=n.join(e.backend.paths.bundlesDir,e.skillSlug,e.envelope.generation.semanticVersion,encodeURIComponent(e.envelope.generation.generationId),"bundle.zip"),o=n.join(e.skillsPath,zr(e.skillSlug)),s=et(e.backend.env,e.backend.platform,e.backend.cwd).filter(G=>{let ee=e.scope==="global"?G.targets.globalSkillsPath:G.targets.projectSkillsPath;return ee!==null&&Mo(ee,e.backend.platform)===Mo(e.skillsPath,e.backend.platform)}).map(G=>G.id).sort(),a=`activation_${Ge(16).toString("hex")}`,l={targetDir:o,generation:e.envelope.generation,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,files:e.envelope.manifest.files},c=hz({scope:e.scope,targetDir:o,platform:e.backend.platform}),u=await lt(e.backend);for(let[G,ee]of Object.entries(u.installs)){let te=[ee,...Rn(ee).map(Q=>Q.record)].flatMap(Q=>[Yt(Q)?.receipt.targetDir,f(Q,"materializedSkillRoot"),f(Q,"materializedPath")]);if(G!==e.skillSlug&&te.some(Q=>Q&&bA(o,Q,e.backend.platform)))throw new Error(`Install folder already belongs to another skill (${G}). Remove that installation or choose a different target before installing ${e.skillSlug}.`)}let d=u.installs[e.skillSlug],p=Xt(d)[c],m=JSON.stringify(p??null),h=Zu({state:"pending_activation",operationId:a,receipt:l,backend:e.backend}),g=Zu({state:"active",operationId:a,receipt:l,backend:e.backend}),y={skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,targetAgents:s.length>0?s:[e.agent.id],materializedPath:o,materializedSkillRoot:o,materializationId:c,bundlePath:i,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,...Uu(e.backend),...LP(e.backend,e.agent.id,e.scope),localLifecycle:h,savedAt:e.backend.now()};await EA(i,e.bytes);let v=e.files.find(G=>ot(G.path).toLowerCase()==="skill.md"),b=v?await Zae({backend:e.backend,skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,skillDocumentPath:n.join(o,...fM(v.path)),skillDocumentContent:v.content??""}):void 0,w,_=!1,C;try{let G={targetDir:o,...t==="verified"&&p?.verificationStatus==="unverified"&&!e.replaceUnverifiedSource?{expectedPreviousReceipt:l}:{},archiveBytes:e.bytes,envelope:e.envelope,preActivate:async({stageDir:ee})=>{let te=await zoe({backend:e.backend,stageDir:ee,envelope:e.envelope});return te.status==="passed"?(w=te.evalRun,{status:"passed",evidenceId:te.evidenceId}):{status:"failed",reasonCode:te.reasonCode}},checkpoint:async ee=>{if(ee==="after_static_eval"){await Mr(e.backend,te=>{let Q=te.installs[e.skillSlug],Ie=Xt(Q)[c];if(JSON.stringify(Ie??null)!==m)throw new Error(`Local install materialization for ${e.skillSlug} changed during atomic activation.`);te.installs[e.skillSlug]=Br({existing:Q,skillSlug:e.skillSlug,materialization:y,backend:e.backend})}),_=!0;return}ee==="after_stage_activated"&&await Mr(e.backend,te=>{let Q=te.installs[e.skillSlug],Ie=Xt(Q)[c],fn=Ie?Yt(Ie):null;if(!fn||fn.state!=="pending_activation"||fn.operationId!==a)throw new Error(`Atomic activation receipt reservation for ${e.skillSlug} was lost before commit.`);te.installs[e.skillSlug]=Br({existing:Q,skillSlug:e.skillSlug,materialization:{...y,localLifecycle:g,savedAt:e.backend.now()},backend:e.backend})})}};C=t==="verified"?await l2({...G,approval:e.approval}):await c2(G)}catch(G){throw _&&await ble({backend:e.backend,skillSlug:e.skillSlug,materializationId:c,operationId:a,baselineMaterialization:p}),G}if(!w)throw new Error("Static pre-activation Eval did not produce generation-bound evidence.");let A=await lt(e.backend),N=Xt(A.installs[e.skillSlug])[c],O=N?Yt(N):null;if(!O||O.state!=="active"||O.operationId!==a)throw new Error(`Atomic activation receipt for ${e.skillSlug} was not committed.`);let X=C.receipt.files.map(G=>({path:EU(e.backend.cwd,n.join(o,...fM(G.path))),bytes:G.sizeBytes}));return{...e.backend.config?.workingModeType==="enterprise_workspace"?{status:"installed"}:{},bundlePath:i,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,...Uu(e.backend),...LP(e.backend,e.agent.id,e.scope),materializedPath:o,materializedSkillRoot:o,materializationId:c,targetAgents:s.length>0?s:[e.agent.id],archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,materializedWrites:X,...b?{guardianRuntimeMetadata:b}:{},localLifecycle:g,atomicActivation:{status:C.status,receipt:C.receipt,generation:C.receipt.generation,archiveSha256:C.receipt.archiveSha256,manifestSha256:C.receipt.manifestSha256,staticEvaluation:C.staticEvaluation,cleanupPending:C.cleanupPending,...C.cleanupPath?{cleanupPath:C.cleanupPath}:{}},[Ph]:w}}var Ph=Symbol("skills-layer.pre-activation-eval"),Uoe=new Set(["file_exists","json_valid","schema_match","section_exists","regex_match","artifact_valid"]);async function zoe(e){let t=await _U(e.stageDir),n=ct(t),r=CU(t,n),i=l=>cT({pack:l,files:t,activationState:"inactive_staging",skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now(),runnerVersion:jP()}),o=i(r.pack);if(o.outcome!=="completed")return{status:"failed",reasonCode:o.reasonCode};let s=i(IU(t,n));if(s.outcome!=="completed")return{status:"failed",reasonCode:s.reasonCode};if(s.result.summary.status!=="passed")return{status:"failed",reasonCode:`static_eval_${s.result.summary.status}`};let a=xU({files:t,skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now()});return{status:"passed",evidenceId:`${s.result.summary.evalPackDigest??"eval-pack-unavailable"}:${s.result.summary.artifactDigest}`,evalRun:a}}async function uA(e,t,n,r){let i=f(t,"materializedSkillRoot");if(!i)return t;let o=f(t,"skillSlug")??f(t,"slug")??n,s=f(t,"version")??f(t,"currentVersion")??k(r.version)??"local";try{let a=t[Ph],l;if(bU(a))l=a;else{let u=await _U(Tt(e.cwd,i));if(u.length===0)return gh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"installed_files_unreadable"});l=xU({files:u,skillSlug:o,version:s,generatedAt:e.now()})}let c=await Yoe(e,l.summary);return c.status==="recorded"?gh({...t,...c.effectiveness?{effectiveness:c.effectiveness}:{}},r,{status:"recorded",source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,evidenceRevision:c.evidenceRevision}):gh(t,r,{status:c.status,source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,reasonCode:c.reasonCode})}catch(a){return gh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"local_eval_failed",message:ke(a)})}}function bU(e){return j(e)&&(e.source==="submitted"||e.source==="inferred"||e.source==="invalid_submitted")&&j(e.summary)&&e.summary.schemaVersion==="skills-layer.eval.summary.v1"}async function _U(e){let t=[];return await SU(e,e,t),t.sort((n,r)=>n.path.localeCompare(r.path))}async function SU(e,t,n){for(let r of await mre(t,{withFileTypes:!0})){if(qoe(r.name))continue;let i=K(t,r.name);if(r.isDirectory()){await SU(e,i,n);continue}if(!(!r.isFile()||Goe(r.name)))try{n.push({path:Mu(e,i).split("\\").join("/"),content:await Ui(i,"utf8")})}catch{continue}}}function qoe(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Voe()||e==="dist"}function Voe(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}function Goe(e){return e==="bundle.zip"||/^\.skills-layer-.*\.json$/u.test(e)}function xU(e){let t=ct(e.files),n=CU(e.files,t);if(!uf(n.pack).valid)return{source:"invalid_submitted",summary:$s({status:"runner_unavailable",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:t,evalPackDigest:Es(n.pack),generatedAt:e.generatedAt,runnerVersion:jP(),counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})};let i=Koe(n.pack).map(s=>({id:s.id,assertions:s.assertions.map(a=>Woe(a,e.files))})),o=Zoe(i);return{source:n.source,summary:$s({status:Joe(o),skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:typeof n.pack.artifactDigest=="string"?n.pack.artifactDigest:t,evalPackDigest:Es(n.pack),generatedAt:e.generatedAt,runnerVersion:jP(),counts:{cases:i.length,assertions:o.total,passed:o.passed,failed:o.failed,skipped:o.skipped}})}}function CU(e,t){let n=Hoe(e);return n?{pack:n,source:"submitted"}:{pack:IU(e,t),source:"inferred"}}function Hoe(e){for(let t of e){let n=Dn(t.path,e);if(!(n.type!=="evidence"||!t.content||!n.relativePath.toLowerCase().endsWith(".eval.json")))try{let r=JSON.parse(t.content);if(j(r))return r}catch{return{schemaVersion:"invalid",artifactDigest:ct(e),origin:"submitted",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[]}}}}function IU(e,t){let r=e.find(i=>i.path.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()==="skill.md")?.path??"SKILL.md";return{schemaVersion:"skills-layer.eval.pack.v1",artifactDigest:t,origin:"inferred",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[{id:"starter-runtime-shape",assertions:[{type:"file_exists",path:r},{type:"regex_match",path:r,pattern:"name:"},{type:"artifact_valid",artifactDigest:t}]}]}}function Koe(e){return Array.isArray(e.cases)?e.cases.flatMap(t=>!j(t)||typeof t.id!="string"||!Array.isArray(t.assertions)?[]:[{id:t.id,assertions:t.assertions.filter(j)}]):[]}function Woe(e,t){return typeof e.type=="string"&&!Uoe.has(e.type)?{status:"skipped",reasonCode:"runner_unavailable"}:lf(e,{files:t})}function Zoe(e){return e.reduce((t,n)=>{for(let r of n.assertions)t.total+=1,r.status==="passed"&&(t.passed+=1),r.status==="failed"&&(t.failed+=1),r.status==="skipped"&&(t.skipped+=1);return t},{total:0,passed:0,failed:0,skipped:0})}function Joe(e){return e.failed>0?"failed":e.passed>0?"passed":e.skipped>0?"runner_unavailable":"not_run"}function jP(){return`skills-layer-public-cli:${Co}:local-install`}async function Yoe(e,t){if(!e.apiKey)return{status:"local_only",reasonCode:"not_authenticated"};try{let n=await D(e,"/api/v1/me/evals/results",{method:"POST",headers:{"content-type":"application/json",...ne(e.apiKey,e.authBlockedMessage)},body:JSON.stringify({evalSummary:t})}),r=T(n,"evalEvidence");return{status:"recorded",effectiveness:T(n,"effectiveness"),evidenceRevision:r?J(r,"revision"):void 0}}catch(n){return{status:"submit_failed",reasonCode:n instanceof Z?`http_${n.status}`:"request_failed"}}}function gh(e,t,n){return t.json?{...e,localEval:n}:e}function fM(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(r=>r.length>0);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function mM(e,t,n,r,i){let o=k(r.visibility)??"private";if(o!=="private"&&o!=="public")return x({status:"invalid_visibility",reasonCode:"invalid_visibility",source:e,requestedVisibility:o,nextStep:`Use \`skills-layer install ${e} --visibility private\` or \`--visibility public\`.`},"Local path install visibility must be private or public.",r.json,"invalid_visibility");let s=dA(e,t,n);if(r.list)return R(s,"Local source skills loaded.",r.json,i);let a=Ah(e,s,r);if(a)return a;let l=await Nu({source:e,inspection:s,requestedSkillSlug:n,mode:"install",flags:r,backend:i});if(l.kind==="failure")return l.result;let c=l.skillSlug??ur(s)[0]?.value??RU(e),u=Xoe(t.files,c),d=Jr({files:u,limits:ko}),p={mode:r.localOnly?"local_only":o==="public"?"explicit_public":"managed_private",upload:!r.localOnly,destination:r.localOnly?null:i.baseUrl,audience:r.localOnly?"local_device":o==="public"?"public_after_governed_review":"account_private",authentication:r.localOnly?"not_required":"required",files:d.preview.files.map(y=>({path:y.path,bytes:y.bytes})),totalBytes:d.preview.totalBytes};if(r.dryRun)return R({...BP(e,s,c,r),installKind:"local_source_submission",visibility:o,publicationStatus:"preview",catalogRecord:o,activationStatus:"not_started",uploadIntent:p,nextStep:r.localOnly?"Re-run without --dry-run for unverified, unscored local activation without upload.":`Re-run without --dry-run to create or reuse the ${o} central item. Local activation remains held until the exact generation completes security review and Artifact-v1 approval.`},"Local source submission preview ready.",r.json,i);if(r.localOnly){let y=await NP({backend:i,flags:r,source:e,skillSlug:c,files:u,defaultAcceptUnverifiedSource:!0});if(fe(y))return y;let v={...y,status:"installed_unverified",activationStatus:"installed_unverified",uploadIntent:p,intakeAdmission:{status:"not_requested"},assessmentStatus:"not_requested",publicationStatus:"not_requested",distributionStatus:"unverified_local",backgroundWorkStatus:"not_requested"};return await Ka(i,v,c),Ga(v,"Local source installed as unverified and unscored. No files were uploaded.",r.json,i)}if(!i.apiKey)return x({reasonCode:"local_source_authentication_required",uploadIntent:p,nextStep:"Sign in for managed submission, or use --local-only for an unverified installation without upload."},"Managed local source submission requires authentication before uploading files.",r.json,"local_source_authentication_required");i.emitInfo(`Upload intent: ${p.files.length} selected files (${p.totalBytes} bytes) to ${i.baseUrl}; audience ${p.audience}; authenticated account required. Use --dry-run --json to inspect the file list or --local-only to avoid upload.`);let m=await rA(i,c,r);if(m)return m;let h;if(PU(r,i)){let y=await NP({backend:i,flags:r,source:e,skillSlug:c,files:u});if(fe(y))return y;h=y}let g;try{let y=gg(u)?await IC({baseUrl:i.baseUrl,apiKey:i.apiKey,fetchFn:i.fetchFn,files:u}):null;g=await D(i,"/api/v1/me/source-installs",{method:"POST",headers:{"content-type":"application/json",...ne(i.apiKey,i.authBlockedMessage)},body:JSON.stringify(ie({...y?{hydrationManifestId:y.manifestId}:{files:u},skillSlug:c,version:k(r.version),visibility:o,category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),sourceMetadata:t.sourceMetadata}))})}catch(y){return h?await zu({backend:i,flags:r,source:e,fallbackSlug:c,sourceAccess:"authenticated",requestedVisibility:o,unverifiedMaterialization:h,result:{status:"catalogue_submission_failed",skillSlug:c,uploadIntent:p,reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable"}}):x({status:"catalogue_submission_failed",uploadIntent:p,activationStatus:"not_started",intakeAdmission:{status:"rejected"},assessmentStatus:"not_requested",publicationStatus:"not_published",distributionStatus:"verified_artifact_required",reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable",skillSlug:c,nextStep:"Retry the source submission when catalogue service is available. No local files were written."},"The source was not installed because catalogue submission did not complete.",r.json,"catalogue_submission_failed")}return await zu({backend:i,result:{...g,uploadIntent:p},fallbackSlug:f(g,"skillSlug")??c,source:e,sourceAccess:"authenticated",flags:r,requestedVisibility:o,...h?{unverifiedMaterialization:h}:{}})}function Xoe(e,t){let n=pA(e).find(i=>i.skillSlug===t);if(!n||n.relativeSkillRoot===".")return e.map(i=>({...i}));let r=`${n.relativeSkillRoot.replace(/\/+$/u,"")}/`;return e.filter(i=>i.path.replaceAll("\\","/").startsWith(r)).map(i=>({...i,path:i.path.replaceAll("\\","/").slice(r.length)}))}async function gM(e){if(!e.flags.all&&!(!e.defaultAcceptUnverifiedSource&&!PU(e.flags,e.backend)))try{let t=ir(e.source),n=await Ej({source:t,cwd:e.backend.cwd,platform:e.backend.platform,fetchFn:e.backend.fetchFn,...e.skillSlug?{requestedSkillSlug:e.skillSlug}:{}}),r=e.skillSlug?n.results.find(i=>i.skillSlug===e.skillSlug):n.results.length===1?n.results[0]:void 0;return r?await NP({backend:e.backend,flags:e.flags,source:e.source,skillSlug:r.skillSlug,files:r.files,relativeSkillRoot:r.relativeSkillRoot,defaultAcceptUnverifiedSource:e.defaultAcceptUnverifiedSource}):e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,nextStep:"Use --list to inspect the source and --skill <skill-slug> to select one exact skill before retrying."},"The CLI could not resolve one immutable external skill snapshot for local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}catch(t){return e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,error:t instanceof Error?t.message.slice(0,512):"Source snapshot could not be loaded.",nextStep:"Check source access and retry the exact source after its immutable snapshot is available."},"The CLI could not load the external source snapshot for unverified local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}}async function NP(e){let t=Jr({files:e.files,limits:ko}),n=nt(e.files,{profile:"external_ingest_tolerant"}),r=x2(e.files,S2),i=[...t.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:/^(?:secret_|pii_|sensitive_)/u.test(_.code)?"privacy":"integrity",..._.path?{path:_.path}:{}})),...n.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:"package_validity"})),...r.filter(_=>_.severity==="high"||_.severity==="critical").map(_=>({code:_.ruleId,concern:"security",path:_.filePath,..._.lineNumber?{lineNumber:_.lineNumber}:{}}))],o=i.map(_=>_.code);if(o.length>0){let _=i.some(C=>C.concern==="security")?"critical_local_preflight_blocked":"source_package_invalid";return x({status:"unverified_install_blocked",reasonCode:_,skillSlug:e.skillSlug,findingCodes:[...new Set(o)].sort((C,A)=>C.localeCompare(A)),blockingFindings:i,nextStep:"Do not activate this source. Review or remove the blocking content, then retry from a new immutable generation."},"External source did not satisfy the required local package checks and was not installed.",e.flags.json,_)}if(!(e.flags.acceptUnverifiedSource===!0||e.defaultAcceptUnverifiedSource===!0||await Qoe(e)))return x({status:"unverified_install_consent_required",reasonCode:"unverified_source_consent_required",skillSlug:e.skillSlug,nextStep:"Review the source, then retry with --accept-unverified-source to install it before platform approval."},"External source was not installed because informed unverified-source consent was not provided.",e.flags.json,"unverified_source_consent_required");let a=lA(e.backend,{skillSlug:e.skillSlug,materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex"}},e.skillSlug,e.flags);if(a.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:e.skillSlug,nextStep:a.nextStep},a.message,e.flags.json,"materialization_target_invalid");if(a.status==="skip"||a.status==="cache_only")return x({status:"materialization_target_required",reasonCode:"materialization_target_required",skillSlug:e.skillSlug,nextStep:"Retry with --scope project|global and --agent <agent>."},"An explicit local target is required for an unverified external installation.",e.flags.json,"materialization_target_required");let l=await Xa({backend:e.backend,skillSlug:e.skillSlug,agentId:a.agent.id,scope:a.scope,flags:e.flags});if(l)return l;let c=ct(e.files),u=ir(e.source),d=u.kind==="github"?u.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,p=e.relativeSkillRoot,m=u.kind==="github"&&/^[a-f0-9]{40}$/u.test(u.ref)?{provider:"github",repository:`${u.owner}/${u.repo}`,commitSha:u.ref,sourceRoot:!p||p==="."?d:d==="."?p:`${d}/${p}`,sourceContentDigest:t.preview.bundleSha256}:void 0,h=c.slice(7,19),g=k(e.flags.version)??`0.0.0-external.${h}`,y=`generation_unverified_${c.slice(7,39)}`,v=e.files.filter(_=>Dn(_.path,e.files).type==="runtime").map(_=>_.path),b=y0({generation:{skillSlug:e.skillSlug,semanticVersion:g,generationId:y},reviewPackageFiles:e.files,runtimeAllowlist:v});return{...await cA({backend:e.backend,skillSlug:e.skillSlug,scope:a.scope,agent:a.agent,skillsPath:a.skillsPath,bytes:b.archiveBytes,files:Il({archiveBytes:b.archiveBytes,envelope:b.envelope}),envelope:b.envelope,verificationStatus:"unverified"}),source:e.source,sourceContentDigest:c,...m?{sourceSnapshot:{...m,runtimeDigest:c,archiveSha256:b.envelope.archive.sha256}}:{},platformScoreDecision:null,scoreAvailability:"unscored",scoreReasonCode:"unscored_local_source",localPreflight:{status:"passed",recommendation:t.issues.length+n.issues.length+r.length>0?"approved_with_notes":"approved",issueCount:t.issues.length+n.issues.length+r.length,findingCodes:[...t.issues.map(_=>_.code),...n.issues.map(_=>_.code),...r.map(_=>_.ruleId)]}}}function PU(e,t){return e.acceptUnverifiedSource===!0||!e.json&&!t.nonInteractive&&t.stdoutIsTty}async function Qoe(e){if(e.flags.json||e.backend.nonInteractive)return!1;try{return await e.backend.promptSelect(`${e.skillSlug} comes from ${e.source} and has not completed Skills Layer Security/Eval. Install this immutable generation as unverified?`,[{value:"decline",label:"Do not install",description:"Keep local agent files unchanged."},{value:"accept",label:"Install unverified",description:"Use locally now while catalogue review runs in parallel."}])==="accept"}catch{return!1}}function dA(e,t,n){let r=pA(t.files),i=n?r.find(o=>o.skillSlug===n)??null:r.length===1?r[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:i,results:r,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function pA(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=Me(t.path).replaceAll("\\","/"),r=n==="."?".":n,i=AU(t.content??"")??RU(r==="."?t.path:r),o=ese(t.content??"");return{skillSlug:i,name:i,...o?{description:o}:{},relativeSkillRoot:r,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function AU(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function ese(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function RU(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}function EU(e,t){let n=Mu(e,t);return n&&!n.startsWith("..")&&!st.isAbsolute(n)?n.split("\\").join("/"):t}function ji(e,t,n,r="unknown"){let i=k(t.visibility);return i==="public"||i==="private"?i:r==="anonymous"&&FP(e)?"public":r==="authenticated"?"private":!n.apiKey&&FP(e)?"public":"private"}function FP(e){try{let t=ir(e).kind;return t==="github"||t==="gitlab"}catch{return/^https:\/\/(?:github|gitlab)\.com\//iu.test(e.trim())}}function fA(e,t,n,r="unknown"){return ji(e,t,n,r)==="private"||k(t.visibility)==="unlisted"||r==="authenticated"?"/api/v1/me/source-installs":"/api/v1/source-imports"}function $U(e,t,n,r="unknown"){return{"content-type":"application/json",...fA(e,t,n,r)==="/api/v1/me/source-installs"?ne(n.apiKey,n.authBlockedMessage):{}}}function tse(e,t,n,r,i="unknown"){let o=r?f(r,"visibility")??f(r,"versionVisibility"):void 0,s=r?f(r,"publicationStatus"):void 0,a=r?f(r,"catalogRecord"):void 0,l=r?f(r,"status"):void 0;return o==="public"||s==="clean_publishable"||s==="publishable_with_findings"||l==="published"?"Public source install planned.":o==="private"||s==="private"||a==="private"||l==="private_source_installed"?"Private source skill installed.":ji(e,t,n,i)==="public"?"Public source install planned.":"Private source skill installed."}async function Nu(e){let t=ur(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:nse(e.source,e.requestedSkillSlug,t.map(n=>n.value),e.flags)}:{kind:"selected",skillSlug:e.requestedSkillSlug};if(e.flags.all||e.flags.json&&e.flags.dryRun)return{kind:"selected",skillSlug:e.requestedSkillSlug};if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};if(e.flags.json)return{kind:"failure",result:hM(e.source,t,e.flags)};try{return{kind:"selected",skillSlug:await e.backend.promptSelect(`${e.source} exposes multiple skills. Select one to ${e.mode}:`,t)}}catch{return{kind:"failure",result:hM(e.source,t,e.flags)}}}function hM(e,t,n){let r=t.map(i=>i.value);return x({status:"selection_required",reasonCode:"source_skill_selection_required",source:e,availableSkills:r,nextAction:"install.source.select",nextStep:`Re-run with --skill <skill-slug> using one of: ${r.join(", ")}. Use --all only if you intend to install every discovered skill.`},`Source "${e}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${r.join(", ")}.`,n.json,"source_skill_selection_required")}function yM(e,t,n){if(n.all&&t)return x({status:"error",reasonCode:"conflicting_source_selection",source:e,selectedSkillSlug:t,all:!0,nextAction:"install",nextStep:"Use either --all to install every discovered skill or --skill <skill-slug> to install one skill, not both."},"Source install cannot combine --all with --skill. Choose one selection mode before retrying.",n.json,"conflicting_source_selection")}function vM(e,t){try{if(ir(e).kind!=="local")return}catch{return}return x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:qu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source URL, or run `skills-layer install --source <source> --list` with a supported source."},qu(e)?`Install source ${e} was not found or is not readable.`:`Install source "${e}" is not a supported remote source and no local path was found.`,t.json,"invalid_source")}function nse(e,t,n,r){return x({status:"not_found",reasonCode:"source_skill_not_found",source:e,requestedSkillSlug:t,availableSkills:n,nextAction:"install.source.list",nextStep:`Run \`skills-layer install --source ${e} --list\` to inspect discovered skills, then retry with one of the listed slugs.`},`Source ${e} does not contain a discovered skill named ${t}. Run with --list to inspect available skills.`,r.json,"source_skill_not_found")}function ur(e){let t=[e.results,e.skills,e.discoveredSkills,T(e,"source")?.results,T(e,"inspection")?.results],n=new Set,r=[];for(let i of t)if(Array.isArray(i))for(let o of i){let s=rse(o);!s||n.has(s.value)||(n.add(s.value),r.push(s))}return r}function rse(e){if(!j(e))return;let t=f(e,"skillSlug")??f(e,"slug")??f(e,"name");if(!t)return;let n=f(e,"displayName")??f(e,"title")??f(e,"name"),r=n&&n!==t?`${t} - ${n}`:t,i=T(e,"parsedSkill"),o=T(e,"frontmatter")??(i?T(i,"frontmatter"):void 0),s=f(e,"shortDescription")??f(e,"summary")??f(e,"description")??(o?f(o,"description"):void 0)??f(e,"relativeSkillRoot")??f(e,"path")??f(e,"discoveryRoute")??f(e,"sourceKind");return s?{value:t,label:r,description:s}:{value:t,label:r}}function kM(e,t,n,r,i,o={}){return ie({...t,skillSlug:n,scope:k(r.scope),agent:k(r.agent),workspace:k(r.workspace),version:k(r.version),visibility:o.visibility??k(r.visibility),category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),all:r.all,acceptCapability:r.acceptCapability})}async function wM(e){let t=e.sourceAccess??"unknown",n=fA(e.source,e.flags,e.backend,t);try{return await D(e.backend,n,{method:"POST",headers:$U(e.source,e.flags,e.backend,t),body:JSON.stringify(kM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{sourceAccess:t,...n==="/api/v1/source-imports"?{visibility:"public"}:{}}))})}catch(r){if(r instanceof Z&&r.status===401&&k(e.flags.visibility)!=="private"&&t!=="authenticated"&&FP(e.source))return await D(e.backend,"/api/v1/source-imports",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(kM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{visibility:"public"}))});throw r}}function BP(e,t,n,r){return ie({status:"dry_run",source:e,selectedSkillSlug:n,all:r.all,scope:k(r.scope)??"local",agent:k(r.agent),workspace:k(r.workspace),acceptCapability:r.acceptCapability,candidates:ur(t).map(i=>({skillSlug:i.value,name:i.label,description:i.description})),nextStep:r.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function DU(e,t,n,r,i={}){try{return{kind:"ok",inspection:await D(e,"/api/v1/source-inspect",{method:"POST",headers:TU(e,i.authMode??"auto"),body:JSON.stringify(ie(n))})}}catch(o){if(o instanceof Z)return{kind:"failure",result:UP(t,o,r)};throw o}}function TU(e,t){return t==="anonymous"?{"content-type":"application/json"}:V(e.apiKey)}async function MP(e,t,n,r){try{let s=await D(e,"/api/v1/source-inspect",{method:"POST",headers:TU(e,"anonymous"),body:JSON.stringify(ie(n))}),a=bM(t,s,r);return a?{kind:"failure",result:a}:{kind:"ok",inspection:s,sourceAccess:"anonymous"}}catch(s){if(!(s instanceof Z))throw s;let a=s.details??{},l=f(a,"error")??s.message;if(!mA(s.status,l))return{kind:"failure",result:UP(t,s,r)};if(!e.apiKey)return{kind:"failure",result:UP(t,s,r)}}let i=await DU(e,t,n,r,{authMode:"authenticated"});if(i.kind==="failure")return i;let o=bM(t,i.inspection,r);return o?{kind:"failure",result:o}:{kind:"ok",inspection:i.inspection,sourceAccess:"authenticated"}}function bM(e,t,n){if(n.list||n.dryRun)return null;let r=[t.catalogueDecision,...Array.isArray(t.catalogueDecisions)?t.catalogueDecisions:[]].filter(i=>i!==void 0);for(let i of r){let o=j(i)?i.status:void 0;if(!j(i)||i.schemaVersion!=="skills-layer.source-catalogue-decision.v1"||!["approved","pending","new"].includes(String(o))){let s=["security_blocked","revoked","restricted","unavailable"].includes(String(o))?`source_catalogue_${o}`:"source_catalogue_identity_invalid";return x({status:s,reasonCode:s,source:e,catalogueDecision:i,nextStep:"Resolve the current catalogue decision before retrying this exact source."},"This source cannot be activated under its current catalogue decision.",n.json,s)}}if(t.catalogueSourceInput!==void 0){let i=ir(e),o=typeof t.catalogueSourceInput=="string"?ir(t.catalogueSourceInput):void 0,s=l=>l.replace(/(?:^|\/)SKILL\.md$/u,"")||".";if(!(i.kind==="github"&&o?.kind==="github"&&`${i.owner}/${i.repo}`.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&s(i.subpath)===s(o.subpath)&&/^[a-f0-9]{40}$/u.test(o.ref)&&(!/^[a-f0-9]{40}$/iu.test(i.ref)||i.ref.toLowerCase()===o.ref)&&r.every(l=>{let c=j(l)?T(l,"subject"):void 0,u=c?f(c,"sourceRoot"):void 0,d=s(o.subpath);return c?.commitSha===o.ref&&typeof c.repository=="string"&&c.repository.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&u&&(u==="."||!u.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)))&&(d==="."||u===d||u.startsWith(`${d}/`))})))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e},"The inspected snapshot does not identify this exact source.",n.json,"source_catalogue_identity_invalid")}return null}function Ah(e,t,n){if(ur(t).length>0)return null;let i=ise(t);return x({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:i,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},ose(e,i),n.json)}function ise(e){return(Array.isArray(e.issues)?e.issues:[]).filter(j).map(n=>({...f(n,"code")?{code:f(n,"code")}:{},...f(n,"message")?{message:f(n,"message")}:{},...f(n,"path")?{path:f(n,"path")}:{}}))}function UP(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(mA(t.status,i))return OU(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Ho(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be inspected as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}function _M(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(mA(t.status,i))return OU(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Ho(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be installed as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}async function SM(e){let t=e.error instanceof Z?e.error.details??{}:{},n=e.error instanceof Z?f(t,"reasonCode")??"catalogue_submission_failed":"catalogue_submission_unavailable";return await zu({backend:e.backend,result:{...t,status:"catalogue_submission_failed",reasonCode:n,publiclyDiscoverable:!1},fallbackSlug:e.skillSlug,source:e.source,sourceAccess:e.sourceAccess,flags:e.flags,requestedVisibility:ji(e.source,e.flags,e.backend,e.sourceAccess),unverifiedMaterialization:e.unverifiedMaterialization})}function mA(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function OU(e,t,n,r){let i=t.details??{},o=f(i,"error")??t.message,a=`skills-layer source connection start --provider ${LU(e)} --source ${e} --visibility private --provenance-intent private_source_import`,l={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:o,nextStep:a};return x(l,`Cloud could not ${r} ${e} directly. If this is a private source, start a private source connection first:
2167
2167
  ${a}`,n.json,"private_source_access_required")}function LU(e){return/gitlab\./iu.test(e)?"gitlab":/github\./iu.test(e)||/^gh:/iu.test(e)?"github":"generic_git"}function ose(e,t){let n=[`No Skills Layer-compatible skills were found in ${e}.`];if(t.length>0){n.push("Detected issues:");for(let r of t.slice(0,5)){let i=r.code??"source-inspection";n.push(`- ${i}: ${r.message??"No details returned."}${r.path?` (${r.path})`:""}`)}}return n.push("Try --list, a subfolder containing SKILL.md, or a Skills Layer-compatible source layout."),n.join(`
2168
- `)}async function jU(e,t,n){if(NU(e)){let l=f(e,"reasonCode")??f(e,"reason")??"install_not_ready",c=f(e,"why")??f(e,"summary")??"The requested skill is not ready to install from this backend.";return x(e,`Install preview is not ready: ${c}`,t.json,l)}let r=k(t.agent)==="all"?et(n.env,n.platform,n.cwd).map(l=>({...t,agent:l.id})):[t];for(let l of r){let c=lA(n,e,"",l);if(c.status!=="ok")continue;let u=await Xa({backend:n,skillSlug:c.skillSlug,agentId:c.agent.id,scope:c.scope,flags:t});if(u)return u}let i=Object.values(n.guardianActivationReceipts??{}).map(l=>LP(n,l.agent,l.scope)),o=i.flatMap(l=>Array.isArray(l.warnings)?l.warnings:[]),s=await FU({...e,...i[0],warnings:[...Array.isArray(e.warnings)?e.warnings:[],...o]},n),a=Array.isArray(s.warnings)&&s.warnings.length>0;return sse(s,a?"Install preview ready with warnings.":"Install preview ready.",t,n)}function sse(e,t,n,r){return n.json?R(e,t,!0,r):{exitCode:0,stdout:gA(e,t,r),stderr:""}}async function ase(e,t,n,r){if(NU(e)){let o=f(e,"reasonCode")??f(e,"reason")??"workspace_approval_not_ready",s=f(e,"why")??f(e,"summary")??f(e,"nextStep")??"The requested workspace approval is not ready.";return x(e,`Workspace approval preview is not ready: ${s}`,n.json,o)}let i=await FU(e,r);return n.json?R(i,t,!0,r):{exitCode:0,stdout:gA(i,t,r),stderr:""}}function NU(e){let t=f(e,"status")?.toLowerCase(),n=f(e,"reasonCode")?.toLowerCase();return t==="not_found"||t==="missing"||t==="blocked"||t==="not_ready"||n==="skill_not_found"||n==="not_found"}async function FU(e,t){let n=o=>({...e,...o,warnings:[...new Set([...Be(e,"warnings")??[],...Be(o,"warnings")??[]])]}),r=xM(e);if(r)return n(r);let i=f(e,"skillSlug")??f(e,"slug");if(!i)return e;try{let o=await D(t,`/api/v1/skills/${encodeURIComponent(i)}/trust`),s=xM(o);return s?n(s):e}catch{return e}}function xM(e){let t=T(e,"securityReport")??T(e,"report")??e,n=T(e,"trust")??T(t,"trust")??t,r=T(e,"securityPosture")??T(t,"securityPosture"),i=T(e,"capabilityProfile")??T(t,"capabilityProfile"),o=ie({securityScore:J(n,"securityScore")??J(n,"score")??J(e,"securityScore")??(r?J(r,"securityScore"):void 0),runtimeRisk:f(n,"runtimeRisk")??f(e,"runtimeRisk")??(r?f(r,"runtimeRisk"):void 0)??(i?f(i,"runtimeRisk"):void 0),recommendation:f(n,"recommendation")??f(e,"recommendation")??(r?f(r,"recommendation"):void 0),detectedCapabilities:Be(n,"detectedCapabilities")??Be(e,"detectedCapabilities")??(i?Be(i,"detectedCapabilities"):void 0),capabilityMismatches:Be(n,"capabilityMismatches")??Be(e,"capabilityMismatches")??(i?Be(i,"capabilityMismatches"):void 0),organizationPolicyDecision:f(n,"organizationPolicyDecision")??f(n,"policyDecision")??f(e,"organizationPolicyDecision")??f(e,"policyDecision")??(r?f(r,"organizationPolicyDecision"):void 0)});if(Object.keys(o).length!==0)return ie({trust:o,effectiveness:T(e,"effectiveness")??T(t,"effectiveness"),runtimeRisk:f(o,"runtimeRisk"),detectedCapabilities:Array.isArray(o.detectedCapabilities)?o.detectedCapabilities:void 0,capabilityMismatches:Array.isArray(o.capabilityMismatches)?o.capabilityMismatches:void 0,organizationPolicyDecision:f(o,"organizationPolicyDecision"),warnings:Be(e,"warnings")??Be(t,"warnings")??Be(n,"warnings")})}function Ga(e,t,n,r,i){return n?R(e,t,!0,r):{exitCode:0,stdout:gA(e,t,r,i),stderr:""}}function gA(e,t,n,r){let i=Ae(n),o=[`${i.ok("OK")} ${t}`];for(let O of Be(e,"warnings")??[])typeof O=="string"&&o.push(`Warning: ${O}`);if(e.verificationStatus==="unverified"&&e.publiclyDiscoverable===!1){o.push("","Local installation complete \u2014 Unverified / Unscored."),e.catalogueVisibilityRequested==="public"?o.push("This skill is not publicly listed. Catalogue admission does not guarantee publication."):o.push("This is not a public listing. Private catalogue approval is separate from local installation.");let O=f(e,"reasonCode");O&&o.push(`Catalogue review reason: ${O}`)}let s=f(e,"skillSlug")??f(e,"slug"),a=f(e,"version")??f(e,"currentVersion"),l=f(e,"catalogueCandidateVersion"),c=f(e,"localProvisionalVersion"),u=f(e,"localGeneration"),d=f(e,"sourceContentDigest");(s||a||l||c||u||d)&&(o.push("",i.section("Skill")),s&&o.push(` ${i.label("Slug")}: ${s}`),l?o.push(` ${i.label("Catalogue Candidate Version")}: ${l}`):a&&o.push(` ${i.label("Version")}: ${a}`),c&&o.push(` ${i.label("Local Provisional Version")}: ${c}`),u&&o.push(` ${i.label("Local Generation")}: ${u}`),d&&o.push(` ${i.label("Source Content Digest")}: ${d}`));let p=f(e,"visibility")??f(e,"versionVisibility"),m=f(e,"catalogueVisibilityRequested")??f(e,"requestedVisibility"),h=f(e,"catalogueStatus"),g=typeof e.publiclyDiscoverable=="boolean"?e.publiclyDiscoverable:void 0,y=f(e,"publicationStatus"),v=f(e,"catalogRecord");(p||m||h||g!==void 0||y||v)&&(o.push("",i.section("Privacy")),m?o.push(` ${i.label("Catalogue Visibility Requested")}: ${m}`):p&&o.push(` ${i.label("Visibility")}: ${p}`),h&&o.push(` ${i.label("Catalogue Status")}: ${h}`),g!==void 0&&o.push(` ${i.label("Publicly Discoverable")}: ${g?"yes":"no"}`),y&&o.push(` ${i.label("Publication")}: ${y}`),v&&o.push(` ${i.label("Catalog record")}: ${v}`));let b=T(e,"materializationPlan")??T(e,"installPlan"),w=f(e,"scope")??(b?f(b,"scope"):void 0),_=f(e,"agent")??f(e,"targetAgent")??(b?f(b,"agent")??f(b,"targetAgent"):void 0),C=Array.isArray(e.materializedWrites)?e.materializedWrites.filter(j):[];if(w||_||C.length>0)if(o.push("",i.section("Local Materialization")),w&&o.push(` ${i.label("Scope")}: ${w}`),_&&o.push(` ${i.label("Agent")}: ${_}`),C.length===0)o.push(` ${i.muted("No local files were written by this command.")}`);else for(let O of C.slice(0,at)){let X=f(O,"path");X&&o.push(` ${i.arrow} ${X}`)}let P=ace(e,i).filter(O=>!O.includes("materialized writes:"));P.length>0&&o.push("",...P);let N=!w&&C.length===0&&s?[`skills-layer install ${s} --scope project --agent ${_??r??"<agent>"}`]:gce(e);return N.length>0&&o.push("",i.section("Next"),...N.map(O=>` ${i.arrow} ${O}`)),o.join(`
2168
+ `)}async function jU(e,t,n){if(NU(e)){let l=f(e,"reasonCode")??f(e,"reason")??"install_not_ready",c=f(e,"why")??f(e,"summary")??"The requested skill is not ready to install from this backend.";return x(e,`Install preview is not ready: ${c}`,t.json,l)}let r=k(t.agent)==="all"?et(n.env,n.platform,n.cwd).map(l=>({...t,agent:l.id})):[t];for(let l of r){let c=lA(n,e,"",l);if(c.status!=="ok")continue;let u=await Xa({backend:n,skillSlug:c.skillSlug,agentId:c.agent.id,scope:c.scope,flags:t});if(u)return u}let i=Object.values(n.guardianActivationReceipts??{}).map(l=>LP(n,l.agent,l.scope)),o=i.flatMap(l=>Array.isArray(l.warnings)?l.warnings:[]),s=await FU({...e,...i[0],warnings:[...Array.isArray(e.warnings)?e.warnings:[],...o]},n),a=Array.isArray(s.warnings)&&s.warnings.length>0;return sse(s,a?"Install preview ready with warnings.":"Install preview ready.",t,n)}function sse(e,t,n,r){return n.json?R(e,t,!0,r):{exitCode:0,stdout:gA(e,t,r),stderr:""}}async function ase(e,t,n,r){if(NU(e)){let o=f(e,"reasonCode")??f(e,"reason")??"workspace_approval_not_ready",s=f(e,"why")??f(e,"summary")??f(e,"nextStep")??"The requested workspace approval is not ready.";return x(e,`Workspace approval preview is not ready: ${s}`,n.json,o)}let i=await FU(e,r);return n.json?R(i,t,!0,r):{exitCode:0,stdout:gA(i,t,r),stderr:""}}function NU(e){let t=f(e,"status")?.toLowerCase(),n=f(e,"reasonCode")?.toLowerCase();return t==="not_found"||t==="missing"||t==="blocked"||t==="not_ready"||n==="skill_not_found"||n==="not_found"}async function FU(e,t){let n=o=>({...e,...o,warnings:[...new Set([...Be(e,"warnings")??[],...Be(o,"warnings")??[]])]}),r=xM(e);if(r)return n(r);let i=f(e,"skillSlug")??f(e,"slug");if(!i)return e;try{let o=await D(t,`/api/v1/skills/${encodeURIComponent(i)}/trust`),s=xM(o);return s?n(s):e}catch{return e}}function xM(e){let t=T(e,"securityReport")??T(e,"report")??e,n=T(e,"trust")??T(t,"trust")??t,r=T(e,"securityPosture")??T(t,"securityPosture"),i=T(e,"capabilityProfile")??T(t,"capabilityProfile"),o=ie({securityScore:J(n,"securityScore")??J(n,"score")??J(e,"securityScore")??(r?J(r,"securityScore"):void 0),runtimeRisk:f(n,"runtimeRisk")??f(e,"runtimeRisk")??(r?f(r,"runtimeRisk"):void 0)??(i?f(i,"runtimeRisk"):void 0),recommendation:f(n,"recommendation")??f(e,"recommendation")??(r?f(r,"recommendation"):void 0),detectedCapabilities:Be(n,"detectedCapabilities")??Be(e,"detectedCapabilities")??(i?Be(i,"detectedCapabilities"):void 0),capabilityMismatches:Be(n,"capabilityMismatches")??Be(e,"capabilityMismatches")??(i?Be(i,"capabilityMismatches"):void 0),organizationPolicyDecision:f(n,"organizationPolicyDecision")??f(n,"policyDecision")??f(e,"organizationPolicyDecision")??f(e,"policyDecision")??(r?f(r,"organizationPolicyDecision"):void 0)});if(Object.keys(o).length!==0)return ie({trust:o,effectiveness:T(e,"effectiveness")??T(t,"effectiveness"),runtimeRisk:f(o,"runtimeRisk"),detectedCapabilities:Array.isArray(o.detectedCapabilities)?o.detectedCapabilities:void 0,capabilityMismatches:Array.isArray(o.capabilityMismatches)?o.capabilityMismatches:void 0,organizationPolicyDecision:f(o,"organizationPolicyDecision"),warnings:Be(e,"warnings")??Be(t,"warnings")??Be(n,"warnings")})}function Ga(e,t,n,r,i){return n?R(e,t,!0,r):{exitCode:0,stdout:gA(e,t,r,i),stderr:""}}function gA(e,t,n,r){let i=Ae(n),o=[`${i.ok("OK")} ${t}`];for(let O of Be(e,"warnings")??[])typeof O=="string"&&o.push(`Warning: ${O}`);if(e.verificationStatus==="unverified"&&e.publiclyDiscoverable===!1){o.push("","Local installation complete \u2014 Unverified / Unscored."),e.catalogueVisibilityRequested==="public"?o.push("This skill is not publicly listed. Catalogue admission does not guarantee publication."):o.push("This is not a public listing. Private catalogue approval is separate from local installation.");let O=f(e,"reasonCode");O&&o.push(`Catalogue review reason: ${O}`)}let s=f(e,"skillSlug")??f(e,"slug"),a=f(e,"version")??f(e,"currentVersion"),l=f(e,"catalogueCandidateVersion"),c=f(e,"localProvisionalVersion"),u=f(e,"localGeneration"),d=f(e,"sourceContentDigest");(s||a||l||c||u||d)&&(o.push("",i.section("Skill")),s&&o.push(` ${i.label("Slug")}: ${s}`),l?o.push(` ${i.label("Catalogue Candidate Version")}: ${l}`):a&&o.push(` ${i.label("Version")}: ${a}`),c&&o.push(` ${i.label("Local Provisional Version")}: ${c}`),u&&o.push(` ${i.label("Local Generation")}: ${u}`),d&&o.push(` ${i.label("Source Content Digest")}: ${d}`));let p=f(e,"visibility")??f(e,"versionVisibility"),m=f(e,"catalogueVisibilityRequested")??f(e,"requestedVisibility"),h=f(e,"catalogueStatus"),g=typeof e.publiclyDiscoverable=="boolean"?e.publiclyDiscoverable:void 0,y=f(e,"publicationStatus"),v=f(e,"catalogRecord");(p||m||h||g!==void 0||y||v)&&(o.push("",i.section("Privacy")),m?o.push(` ${i.label("Catalogue Visibility Requested")}: ${m}`):p&&o.push(` ${i.label("Visibility")}: ${p}`),h&&o.push(` ${i.label("Catalogue Status")}: ${h}`),g!==void 0&&o.push(` ${i.label("Publicly Discoverable")}: ${g?"yes":"no"}`),y&&o.push(` ${i.label("Publication")}: ${y}`),v&&o.push(` ${i.label("Catalog record")}: ${v}`));let b=T(e,"materializationPlan")??T(e,"installPlan"),w=f(e,"scope")??(b?f(b,"scope"):void 0),_=f(e,"agent")??f(e,"targetAgent")??(b?f(b,"agent")??f(b,"targetAgent"):void 0),C=Array.isArray(e.materializedWrites)?e.materializedWrites.filter(j):[];if(w||_||C.length>0)if(o.push("",i.section("Local Materialization")),w&&o.push(` ${i.label("Scope")}: ${w}`),_&&o.push(` ${i.label("Agent")}: ${_}`),C.length===0)o.push(` ${i.muted("No local files were written by this command.")}`);else for(let O of C.slice(0,at)){let X=f(O,"path");X&&o.push(` ${i.arrow} ${X}`)}let A=ace(e,i).filter(O=>!O.includes("materialized writes:"));A.length>0&&o.push("",...A);let N=!w&&C.length===0&&s?[`skills-layer install ${s} --scope project --agent ${_??r??"<agent>"}`]:gce(e);return N.length>0&&o.push("",i.section("Next"),...N.map(O=>` ${i.arrow} ${O}`)),o.join(`
2169
2169
  `)}function lse(e,t){let n=T(e,"trust"),r=T(e,"securityPosture"),i=T(e,"capabilityProfile"),o=n?.securityScore??n?.score??e.securityScore??r?.securityScore,s=qe(n,"runtimeRisk")??f(e,"runtimeRisk")??qe(r,"runtimeRisk")??qe(i,"runtimeRisk"),a=qe(n,"recommendation")??f(e,"recommendation")??qe(r,"recommendation"),l=qe(n,"label")??qe(n,"trust")??f(e,"trustStatus")??f(e,"trust")??qe(r,"label");if(o===void 0&&!s&&!a&&!l)return[];let c=[t.section("Trust")];return s&&c.push(` ${t.label("Runtime risk")}: ${s}`),a&&c.push(` ${t.label("Recommendation")}: ${a}`),l&&c.push(` ${t.label("Status")}: ${l}`),c.push(` ${t.label("Source")}: skills-layer trust`),c}async function td(e,t,n){let r=[],i=[];if(!t.apiKey)return{warnings:r,revokedSlugs:i};let o=await lt(t),s=Object.entries(o.installs).filter(([l,c])=>(!n||l===n)&&c.acquisitionMode==="authenticated_account"&&(!c.acquisitionBaseUrl||c.acquisitionBaseUrl===t.baseUrl));if(!s.length)return{warnings:r,revokedSlugs:i};let a=[];try{for(let l=0;l<s.length;l+=50){let c=new URLSearchParams({slugs:s.slice(l,l+50).map(([d])=>d).join(",")}),u=await D(t,`/api/v1/me/entitlements?${c}`,{headers:ne(t.apiKey,t.authBlockedMessage)});if(!Array.isArray(u.results))throw new Error("Entitlement status unavailable");a.push(...u.results.filter(j))}}catch{return{warnings:["Could not verify entitlements online; local copies were kept."],revokedSlugs:i}}for(let[l,c]of s){let u=a.find(h=>h.skillSlug===l);if(!u||u.status!=="revoked"||u.reason!=="refunded"||u.paid!==!0)continue;let d=typeof c.entitlementId=="string"&&c.entitlementId===u.entitlementId,p=typeof c.acquiredByUserId=="string"&&c.acquiredByUserId===t.config?.userId&&c.acquisitionBaseUrl===t.baseUrl;if(!d&&!p){r.push(`Kept ${l}: its receipt cannot be matched to this buyer's refunded grant.`);continue}let m=Rn(c);if(!m.length){r.push(`No managed agent copy found for refunded ${l}. Manually copied folders cannot be removed automatically.`);continue}for(let h of m){let g=typeof h.record.acquisitionBaseUrl=="string"?h.record:m.length===1?c:{},y=typeof g.entitlementId=="string"&&g.entitlementId===u.entitlementId,v=g.acquiredByUserId===t.config?.userId&&typeof g.acquiredByUserId=="string"&&g.acquisitionBaseUrl===t.baseUrl;if(!y&&!v){r.push(`Kept ${l}: this agent copy belongs to an unverified buyer receipt.`);continue}if(i.includes(l)||i.push(l),!(h.lifecycle?.state==="quarantined"||h.lifecycle?.state==="externally_removed")){if(!h.lifecycle||!["active","pending_activation"].includes(h.lifecycle.state)){r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`);continue}if(e.dryRun){r.push(`Would remove ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`);continue}try{await hA({backend:t,skillSlug:l,record:hr(c,h),materializationId:h.materializationId,lifecycle:h.lifecycle,reasonCode:"refunded",purpose:"quarantine_revoked",status:"removed"}),r.push(`Removed ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`)}catch{r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`)}}}}return{warnings:r,revokedSlugs:i}}async function cse(e,t){let n=ed("installed",e);if(n.failure)return n.failure;let r=await td(e,t),i=e.dryRun?await lt(t):await zi(t),o=vz(i).filter(s=>(!n.scope||f(s,"scope")===n.scope)&&(!n.agent||gr(s).includes(n.agent)));return R({status:"ok",results:o,warnings:r.warnings},`Found ${o.length} local install records. ${r.warnings.join(" ")}`,e.json,t,"installed")}async function use(e,t,n){let r=L(e[0],"remove requires a skill slug."),i=cU("remove",t);if(i)return i;let s=(t.dryRun?await lt(n):await zi(n,r)).installs[r];if(!s)return x({status:"not_installed",reasonCode:"local_install_not_found",skillSlug:r},`${r} is not installed locally. Run \`skills-layer installed\` or \`skills-layer sync\` to inspect local records.`,t.json,"local_install_not_found");let a=k(t.scope),l=k(t.agent),c=Vn(s,{scope:a,agent:l});if(c.length>1){let g=yle({backend:n,skillSlug:r,materializations:c,scope:a,agent:l});g.length===1&&(c=g)}if(c.length===0&&Rn(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:a,requestedAgent:l},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(c.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,availableTargets:c.map(g=>({materializationId:g.materializationId,scope:f(g.record,"scope"),targetAgents:gr(g.record),materializedSkillRoot:f(g.record,"materializedSkillRoot")})),nextAction:"remove",nextStep:`Run the command from the intended project folder, or retry with --scope project|global and --agent <agent> to remove one exact ${r} materialization.`},`${r} is installed in more than one local target. Select the exact target to remove.`,t.json,"local_install_target_selection_required");let u=c[0],d=u?hr(s,u):s,p=u?.lifecycle??null;if(!p){let g=kz(s);if(g){try{await dse({backend:n,skillSlug:r,record:s,cachedArtifact:g})}catch{return x({status:"blocked",reasonCode:"cached_artifact_remove_failed",skillSlug:r,nextAction:"install",nextStep:"The cache receipt or its immutable bundle could not be verified. Leave it unchanged and reinstall only after resolving the local cache issue."},`Skills Layer could not safely remove ${r}'s verified cache receipt.`,t.json,"cached_artifact_remove_failed")}let y={status:"removed",skillSlug:r,storageKind:"cached_artifact"};return t.json?R(y,`Removed cached ${r}.`,!0,n):{exitCode:0,stdout:mP(r,n),stderr:""}}return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:r,nextAction:"install",nextStep:`Reinstall ${r} from an approved Artifact Format v1 export before removing or quarantining it.`},`Skills Layer cannot safely remove ${r} because its exact-generation receipt is missing or invalid.`,t.json,"exact_install_receipt_missing")}if(p.state==="quarantined"){let g={status:"removed",skillSlug:r,removedRecord:d,localLifecycle:p};return t.json?R(g,`${r} is already removed from discovery.`,!0,n):{exitCode:0,stdout:mP(r,n),stderr:""}}if(p.state==="externally_removed"||p.state==="host_detached"){if(t.forget){let g=Hr(p.receipt),y=await mae(n,{skillSlug:r,generationId:p.receipt.generation.generationId,receiptSha256:g});return await Mr(n,v=>{let b=v.installs[r];if(!b)return;let w=yz({existing:b,materializationId:u.materializationId,backend:n});w?v.installs[r]=w:delete v.installs[r]}),R({status:"forgotten",skillSlug:r,materializationId:u.materializationId,receiptSha256:g,forgottenAssociationCount:y,cloudAuthorityChanged:!1,nextAction:"installed",nextStep:"The local terminal tombstone and its terminal session evidence were removed. Cloud ownership, entitlement, workspace approval, and Trust Ledger history remain unchanged."},`${r}'s exact local tombstone was forgotten.`,t.json,n)}return R({status:p.state,skillSlug:r,tombstoneRetained:!0,localLifecycle:p,nextAction:"install",nextStep:`Reinstall ${r} to rematerialize it. Its local tombstone remains available for audit and recovery.`},`${r} is already absent from the exact local target; its recovery tombstone was retained.`,t.json,n)}if(t.forget)return x({status:"blocked",reasonCode:"guardian_forget_requires_terminal_tombstone",skillSlug:r,localLifecycle:p,nextAction:"remove",nextStep:"Use normal remove for an active installation. --forget only deletes a retained externally_removed or host_detached tombstone."},"Skills Layer only forgets an explicit terminal local tombstone.",t.json,"guardian_forget_requires_terminal_tombstone");if(p.state!=="active"&&p.state!=="pending_activation")return x({status:"blocked",reasonCode:"local_lifecycle_busy",skillSlug:r,localLifecycle:p},`${r} cannot be removed while its local lifecycle is ${p.state}.`,t.json,"local_lifecycle_busy");let m;try{m=await hA({backend:n,skillSlug:r,record:d,materializationId:u.materializationId,lifecycle:p,reasonCode:"user_removed",purpose:"quarantine_revoked",status:"removed"})}catch(g){return x({status:"blocked",reasonCode:"exact_generation_quarantine_failed",skillSlug:r,error:ke(g),nextAction:"guardian.incident.review",nextStep:"Do not run the skill. Inspect local drift or permissions, then retry removal after the exact tree is restored."},`Skills Layer could not atomically remove the exact installed generation for ${r}.`,t.json,"exact_generation_quarantine_failed")}let h={status:"removed",skillSlug:r,removedRecord:m.record,localLifecycle:m.lifecycle};return t.json?R(h,`Removed ${r}.`,!0,n):{exitCode:0,stdout:mP(r,n),stderr:""}}async function dse(e){let t=e.backend.platform==="win32"?st:Lt,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.cachedArtifact.generation.semanticVersion,encodeURIComponent(e.cachedArtifact.generation.generationId),"bundle.zip");if(t.normalize(e.cachedArtifact.bundlePath)!==t.normalize(n))throw new Error("Cached artifact path does not match its exact generation.");let r=await Qu(n);if(!r.isFile()||r.isSymbolicLink())throw new Error("Cached artifact is not a regular file.");if(`sha256:${Ue("sha256").update(await Ui(n)).digest("hex")}`!==e.cachedArtifact.archiveSha256)throw new Error("Cached artifact digest does not match its receipt.");let o=K(Me(n),`.bundle.remove-${Ge(12).toString("hex")}`);await qo(n,o);try{let s=await lt(e.backend),a=s.installs[e.skillSlug],l=a?kz(a):null;if(!a||!l||l.bundlePath!==e.cachedArtifact.bundlePath||l.archiveSha256!==e.cachedArtifact.archiveSha256)throw new Error("Cached install record changed during removal.");delete s.installs[e.skillSlug],await IA(e.backend,s)}catch(s){throw await qo(o,n).catch(()=>{}),s}await Ze(o,{force:!0})}async function hA(e){if(e.lifecycle.receipt.generation.skillSlug!==e.skillSlug)throw new Error("Install receipt skill identity does not match the indexed slug.");let t=`quarantine_${Ge(16).toString("hex")}`,n={status:"authorized",authorizationId:`${e.purpose}_${Ge(16).toString("hex")}`,purpose:e.purpose,generation:e.lifecycle.receipt.generation,archiveSha256:e.lifecycle.receipt.archiveSha256,manifestSha256:e.lifecycle.receipt.manifestSha256},r=await p2({receipt:e.lifecycle.receipt,reasonCode:e.reasonCode,quarantineRoot:K(e.backend.paths.stateDir,"quarantine"),discoveryRoots:pse(e.backend,e.lifecycle.receipt.targetDir),authorizeQuarantine:async()=>n}),i=Zu({state:"quarantined",operationId:t,receipt:e.lifecycle.receipt,quarantine:r,backend:e.backend}),o;if(await Mr(e.backend,s=>{let a=s.installs[e.skillSlug],l=a?Xt(a)[e.materializationId]:void 0,c=l?Yt(l):null;if(!a||!l||!c||c.operationId!==e.lifecycle.operationId)throw new Error("Local install record changed while its exact generation was quarantined.");o={...l,status:e.status,...e.reasonCode==="refunded"?{removedReason:"refunded"}:{},localLifecycle:i,savedAt:e.backend.now()},s.installs[e.skillSlug]=Br({existing:a,skillSlug:e.skillSlug,materialization:o,backend:e.backend})}),!o)throw new Error("Local install quarantine did not commit its exact target record.");return{record:o,lifecycle:i,quarantine:r}}function pse(e,t){let n=new Set([Me(t)]);for(let r of et(e.env,e.platform,e.cwd)){n.add(r.targets.projectSkillsPath),r.targets.globalSkillsPath&&n.add(r.targets.globalSkillsPath);for(let i of[r.pathContracts.project,r.pathContracts.global]){i.preferredPath&&n.add(i.preferredPath);for(let o of[...i.compatibleReadOnlyPaths,...i.legacyReadOnlyPaths])n.add(o.path)}}return[...n]}async function fse(e,t,n){let r=L(e[0],"update requires a skill slug."),i=ed("update",t);if(i.failure)return i.failure;let o=new URLSearchParams,s=k(t.pin);if(s&&!Lh(s))return x({status:"error",reasonCode:"invalid_pin",skillSlug:r,requestedPin:s,nextAction:"update",nextStep:"Use --pin with a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --pin "${s}". Use a semver version or an external-<digest> version.`,t.json,"invalid_pin");We(o,"pin",s),t.dryRun&&o.set("dryRun","true");let a=await td(t,n,r);if(a.revokedSlugs.includes(r))return R({status:"entitlement_revoked",skillSlug:r,reasonCode:"entitlement_revoked_refunded",warnings:a.warnings,nextStep:`Buy ${r} again to restore access.`},a.warnings.join(" ")||`${r} was refunded; access is revoked.`,t.json,n);let c=(t.dryRun?await lt(n):await zi(n,r)).installs[r],u=Vn(c,i);if(u.length===0&&Rn(c).length>0&&(i.scope||i.agent))return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:i.scope,requestedAgent:i.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded targets."},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(u.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,nextAction:"update",nextStep:"Retry with --scope and --agent to update one exact materialization."},`${r} has more than one local materialization. Select the exact target to update.`,t.json,"local_install_target_selection_required");let d=u[0]&&c?hr(c,u[0]):c,p=Eoe(d),m=n,h;try{h=await D(n,`/api/v1/skills/${encodeURIComponent(r)}${Qe(o)}`,{headers:Zo(n.apiKey)})}catch(y){if(OP(p,y))m={...n,apiKey:void 0,authBlockedMessage:void 0},h=await D(m,`/api/v1/skills/${encodeURIComponent(r)}${Qe(o)}`);else{if(y instanceof Z&&y.status===404&&d){let v={status:"backend_missing",reasonCode:"local_install_backend_missing",skillSlug:r,localInstall:d,installedVersion:f(d,"version")??f(d,"currentVersion"),selectedBackend:n.baseUrl,nextStep:`This skill is installed locally, but no catalog update source was found on ${n.baseUrl}. Reinstall from its source, run \`skills-layer search ${r}\`, or run \`skills-layer remove ${r}\` if you no longer need it.`};return x(v,`${r} is installed locally, but no catalog update source was found on this backend. Reinstall from its source, search for a replacement, or remove the local install.`,t.json,"local_install_backend_missing")}if(y instanceof Z)return Ho(y,t.json);throw y}}if(h.catalogRefreshPending===!0||j(h.skill)&&h.skill.catalogRefreshPending===!0)return R({status:"catalog_refresh_pending",skillSlug:r,nextStep:`Publication is still refreshing. Retry skills-layer update ${r} shortly.`,localInstall:d},"Publication is still refreshing. Your installed copy is unchanged; retry update shortly.",t.json,n);let g=hse(r,h,d,n);if(s&&!mse(g,s))return x({status:"not_found",reasonCode:"pin_not_resolved",skillSlug:r,requestedPin:s,installedVersion:f(d,"version")??f(d,"currentVersion"),currentVersion:f(g,"currentVersion"),nextAction:"update",nextStep:`Choose a version returned by \`skills-layer show ${r} --json\` or omit --pin to check the latest available version.`},`${r} does not have a resolvable version for --pin ${s}.`,t.json,"pin_not_resolved");if(!t.dryRun&&d){let y=f(d,"version")??f(d,"currentVersion"),v=f(g,"latestAvailableVersion"),b=s??v;if(!!(b&&b!==y)){let _={...t,dryRun:!1,pin:void 0,version:b,scope:k(t.scope)??f(d,"scope")??"project",agent:k(t.agent)??f(d,"agent")??f(d,"targetAgent")??"codex"};return await Za([r],_,m,p)}}return t.json?R(g,"Update check complete.",!0,n):{exitCode:0,stdout:kse(g,n),stderr:""}}function Lh(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u.test(e)||/^external-[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(e)}function mse(e,t){let n=[f(e,"version"),f(e,"currentVersion"),f(e,"latestVersion"),f(e,"targetVersion"),f(e,"availableVersion")].filter(Boolean),r=T(e,"update");return r&&n.push(f(r,"version"),f(r,"currentVersion"),f(r,"latestVersion"),f(r,"targetVersion"),f(r,"availableVersion")),n.some(i=>i===t)}async function gse(e,t){let n=ed("sync",e);if(n.failure)return n.failure;let r=await td(e,t),i=e.dryRun?await lt(t):await zi(t),o=vz(i).filter(l=>(!n.scope||f(l,"scope")===n.scope)&&(!n.agent||gr(l).includes(n.agent))),a={status:"synced",results:await Promise.all(o.map(async l=>yse(l,t))),warnings:r.warnings};return e.json?R(a,"Local install records synced.",!0,t):{exitCode:0,stdout:wse(a,t)+r.warnings.map(l=>`
2170
2170
  ${l}`).join(""),stderr:""}}function hse(e,t,n,r){let i=n?f(n,"version")??f(n,"currentVersion"):void 0,o=f(t,"currentVersion")??f(t,"version"),s=n?i&&o&&i!==o?"update_available":"up_to_date":"not_installed";return ie({...t,skillSlug:f(t,"skillSlug")??f(t,"slug")??e,updateStatus:s,installedVersion:i,latestAvailableVersion:o,selectedBackend:r.baseUrl,localInstall:n,nextStep:s==="not_installed"?`Run \`skills-layer install ${e}\` to install this skill locally.`:s==="update_available"?`Run \`skills-layer install ${e}\` to apply the latest available version.`:`No update is needed for ${e}.`})}async function yse(e,t){let n=f(e,"skillSlug")??f(e,"slug");if(!n)return{...e,syncStatus:"local_only",backendStatus:"unchecked"};try{let r=await D(t,`/api/v1/skills/${encodeURIComponent(n)}`,{headers:Zo(t.apiKey)}),o=(f(r,"claimedOrigin")??f(r,"sourceKind")??f(e,"sourceKind"))==="public_source"||f(e,"sourceKind")==="external";return{...e,syncStatus:o?"source_backed":"catalog_backed",backendStatus:"found",latestAvailableVersion:f(r,"currentVersion")??f(r,"version"),catalog:vse(r)}}catch(r){return r instanceof Z&&r.status===404?{...e,syncStatus:"backend_missing",backendStatus:"not_found",selectedBackend:t.baseUrl}:{...e,syncStatus:"unchecked",backendStatus:"error",backendError:ke(r)}}}function vse(e){return ie({slug:f(e,"slug")??f(e,"skillSlug"),currentVersion:f(e,"currentVersion")??f(e,"version"),claimedOrigin:f(e,"claimedOrigin"),trust:f(e,"trust")??f(e,"publicationStatus")})}function kse(e,t){let n=Ae(t),r=f(e,"skillSlug")??f(e,"slug")??"skill",i=f(e,"updateStatus")??"checked",o=[`${n.ok("OK")} Update check complete.`,"",n.section("Update")];o.push(` ${n.label("Skill")}: ${r}`),o.push(` ${n.label("Status")}: ${i.replaceAll("_"," ")}`);let s=f(e,"installedVersion"),a=f(e,"latestAvailableVersion");s&&o.push(` ${n.label("Installed version")}: ${s}`),a&&o.push(` ${n.label("Latest available version")}: ${a}`);let l=T(e,"localInstall"),c=l?f(l,"materializedPath")??f(l,"path"):void 0,u=l?f(l,"scope"):void 0,d=l?f(l,"targetAgent")??f(l,"agent"):void 0;l&&(o.push("",n.section("Local Install")),u&&o.push(` ${n.label("Scope")}: ${u}`),d&&o.push(` ${n.label("Agent")}: ${d}`),c&&o.push(` ${n.label("Path")}: ${c}`));let p=f(e,"nextStep");return p&&o.push("",n.section("Next"),` ${n.arrow} ${p}`),o.join(`
2171
2171
  `)}function wse(e,t){let n=Ae(t),r=[`${n.ok("OK")} Local install records synced.`,"",n.section(`Results (${e.results.length})`)];return e.results.length===0?(r.push(` ${n.muted("No local install records found.")}`),r.join(`
@@ -2173,11 +2173,11 @@ ${l}`).join(""),stderr:""}}function hse(e,t,n,r){let i=n?f(n,"version")??f(n,"cu
2173
2173
  `))}function mP(e,t){let n=Ae(t);return[`${n.ok("OK")} Removed ${e}.`,"",n.section("Local Install"),` ${n.label("Skill")}: ${e}`,` ${n.label("Status")}: removed locally`,"",n.section("Next"),` ${n.arrow} skills-layer installed`,` ${n.arrow} skills-layer sync`].join(`
2174
2174
  `)}function bse(e,t,n){let r=Ae(n),i=f(t,"version")??f(t,"currentVersion"),o=f(t,"scope");return[`${r.ok("OK")} Restore record found for ${e}.`,"",r.section("Local Install"),` ${r.label("Skill")}: ${e}`,...i?[` ${r.label("Version")}: ${i}`]:[],...o?[` ${r.label("Scope")}: ${o}`]:[],"",r.section("Next"),` ${r.arrow} skills-layer installed`,` ${r.arrow} skills-layer sync`,` ${r.arrow} skills-layer update ${e}`].join(`
2175
2175
  `)}function _se(e){let t=f(e,"status"),n=f(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function Sse(e,t){let n=f(e,"why")??f(e,"reason")??f(e,"error"),r=f(e,"currentVisibility"),i=f(e,"nextVisibility")??f(e,"visibility"),o=r||i?` Current visibility: ${r??"unknown"}; requested visibility: ${i??"unknown"}.`:"",s=f(e,"nextStep")??`Run \`skills-layer creator status ${t}\` and choose a valid visibility transition.`;return`Visibility was not changed for ${t}.${o}${n?` ${n}`:""}
2176
- Next step: ${s}`}async function xse(e,t,n){let r=ed("restore",t);if(r.failure)return r.failure;let i=await lt(n),o=L(e[0],"restore requires a skill slug."),s=i.installs[o];if(!s)return x({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:o,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${o}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${o}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${o}\` next.`,t.json,"restore_record_not_found");if(s.removedReason==="refunded"||Rn(s).some(_=>_.record.removedReason==="refunded")){let _=!1;try{let C=await D(n,`/api/v1/me/entitlements?${new URLSearchParams({slugs:o})}`,{headers:ne(n.apiKey,n.authBlockedMessage)});_=dn(C.results).some(P=>P.skillSlug===o&&P.status==="active")}catch{}if(!_)return x({status:"blocked",reasonCode:"entitlement_revoked_refunded",skillSlug:o,nextStep:`Buy ${o} again before restoring it.`},"A refunded skill cannot be restored without active access.",t.json,"entitlement_revoked_refunded")}let a=Vn(s,{scope:r.scope,agent:r.agent});if(a.length===0&&Rn(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:o,requestedScope:r.scope,requestedAgent:r.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded quarantined targets."},`${o} has no restorable record for the requested local target.`,t.json,"local_install_target_not_found");if(a.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:o,nextAction:"restore",nextStep:"Retry with --scope and --agent to restore one exact quarantined materialization."},`${o} has more than one local materialization. Select the exact target to restore.`,t.json,"local_install_target_selection_required");let l=a[0],c=l?hr(s,l):s,u=l?.lifecycle??null;if(!u)return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:o,nextAction:"install",nextStep:`Reinstall ${o} from the approved catalog; legacy records cannot authorize an exact-generation restore.`},`Skills Layer cannot restore ${o} because its exact-generation lifecycle record is missing or invalid.`,t.json,"exact_install_receipt_missing");if(u.state!=="quarantined"||!u.quarantine)return x({status:"blocked",reasonCode:"restore_not_quarantined",skillSlug:o,localLifecycle:u,nextAction:"installed",nextStep:"Only a physically quarantined exact generation can be restored."},`${o} does not have a quarantined exact generation to restore.`,t.json,"restore_not_quarantined");let d=new URLSearchParams({version:u.receipt.generation.semanticVersion,operation:"restore",generationId:u.receipt.generation.generationId}),p=f(c,"acquisitionMode")==="anonymous_public",m;try{m=await D(n,p?`/api/v1/skills/${encodeURIComponent(o)}/export${Qe(d)}`:`/api/v1/me/library/${encodeURIComponent(o)}/export${Qe(d)}`,{headers:p?{}:ne(n.apiKey,n.authBlockedMessage)})}catch(_){if(_ instanceof Z)return Ho(_,t.json);throw _}if(m.restoreAuthorization===void 0)return x({status:"blocked",reasonCode:"restore_authorization_missing",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Retry after the Skills Layer API returns a fresh restoreAuthorization bound to this exact generation."},`The backend did not authorize restoration of ${o}'s exact quarantined generation.`,t.json,"restore_authorization_missing");let h=bz(m.restoreAuthorization);if(!h||h.purpose!=="restore_fresh_approval"||!Cse(h,u.receipt))return x({status:"blocked",reasonCode:"restore_authorization_invalid",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Do not restore. Refresh backend approval for this exact artifact generation."},`The backend returned an invalid or mismatched restore authorization for ${o}.`,t.json,"restore_authorization_invalid");let g=`restore_${Ge(16).toString("hex")}`,y=Zu({state:"restore_pending",operationId:g,receipt:u.receipt,quarantine:u.quarantine,backend:n});await Mr(n,_=>{let C=_.installs[o],P=C&&l?Xt(C)[l.materializationId]:void 0,N=P?Yt(P):null;if(!C||!P||N?.operationId!==u.operationId||N.state!=="quarantined")throw new Error("Local install record changed before its exact restore reservation was created.");_.installs[o]=Br({existing:C,skillSlug:o,materialization:{...P,localLifecycle:y,savedAt:n.now()},backend:n})});let v;try{await f2({quarantine:u.quarantine,authorizeRestore:async()=>h,finalizeRestore:async()=>{let _=!0;return await Mr(n,C=>{let P=C.installs[o],N=P&&l?Xt(P)[l.materializationId]:void 0,O=N?Yt(N):null;if(!P||!N||!O||O.state!=="restore_pending"||O.operationId!==g){_=!1;return}let X=Zu({state:"active",operationId:g,receipt:u.receipt,backend:n});v={...N,status:"restored",localLifecycle:X,savedAt:n.now()},C.installs[o]=Br({existing:P,skillSlug:o,materialization:v,backend:n})}),_?{status:"released",releaseId:`local_restore_${Ge(16).toString("hex")}`}:{status:"denied",reasonCode:"restore_reservation_lost"}}})}catch(_){return await Mr(n,C=>{let P=C.installs[o],N=P&&l?Xt(P)[l.materializationId]:void 0,O=N?Yt(N):null;!P||!N||O?.operationId!==g||(C.installs[o]=Br({existing:P,skillSlug:o,materialization:{...N,localLifecycle:u,savedAt:n.now()},backend:n}))}).catch(()=>{}),x({status:"blocked",reasonCode:"exact_generation_restore_failed",skillSlug:o,error:ke(_),nextAction:"restore",nextStep:"Keep the generation quarantined. Resolve local path, drift, or permission problems before retrying."},`Skills Layer could not atomically restore ${o}.`,t.json,"exact_generation_restore_failed")}if(!v)throw new Error(`Atomic restore for ${o} completed without committing its local lifecycle record.`);let b=Yt(v),w={status:"restored",skillSlug:o,record:v,localLifecycle:b};return t.json?R(w,`Restored ${o}.`,!0,n):{exitCode:0,stdout:bse(o,v,n),stderr:""}}function Cse(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archiveSha256&&e.manifestSha256===t.manifestSha256}async function Ise(e,t,n){let r=L(e[0],"check requires a skill slug.");return await he(`/api/v1/skills/${encodeURIComponent(r)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function Pse(e,t,n){let r=L(e[0]??t.source,"import requires a source."),i=pr("import","visibility",t.visibility,qa,t,"invalid_visibility");if(i)return i;let o=await Ku(r,n.cwd);if(o)return await Ase(r,o,t,n);let s=Rse(r,t);if(s)return s;let a=fA(r,t,n,n.apiKey?"authenticated":"unknown"),l=await D(n,a,{method:"POST",headers:$U(r,t,n,n.apiKey?"authenticated":"unknown"),body:JSON.stringify(ie({source:r,skillSlug:k(t.skill),visibility:k(t.visibility)??ji(r,t,n)}))});return await Ve(n.paths.importsPath,{version:1,lastImport:l,savedAt:n.now()}),R(l,"Source import submitted.",t.json,n)}async function Ase(e,t,n,r){let i=k(n.skill),o=dA(e,t,i);if(!r.apiKey)return x({status:"error",reasonCode:"local_import_sign_in_required",source:e,nextAction:"login",nextStep:`Run \`skills-layer login\`, then retry \`skills-layer import ${e}\` (the same flow as \`skills-layer creator submit ${e}\`).`},"Importing a local folder submits it through your creator account, so you must sign in first. Run `skills-layer login`, then retry. Nothing was uploaded.",n.json,"local_import_sign_in_required");let s=Ah(e,o,n);if(s)return s;let a=await Nu({source:e,inspection:o,requestedSkillSlug:i,mode:"import",flags:n,backend:r});if(a.kind==="failure")return a.result;let c=pA(t.files).find(d=>d.skillSlug===a.skillSlug),u=c.relativeSkillRoot==="."?e:`${e.replace(/[\\/]+$/u,"")}/${c.relativeSkillRoot}`;return k(n.version)?await DP([u],{...n,source:void 0,path:void 0,skill:c.skillSlug},r,!1):x({status:"error",nextAction:"import",nextStep:"Pass --version <semver>, for example --version 1.0.0."},"A local import requires --version <semver>.",n.json,"version_required")}function Rse(e,t){try{return ir(e).kind!=="local"?null:x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:qu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or --help for import examples."},qu(e)?`Import source ${e} was not found or is not readable.`:`Import source "${e}" is not a supported source. Use a local path, GitHub/GitLab source, or URL.`,t.json,"invalid_source")}catch(n){return x({status:"error",reasonCode:"invalid_source",source:e,error:ke(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ke(n)}`,t.json,"invalid_source")}}function qu(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function BU(e,t,n,r){let i=Tt(r.cwd,t);return x({status:"error",reasonCode:"source_path_not_found",path:i,nextAction:e,nextStep:`Check that ${t} exists and contains a readable SKILL.md, then retry.`},`${e} source path does not exist: ${i}`,n.json,"source_path_not_found")}async function Ese(e,t,n){let r=e[0];if(r==="reference"&&e[1]==="resolve"){let i=L(e[2],"source reference resolve requires a reference."),o=await D(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(i)}`);return o.status==="not_found"?x({...o,status:"not_found",reasonCode:"source_reference_not_found",reference:i,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${i} was not found.`,t.json,"source_reference_not_found"):R(o,"Source reference resolved.",t.json,n)}return r==="connection"?await $se(e.slice(1),t,n):E(`Unknown source command "${e.join(" ")}".`,t.json)}async function $se(e,t,n){let r=e[0];if(r==="start"){let o=k(t.provider),s=k(t.source),a=k(t.visibility),l=o?.replace(/-/gu,"_");if(l&&!YB.includes(l))return Fr("source.connection.start","provider",o??"",YB,t,"invalid_source_provider");let c=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=Dse(o,s,a,t);if(u)return u;let d=Ft(t,["provider","source","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),p=k(t.skill);return p&&(d.requestedSkillSlug=p),await Le("/api/v1/me/source-connections",d,t,n,"Source connection started.")}let i=L(e[1],`source connection ${r??""} requires a connection id.`);if(r==="status")return await he(`/api/v1/me/source-connections/${encodeURIComponent(i)}`,t,n,"Source connection loaded.",{authenticated:!0});if(r==="complete"){let o=Uie("source.connection.complete",t);return o||await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/complete`,Ft(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return r==="cancel"?await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/cancel`,{},t,n,"Source connection cancelled."):r==="revoke"?await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/revoke`,{},t,n,"Source connection revoked."):E(`Unknown source connection command "${r??""}".`,t.json)}function Dse(e,t,n,r){if(n){let i=dc(n);if(!i||!qa.includes(i))return x({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:qa,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${qa.join(", ")}.`,r.json,"invalid_visibility")}if(!e||!t)return null;try{let i=ir(t);if((e==="github"||e==="gitlab")&&i.kind!==e)return gP(e,t,r);if(e==="domain"){let o=new URL(t);if(o.protocol!=="https:"||!o.hostname)return gP(e,t,r)}}catch{return gP(e,t,r)}return null}function gP(e,t,n){return x({status:"error",reasonCode:"invalid_source",provider:e,source:t,nextAction:"source.connection.start",nextStep:e==="github"?"Use a GitHub source such as https://github.com/OWNER/REPO or github:OWNER/REPO.":e==="gitlab"?"Use a GitLab source such as https://gitlab.com/GROUP/REPO or gitlab:GROUP/REPO.":"Use a valid source URL or provider-specific source."},`Invalid ${e} source "${t}".`,n.json,"invalid_source")}async function Tse(e,t,n){if(e[0]!=="request")return E(`Unknown approval command "${e[0]??""}".`,t.json);let r=e[1];if(r!=="status"&&r!=="complete")return E("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let i=L(e[2],`approval request ${r??""} requires an approval id.`);if(r==="status")return await he(`/api/v1/me/approvals/${encodeURIComponent(i)}`,t,n,"Approval status loaded.",{authenticated:!0});let o=L(t.decision,"approval request complete requires --decision."),s=pr("approval.request.complete","decision",o,Eie,t,"invalid_decision");return s||await Le(`/api/v1/me/approvals/${encodeURIComponent(i)}/complete`,ie({decision:o,evidence:cn(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed.")}async function Ose(e,t,n){let r=e[0]??"list";if(r==="list"){let o=await D(n,"/api/v1/me/workspaces",{headers:ne(n.apiKey,n.authBlockedMessage)});return un(o,Lse(o,n),"Available workspaces loaded.",t.json,n)}if(r==="current"){let o=await D(n,"/api/v1/me/working-mode",{headers:ne(n.apiKey,n.authBlockedMessage)});return await Bi(n,o),un(o,jse(o,n),"Selected workspace loaded.",t.json,n)}if(r==="select"||r==="use"){let o=L(e[1],"workspace select requires personal or a workspace id."),s=await D(n,"/api/v1/me/working-modes",{headers:ne(n.apiKey,n.authBlockedMessage)}),a=(Array.isArray(s.modes)?s.modes:[]).filter(j),l=o.toLowerCase()==="personal",c=a.filter(m=>l?f(m,"type")==="personal"&&f(m,"modeId")==="personal":f(m,"type")==="enterprise_workspace"&&f(m,"workspaceId")===o);if(c.length===0)return x({status:"not_found_or_forbidden",reasonCode:"workspace_working_mode_not_found",...l?{selection:"personal"}:{workspaceId:o},nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list`, then select Personal or an exact workspace id shown there."},l?"Personal is not available for this account.":`Workspace ${o} was not found in your Enterprise workspace access.`,t.json,"workspace_working_mode_not_found");if(c.length>1)return x({status:"ambiguous_workspace",reasonCode:"workspace_working_mode_ambiguous",workspaceId:o,nextAction:"workspace.list",nextStep:"Workspace ids should be unique. Run `skills-layer workspace list` and use the exact workspace id shown there."},`Workspace ${o} matched more than one Enterprise workspace.`,t.json,"workspace_working_mode_ambiguous");let u=f(c[0],"modeId");if(!u)return x({status:"error",reasonCode:"workspace_working_mode_invalid",workspaceId:o,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` and retry with Personal or an exact selectable workspace id."},`Workspace ${o} is missing its selection identifier.`,t.json,"workspace_working_mode_invalid");let d=await D(n,"/api/v1/me/working-mode",{method:"PUT",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({modeId:u})});await Bi(n,d);let p=f(c[0],"label");return R(d,l?"Selected workspace: Personal.":`Selected workspace: ${p?`${p} (${o})`:o}.`,t.json,n)}if(!["request","approve","reject","skills","guide"].includes(r))return E(`Unknown workspace command "${r}".`,t.json);let i=L(e[1],`workspace ${r} requires a workspace id.`);if(r==="request"||r==="approve"||r==="reject"){let o=L(e[2],`workspace ${r} requires a skill slug.`);try{if(r==="request")return await Le(`/api/v1/workspaces/${encodeURIComponent(i)}/skill-requests`,{skillSlug:o,reason:k(t.reason)},t,n,"Workspace skill request captured.");if(r==="approve"){let s=await hU(n,`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/approve`,{},t);return fe(s)?s:R(s,"Workspace skill approval evaluated.",t.json,n)}return await Le(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r}`,{},t,n,"Workspace skill rejected.")}catch(s){if(s instanceof Z&&(s.status===403||s.status===404))return r==="reject"&&IM(s)?CM(i,o,t):r==="approve"&&Nse(s)?Fse(i,o,t,s):hP(i,t);throw s}}if(r==="skills")try{return await he(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&(o.status===403||o.status===404))return hP(i,t);throw o}if(r==="guide"){let o=L(e[2],"workspace guide requires a skill slug.");try{return await he(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(s){if(s instanceof Z&&s.status===404)return IM(s)?CM(i,o,t):hP(i,t);throw s}}return E(`Unknown workspace command "${r}".`,t.json)}function Lse(e,t){let n=Ae(t),r=Array.isArray(e.results)?e.results.filter(j):[],i=[`${n.ok("OK")} Available workspaces loaded.`,"",n.section(`Available workspaces (${r.length+1})`),"1. Personal",` ${n.label("Type")}: Personal`];return r.forEach((o,s)=>{i.push(`${s+2}. ${f(o,"name")??"Unnamed workspace"}`),i.push(` ${n.label("ID")}: ${f(o,"workspaceId")??"unknown"}`),i.push(` ${n.label("Enterprise ID")}: ${f(o,"enterpriseId")??"unknown"}`),i.push(` ${n.label("Status")}: ${jt(f(o,"status")??"unknown")}`)}),i.push("",n.section("Next"),` ${n.arrow} skills-layer workspace select personal`,` ${n.arrow} skills-layer workspace select <workspace-id>`),i.join(`
2176
+ Next step: ${s}`}async function xse(e,t,n){let r=ed("restore",t);if(r.failure)return r.failure;let i=await lt(n),o=L(e[0],"restore requires a skill slug."),s=i.installs[o];if(!s)return x({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:o,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${o}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${o}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${o}\` next.`,t.json,"restore_record_not_found");if(s.removedReason==="refunded"||Rn(s).some(_=>_.record.removedReason==="refunded")){let _=!1;try{let C=await D(n,`/api/v1/me/entitlements?${new URLSearchParams({slugs:o})}`,{headers:ne(n.apiKey,n.authBlockedMessage)});_=dn(C.results).some(A=>A.skillSlug===o&&A.status==="active")}catch{}if(!_)return x({status:"blocked",reasonCode:"entitlement_revoked_refunded",skillSlug:o,nextStep:`Buy ${o} again before restoring it.`},"A refunded skill cannot be restored without active access.",t.json,"entitlement_revoked_refunded")}let a=Vn(s,{scope:r.scope,agent:r.agent});if(a.length===0&&Rn(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:o,requestedScope:r.scope,requestedAgent:r.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded quarantined targets."},`${o} has no restorable record for the requested local target.`,t.json,"local_install_target_not_found");if(a.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:o,nextAction:"restore",nextStep:"Retry with --scope and --agent to restore one exact quarantined materialization."},`${o} has more than one local materialization. Select the exact target to restore.`,t.json,"local_install_target_selection_required");let l=a[0],c=l?hr(s,l):s,u=l?.lifecycle??null;if(!u)return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:o,nextAction:"install",nextStep:`Reinstall ${o} from the approved catalog; legacy records cannot authorize an exact-generation restore.`},`Skills Layer cannot restore ${o} because its exact-generation lifecycle record is missing or invalid.`,t.json,"exact_install_receipt_missing");if(u.state!=="quarantined"||!u.quarantine)return x({status:"blocked",reasonCode:"restore_not_quarantined",skillSlug:o,localLifecycle:u,nextAction:"installed",nextStep:"Only a physically quarantined exact generation can be restored."},`${o} does not have a quarantined exact generation to restore.`,t.json,"restore_not_quarantined");let d=new URLSearchParams({version:u.receipt.generation.semanticVersion,operation:"restore",generationId:u.receipt.generation.generationId}),p=f(c,"acquisitionMode")==="anonymous_public",m;try{m=await D(n,p?`/api/v1/skills/${encodeURIComponent(o)}/export${Qe(d)}`:`/api/v1/me/library/${encodeURIComponent(o)}/export${Qe(d)}`,{headers:p?{}:ne(n.apiKey,n.authBlockedMessage)})}catch(_){if(_ instanceof Z)return Ho(_,t.json);throw _}if(m.restoreAuthorization===void 0)return x({status:"blocked",reasonCode:"restore_authorization_missing",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Retry after the Skills Layer API returns a fresh restoreAuthorization bound to this exact generation."},`The backend did not authorize restoration of ${o}'s exact quarantined generation.`,t.json,"restore_authorization_missing");let h=bz(m.restoreAuthorization);if(!h||h.purpose!=="restore_fresh_approval"||!Cse(h,u.receipt))return x({status:"blocked",reasonCode:"restore_authorization_invalid",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Do not restore. Refresh backend approval for this exact artifact generation."},`The backend returned an invalid or mismatched restore authorization for ${o}.`,t.json,"restore_authorization_invalid");let g=`restore_${Ge(16).toString("hex")}`,y=Zu({state:"restore_pending",operationId:g,receipt:u.receipt,quarantine:u.quarantine,backend:n});await Mr(n,_=>{let C=_.installs[o],A=C&&l?Xt(C)[l.materializationId]:void 0,N=A?Yt(A):null;if(!C||!A||N?.operationId!==u.operationId||N.state!=="quarantined")throw new Error("Local install record changed before its exact restore reservation was created.");_.installs[o]=Br({existing:C,skillSlug:o,materialization:{...A,localLifecycle:y,savedAt:n.now()},backend:n})});let v;try{await f2({quarantine:u.quarantine,authorizeRestore:async()=>h,finalizeRestore:async()=>{let _=!0;return await Mr(n,C=>{let A=C.installs[o],N=A&&l?Xt(A)[l.materializationId]:void 0,O=N?Yt(N):null;if(!A||!N||!O||O.state!=="restore_pending"||O.operationId!==g){_=!1;return}let X=Zu({state:"active",operationId:g,receipt:u.receipt,backend:n});v={...N,status:"restored",localLifecycle:X,savedAt:n.now()},C.installs[o]=Br({existing:A,skillSlug:o,materialization:v,backend:n})}),_?{status:"released",releaseId:`local_restore_${Ge(16).toString("hex")}`}:{status:"denied",reasonCode:"restore_reservation_lost"}}})}catch(_){return await Mr(n,C=>{let A=C.installs[o],N=A&&l?Xt(A)[l.materializationId]:void 0,O=N?Yt(N):null;!A||!N||O?.operationId!==g||(C.installs[o]=Br({existing:A,skillSlug:o,materialization:{...N,localLifecycle:u,savedAt:n.now()},backend:n}))}).catch(()=>{}),x({status:"blocked",reasonCode:"exact_generation_restore_failed",skillSlug:o,error:ke(_),nextAction:"restore",nextStep:"Keep the generation quarantined. Resolve local path, drift, or permission problems before retrying."},`Skills Layer could not atomically restore ${o}.`,t.json,"exact_generation_restore_failed")}if(!v)throw new Error(`Atomic restore for ${o} completed without committing its local lifecycle record.`);let b=Yt(v),w={status:"restored",skillSlug:o,record:v,localLifecycle:b};return t.json?R(w,`Restored ${o}.`,!0,n):{exitCode:0,stdout:bse(o,v,n),stderr:""}}function Cse(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archiveSha256&&e.manifestSha256===t.manifestSha256}async function Ise(e,t,n){let r=L(e[0],"check requires a skill slug.");return await he(`/api/v1/skills/${encodeURIComponent(r)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function Pse(e,t,n){let r=L(e[0]??t.source,"import requires a source."),i=pr("import","visibility",t.visibility,qa,t,"invalid_visibility");if(i)return i;let o=await Ku(r,n.cwd);if(o)return await Ase(r,o,t,n);let s=Rse(r,t);if(s)return s;let a=fA(r,t,n,n.apiKey?"authenticated":"unknown"),l=await D(n,a,{method:"POST",headers:$U(r,t,n,n.apiKey?"authenticated":"unknown"),body:JSON.stringify(ie({source:r,skillSlug:k(t.skill),visibility:k(t.visibility)??ji(r,t,n)}))});return await Ve(n.paths.importsPath,{version:1,lastImport:l,savedAt:n.now()}),R(l,"Source import submitted.",t.json,n)}async function Ase(e,t,n,r){let i=k(n.skill),o=dA(e,t,i);if(!r.apiKey)return x({status:"error",reasonCode:"local_import_sign_in_required",source:e,nextAction:"login",nextStep:`Run \`skills-layer login\`, then retry \`skills-layer import ${e}\` (the same flow as \`skills-layer creator submit ${e}\`).`},"Importing a local folder submits it through your creator account, so you must sign in first. Run `skills-layer login`, then retry. Nothing was uploaded.",n.json,"local_import_sign_in_required");let s=Ah(e,o,n);if(s)return s;let a=await Nu({source:e,inspection:o,requestedSkillSlug:i,mode:"import",flags:n,backend:r});if(a.kind==="failure")return a.result;let c=pA(t.files).find(d=>d.skillSlug===a.skillSlug),u=c.relativeSkillRoot==="."?e:`${e.replace(/[\\/]+$/u,"")}/${c.relativeSkillRoot}`;return k(n.version)?await DP([u],{...n,source:void 0,path:void 0,skill:c.skillSlug},r,!1):x({status:"error",nextAction:"import",nextStep:"Pass --version <semver>, for example --version 1.0.0."},"A local import requires --version <semver>.",n.json,"version_required")}function Rse(e,t){try{return ir(e).kind!=="local"?null:x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:qu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or --help for import examples."},qu(e)?`Import source ${e} was not found or is not readable.`:`Import source "${e}" is not a supported source. Use a local path, GitHub/GitLab source, or URL.`,t.json,"invalid_source")}catch(n){return x({status:"error",reasonCode:"invalid_source",source:e,error:ke(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ke(n)}`,t.json,"invalid_source")}}function qu(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function BU(e,t,n,r){let i=Tt(r.cwd,t);return x({status:"error",reasonCode:"source_path_not_found",path:i,nextAction:e,nextStep:`Check that ${t} exists and contains a readable SKILL.md, then retry.`},`${e} source path does not exist: ${i}`,n.json,"source_path_not_found")}async function Ese(e,t,n){let r=e[0];if(r==="reference"&&e[1]==="resolve"){let i=L(e[2],"source reference resolve requires a reference."),o=await D(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(i)}`);return o.status==="not_found"?x({...o,status:"not_found",reasonCode:"source_reference_not_found",reference:i,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${i} was not found.`,t.json,"source_reference_not_found"):R(o,"Source reference resolved.",t.json,n)}return r==="connection"?await $se(e.slice(1),t,n):E(`Unknown source command "${e.join(" ")}".`,t.json)}async function $se(e,t,n){let r=e[0];if(r==="start"){let o=k(t.provider),s=k(t.source),a=k(t.visibility),l=o?.replace(/-/gu,"_");if(l&&!YB.includes(l))return Fr("source.connection.start","provider",o??"",YB,t,"invalid_source_provider");let c=Mi(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=Dse(o,s,a,t);if(u)return u;let d=Ft(t,["provider","source","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),p=k(t.skill);return p&&(d.requestedSkillSlug=p),await Le("/api/v1/me/source-connections",d,t,n,"Source connection started.")}let i=L(e[1],`source connection ${r??""} requires a connection id.`);if(r==="status")return await he(`/api/v1/me/source-connections/${encodeURIComponent(i)}`,t,n,"Source connection loaded.",{authenticated:!0});if(r==="complete"){let o=Uie("source.connection.complete",t);return o||await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/complete`,Ft(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return r==="cancel"?await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/cancel`,{},t,n,"Source connection cancelled."):r==="revoke"?await Le(`/api/v1/me/source-connections/${encodeURIComponent(i)}/revoke`,{},t,n,"Source connection revoked."):E(`Unknown source connection command "${r??""}".`,t.json)}function Dse(e,t,n,r){if(n){let i=dc(n);if(!i||!qa.includes(i))return x({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:qa,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${qa.join(", ")}.`,r.json,"invalid_visibility")}if(!e||!t)return null;try{let i=ir(t);if((e==="github"||e==="gitlab")&&i.kind!==e)return gP(e,t,r);if(e==="domain"){let o=new URL(t);if(o.protocol!=="https:"||!o.hostname)return gP(e,t,r)}}catch{return gP(e,t,r)}return null}function gP(e,t,n){return x({status:"error",reasonCode:"invalid_source",provider:e,source:t,nextAction:"source.connection.start",nextStep:e==="github"?"Use a GitHub source such as https://github.com/OWNER/REPO or github:OWNER/REPO.":e==="gitlab"?"Use a GitLab source such as https://gitlab.com/GROUP/REPO or gitlab:GROUP/REPO.":"Use a valid source URL or provider-specific source."},`Invalid ${e} source "${t}".`,n.json,"invalid_source")}async function Tse(e,t,n){if(e[0]!=="request")return E(`Unknown approval command "${e[0]??""}".`,t.json);let r=e[1];if(r!=="status"&&r!=="complete")return E("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let i=L(e[2],`approval request ${r??""} requires an approval id.`);if(r==="status")return await he(`/api/v1/me/approvals/${encodeURIComponent(i)}`,t,n,"Approval status loaded.",{authenticated:!0});let o=L(t.decision,"approval request complete requires --decision."),s=pr("approval.request.complete","decision",o,Eie,t,"invalid_decision");return s||await Le(`/api/v1/me/approvals/${encodeURIComponent(i)}/complete`,ie({decision:o,evidence:cn(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed.")}async function Ose(e,t,n){let r=e[0]??"list";if(r==="list"){let o=await D(n,"/api/v1/me/workspaces",{headers:ne(n.apiKey,n.authBlockedMessage)});return un(o,Lse(o,n),"Available workspaces loaded.",t.json,n)}if(r==="current"){let o=await D(n,"/api/v1/me/working-mode",{headers:ne(n.apiKey,n.authBlockedMessage)});return await Bi(n,o),un(o,jse(o,n),"Selected workspace loaded.",t.json,n)}if(r==="select"||r==="use"){let o=L(e[1],"workspace select requires personal or a workspace id."),s=await D(n,"/api/v1/me/working-modes",{headers:ne(n.apiKey,n.authBlockedMessage)}),a=(Array.isArray(s.modes)?s.modes:[]).filter(j),l=o.toLowerCase()==="personal",c=a.filter(m=>l?f(m,"type")==="personal"&&f(m,"modeId")==="personal":f(m,"type")==="enterprise_workspace"&&f(m,"workspaceId")===o);if(c.length===0)return x({status:"not_found_or_forbidden",reasonCode:"workspace_working_mode_not_found",...l?{selection:"personal"}:{workspaceId:o},nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list`, then select Personal or an exact workspace id shown there."},l?"Personal is not available for this account.":`Workspace ${o} was not found in your Enterprise workspace access.`,t.json,"workspace_working_mode_not_found");if(c.length>1)return x({status:"ambiguous_workspace",reasonCode:"workspace_working_mode_ambiguous",workspaceId:o,nextAction:"workspace.list",nextStep:"Workspace ids should be unique. Run `skills-layer workspace list` and use the exact workspace id shown there."},`Workspace ${o} matched more than one Enterprise workspace.`,t.json,"workspace_working_mode_ambiguous");let u=f(c[0],"modeId");if(!u)return x({status:"error",reasonCode:"workspace_working_mode_invalid",workspaceId:o,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` and retry with Personal or an exact selectable workspace id."},`Workspace ${o} is missing its selection identifier.`,t.json,"workspace_working_mode_invalid");let d=await D(n,"/api/v1/me/working-mode",{method:"PUT",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({modeId:u})});await Bi(n,d);let p=f(c[0],"label");return R(d,l?"Selected workspace: Personal.":`Selected workspace: ${p?`${p} (${o})`:o}.`,t.json,n)}if(!["request","approve","reject","skills","guide"].includes(r))return E(`Unknown workspace command "${r}".`,t.json);let i=L(e[1],`workspace ${r} requires a workspace id.`);if(r==="request"||r==="approve"||r==="reject"){let o=L(e[2],`workspace ${r} requires a skill slug.`);try{if(r==="request")return await Le(`/api/v1/workspaces/${encodeURIComponent(i)}/skill-requests`,{skillSlug:o,reason:k(t.reason)},t,n,"Workspace skill request captured.");if(r==="approve"){let s=await hU(n,`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/approve`,{},t);return fe(s)?s:R(s,"Workspace skill approval evaluated.",t.json,n)}return await Le(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r}`,{},t,n,"Workspace skill rejected.")}catch(s){if(s instanceof Z&&(s.status===403||s.status===404))return r==="reject"&&IM(s)?CM(i,o,t):r==="approve"&&Nse(s)?Fse(i,o,t,s):hP(i,t);throw s}}if(r==="skills")try{return await he(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&(o.status===403||o.status===404))return hP(i,t);throw o}if(r==="guide"){let o=L(e[2],"workspace guide requires a skill slug.");try{return await he(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(s){if(s instanceof Z&&s.status===404)return IM(s)?CM(i,o,t):hP(i,t);throw s}}return E(`Unknown workspace command "${r}".`,t.json)}function Lse(e,t){let n=Ae(t),r=Array.isArray(e.results)?e.results.filter(j):[],i=[`${n.ok("OK")} Available workspaces loaded.`,"",n.section(`Available workspaces (${r.length+1})`),"1. Personal",` ${n.label("Type")}: Personal`];return r.forEach((o,s)=>{i.push(`${s+2}. ${f(o,"name")??"Unnamed workspace"}`),i.push(` ${n.label("ID")}: ${f(o,"workspaceId")??"unknown"}`),i.push(` ${n.label("Enterprise ID")}: ${f(o,"enterpriseId")??"unknown"}`),i.push(` ${n.label("Status")}: ${jt(f(o,"status")??"unknown")}`)}),i.push("",n.section("Next"),` ${n.arrow} skills-layer workspace select personal`,` ${n.arrow} skills-layer workspace select <workspace-id>`),i.join(`
2177
2177
  `)}function jse(e,t){let n=Ae(t),r=j(e.mode)?e.mode:void 0,i=r?f(r,"type"):void 0,o=f(e,"selectedModeId"),s=[`${n.ok("OK")} Selected workspace loaded.`,""];return i==="personal"||o==="personal"?(s.push(n.section("Selected workspace: Personal")),s.join(`
2178
2178
  `)):r?(s.push(n.section(`Selected workspace: ${f(r,"label")??f(r,"name")??"Enterprise workspace"}`)),s.push(` ${n.label("Workspace ID")}: ${f(r,"workspaceId")??"unknown"}`),s.push(` ${n.label("Enterprise ID")}: ${f(r,"enterpriseId")??"unknown"}`),s.join(`
2179
2179
  `)):(s.push(n.section("Selected workspace"),` ${n.muted("No workspace is currently selected.")}`),s.join(`
2180
- `))}function hP(e,t){return x({status:"not_found_or_forbidden",reasonCode:"workspace_not_found_or_forbidden",workspaceId:e,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` to find a workspace you can access, then retry with that workspace id."},`Workspace ${e} was not found or you do not have access. Run \`skills-layer workspace list\` to inspect accessible workspaces.`,t.json,"workspace_not_found_or_forbidden")}function CM(e,t,n){let r={status:"approval_not_found",reasonCode:"workspace_skill_approval_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.approve",nextStep:`Run \`skills-layer workspace approve ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the approval exists.`};return x(r,`Workspace approval not found for ${t}. Run \`skills-layer workspace approve ${e} ${t}\` first.`,n.json,"workspace_skill_approval_not_found")}function IM(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="workspace_skill_approval_not_found"||r.includes("workspace")&&r.includes("approval")&&r.includes("not found")}function Nse(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="skill_not_found"||r.includes("skill")&&r.includes("not found")}function Fse(e,t,n,r){let i=r.details??{},o={status:"not_found",reasonCode:"skill_not_found",workspaceId:e,skillSlug:t,nextAction:"search",nextStep:f(i,"nextStep")??`Run \`skills-layer search ${t}\` to find the public skill before approving it for workspace ${e}.`};return x(o,`Skill ${t} was not found. Run \`skills-layer search ${t}\` before approving it for the workspace.`,n.json,"skill_not_found")}async function Bse(e,t,n){let r=L(e[0],"buy requires a skill slug."),i=Hie(t);if(i.failure)return i.failure;if(k(t.workspace))return x({reasonCode:"invalid_input"},"buy does not support --workspace; use skills-layer enterprise skill buy <enterprise-id> <skill-slug>.",t.json,"invalid_input");let o=await sA(n,{skillSlug:r,paymentMethod:i.value},t,"/api/v1/buy");if(fe(o))return o;if(o.status==="already_owned")return R(o,`You already own ${r}. Run \`skills-layer install ${r}\` to install or update it.`,t.json,n);if(t.noOpen&&o.status==="checkout_required"&&typeof o.checkoutUrl=="string")return R({...o,nextAction:"open_checkout_url",nextStep:`Open ${o.checkoutUrl} to complete payment, then run skills-layer install ${r}.`},`Payment is required for ${r}.`,t.json,n);if(t.json||t.noOpen||o.status!=="checkout_required"||typeof o.checkoutUrl!="string"||typeof o.purchaseId!="string")return R(o,`Purchase flow started for ${r}.`,t.json,n);n.emitInfo(`Opening checkout for ${r}. Complete the payment in your browser, then come back here.`),await n.openUrl(o.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${o.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let a=await ole(o.purchaseId,n);return fe(a)?a:a.status!=="succeeded"?R({...o,purchaseStatus:a.status},`Checkout is still ${a.status} for ${r}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await Za([r],t,n,{origin:"post_purchase",fallbackPolicy:"account_required"}))}async function Mse(e,t,n){let r=e[0]??"list";if(r==="list")return await he("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(r==="spending")return await he("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let i=L(e[1],`purchases ${r} requires a purchase id.`);if(r==="status")return await he(`/api/v1/purchases/${encodeURIComponent(i)}`,t,n,"Purchase status loaded.",{authenticated:!0});if(r==="invoice")return await he(`/api/v1/purchases/${encodeURIComponent(i)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0});if(r==="refund-quote"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund-quote`,{headers:ne(n.apiKey,n.authBlockedMessage)}),s=j(o.quote)?o.quote:o,a=l=>typeof l=="number"?`USD ${(l/100).toFixed(2)}`:"unavailable";return R(o,`Refundable: ${a(s.refundableAmountCents)}. Non-refundable: ${a(s.nonRefundableAmountCents)}. Refund window ends: ${String(s.refundWindowEndsAt??"unavailable")}.`,t.json,n)}if(r==="refund"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(Ft(t,["reason"]))}),s=o.status==="refunded"?await td(t,n):{warnings:[]};return R({...o,warnings:[...s.warnings,"Manually copied folders cannot be removed automatically; other machines check on sync, installed or update."]},o.status==="refunded"?"Refund completed.":"Refund requested.",t.json,n)}return E(`Unknown purchases command "${r}".`,t.json)}function MU(e,t,n,r){let i=typeof e.amountCents=="number"?` (USD ${(e.amountCents/100).toFixed(2)})`:"";return R({...e,status:"action_required",reasonCode:"purchase_required",nextAction:"buy",nextStep:`skills-layer buy ${t}`},`Purchase required${i}. Run \`skills-layer buy ${t}\`.`,n.json,r)}async function Use(e,t,n){let r=e[0];if(r==="search"){let i=new URLSearchParams;return We(i,"query",e.slice(1).join(" ").trim()||k(t.query)),We(i,"limit",k(t.limit)),await he(`/api/v1/me/search${Qe(i)}`,t,n,"Authenticated library search complete.",{authenticated:!0})}if(r==="add"){let i=L(e[1],"library add requires a skill slug."),o=await sA(n,{skillSlug:i},t);return fe(o)?o:o.status==="purchase_required"?MU(o,i,t,n):R(o,"Skill added to library.",t.json,n)}return E(`Unknown library command "${r}".`,t.json)}async function zse(e,t,n){let r=L(e[0],"export requires a skill slug.");if(t.showUrl&&k(t.output))return x({status:"error",reasonCode:"conflicting_export_output",nextAction:"export",nextStep:"Use either --show-url to inspect the signed URL or --output <file> to download the bundle, not both."},"export cannot use --show-url and --output together.",t.json,"conflicting_export_output");let i=new URLSearchParams,o=k(t.version);if(o&&!Lh(o))return iA("export",o,t);We(i,"version",o);let s=await D(n,`/api/v1/me/library/${encodeURIComponent(r)}/export${Qe(i)}`,{headers:ne(n.apiKey,n.authBlockedMessage)}),a=k(t.output);if(a){let l=await Ih({backend:n,exportResult:s,flags:t,skillSlug:r});if(fe(l))return l;let c=Tt(n.cwd,a);await EA(c,l.bytes);let u={...s};return delete u.downloadUrl,R({...u,archiveSha256:l.archiveSha256,archiveSha256Meaning:"artifact_v1_exact_zip_bytes_sha256",downloadedArchiveSha256:l.archiveBytesSha256,downloadedFileSha256:l.archiveBytesSha256,archiveHashFormat:l.archiveHashFormat,generationId:l.envelope.generation.generationId,manifestSha256:l.envelope.manifest.sha256,outputPath:c,downloaded:!0},`Exported ${r} to ${c}. Downloaded file SHA-256: ${l.archiveBytesSha256}.`,t.json,n)}return R(s,a?`Exported ${r} to ${a}.`:"Export prepared.",t.json,n)}async function PM(e,t,n,r){if(e==="show"){let a=t[0]?.trim(),l=a?`?skillSlug=${encodeURIComponent(a)}`:"";return await he(`/api/v1/me/library/reviews${l}`,n,r,"Reviews loaded.",{authenticated:!0})}let i=L(t[0],"add-review requires a skill slug."),o=L(n.rating,"add-review requires --rating.");if(!/^[1-5]$/u.test(o))return x({status:"error",reasonCode:"invalid_rating",rating:o,acceptedValues:["1","2","3","4","5"],nextAction:"add-review",nextStep:"Use --rating with a whole number from 1 to 5."},`Invalid review rating "${o}". Use a whole number from 1 to 5.`,n.json,"invalid_rating");let s=Ft(n,["rating","feedback"]);if(typeof n.evalSummary=="string"){let a=await be(Vo(r.cwd,n.evalSummary));if(a===null)return x({status:"error",reasonCode:"invalid_eval_summary_file",path:n.evalSummary,nextAction:"add-review",nextStep:"Pass --eval-summary with a readable JSON redacted eval summary envelope."},`Could not read eval summary JSON from ${n.evalSummary}.`,n.json,"invalid_eval_summary_file");s.evalSummary=a}return await Le(`/api/v1/me/library/${encodeURIComponent(i)}/review`,s,n,r,"Review added.")}async function AM(e,t,n,r){let i=L(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await he(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});L(n.message,"add-issue requires --message.");let o=pr("add-issue","issueType",n.issueType,Rie,n,"invalid_issue_type","issue-type");return o||await Le(`/api/v1/me/library/${encodeURIComponent(i)}/report-issue`,Ft(n,["issueType","message"]),n,r,"Issue reported.")}async function qse(e,t,n){let r=e[0];if(r==="hook"){let i=e[1];if(i==="install")return await qU(t,n);if(i==="status")return await Qse(t,n);if(i==="run"){let o=await nae(t,n),s=k(t.agent);if(s&&kr(s)){let a=cs(n.env);await Sy({agentId:s,associationState:a?await Gse(s,t,n):"unreadable",activationEvent:a?await Kse(s,n):!1,delegatedExecution:o[UU]===!0,env:n.env,rawPayloadBase64:Ee(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64),result:o})}return o}return E(`Unknown guardian hook command "${i??""}".`,t.json)}if(r==="session"){let i=e[1];return i==="bind"?await eae(e.slice(2),t,n):E(`Unknown guardian session command "${i??""}".`,t.json)}if(r==="enable")return e[1]||t.skill?await yP("enforce",e,t,n):E("guardian enable requires a skill slug.",t.json);if(r==="disable")return await yP("disabled",e,t,n);if(r==="enable-warnings-only")return await yP("warning_only",e,t,n);if(r==="status")return await Zse(e,t,n);if(r==="launch")return await tae(e.slice(1),t,n);if(r==="exec")try{let i=await Wse(e,t,n);return await RM(i,e,t,n),i}catch(i){throw await RM({exitCode:1,stdout:"",stderr:ke(i)},e,t,n),i}if(r==="check"){let i=L(e[1]??t.skill,"guardian check requires a skill slug.");if((await td({...t,dryRun:!0},n,i)).revokedSlugs.includes(i))return R({status:"blocked",decision:"block",reasonCode:"entitlement_revoked_refunded",skillSlug:i,nextStep:`Run skills-layer remove ${i}, or buy it again.`},"This skill was refunded; execution is blocked.",t.json,n);let s=zM(t,"check");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.approval.prepare",nextStep:"Use an authenticated one-action approval or `skills-layer guardian exec` for shell execution."},"Guardian enforcement does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let a=Ece(t.cloudTrustLedger);if(a.status==="invalid")return E(a.message,t.json);let l=GP(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(l.status==="invalid")return E(l.message,t.json);let c=await tz({skillSlug:i,version:k(t.version),action:s,flags:t,backend:n,telemetryMode:l.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=k(t.version)??c.context.version,p=ie({skillSlug:i,version:d,action:s,path:u,guardianPreference:await id(n,i),unmanagedPolicy:c.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:l.mode,localPreflight:Vu(c.context)}),m=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(p)});return await Ha(n,{skillSlug:i,version:d,action:s,decisionStatus:KP(m),reasonCode:Eh(m),telemetryMode:l.mode,path:u,authority:m}),R({...m,localPreflight:Vu(c.context)},"Guardian check complete.",t.json,n)}if(r==="incident"){let i=L(e[1]??t.skill,"guardian incident requires a skill slug."),o=L(t.version,"guardian incident requires --version."),s=GP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return E(s.message,t.json);let a=k(t.path);if(a&&!await fr(Tt(n.cwd,a)))return x({status:"error",reasonCode:"invalid_incident_path",path:a,nextAction:"guardian.incident",nextStep:"Use --path with an installed skill directory, or omit --path so Skills Layer resolves the local install record."},`Guardian incident path does not exist: ${a}`,t.json,"invalid_incident_path");let l=a??(await nz({skillSlug:i,flags:t,backend:n})).installedPath,c=zM(t,"incident"),u=cn(t.evidenceJson,"evidence-json"),d=s.mode==="cloud_managed"&&!n.apiKey?"local_only":s.mode,p=n.now(),m=ie({skillSlug:i,version:o,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:k(t.reason),generatedAt:p,...d==="cloud_managed"?{incidentIdempotencyKey:fle()}:{}});if(d==="local_only"){if(!l)return E("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let v=await FM({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian local-only incident"});if(f(v,"status")!=="quarantined"){let w=f(v,"reasonCode")??"guardian_exact_quarantine_failed";return x(v,`Guardian could not physically quarantine the exact installed generation for ${i}.`,t.json,w)}await Ha(n,{skillSlug:i,version:o,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:l});let b=BM(n,i);return await KM(b,JSON.stringify({request:m,response:null,localResponse:v,savedAt:n.now()},null,2)),R({status:"written",skillSlug:i,version:o,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:v,incidentStatePath:b,incidentPath:v.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let h=await mle(n,m),g=l?await FM({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian Cloud-managed incident"}):null;if(g&&f(g,"status")!=="quarantined"){let v=f(g,"reasonCode")??"guardian_exact_quarantine_failed";return x({...g,cloudResponse:h},`Guardian recorded the Cloud incident but could not physically quarantine the exact local generation for ${i}.`,t.json,v)}await Uo(n.paths.incidentsDir,{recursive:!0});let y=BM(n,i);return await KM(y,JSON.stringify({request:m,response:h,localResponse:g,savedAt:n.now()},null,2)),await Ha(n,{skillSlug:i,version:o,action:c,decisionStatus:KP(h),reasonCode:Eh(h),telemetryMode:s.mode,path:l,authority:h}),R({...h,telemetryMode:s.mode,localResponse:g,incidentPath:y},"Guardian incident recorded.",t.json,n)}return E(`Unknown guardian command "${r??""}".`,t.json)}var UU=Symbol("guardian-delegated-execution");async function RM(e,t,n,r){if(!cs(r.env))return;let i=r.env.SKILLS_LAYER_GUARDIAN_CANARY_AGENT_ID,o=r.env.SKILLS_LAYER_GUARDIAN_CANARY_SCOPE;if(!i||!kr(i)||o!=="project"&&o!=="global")return;let s=k(n.skill)??t[1];s&&await Sy({agentId:i,associationState:await Vse(i,o,s,r),activationEvent:!1,env:r.env,rawPayloadBase64:Buffer.from(JSON.stringify({positionals:t,json:n.json})).toString("base64url"),reportingSource:"guarded_execution",result:e})}async function Vse(e,t,n,r){let i=await CE({agentId:e,scope:t,skillSlug:n,env:r.env});if(!i)return"unreadable";try{let o=await Go(r,t),s=o.associations[i.associationKey];if(!s||s.agentId!==e||s.scope!==t||s.skillSlug!==n)return"missing";let a=fl(o,{agentId:e,sessionId:s.sessionId,asOf:r.now()});return a.associations.some(c=>tt(c)===i.associationKey)?a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="terminal"?"terminal":a.status==="ambiguous"?"ambiguous":"missing":"missing"}catch{return"unreadable"}}async function Gse(e,t,n){let r=Qa(k(t.scope));return r.status==="invalid"?"unreadable":await Hse(e,r.scope,n)}async function Hse(e,t,n){let r=Ee(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!r)return"unreadable";let i;try{i=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{return"unreadable"}let o=wd(e,i)?.sessionId??GU(e,i);if(!o)return"unreadable";try{let s=await Go(n,t),a=fl(s,{agentId:e,sessionId:o,asOf:n.now()});return a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="unrelated"||a.status==="expected_missing_authority"?"missing":a.status}catch{return"unreadable"}}async function Kse(e,t){let n=Ee(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!n)return!1;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return wd(e,r)!==null}catch{return!1}}async function Wse(e,t,n){let r=k(t.skill),i=L(r??e[1],"guardian exec requires a skill slug."),o=r?e.slice(1):e.slice(2);if(o.length===0)return E("guardian exec requires a command after --.",t.json);if(t.actionJson!==void 0)return x({status:"error",reasonCode:"caller_supplied_execution_action_rejected",nextAction:"guardian.execution.prepare",nextStep:"Guardian derives the canonical shell action from the exact command and execution plan."},"Guardian guarded execution does not accept a caller-authored action.",t.json,"caller_supplied_execution_action_rejected");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.execution.prepare",nextStep:"Use the authenticated atomic Guardian execution prepare flow."},"Guardian guarded execution does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let s=GP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return E(s.message,t.json);let a=LM(o),l=await tz({skillSlug:i,version:k(t.version),action:a,flags:t,backend:n,telemetryMode:s.mode});if(l.status!=="ok")return l.result;let c=l.context.installedPath,u=k(t.version)??l.context.version;if(!u)return x({status:"blocked",reasonCode:"guardian_exact_version_required",skillSlug:i,nextStep:"Install the skill through Skills Layer or pass its exact --version before guarded execution."},"Guardian guarded execution requires an exact installed skill version.",t.json,"guardian_exact_version_required");let d=await Pae({commandArgs:o,skillSlug:i,version:u,flags:t,backend:n,localContext:l.context});if(d.status==="blocked")return d.result;let p=LM(o,d.request),m=await D(n,"/api/v1/guardian/execution/prepare",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({request:d.request,...t.dryRun?{dryRun:!0}:{}})}),h=typeof f(m,"token")=="string"&&T(m,"plan")!==void 0&&T(m,"binding")!==void 0;if(!Iae(m)&&!h){let C=Eh(m);return await Ha(n,{skillSlug:i,version:u,action:p,decisionStatus:"blocked",reasonCode:C,telemetryMode:s.mode,path:c,authority:m}),x({...m,status:"blocked",reasonCode:C,skillSlug:i},"Guardian blocked guarded execution.",t.json,C)}if(await Ha(n,{skillSlug:i,version:u,action:p,decisionStatus:"allowed",reasonCode:"within_contract",telemetryMode:s.mode,path:c,authority:m}),t.dryRun)return R({status:"allowed",skillSlug:i,guardian:m,localPreflight:Vu(l.context),command:{executable:ot(d.request.executableRealPath),executableSha256:d.request.executableSha256,argvSha256:oz(d.request.argv),cwdRealPath:d.request.cwdRealPath,executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let g=m,y=f(g,"token"),v=T(g,"plan"),b=T(g,"binding");if(!y||!v||!b)return x({status:"blocked",reasonCode:"guardian_grant_response_invalid",skillSlug:i},"Guardian returned an invalid execution grant.",t.json,"guardian_grant_response_invalid");await D(n,"/api/v1/guardian/execution-grants/consume",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({token:y,plan:v,binding:b})});let w;try{w=await U2({plan:v,ambientEnvironment:n.env,approvedSecrets:d.approvedSecrets})}catch(C){let P=C instanceof De?C.reasonCode:"guardian_process_failed";return x({status:"blocked",reasonCode:P,skillSlug:i,planHash:b.planHash},"Guardian refused the contained process launch.",t.json,P)}let _={executable:ot(v.executableRealPath),argsCount:v.argv.length,exitCode:w.exitCode??1,reason:w.reason,signal:w.signal,stdout:w.stdout,stderr:w.stderr,outputTruncated:w.outputTruncated,planHash:w.planHash};return{exitCode:_.exitCode,stdout:t.json?JSON.stringify({status:_.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:i,guardian:m,localPreflight:Vu(l.context),command:_},warnings:[],links:[],reasonCode:_.exitCode===0?null:"command_failed",handoff:null},null,2):jae(_),stderr:_.stderr}}async function yP(e,t,n,r){let i=L(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),o=await D(r,"/api/v1/guardian/mode",{method:"POST",headers:V(r.apiKey),body:JSON.stringify({skillSlug:i,requestedPreference:e,source:"public-cli"})});if(o.preferenceAccepted===!0){if(f(o,"effectiveMode")==="enforce"){let s=(await zi(r,i)).installs[i],a=Rn(s).filter(u=>u.lifecycle?.state==="active"||u.lifecycle?.state==="pending_activation"),l=et(r.env,r.platform,r.cwd),c=new Set;for(let u of a){let d=f(u.record,"scope"),p=gr(u.record);if(d!=="project"&&d!=="global"||p.length===0)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,scope:d,targetAgents:p,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode could not identify every supported local activation target.",n.json,"guardian_install_target_unavailable");for(let m of p){let h=l.find(v=>v.id===m);if(!h)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,agent:m,scope:d,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode found an unsupported local activation target.",n.json,"guardian_install_target_unavailable");let g=`${d}:${h.id}`;if(c.has(g))continue;c.add(g);let y=await Xa({backend:r,skillSlug:i,agentId:h.id,scope:d,flags:n,enforceRequired:!0});if(y)return y}}}await Nae(r,i,o)}return R(o,o.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,r)}async function Zse(e,t,n){let r=k(t.skill)??k(e[1]),i;try{i=await zU(n,r)}catch(m){i={status:"unavailable",skillSlug:r,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ke(m),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let o=await qn(n),s=r?await Fae(n,r):void 0,a=f(i,"status")==="unavailable",l=f(o,"enforcementLayer")??"not_installed",d=l!=="not_installed"&&o.strictPreActionBlocking===!0?{status:"strict_installed",reasonCode:"guardian_hook_strict",enforcementLayer:l,strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:"Cloud Guardian policy is enforced when checked, and the local host hook can block supported risky actions before execution."}:l==="native_hook_candidate"?{status:"candidate_installed",reasonCode:"guardian_hook_candidate",enforcementLayer:l,strictPreActionBlocking:!1,nextAction:"guardian.hook.status",nextStep:"A Guardian candidate hook is installed, but strict pre-action blocking is not verified. Run `skills-layer guardian hook status --scope project` to inspect the current binding."}:{status:"not_installed",reasonCode:"guardian_hook_not_installed",enforcementLayer:"not_installed",strictPreActionBlocking:!1,nextAction:"guardian.hook.install",nextStep:"Cloud Guardian policy is enforced when checked, but local pre-action blocking is not installed for this host. Run `skills-layer guardian hook install --agent codex --scope global` or `skills-layer setup`."},p=await Jse({backend:n,skillSlug:r,policy:i,hook:o,localPreference:s});return R(ie({status:a?"degraded":"ok",skillSlug:f(i,"skillSlug")??r,policy:i,localPreference:s,hook:o,cloudPolicy:{status:f(i,"effectiveMode")??f(i,"status")??"unknown",reasonCode:f(i,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:f(i,"nextAction"),nextStep:f(i,"nextStep")},localEnforcement:d,measuredProtection:p,nextAction:f(d,"nextAction"),nextStep:f(d,"nextStep")}),a?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function Jse(e){let t=f(e.policy,"effectiveMode")??(e.localPreference?f(e.localPreference,"effectiveMode")??f(e.localPreference,"requestedPreference"):void 0),n=t==="warning_only"?"warning":t==="disabled"?"disabled":"enforce",r="active",i,o,s=[];if(e.skillSlug){o=(await zi(e.backend,e.skillSlug)).installs[e.skillSlug],s=Rn(o);let b=s.map(w=>w.lifecycle?.state??"unreadable");b.some(w=>w==="active"||w==="pending_activation")||(b.includes("externally_removed")?r="externally_removed":b.includes("host_detached")?r="host_detached":b.includes("drifted")?r="drifted":b.length>0&&(r="unreadable")),i=o?f(o,"workspaceId")??f(o,"workingModeWorkspaceId"):void 0}let a=[],l=new Set;for(let v of["project","global"])try{a.push(...Object.values((await Go(e.backend,v)).associations).filter(b=>!e.skillSlug||b.skillSlug===e.skillSlug))}catch{l.add(v)}let c=EM(a,l.size>0),d=(Be(e.hook,"hooks")?.filter(j)??[]).filter(v=>v.active===!0),p=s.flatMap(v=>{let b=f(v.record,"scope");if(b!=="project"&&b!=="global")return[];let w=o?hr(o,v):v.record,_=f(w,"workspaceId")??f(w,"workingModeWorkspaceId"),C=f(v.record,"receiptSha256"),P=v.lifecycle?.receipt.generation.generationId,N=Yse(v.lifecycle?.state);return gr(v.record).map(O=>{let X=br(O),G=d.find(Ie=>f(Ie,"agent")===O&&f(Ie,"scope")===b),ee=a.filter(Ie=>Ie.agentId===O&&Ie.scope===b&&(!C||Ie.receiptSha256===C)&&(!P||Ie.generationId===P)),te=EM(ee,l.has(b)),Q=vl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:_?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:X?.maximumTier==="strict_candidate",hookInstalled:!!G,strictHookVerified:G?.strictPreActionBlocking===!0,exactActivationVerified:G?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:te,materializationState:N});return{materializationId:v.materializationId,agent:O,scope:b,installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:C,generationId:P,materializationState:N,associationState:te,activeAssociationCount:ee.filter(Ie=>Ie.state==="active").length,hookState:G?f(G,"hookState")??"active":"not_installed",evidenceCapability:G?.evidenceCapability??"unverified",exactActivationVerified:G?.exactActivationVerified===!0,activationRoute:G?.activationRoute??null,workspaceRequired:!!_,...Q}})}),m=vl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:i?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:d.some(v=>br(f(v,"agent")??"")?.maximumTier==="strict_candidate"),hookInstalled:d.length>0,strictHookVerified:d.some(v=>v.strictPreActionBlocking===!0),exactActivationVerified:d.some(v=>v.strictPreActionBlocking===!0&&v.exactActivationVerified===!0),completeWrapperVerified:!1,associationState:c,materializationState:r}),h=new Set(p.map(v=>v.label)),g=p.length===0?m:{label:h.size===1?p[0].label:"mixed",countedAsEnforced:p.every(v=>v.countedAsEnforced),activationAllowed:p.every(v=>v.activationAllowed),runtimeGuardian:p.every(v=>v.runtimeGuardian),reasonCode:h.size===1?p[0].reasonCode:"mixed_target_protection"},y=s.map(v=>({materializationId:v.materializationId,scope:f(v.record,"scope"),agent:f(v.record,"agent")??f(v.record,"targetAgent"),targetAgents:gr(v.record),installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:f(v.record,"receiptSha256"),state:v.lifecycle?.state??"unreadable",protectionTargets:p.filter(b=>b.materializationId===v.materializationId)}));return{...g,requestedMode:n,workspaceRequired:!!i,associationState:c,materializationState:r,materializations:y,targets:p,targetCount:p.length,activeAssociationCount:a.filter(v=>v.state==="active").length}}function Yse(e){return e==="active"||e==="pending_activation"?"active":e==="externally_removed"||e==="host_detached"||e==="drifted"?e:"unreadable"}function EM(e,t){return t?"stale":e.some(n=>n.state==="active")?"active":e.some(n=>n.state==="externally_removed")?"externally_removed":e.some(n=>n.state==="host_detached")?"host_detached":e.some(n=>n.state==="stale")?"stale":e.some(n=>n.state==="pending_authority")?"pending_authority":"none"}async function zU(e,t){let n=t?await id(e,t):void 0;return await D(e,"/api/v1/guardian/status",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(ie({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Xse(e){if(!e.apiKey)return{status:"unknown",policySource:"cloud",reasonCode:"login_required",nextAction:"skills-layer login",nextStep:"Sign in to read the Cloud Guardian policy that applies to your account."};try{return await zU(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ke(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function qU(e,t){let n=k(e.agent)??"codex",r=Qa(e.scope);if(r.status==="invalid")return E(r.message,e.json);let i=et(t.env,t.platform,t.cwd).find(m=>m.id===n);if(!i)return x({status:"error",reasonCode:"unknown_agent",agent:n,nextAction:"agents.list",nextStep:"Run `skills-layer agents list` to see supported agents, then retry Guardian hook install with a supported --agent value."},`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json,"unknown_agent");let o=Bae(i,r.scope,t,k(e.hostVersion)??i.installEvidence.hostVersion??"unverified");if(!o)return E(`Guardian ${r.scope} hooks are not available for ${i.displayName}.`,e.json);let s=lz(t,r.scope),a=UM(Mu(t.cwd,o.hookPath)),l=UM(Mu(t.cwd,o.configPath)),c=await cz(s),u=c.hooks.find(m=>f(m,"agent")===i.id&&f(m,"scope")===r.scope),d=await Mae(o,t,u),p=[...c.hooks.filter(m=>f(m,"agent")!==i.id||f(m,"scope")!==r.scope),{hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:a.startsWith("..")?o.hookPath:a,configPath:l.startsWith("..")?o.configPath:l,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,hookFileOwnership:d.hookFileOwnership,...d.configEntryOwnership?{configEntryOwnership:d.configEntryOwnership}:{},...d.configEntryOwnerships?{configEntryOwnerships:d.configEntryOwnerships}:{},...d.activationConfigEntryOwnership?{activationConfigEntryOwnership:d.activationConfigEntryOwnership}:{},...d.configFileOwnership?{configFileOwnership:d.configFileOwnership}:{},absoluteCliPath:d.absoluteCliPath,hostVersion:o.hostVersion,adapterRevision:Hn(o.agent).adapterRevision,evidencePath:Uae(t,r.scope,o.agent,o.hostVersion),enabledAt:t.now()}];return await Ve(s,{version:1,hooks:p}),R({status:"enabled",hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:o.hookPath,configPath:o.configPath,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,agentCommandMatrix:KC({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json"}),nextStep:"Guardian is installed into the selected host configuration. Installed hooks route host pre-tool events through the internal Guardian hook runtime. `skills-layer guardian check` and MCP `guardian.check` remain diagnostic; use `skills-layer guardian exec` for atomic guarded shell execution, while supported hooks call MCP/Cloud `guardian.enforce` before a mapped tool action.",warnings:["This hook is installed as a candidate integration and is not counted as strict Guardian enforcement until a real agent/platform allow/deny canary proves the exact adapter, script, config, and CLI binding."]},"Guardian hook enabled.",e.json,t)}async function Qse(e,t){let n=k(e.scope),r=n?Qa(n):null;if(r?.status==="invalid")return E(r.message,e.json);let i=await qn(t,r?.status==="valid"?r.scope:void 0);return R(i,"Guardian status loaded.",e.json,t)}async function eae(e,t,n){let r=Qa(k(t.scope));if(r.status==="invalid")return E(r.message,t.json);let i=L(e[0]??t.skill,"guardian session bind requires a skill slug."),o=L(t.version,"guardian session bind requires --version."),s=k(t.agent);if(!s||!kr(s))return E("guardian session bind requires an agent with an implemented Guardian pre-tool adapter.",t.json);let a=L(t.hostVersion,"guardian session bind requires --host-version."),l=XU(k(t.guardianPreference)??k(t.mode));if(!l)return E("guardian session bind --mode must be enforce, warning-only, or disabled.",t.json);let c={version:1,scope:r.scope,skillSlug:i,skillVersion:o,...k(t.workspaceId)?{workspaceId:k(t.workspaceId)}:{},agentId:s,hostVersion:a,requestedPreference:l,boundAt:n.now()},u=YU(n,r.scope);return await Uo(Me(u),{recursive:!0,mode:448}),await Ve(u,c),await Ze(VP(n,r.scope),{force:!0}),R({status:"bound",binding:c,bindingPath:u,nextAction:"guardian.hook.run",nextStep:"Start the bound host session. The hook will obtain short-lived signed attribution for the exact Cloud generation."},"Guardian exact skill session bound.",t.json,n)}async function tae(e,t,n){let r=L(e[0]??t.skill,"guardian launch requires a skill slug."),i=Qa(k(t.scope));if(i.status==="invalid")return E(i.message,t.json);let o=k(t.agent);if(o!=="codex"&&o!=="kiro-cli")return x({status:"blocked",reasonCode:"guardian_approved_launcher_unavailable",skillSlug:r,agent:o,supportedLauncherAgents:["codex","kiro-cli"],nextAction:"guardian.status",nextStep:"Use a host with verified native activation, or use the managed launcher for Codex or Kiro CLI. Cline and Cursor IDE processes do not expose a trustworthy inherited-session launcher boundary."},"A trustworthy managed Guardian launcher is unavailable for this host.",t.json,"guardian_approved_launcher_unavailable");let s=e[1];if(!s)return E("guardian launch requires `-- <codex|kiro-cli> [arguments]`.",t.json);if(!(o==="codex"?new Set(["codex","codex.exe"]):new Set(["kiro","kiro-cli","kiro.exe","kiro-cli.exe"])).has(ot(s).toLowerCase()))return x({status:"blocked",reasonCode:"guardian_launcher_executable_mismatch",agent:o,executable:ot(s),nextAction:"guardian.launch",nextStep:`Launch the real ${o} executable after --; arbitrary commands cannot receive a Guardian launch token.`},"Guardian refused to pass managed-session authority to a different executable.",t.json,"guardian_launcher_executable_mismatch");let l=(await zi(n,r)).installs[r],c=Vn(l,{scope:i.scope,agent:o}).filter(N=>N.lifecycle?.state==="active");if(c.length!==1||!c[0].lifecycle)return x({status:"blocked",reasonCode:c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous",skillSlug:r,agent:o,scope:i.scope,matchingMaterializationCount:c.length,nextAction:"installed",nextStep:"Keep exactly one active exact materialization for this agent and scope before launching a guarded session."},"Guardian could not resolve one exact installed generation for the managed launch.",t.json,c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous");let u=c[0].lifecycle,d=await Tr(u.receipt);if(d.status!=="verified")return x({status:"blocked",reasonCode:d.reasonCode,skillSlug:r,agent:o,scope:i.scope,nextAction:"install",nextStep:"Repair or reinstall the exact generation before starting a managed Guardian session."},"Guardian refused to launch from a stale or changed local generation.",t.json,d.reasonCode);let p=await Xa({backend:n,skillSlug:r,agentId:o,scope:i.scope,flags:t,enforceRequired:!0});if(p)return p;let m=await qn(n,i.scope),h=(Be(m,"hooks")??[]).filter(j).find(N=>f(N,"agent")===o&&f(N,"scope")===i.scope&&N.active===!0&&N.strictPreActionBlocking===!0&&N.exactActivationVerified===!0);if(!h)return x({status:"blocked",reasonCode:"guardian_launcher_route_unavailable",agent:o,nextAction:"guardian.hook.status",nextStep:"Install and verify the Guardian activation route before launching."},"Guardian refused to launch because the verified hook route is unavailable.",t.json,"guardian_launcher_route_unavailable");let g=k(t.hostVersion)??f(h,"hostVersion")??"unverified",y;try{y=await iz(s,n,mr(n.platform))}catch(N){return E(ke(N),t.json)}let v=Ge(32).toString("base64url"),b=n.now(),w={version:1,launchId:`guardian_launch_${Ge(12).toString("hex")}`,tokenSha256:`sha256:${Ue("sha256").update(v,"utf8").digest("hex")}`,scope:i.scope,agentId:o,hostVersion:g,skillSlug:r,generationId:u.receipt.generation.generationId,receiptSha256:Hr(u.receipt),status:"pending",createdAt:b,expiresAt:new Date(Date.parse(b)+15*6e4).toISOString()};await uae(n,i.scope,w);let _=await new Promise((N,O)=>{let X=ZM(y,e.slice(2),{cwd:n.cwd,env:{...n.env,SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN:v,SKILLS_LAYER_GUARDIAN_LAUNCH_SCOPE:i.scope},stdio:"inherit"});X.once("error",O),X.once("exit",(G,ee)=>N({exitCode:G??1,signal:ee}))}).catch(async N=>{throw await TM(n,i.scope,w.launchId).catch(()=>{}),N}),P=(await ZU(n,i.scope)).launches[w.launchId]?.status==="associated";return await TM(n,i.scope,w.launchId).catch(()=>{}),R({status:P?"managed_session_completed":"host_exited_before_association",launchId:w.launchId,skillSlug:r,agent:o,scope:i.scope,generationId:w.generationId,hostExitCode:_.exitCode,hostSignal:_.signal,associationObserved:P,nextAction:"guardian.status",nextStep:P?"The one-time launch authority was consumed by the exact host session; inspect per-target Guardian status for the resulting association.":"The host exited before its hook completed an exact active Guardian association. The one-time authority was discarded and is not strict-session evidence."},P?"Managed Guardian host session completed.":"The managed host exited without an observed Guardian session association.",t.json,n)}async function nae(e,t){let n=Qa(k(e.scope)),r=k(e.agent);if(n.status==="invalid"||!r||!kr(r))return it(r&&kr(r)?r:"codex","deny","Guardian hook configuration is invalid.");let i=Ee(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!i||i.length>512*1024)return it(r,"deny","Guardian could not read the bounded host event.");let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return it(r,"deny","Guardian could not parse the host event.")}let s=wd(r,o);if(s)return await $M({agentId:r,scope:n.scope,observation:s,rawPayload:o,flags:e,backend:t});let a=GU(r,o);if(!a)return it(r,"deny","Guardian could not bind this event to the host session.");let l=Ee(t.env.SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN);if(l){let h=await dae(t,n.scope,l,r,t.now());if(!h)return it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token.");let g=h.launch;if(h.disposition==="associated"){let y;try{y=await Go(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let v=fl(y,{agentId:r,sessionId:a,asOf:t.now()}),b=v.associations.length===1?v.associations[0]:void 0;return!b||tt(b)!==g.associationKey?it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token."):await zP({agentId:r,scope:n.scope,lookup:v,rawPayload:o,backend:t})}return await $M({agentId:r,scope:n.scope,observation:{sessionId:a,skillReference:g.skillSlug,referenceKind:"slug",source:"approved_launcher",evidence:`approved-launcher:${g.launchId}`},expectedReceiptSha256:g.receiptSha256,expectedGenerationId:g.generationId,managedLaunchId:g.launchId,qualificationCandidate:g.qualificationOnly===!0,rawPayload:o,flags:e,backend:t})}let c;try{c=await Go(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let u=fl(c,{agentId:r,sessionId:a,asOf:t.now()});if(u.status!=="unrelated")return await zP({agentId:r,scope:n.scope,lookup:u,rawPayload:o,backend:t});let d=await be(YU(t,n.scope));if(!d||d.version!==1||d.agentId!==r)return await fae(t,n.scope,r)?it(r,"deny",`Guardian requires \`skills-layer guardian launch <skill> --agent ${r} --scope ${n.scope} -- <host>\` because this host has no trustworthy native skill-activation signal.`):it(r,"allow","No Skills Layer skill session is bound; unrelated host activity remains outside Guardian.");let p=await be(VP(t,n.scope));if(!oae(p,d,a,t.now()))try{let h=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:d.skillSlug,version:d.skillVersion,...d.workspaceId?{workspaceId:d.workspaceId}:{},agentId:r,platform:t.platform,hostVersion:d.hostVersion,sessionId:a,requestedPreference:d.requestedPreference})}),g=T(h,"envelope"),y=QU(h,"publicKeys");if(!g||!y)throw new Error("Guardian session authority returned an invalid envelope.");p={version:1,envelope:g,publicKeys:y,savedAt:t.now()},await Ve(VP(t,n.scope),p)}catch{return it(r,"deny","Guardian could not obtain current signed skill-session authority.")}await sae({binding:d,sessionId:a,cache:p,backend:t}).catch(()=>{});let m=await gy({agentId:r,platform:t.platform==="darwin"||t.platform==="linux"||t.platform==="win32"?t.platform:"linux",hostVersion:d.hostVersion,rawPayload:o,attributionEnvelope:p.envelope,attributionPublicKeys:p.publicKeys,now:t.now(),evaluate:async h=>VU(h,d,t)});return{exitCode:m.exitCode,stdout:m.stdout,stderr:m.stderr}}async function $M(e){let t;try{t=await aae(e.observation,e.agentId,e.backend)}catch(c){return Oi(e.agentId,e.observation,"deny",ke(c))}let n=Hr(t.receipt);if(e.expectedReceiptSha256&&e.expectedReceiptSha256!==n||e.expectedGenerationId&&e.expectedGenerationId!==t.receipt.generation.generationId)return Oi(e.agentId,e.observation,"deny","Guardian managed launch no longer matches the exact installed generation.");if(!t.workspaceId&&(t.requestedPreference===null||t.requestedPreference==="disabled"))return Oi(e.agentId,e.observation,"allow","Guardian is not enabled for this Personal skill; no runtime association was created.");let r=t.requestedPreference??"enforce",i=Hn(e.agentId),o=lae(e.agentId,e.rawPayload,e.flags)??"unverified",s=e.backend.now(),a={version:2,revision:1,state:"pending_authority",scope:e.scope,agentId:e.agentId,hostVersion:o,sessionId:e.observation.sessionId,skillSlug:t.skillSlug,skillVersion:t.receipt.generation.semanticVersion,generationId:t.receipt.generation.generationId,receiptSha256:n,...t.workspaceId?{workspaceId:t.workspaceId}:{},requestedPreference:r,activationSource:e.observation.source,activationEvidence:e.observation.evidence,adapterRevision:i.adapterRevision,createdAt:s,updatedAt:s},l;try{l=await JU(e.backend,e.scope,a)}catch{return Oi(e.agentId,e.observation,DM(a),"Guardian could not safely record this exact skill-session association.")}try{let c=await HU(l,e.backend),u=e.backend.now(),d=dl({envelope:c.cache.envelope,publicKeys:c.cache.publicKeys,expectedAgentId:e.agentId,expectedPlatform:mr(e.backend.platform),now:u});if(d.skillSlug!==l.skillSlug||d.version!==l.skillVersion||d.generationId!==l.generationId||d.sessionId!==l.sessionId||d.workspaceId!==l.workspaceId)throw new Error("Guardian Cloud authority did not match the exact local association.");let p=await qn(e.backend,e.scope),m=Be(p,"hooks")?.filter(j).find(_=>f(_,"agent")===e.agentId&&_.active===!0),h=l.requestedPreference==="warning_only"?"warning":l.requestedPreference,g=d.workspaceRequiredMode===null?null:{requiredMode:d.workspaceRequiredMode,revision:c.policyRevision,updatedBy:"skills-layer-cloud",updatedAt:d.issuedAt},y=rae({enabled:e.qualificationCandidate===!0,managedLaunchId:e.managedLaunchId,agentId:e.agentId,exactHook:m,env:e.backend.env}),v=vl({evaluationContext:"activation_eligibility",requestedMode:h,workspacePolicy:g,hostSupported:br(e.agentId)?.maximumTier==="strict_candidate",hookInstalled:!!m,strictHookVerified:y||m?.strictPreActionBlocking===!0,exactActivationVerified:y||m?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"pending_authority",materializationState:"active"});if(!v.activationAllowed)return await No(e.backend,e.scope,tt(l),{state:"stale",reasonCode:v.reasonCode,updatedAt:s}),Oi(e.agentId,e.observation,"deny",`Guardian refused activation because verified enforcement is unavailable (${v.reasonCode}).`);let b=await No(e.backend,e.scope,tt(l),{state:"active",trustLedgerId:c.trustLedgerId,attributionExpiresAt:d.expiresAt,updatedAt:u}),w=tt(b);return await vA(e.backend,e.scope,w,c.cache),!e.managedLaunchId&&cs(e.backend.env)==="missing_attribution"?(await No(e.backend,e.scope,w,{state:"stale",reasonCode:"phase149_missing_attribution_canary",updatedAt:u}),await gae(e.backend,e.scope,w),Oi(e.agentId,e.observation,"allow","Guardian qualification removed signed attribution after exact activation.")):(e.managedLaunchId&&await pae(e.backend,e.scope,e.managedLaunchId,w),await SE(e.backend.env),e.managedLaunchId?await zP({agentId:e.agentId,scope:e.scope,lookup:{status:"active",associations:[b]},rawPayload:e.rawPayload,backend:e.backend}):Oi(e.agentId,e.observation,"allow",v.label==="warning_only"?"Guardian warning-only activation is associated with this exact installed generation; it is not counted as strict enforcement.":"Guardian associated this host session with the exact installed generation."))}catch(c){return await No(e.backend,e.scope,tt(l),{state:"pending_authority",reasonCode:"guardian_session_authority_unavailable",updatedAt:s}).catch(()=>{}),Oi(e.agentId,e.observation,qP(c)?"deny":DM(l),l.requestedPreference==="warning_only"&&!l.workspaceId&&!qP(c)?"Guardian warning-only activation continued without runtime authority; protection is diagnostic only.":`Guardian could not establish exact skill-session authority (${ke(c)}).`)}}function rae(e){if(!e.enabled||!e.managedLaunchId?.startsWith("guardian_launch_phase149_")||br(e.agentId)?.automaticAssociation!=="approved_launcher_required"||e.exactHook?.active!==!0||e.exactHook.configActive!==!0||e.exactHook.evidenceCapability!=="unverified")return!1;let t=Be(e.exactHook,"evidenceReasons");return t?.length!==1||t[0]!=="live_canary_evidence_missing"?!1:cs(e.env)!==null}async function zP(e){if(e.lookup.status==="ambiguous")return it(e.agentId,"deny","Guardian found multiple active skill associations for this host session.");let t=e.lookup.associations[0];if(!t)return it(e.agentId,"deny","Guardian expected an exact association but could not load it.");if(e.lookup.status==="terminal")return it(e.agentId,"deny","Guardian blocked a session whose exact skill was removed or detached.");if(e.lookup.status==="expected_missing_authority")return it(e.agentId,t.requestedPreference==="warning_only"&&!t.workspaceId?"allow":"deny",t.requestedPreference==="warning_only"&&!t.workspaceId?"Guardian warning only: exact runtime authority is missing; this is not strict enforcement.":"Guardian blocked an expected skill session because exact runtime authority is missing.");let n=await cae(t,e.backend);if(n.status!=="verified")return await No(e.backend,e.scope,tt(t),{state:n.state,reasonCode:n.reasonCode,updatedAt:e.backend.now()}).catch(()=>{}),it(e.agentId,"deny","Guardian blocked this session because the exact installed generation is no longer current.");let r=await hae(e.backend,e.scope,tt(t));if(e.lookup.status==="active_authority_stale"||!yae(r,t,e.backend.now()))try{let a=await HU(t,e.backend);r=a.cache;let l=dl({envelope:r.envelope,publicKeys:r.publicKeys,expectedAgentId:e.agentId,expectedPlatform:mr(e.backend.platform),now:e.backend.now()});await No(e.backend,e.scope,tt(t),{state:"active",trustLedgerId:a.trustLedgerId,attributionExpiresAt:l.expiresAt,updatedAt:e.backend.now()}),await vA(e.backend,e.scope,tt(t),r)}catch(a){let l=t.requestedPreference==="warning_only"&&!t.workspaceId&&!qP(a);return it(e.agentId,l?"allow":"deny",l?"Guardian warning only: signed runtime authority could not be refreshed.":"Guardian blocked this action because signed runtime authority could not be refreshed.")}let i={version:1,scope:t.scope,skillSlug:t.skillSlug,skillVersion:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},agentId:e.agentId,hostVersion:t.hostVersion,requestedPreference:t.requestedPreference,boundAt:t.createdAt},o=!1,s=await gy({agentId:e.agentId,platform:mr(e.backend.platform),hostVersion:t.hostVersion,rawPayload:e.rawPayload,attributionEnvelope:r.envelope,attributionPublicKeys:r.publicKeys,now:e.backend.now(),evaluate:async a=>{let l=await VU(a,i,e.backend);return o=l.delegatedExecution===!0,l}});return o&&await xE({agentId:e.agentId,scope:e.scope,skillSlug:t.skillSlug,associationKey:tt(t),env:e.backend.env}),{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr,...o?{[UU]:!0}:{}}}async function VU(e,t,n){if(e.action.actionFamily==="shell_execution"||e.action.actionFamily==="generated_code_execution"){let i=await qn(n,t.scope),o=(Be(i,"hooks")??[]).filter(j).find(c=>f(c,"agent")===t.agentId&&f(c,"scope")===t.scope&&c.active===!0&&c.configActive===!0&&typeof f(c,"absoluteCliPath")=="string"),s=o?f(o,"absoluteCliPath"):void 0,a=cs(n.env)?IE:void 0;if(s&&e.action.command&&PE({command:e.action.command,cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:mr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}))return{decision:"allow",reason:"Guardian delegated this exact shell action to the atomic guarded execution wrapper.",delegatedExecution:!0};let l=s?AE({cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:mr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}):null;return{decision:"deny",reason:l&&l.length<=800?`Use the exact guarded command prefix: ${l} <command>`:"Use the exact Skills Layer Guardian execution wrapper for one-action guarded shell or generated-code execution."}}let r=iae(e);if(r.length===0)return{decision:"deny",reason:"Guardian has no exact action mapping for this host event."};for(let i of r){let o=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({skillSlug:t.skillSlug,version:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},guardianPreference:t.requestedPreference,telemetryMode:(t.workspaceId,"cloud_managed"),action:i})});if(T(o,"enforcement")?.canExecute!==!0)return{decision:"deny",reason:`Guardian denied this exact action (${Eh(o)}).`}}return{decision:"allow",reason:"Guardian allowed the exact attributed host action."}}function iae(e){let t={strictActionSha256:e.actionSha256,toolInputSha256:e.action.toolInputSha256,adapterRevision:e.adapterRevision,host:e.action.host};switch(e.action.actionFamily){case"filesystem_read":case"filesystem_write":return e.action.fileTargets.map(n=>({type:e.action.actionFamily==="filesystem_read"?"file_read":"file_write",path:n,metadata:t}));case"network_access":return e.action.networkTargets.map(n=>({type:"network_request",url:n,metadata:t}));case"browser_access":return[{type:"browser_action",target:e.action.toolName,metadata:t}];case"device_control":return[{type:"device_action",target:e.action.toolName,metadata:t}];case"api_access":return[{type:"api_call",target:e.action.toolName,metadata:t}];default:return[]}}function it(e,t,n){let r=rs(e,{decision:t,reason:n});return{exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}}function GU(e,t){if(!j(t))return null;let n=e==="cline"?t.taskId:e==="cursor"?t.conversation_id:e==="windsurf"?t.trajectory_id:e==="antigravity"||e==="antigravity-cli"?t.conversationId:t.session_id;return typeof n=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(n)?n:null}function oae(e,t,n,r){if(!e||e.version!==1||!j(e.envelope)||!j(e.envelope.claims))return!1;let i=e.envelope.claims;return i.agentId===t.agentId&&i.sessionId===n&&i.skillSlug===t.skillSlug&&i.version===t.skillVersion&&i.workspaceId===t.workspaceId&&typeof i.expiresAt=="string"&&Date.parse(i.expiresAt)>Date.parse(r)+5e3}async function sae(e){let t=(await lt(e.backend)).installs[e.binding.skillSlug],n=Vn(t,{scope:e.binding.scope,agent:e.binding.agentId}).filter(a=>a.lifecycle?.receipt.generation.semanticVersion===e.binding.skillVersion),r=n.length===1?n[0].lifecycle:null;if(!r||r.state!=="active"||r.receipt.generation.semanticVersion!==e.binding.skillVersion||(await Tr(r.receipt)).status!=="verified")return;let o=dl({envelope:e.cache.envelope,publicKeys:e.cache.publicKeys,expectedAgentId:e.binding.agentId,expectedPlatform:mr(e.backend.platform),now:e.backend.now()});if(o.sessionId!==e.sessionId||o.generationId!==r.receipt.generation.generationId||o.skillSlug!==e.binding.skillSlug||o.version!==e.binding.skillVersion)return;let s=await JU(e.backend,e.binding.scope,{version:2,revision:1,state:"active",scope:e.binding.scope,agentId:e.binding.agentId,hostVersion:e.binding.hostVersion,sessionId:e.sessionId,skillSlug:e.binding.skillSlug,skillVersion:e.binding.skillVersion,generationId:r.receipt.generation.generationId,receiptSha256:Hr(r.receipt),...e.binding.workspaceId?{workspaceId:e.binding.workspaceId}:{},requestedPreference:e.binding.requestedPreference,activationSource:"manual_recovery",activationEvidence:`legacy-bind:${e.binding.boundAt}`,adapterRevision:Hn(e.binding.agentId).adapterRevision,trustLedgerId:e.cache.envelope.version===2?e.cache.envelope.claims.trustLedgerId:"legacy_local",attributionExpiresAt:o.expiresAt,createdAt:e.binding.boundAt,updatedAt:e.backend.now()});await vA(e.backend,e.binding.scope,tt(s),e.cache)}async function aae(e,t,n){let r=await lt(n),i=Object.entries(r.installs).flatMap(([u,d])=>Rn(d).flatMap(p=>{let m=p.lifecycle;if(!m||m.state!=="active")return[];if(!gr(p.record).includes(t))return[];if(e.referenceKind==="slug"){if(e.skillReference!==u&&e.skillReference!==m.receipt.generation.skillSlug)return[]}else{let h=Vo(m.receipt.targetDir),g=Vo(e.skillReference),y=Mu(h,g);if(y.startsWith("..")||st.isAbsolute(y)||Lt.isAbsolute(y))return[]}return[{skillSlug:u,record:hr(d,p),lifecycle:m}]}));if(i.length!==1)throw new Error(i.length===0?"Guardian activation did not resolve to an owned exact installed generation.":"Guardian activation matched more than one installed generation.");let o=i[0],s=await Tr(o.lifecycle.receipt);if(s.status!=="verified")throw new Error(`Guardian activation receipt verification failed (${s.reasonCode}).`);let a=f(o.record,"workspaceId")??f(o.record,"workingModeWorkspaceId"),l=await id(n,o.skillSlug),c=l===void 0?a?"enforce":null:XU(l);if(l!==void 0&&c===null)throw new Error("Guardian activation preference is invalid.");return{skillSlug:o.skillSlug,record:o.record,receipt:o.lifecycle.receipt,requestedPreference:c,...a?{workspaceId:a}:{}}}async function HU(e,t){let n=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:e.skillSlug,version:e.skillVersion,...e.workspaceId?{workspaceId:e.workspaceId}:{},agentId:e.agentId,platform:mr(t.platform),hostVersion:e.hostVersion,sessionId:e.sessionId,requestedPreference:e.requestedPreference})}),r=T(n,"envelope"),i=QU(n,"publicKeys"),o=T(n,"ledger"),s=o?f(o,"ledgerId"):void 0;if(!r||!i||!s)throw new Error("Guardian session authority returned an invalid exact-generation envelope.");return{cache:{version:1,envelope:r,publicKeys:i,savedAt:t.now()},trustLedgerId:s,policyRevision:r.version===2?r.claims.policyRevision:1}}function DM(e){return e.requestedPreference==="warning_only"&&!e.workspaceId?"allow":"deny"}function qP(e){return e instanceof Z?e.status<500:!ke(e).startsWith("Unable to reach ")}function Oi(e,t,n,r){return t.source==="claude_user_prompt_expansion"?n==="deny"?{exitCode:2,stdout:"",stderr:r}:{exitCode:0,stdout:"",stderr:""}:it(e,n,r)}function lae(e,t,n){let r=k(n.hostVersion);if(r)return r;if(!j(t))return null;let i=e==="cline"?t.clineVersion:e==="cursor"?t.cursor_version:t.host_version;return typeof i=="string"&&/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u.test(i)?i:null}function mr(e){return e==="darwin"||e==="win32"?e:"linux"}async function cae(e,t){let n=(await lt(t)).installs[e.skillSlug],r=Vn(n,{receiptSha256:e.receiptSha256}),i=r.length===1?r[0].lifecycle:null;if(!i)return{status:"invalid",state:"externally_removed",reasonCode:"exact_install_record_absent"};if(i.receipt.generation.semanticVersion!==e.skillVersion||i.receipt.generation.generationId!==e.generationId||Hr(i.receipt)!==e.receiptSha256)return{status:"invalid",state:"stale",reasonCode:"exact_generation_replaced"};try{await Qu(i.receipt.targetDir)}catch(s){return s.code==="ENOENT"?{status:"invalid",state:"externally_removed",reasonCode:"exact_target_absent"}:{status:"invalid",state:"stale",reasonCode:"exact_target_unreadable"}}let o=await Tr(i.receipt);return o.status==="verified"?{status:"verified"}:{status:"invalid",state:"stale",reasonCode:o.reasonCode}}function KU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-associations.json"):K(e.cwd,".skills-layer","guardian-session-associations.json")}function WU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-managed-launches.json"):K(e.cwd,".skills-layer","guardian-managed-launches.json")}async function ZU(e,t){let n=await be(WU(e,t));if(!j(n)||n.version!==1||!Number.isSafeInteger(n.revision)||Number(n.revision)<0||!j(n.launches))return{version:1,revision:0,launches:{}};let r=Object.fromEntries(Object.entries(n.launches).flatMap(([i,o])=>{if(!j(o))return[];let s=f(o,"agentId"),a=f(o,"scope"),l=f(o,"tokenSha256"),c=f(o,"receiptSha256"),u=f(o,"status"),d=o;return d.version!==1||d.launchId!==i||s!=="codex"&&s!=="kiro-cli"||a!==t||!l||!/^sha256:[a-f0-9]{64}$/u.test(l)||!c||!/^sha256:[a-f0-9]{64}$/u.test(c)||u!=="pending"&&u!=="claimed"&&u!=="associated"||o.qualificationOnly!==void 0&&o.qualificationOnly!==!0||!f(o,"hostVersion")||!f(o,"skillSlug")||!f(o,"generationId")||u==="associated"&&!f(o,"associationKey")||!f(o,"createdAt")||!f(o,"expiresAt")||!Number.isFinite(Date.parse(d.createdAt))||!Number.isFinite(Date.parse(d.expiresAt))?[]:[[i,d]]}));return{version:1,revision:Number(n.revision),launches:r}}async function nd(e,t,n){let r=WU(e,t);await Jo(Me(r));let i=`${r}.lock`,o=null;for(let s=0;s<50&&!o;s+=1)try{o=await zo(i,"wx",384)}catch(a){if(a.code!=="EEXIST"||s===49)throw a;await e.sleep(10)}if(!o)throw new Error("Guardian managed launch lock is unavailable.");try{let s=await ZU(e,t),a=n(s);return await rd(r,a.store),a.value}finally{await o.close().catch(()=>{}),await Ze(i,{force:!0}).catch(()=>{})}}async function uae(e,t,n){await nd(e,t,r=>({store:{version:1,revision:r.revision+1,launches:{...r.launches,[n.launchId]:n}},value:void 0}))}async function TM(e,t,n){await nd(e,t,r=>{let i={...r.launches};return delete i[n],{store:{version:1,revision:r.revision+1,launches:i},value:void 0}})}async function dae(e,t,n,r,i){if(n.length<32||n.length>256||!/^[A-Za-z0-9_-]+$/u.test(n))return null;let o=`sha256:${Ue("sha256").update(n,"utf8").digest("hex")}`;return await nd(e,t,s=>{let a=Object.values(s.launches).filter(d=>(d.status==="pending"||d.status==="associated")&&d.tokenSha256===o&&d.agentId===r&&(d.status==="associated"||Date.parse(d.expiresAt)>Date.parse(i))),l=a.length===1?a[0]:void 0,c=l?.status==="pending"?{...l,status:"claimed"}:l,u=Object.fromEntries(Object.entries(s.launches).flatMap(([d,p])=>p.status!=="associated"&&Date.parse(p.expiresAt)<=Date.parse(i)?[]:[[d,p.launchId===c?.launchId?c:p]]));return{store:{version:1,revision:s.revision+1,launches:u},value:c?{disposition:l?.status==="pending"?"claimed":"associated",launch:c}:null}})}async function pae(e,t,n,r){await nd(e,t,i=>{let o=i.launches[n];if(!o||o.status!=="claimed")throw new Error("Guardian managed launch is not in the claimed state.");return{store:{version:1,revision:i.revision+1,launches:{...i.launches,[n]:{...o,status:"associated",associationKey:r}}},value:void 0}})}async function fae(e,t,n){if(br(n)?.automaticAssociation!=="approved_launcher_required")return!1;let r=await lt(e);for(let[i,o]of Object.entries(r.installs)){let s=Vn(o,{scope:t,agent:n});for(let a of s){if(a.lifecycle?.state!=="active"&&a.lifecycle?.state!=="pending_activation")continue;let l=hr(o,a);if(f(l,"workspaceId")??f(l,"workingModeWorkspaceId"))return!0;let u=await id(e,i);if(u==="enforce"||u==="enabled")return!0}}return!1}function jh(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-authorities.json"):K(e.cwd,".skills-layer","guardian-session-authorities.json")}async function Go(e,t){let n=await be(KU(e,t));return n===null?rE():iE(n)}async function yA(e,t,n){let r=KU(e,t);await Jo(Me(r));let i=`${r}.lock`,o=null;try{o=await zo(i,"wx",384);let s=await Go(e,t),a=n(s);return await rd(r,a.index),a.value}finally{await o?.close().catch(()=>{}),await Ze(i,{force:!0}).catch(()=>{})}}async function JU(e,t,n){return await yA(e,t,r=>{let i=oE(r,n,r.revision),o=i.associations[tt(n)];return{index:i,value:o}})}async function No(e,t,n,r){return await yA(e,t,i=>{let o=sE(i,{key:n,expectedIndexRevision:i.revision,...r});return{index:o,value:o.associations[n]}})}async function mae(e,t){let n=0;for(let r of["project","global"]){let i=await yA(e,r,o=>{let s=aE(o,{...t,expectedIndexRevision:o.revision});return{index:s.index,value:s.removedKeys}});if(n+=i.length,i.length>0){let o=jh(e,r),s=await Nh(e,r),a=new Set(i);await rd(o,{version:1,revision:s.revision+1,authorities:Object.fromEntries(Object.entries(s.authorities).filter(([l])=>!a.has(l)))})}await nd(e,r,o=>({store:{version:1,revision:o.revision+1,launches:Object.fromEntries(Object.entries(o.launches).filter(([,s])=>s.skillSlug!==t.skillSlug||s.generationId!==t.generationId||s.receiptSha256!==t.receiptSha256))},value:void 0}))}return n}async function Nh(e,t){let n=await be(jh(e,t));return!j(n)||n.version!==1||!Number.isSafeInteger(n.revision)||!j(n.authorities)?{version:1,revision:0,authorities:{}}:{version:1,revision:Number(n.revision),authorities:Object.fromEntries(Object.entries(n.authorities).filter(r=>{let i=r[1];return j(i)&&i.version===1&&j(i.envelope)&&j(i.publicKeys)&&typeof i.savedAt=="string"}))}}async function vA(e,t,n,r){let i=jh(e,t),o=await Nh(e,t);await rd(i,{version:1,revision:o.revision+1,authorities:{...o.authorities,[n]:r}})}async function gae(e,t,n){let r=jh(e,t),i=await Nh(e,t),o={...i.authorities};delete o[n],await rd(r,{version:1,revision:i.revision+1,authorities:o})}async function hae(e,t,n){return(await Nh(e,t)).authorities[n]??null}function yae(e,t,n){if(!e||e.version!==1||!j(e.envelope)||!j(e.envelope.claims))return!1;let r=e.envelope.claims;return r.agentId===t.agentId&&r.sessionId===t.sessionId&&r.skillSlug===t.skillSlug&&r.version===t.skillVersion&&r.generationId===t.generationId&&r.workspaceId===t.workspaceId&&typeof r.expiresAt=="string"&&Date.parse(r.expiresAt)>Date.parse(n)+5e3}async function rd(e,t){let n=Me(e);await Jo(n);let r=K(n,`.${ot(e)}.${Ge(12).toString("hex")}.tmp`),i=null;try{i=await zo(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
2180
+ `))}function hP(e,t){return x({status:"not_found_or_forbidden",reasonCode:"workspace_not_found_or_forbidden",workspaceId:e,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` to find a workspace you can access, then retry with that workspace id."},`Workspace ${e} was not found or you do not have access. Run \`skills-layer workspace list\` to inspect accessible workspaces.`,t.json,"workspace_not_found_or_forbidden")}function CM(e,t,n){let r={status:"approval_not_found",reasonCode:"workspace_skill_approval_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.approve",nextStep:`Run \`skills-layer workspace approve ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the approval exists.`};return x(r,`Workspace approval not found for ${t}. Run \`skills-layer workspace approve ${e} ${t}\` first.`,n.json,"workspace_skill_approval_not_found")}function IM(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="workspace_skill_approval_not_found"||r.includes("workspace")&&r.includes("approval")&&r.includes("not found")}function Nse(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="skill_not_found"||r.includes("skill")&&r.includes("not found")}function Fse(e,t,n,r){let i=r.details??{},o={status:"not_found",reasonCode:"skill_not_found",workspaceId:e,skillSlug:t,nextAction:"search",nextStep:f(i,"nextStep")??`Run \`skills-layer search ${t}\` to find the public skill before approving it for workspace ${e}.`};return x(o,`Skill ${t} was not found. Run \`skills-layer search ${t}\` before approving it for the workspace.`,n.json,"skill_not_found")}async function Bse(e,t,n){let r=L(e[0],"buy requires a skill slug."),i=Hie(t);if(i.failure)return i.failure;if(k(t.workspace))return x({reasonCode:"invalid_input"},"buy does not support --workspace; use skills-layer enterprise skill buy <enterprise-id> <skill-slug>.",t.json,"invalid_input");let o=await sA(n,{skillSlug:r,paymentMethod:i.value},t,"/api/v1/buy");if(fe(o))return o;if(o.status==="already_owned")return R(o,`You already own ${r}. Run \`skills-layer install ${r}\` to install or update it.`,t.json,n);if(t.noOpen&&o.status==="checkout_required"&&typeof o.checkoutUrl=="string")return R({...o,nextAction:"open_checkout_url",nextStep:`Open ${o.checkoutUrl} to complete payment, then run skills-layer install ${r}.`},`Payment is required for ${r}.`,t.json,n);if(t.json||t.noOpen||o.status!=="checkout_required"||typeof o.checkoutUrl!="string"||typeof o.purchaseId!="string")return R(o,`Purchase flow started for ${r}.`,t.json,n);n.emitInfo(`Opening checkout for ${r}. Complete the payment in your browser, then come back here.`),await n.openUrl(o.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${o.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let a=await ole(o.purchaseId,n);return fe(a)?a:a.status!=="succeeded"?R({...o,purchaseStatus:a.status},`Checkout is still ${a.status} for ${r}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await Za([r],t,n,{origin:"post_purchase",fallbackPolicy:"account_required"}))}async function Mse(e,t,n){let r=e[0]??"list";if(r==="list")return await he("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(r==="spending")return await he("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let i=L(e[1],`purchases ${r} requires a purchase id.`);if(r==="status")return await he(`/api/v1/purchases/${encodeURIComponent(i)}`,t,n,"Purchase status loaded.",{authenticated:!0});if(r==="invoice")return await he(`/api/v1/purchases/${encodeURIComponent(i)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0});if(r==="refund-quote"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund-quote`,{headers:ne(n.apiKey,n.authBlockedMessage)}),s=j(o.quote)?o.quote:o,a=l=>typeof l=="number"?`USD ${(l/100).toFixed(2)}`:"unavailable";return R(o,`Refundable: ${a(s.refundableAmountCents)}. Non-refundable: ${a(s.nonRefundableAmountCents)}. Refund window ends: ${String(s.refundWindowEndsAt??"unavailable")}.`,t.json,n)}if(r==="refund"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(Ft(t,["reason"]))}),s=o.status==="refunded"?await td(t,n):{warnings:[]};return R({...o,warnings:[...s.warnings,"Manually copied folders cannot be removed automatically; other machines check on sync, installed or update."]},o.status==="refunded"?"Refund completed.":"Refund requested.",t.json,n)}return E(`Unknown purchases command "${r}".`,t.json)}function MU(e,t,n,r){let i=typeof e.amountCents=="number"?` (USD ${(e.amountCents/100).toFixed(2)})`:"";return R({...e,status:"action_required",reasonCode:"purchase_required",nextAction:"buy",nextStep:`skills-layer buy ${t}`},`Purchase required${i}. Run \`skills-layer buy ${t}\`.`,n.json,r)}async function Use(e,t,n){let r=e[0];if(r==="search"){let i=new URLSearchParams;return We(i,"query",e.slice(1).join(" ").trim()||k(t.query)),We(i,"limit",k(t.limit)),await he(`/api/v1/me/search${Qe(i)}`,t,n,"Authenticated library search complete.",{authenticated:!0})}if(r==="add"){let i=L(e[1],"library add requires a skill slug."),o=await sA(n,{skillSlug:i},t);return fe(o)?o:o.status==="purchase_required"?MU(o,i,t,n):R(o,"Skill added to library.",t.json,n)}return E(`Unknown library command "${r}".`,t.json)}async function zse(e,t,n){let r=L(e[0],"export requires a skill slug.");if(t.showUrl&&k(t.output))return x({status:"error",reasonCode:"conflicting_export_output",nextAction:"export",nextStep:"Use either --show-url to inspect the signed URL or --output <file> to download the bundle, not both."},"export cannot use --show-url and --output together.",t.json,"conflicting_export_output");let i=new URLSearchParams,o=k(t.version);if(o&&!Lh(o))return iA("export",o,t);We(i,"version",o);let s=await D(n,`/api/v1/me/library/${encodeURIComponent(r)}/export${Qe(i)}`,{headers:ne(n.apiKey,n.authBlockedMessage)}),a=k(t.output);if(a){let l=await Ih({backend:n,exportResult:s,flags:t,skillSlug:r});if(fe(l))return l;let c=Tt(n.cwd,a);await EA(c,l.bytes);let u={...s};return delete u.downloadUrl,R({...u,archiveSha256:l.archiveSha256,archiveSha256Meaning:"artifact_v1_exact_zip_bytes_sha256",downloadedArchiveSha256:l.archiveBytesSha256,downloadedFileSha256:l.archiveBytesSha256,archiveHashFormat:l.archiveHashFormat,generationId:l.envelope.generation.generationId,manifestSha256:l.envelope.manifest.sha256,outputPath:c,downloaded:!0},`Exported ${r} to ${c}. Downloaded file SHA-256: ${l.archiveBytesSha256}.`,t.json,n)}return R(s,a?`Exported ${r} to ${a}.`:"Export prepared.",t.json,n)}async function PM(e,t,n,r){if(e==="show"){let a=t[0]?.trim(),l=a?`?skillSlug=${encodeURIComponent(a)}`:"";return await he(`/api/v1/me/library/reviews${l}`,n,r,"Reviews loaded.",{authenticated:!0})}let i=L(t[0],"add-review requires a skill slug."),o=L(n.rating,"add-review requires --rating.");if(!/^[1-5]$/u.test(o))return x({status:"error",reasonCode:"invalid_rating",rating:o,acceptedValues:["1","2","3","4","5"],nextAction:"add-review",nextStep:"Use --rating with a whole number from 1 to 5."},`Invalid review rating "${o}". Use a whole number from 1 to 5.`,n.json,"invalid_rating");let s=Ft(n,["rating","feedback"]);if(typeof n.evalSummary=="string"){let a=await be(Vo(r.cwd,n.evalSummary));if(a===null)return x({status:"error",reasonCode:"invalid_eval_summary_file",path:n.evalSummary,nextAction:"add-review",nextStep:"Pass --eval-summary with a readable JSON redacted eval summary envelope."},`Could not read eval summary JSON from ${n.evalSummary}.`,n.json,"invalid_eval_summary_file");s.evalSummary=a}return await Le(`/api/v1/me/library/${encodeURIComponent(i)}/review`,s,n,r,"Review added.")}async function AM(e,t,n,r){let i=L(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await he(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});L(n.message,"add-issue requires --message.");let o=pr("add-issue","issueType",n.issueType,Rie,n,"invalid_issue_type","issue-type");return o||await Le(`/api/v1/me/library/${encodeURIComponent(i)}/report-issue`,Ft(n,["issueType","message"]),n,r,"Issue reported.")}async function qse(e,t,n){let r=e[0];if(r==="hook"){let i=e[1];if(i==="install")return await qU(t,n);if(i==="status")return await Qse(t,n);if(i==="run"){let o=await nae(t,n),s=k(t.agent);if(s&&kr(s)){let a=cs(n.env);await Sy({agentId:s,associationState:a?await Gse(s,t,n):"unreadable",activationEvent:a?await Kse(s,n):!1,delegatedExecution:o[UU]===!0,env:n.env,rawPayloadBase64:Ee(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64),result:o})}return o}return E(`Unknown guardian hook command "${i??""}".`,t.json)}if(r==="session"){let i=e[1];return i==="bind"?await eae(e.slice(2),t,n):E(`Unknown guardian session command "${i??""}".`,t.json)}if(r==="enable")return e[1]||t.skill?await yP("enforce",e,t,n):E("guardian enable requires a skill slug.",t.json);if(r==="disable")return await yP("disabled",e,t,n);if(r==="enable-warnings-only")return await yP("warning_only",e,t,n);if(r==="status")return await Zse(e,t,n);if(r==="launch")return await tae(e.slice(1),t,n);if(r==="exec")try{let i=await Wse(e,t,n);return await RM(i,e,t,n),i}catch(i){throw await RM({exitCode:1,stdout:"",stderr:ke(i)},e,t,n),i}if(r==="check"){let i=L(e[1]??t.skill,"guardian check requires a skill slug.");if((await td({...t,dryRun:!0},n,i)).revokedSlugs.includes(i))return R({status:"blocked",decision:"block",reasonCode:"entitlement_revoked_refunded",skillSlug:i,nextStep:`Run skills-layer remove ${i}, or buy it again.`},"This skill was refunded; execution is blocked.",t.json,n);let s=zM(t,"check");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.approval.prepare",nextStep:"Use an authenticated one-action approval or `skills-layer guardian exec` for shell execution."},"Guardian enforcement does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let a=Ece(t.cloudTrustLedger);if(a.status==="invalid")return E(a.message,t.json);let l=GP(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(l.status==="invalid")return E(l.message,t.json);let c=await tz({skillSlug:i,version:k(t.version),action:s,flags:t,backend:n,telemetryMode:l.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=k(t.version)??c.context.version,p=ie({skillSlug:i,version:d,action:s,path:u,guardianPreference:await id(n,i),unmanagedPolicy:c.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:l.mode,localPreflight:Vu(c.context)}),m=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(p)});return await Ha(n,{skillSlug:i,version:d,action:s,decisionStatus:KP(m),reasonCode:Eh(m),telemetryMode:l.mode,path:u,authority:m}),R({...m,localPreflight:Vu(c.context)},"Guardian check complete.",t.json,n)}if(r==="incident"){let i=L(e[1]??t.skill,"guardian incident requires a skill slug."),o=L(t.version,"guardian incident requires --version."),s=GP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return E(s.message,t.json);let a=k(t.path);if(a&&!await fr(Tt(n.cwd,a)))return x({status:"error",reasonCode:"invalid_incident_path",path:a,nextAction:"guardian.incident",nextStep:"Use --path with an installed skill directory, or omit --path so Skills Layer resolves the local install record."},`Guardian incident path does not exist: ${a}`,t.json,"invalid_incident_path");let l=a??(await nz({skillSlug:i,flags:t,backend:n})).installedPath,c=zM(t,"incident"),u=cn(t.evidenceJson,"evidence-json"),d=s.mode==="cloud_managed"&&!n.apiKey?"local_only":s.mode,p=n.now(),m=ie({skillSlug:i,version:o,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:k(t.reason),generatedAt:p,...d==="cloud_managed"?{incidentIdempotencyKey:fle()}:{}});if(d==="local_only"){if(!l)return E("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let v=await FM({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian local-only incident"});if(f(v,"status")!=="quarantined"){let w=f(v,"reasonCode")??"guardian_exact_quarantine_failed";return x(v,`Guardian could not physically quarantine the exact installed generation for ${i}.`,t.json,w)}await Ha(n,{skillSlug:i,version:o,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:l});let b=BM(n,i);return await KM(b,JSON.stringify({request:m,response:null,localResponse:v,savedAt:n.now()},null,2)),R({status:"written",skillSlug:i,version:o,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:v,incidentStatePath:b,incidentPath:v.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let h=await mle(n,m),g=l?await FM({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian Cloud-managed incident"}):null;if(g&&f(g,"status")!=="quarantined"){let v=f(g,"reasonCode")??"guardian_exact_quarantine_failed";return x({...g,cloudResponse:h},`Guardian recorded the Cloud incident but could not physically quarantine the exact local generation for ${i}.`,t.json,v)}await Uo(n.paths.incidentsDir,{recursive:!0});let y=BM(n,i);return await KM(y,JSON.stringify({request:m,response:h,localResponse:g,savedAt:n.now()},null,2)),await Ha(n,{skillSlug:i,version:o,action:c,decisionStatus:KP(h),reasonCode:Eh(h),telemetryMode:s.mode,path:l,authority:h}),R({...h,telemetryMode:s.mode,localResponse:g,incidentPath:y},"Guardian incident recorded.",t.json,n)}return E(`Unknown guardian command "${r??""}".`,t.json)}var UU=Symbol("guardian-delegated-execution");async function RM(e,t,n,r){if(!cs(r.env))return;let i=r.env.SKILLS_LAYER_GUARDIAN_CANARY_AGENT_ID,o=r.env.SKILLS_LAYER_GUARDIAN_CANARY_SCOPE;if(!i||!kr(i)||o!=="project"&&o!=="global")return;let s=k(n.skill)??t[1];s&&await Sy({agentId:i,associationState:await Vse(i,o,s,r),activationEvent:!1,env:r.env,rawPayloadBase64:Buffer.from(JSON.stringify({positionals:t,json:n.json})).toString("base64url"),reportingSource:"guarded_execution",result:e})}async function Vse(e,t,n,r){let i=await CE({agentId:e,scope:t,skillSlug:n,env:r.env});if(!i)return"unreadable";try{let o=await Go(r,t),s=o.associations[i.associationKey];if(!s||s.agentId!==e||s.scope!==t||s.skillSlug!==n)return"missing";let a=fl(o,{agentId:e,sessionId:s.sessionId,asOf:r.now()});return a.associations.some(c=>tt(c)===i.associationKey)?a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="terminal"?"terminal":a.status==="ambiguous"?"ambiguous":"missing":"missing"}catch{return"unreadable"}}async function Gse(e,t,n){let r=Qa(k(t.scope));return r.status==="invalid"?"unreadable":await Hse(e,r.scope,n)}async function Hse(e,t,n){let r=Ee(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!r)return"unreadable";let i;try{i=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{return"unreadable"}let o=wd(e,i)?.sessionId??GU(e,i);if(!o)return"unreadable";try{let s=await Go(n,t),a=fl(s,{agentId:e,sessionId:o,asOf:n.now()});return a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="unrelated"||a.status==="expected_missing_authority"?"missing":a.status}catch{return"unreadable"}}async function Kse(e,t){let n=Ee(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!n)return!1;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return wd(e,r)!==null}catch{return!1}}async function Wse(e,t,n){let r=k(t.skill),i=L(r??e[1],"guardian exec requires a skill slug."),o=r?e.slice(1):e.slice(2);if(o.length===0)return E("guardian exec requires a command after --.",t.json);if(t.actionJson!==void 0)return x({status:"error",reasonCode:"caller_supplied_execution_action_rejected",nextAction:"guardian.execution.prepare",nextStep:"Guardian derives the canonical shell action from the exact command and execution plan."},"Guardian guarded execution does not accept a caller-authored action.",t.json,"caller_supplied_execution_action_rejected");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.execution.prepare",nextStep:"Use the authenticated atomic Guardian execution prepare flow."},"Guardian guarded execution does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let s=GP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return E(s.message,t.json);let a=LM(o),l=await tz({skillSlug:i,version:k(t.version),action:a,flags:t,backend:n,telemetryMode:s.mode});if(l.status!=="ok")return l.result;let c=l.context.installedPath,u=k(t.version)??l.context.version;if(!u)return x({status:"blocked",reasonCode:"guardian_exact_version_required",skillSlug:i,nextStep:"Install the skill through Skills Layer or pass its exact --version before guarded execution."},"Guardian guarded execution requires an exact installed skill version.",t.json,"guardian_exact_version_required");let d=await Pae({commandArgs:o,skillSlug:i,version:u,flags:t,backend:n,localContext:l.context});if(d.status==="blocked")return d.result;let p=LM(o,d.request),m=await D(n,"/api/v1/guardian/execution/prepare",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({request:d.request,...t.dryRun?{dryRun:!0}:{}})}),h=typeof f(m,"token")=="string"&&T(m,"plan")!==void 0&&T(m,"binding")!==void 0;if(!Iae(m)&&!h){let C=Eh(m);return await Ha(n,{skillSlug:i,version:u,action:p,decisionStatus:"blocked",reasonCode:C,telemetryMode:s.mode,path:c,authority:m}),x({...m,status:"blocked",reasonCode:C,skillSlug:i},"Guardian blocked guarded execution.",t.json,C)}if(await Ha(n,{skillSlug:i,version:u,action:p,decisionStatus:"allowed",reasonCode:"within_contract",telemetryMode:s.mode,path:c,authority:m}),t.dryRun)return R({status:"allowed",skillSlug:i,guardian:m,localPreflight:Vu(l.context),command:{executable:ot(d.request.executableRealPath),executableSha256:d.request.executableSha256,argvSha256:oz(d.request.argv),cwdRealPath:d.request.cwdRealPath,executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let g=m,y=f(g,"token"),v=T(g,"plan"),b=T(g,"binding");if(!y||!v||!b)return x({status:"blocked",reasonCode:"guardian_grant_response_invalid",skillSlug:i},"Guardian returned an invalid execution grant.",t.json,"guardian_grant_response_invalid");await D(n,"/api/v1/guardian/execution-grants/consume",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({token:y,plan:v,binding:b})});let w;try{w=await U2({plan:v,ambientEnvironment:n.env,approvedSecrets:d.approvedSecrets})}catch(C){let A=C instanceof De?C.reasonCode:"guardian_process_failed";return x({status:"blocked",reasonCode:A,skillSlug:i,planHash:b.planHash},"Guardian refused the contained process launch.",t.json,A)}let _={executable:ot(v.executableRealPath),argsCount:v.argv.length,exitCode:w.exitCode??1,reason:w.reason,signal:w.signal,stdout:w.stdout,stderr:w.stderr,outputTruncated:w.outputTruncated,planHash:w.planHash};return{exitCode:_.exitCode,stdout:t.json?JSON.stringify({status:_.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:i,guardian:m,localPreflight:Vu(l.context),command:_},warnings:[],links:[],reasonCode:_.exitCode===0?null:"command_failed",handoff:null},null,2):jae(_),stderr:_.stderr}}async function yP(e,t,n,r){let i=L(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),o=await D(r,"/api/v1/guardian/mode",{method:"POST",headers:V(r.apiKey),body:JSON.stringify({skillSlug:i,requestedPreference:e,source:"public-cli"})});if(o.preferenceAccepted===!0){if(f(o,"effectiveMode")==="enforce"){let s=(await zi(r,i)).installs[i],a=Rn(s).filter(u=>u.lifecycle?.state==="active"||u.lifecycle?.state==="pending_activation"),l=et(r.env,r.platform,r.cwd),c=new Set;for(let u of a){let d=f(u.record,"scope"),p=gr(u.record);if(d!=="project"&&d!=="global"||p.length===0)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,scope:d,targetAgents:p,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode could not identify every supported local activation target.",n.json,"guardian_install_target_unavailable");for(let m of p){let h=l.find(v=>v.id===m);if(!h)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,agent:m,scope:d,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode found an unsupported local activation target.",n.json,"guardian_install_target_unavailable");let g=`${d}:${h.id}`;if(c.has(g))continue;c.add(g);let y=await Xa({backend:r,skillSlug:i,agentId:h.id,scope:d,flags:n,enforceRequired:!0});if(y)return y}}}await Nae(r,i,o)}return R(o,o.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,r)}async function Zse(e,t,n){let r=k(t.skill)??k(e[1]),i;try{i=await zU(n,r)}catch(m){i={status:"unavailable",skillSlug:r,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ke(m),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let o=await qn(n),s=r?await Fae(n,r):void 0,a=f(i,"status")==="unavailable",l=f(o,"enforcementLayer")??"not_installed",d=l!=="not_installed"&&o.strictPreActionBlocking===!0?{status:"strict_installed",reasonCode:"guardian_hook_strict",enforcementLayer:l,strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:"Cloud Guardian policy is enforced when checked, and the local host hook can block supported risky actions before execution."}:l==="native_hook_candidate"?{status:"candidate_installed",reasonCode:"guardian_hook_candidate",enforcementLayer:l,strictPreActionBlocking:!1,nextAction:"guardian.hook.status",nextStep:"A Guardian candidate hook is installed, but strict pre-action blocking is not verified. Run `skills-layer guardian hook status --scope project` to inspect the current binding."}:{status:"not_installed",reasonCode:"guardian_hook_not_installed",enforcementLayer:"not_installed",strictPreActionBlocking:!1,nextAction:"guardian.hook.install",nextStep:"Cloud Guardian policy is enforced when checked, but local pre-action blocking is not installed for this host. Run `skills-layer guardian hook install --agent codex --scope global` or `skills-layer setup`."},p=await Jse({backend:n,skillSlug:r,policy:i,hook:o,localPreference:s});return R(ie({status:a?"degraded":"ok",skillSlug:f(i,"skillSlug")??r,policy:i,localPreference:s,hook:o,cloudPolicy:{status:f(i,"effectiveMode")??f(i,"status")??"unknown",reasonCode:f(i,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:f(i,"nextAction"),nextStep:f(i,"nextStep")},localEnforcement:d,measuredProtection:p,nextAction:f(d,"nextAction"),nextStep:f(d,"nextStep")}),a?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function Jse(e){let t=f(e.policy,"effectiveMode")??(e.localPreference?f(e.localPreference,"effectiveMode")??f(e.localPreference,"requestedPreference"):void 0),n=t==="warning_only"?"warning":t==="disabled"?"disabled":"enforce",r="active",i,o,s=[];if(e.skillSlug){o=(await zi(e.backend,e.skillSlug)).installs[e.skillSlug],s=Rn(o);let b=s.map(w=>w.lifecycle?.state??"unreadable");b.some(w=>w==="active"||w==="pending_activation")||(b.includes("externally_removed")?r="externally_removed":b.includes("host_detached")?r="host_detached":b.includes("drifted")?r="drifted":b.length>0&&(r="unreadable")),i=o?f(o,"workspaceId")??f(o,"workingModeWorkspaceId"):void 0}let a=[],l=new Set;for(let v of["project","global"])try{a.push(...Object.values((await Go(e.backend,v)).associations).filter(b=>!e.skillSlug||b.skillSlug===e.skillSlug))}catch{l.add(v)}let c=EM(a,l.size>0),d=(Be(e.hook,"hooks")?.filter(j)??[]).filter(v=>v.active===!0),p=s.flatMap(v=>{let b=f(v.record,"scope");if(b!=="project"&&b!=="global")return[];let w=o?hr(o,v):v.record,_=f(w,"workspaceId")??f(w,"workingModeWorkspaceId"),C=f(v.record,"receiptSha256"),A=v.lifecycle?.receipt.generation.generationId,N=Yse(v.lifecycle?.state);return gr(v.record).map(O=>{let X=br(O),G=d.find(Ie=>f(Ie,"agent")===O&&f(Ie,"scope")===b),ee=a.filter(Ie=>Ie.agentId===O&&Ie.scope===b&&(!C||Ie.receiptSha256===C)&&(!A||Ie.generationId===A)),te=EM(ee,l.has(b)),Q=vl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:_?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:X?.maximumTier==="strict_candidate",hookInstalled:!!G,strictHookVerified:G?.strictPreActionBlocking===!0,exactActivationVerified:G?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:te,materializationState:N});return{materializationId:v.materializationId,agent:O,scope:b,installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:C,generationId:A,materializationState:N,associationState:te,activeAssociationCount:ee.filter(Ie=>Ie.state==="active").length,hookState:G?f(G,"hookState")??"active":"not_installed",evidenceCapability:G?.evidenceCapability??"unverified",exactActivationVerified:G?.exactActivationVerified===!0,activationRoute:G?.activationRoute??null,workspaceRequired:!!_,...Q}})}),m=vl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:i?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:d.some(v=>br(f(v,"agent")??"")?.maximumTier==="strict_candidate"),hookInstalled:d.length>0,strictHookVerified:d.some(v=>v.strictPreActionBlocking===!0),exactActivationVerified:d.some(v=>v.strictPreActionBlocking===!0&&v.exactActivationVerified===!0),completeWrapperVerified:!1,associationState:c,materializationState:r}),h=new Set(p.map(v=>v.label)),g=p.length===0?m:{label:h.size===1?p[0].label:"mixed",countedAsEnforced:p.every(v=>v.countedAsEnforced),activationAllowed:p.every(v=>v.activationAllowed),runtimeGuardian:p.every(v=>v.runtimeGuardian),reasonCode:h.size===1?p[0].reasonCode:"mixed_target_protection"},y=s.map(v=>({materializationId:v.materializationId,scope:f(v.record,"scope"),agent:f(v.record,"agent")??f(v.record,"targetAgent"),targetAgents:gr(v.record),installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:f(v.record,"receiptSha256"),state:v.lifecycle?.state??"unreadable",protectionTargets:p.filter(b=>b.materializationId===v.materializationId)}));return{...g,requestedMode:n,workspaceRequired:!!i,associationState:c,materializationState:r,materializations:y,targets:p,targetCount:p.length,activeAssociationCount:a.filter(v=>v.state==="active").length}}function Yse(e){return e==="active"||e==="pending_activation"?"active":e==="externally_removed"||e==="host_detached"||e==="drifted"?e:"unreadable"}function EM(e,t){return t?"stale":e.some(n=>n.state==="active")?"active":e.some(n=>n.state==="externally_removed")?"externally_removed":e.some(n=>n.state==="host_detached")?"host_detached":e.some(n=>n.state==="stale")?"stale":e.some(n=>n.state==="pending_authority")?"pending_authority":"none"}async function zU(e,t){let n=t?await id(e,t):void 0;return await D(e,"/api/v1/guardian/status",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(ie({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Xse(e){if(!e.apiKey)return{status:"unknown",policySource:"cloud",reasonCode:"login_required",nextAction:"skills-layer login",nextStep:"Sign in to read the Cloud Guardian policy that applies to your account."};try{return await zU(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ke(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function qU(e,t){let n=k(e.agent)??"codex",r=Qa(e.scope);if(r.status==="invalid")return E(r.message,e.json);let i=et(t.env,t.platform,t.cwd).find(m=>m.id===n);if(!i)return x({status:"error",reasonCode:"unknown_agent",agent:n,nextAction:"agents.list",nextStep:"Run `skills-layer agents list` to see supported agents, then retry Guardian hook install with a supported --agent value."},`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json,"unknown_agent");let o=Bae(i,r.scope,t,k(e.hostVersion)??i.installEvidence.hostVersion??"unverified");if(!o)return E(`Guardian ${r.scope} hooks are not available for ${i.displayName}.`,e.json);let s=lz(t,r.scope),a=UM(Mu(t.cwd,o.hookPath)),l=UM(Mu(t.cwd,o.configPath)),c=await cz(s),u=c.hooks.find(m=>f(m,"agent")===i.id&&f(m,"scope")===r.scope),d=await Mae(o,t,u),p=[...c.hooks.filter(m=>f(m,"agent")!==i.id||f(m,"scope")!==r.scope),{hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:a.startsWith("..")?o.hookPath:a,configPath:l.startsWith("..")?o.configPath:l,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,hookFileOwnership:d.hookFileOwnership,...d.configEntryOwnership?{configEntryOwnership:d.configEntryOwnership}:{},...d.configEntryOwnerships?{configEntryOwnerships:d.configEntryOwnerships}:{},...d.activationConfigEntryOwnership?{activationConfigEntryOwnership:d.activationConfigEntryOwnership}:{},...d.configFileOwnership?{configFileOwnership:d.configFileOwnership}:{},absoluteCliPath:d.absoluteCliPath,hostVersion:o.hostVersion,adapterRevision:Hn(o.agent).adapterRevision,evidencePath:Uae(t,r.scope,o.agent,o.hostVersion),enabledAt:t.now()}];return await Ve(s,{version:1,hooks:p}),R({status:"enabled",hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:o.hookPath,configPath:o.configPath,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,agentCommandMatrix:KC({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json"}),nextStep:"Guardian is installed into the selected host configuration. Installed hooks route host pre-tool events through the internal Guardian hook runtime. `skills-layer guardian check` and MCP `guardian.check` remain diagnostic; use `skills-layer guardian exec` for atomic guarded shell execution, while supported hooks call MCP/Cloud `guardian.enforce` before a mapped tool action.",warnings:["This hook is installed as a candidate integration and is not counted as strict Guardian enforcement until a real agent/platform allow/deny canary proves the exact adapter, script, config, and CLI binding."]},"Guardian hook enabled.",e.json,t)}async function Qse(e,t){let n=k(e.scope),r=n?Qa(n):null;if(r?.status==="invalid")return E(r.message,e.json);let i=await qn(t,r?.status==="valid"?r.scope:void 0);return R(i,"Guardian status loaded.",e.json,t)}async function eae(e,t,n){let r=Qa(k(t.scope));if(r.status==="invalid")return E(r.message,t.json);let i=L(e[0]??t.skill,"guardian session bind requires a skill slug."),o=L(t.version,"guardian session bind requires --version."),s=k(t.agent);if(!s||!kr(s))return E("guardian session bind requires an agent with an implemented Guardian pre-tool adapter.",t.json);let a=L(t.hostVersion,"guardian session bind requires --host-version."),l=XU(k(t.guardianPreference)??k(t.mode));if(!l)return E("guardian session bind --mode must be enforce, warning-only, or disabled.",t.json);let c={version:1,scope:r.scope,skillSlug:i,skillVersion:o,...k(t.workspaceId)?{workspaceId:k(t.workspaceId)}:{},agentId:s,hostVersion:a,requestedPreference:l,boundAt:n.now()},u=YU(n,r.scope);return await Uo(Me(u),{recursive:!0,mode:448}),await Ve(u,c),await Ze(VP(n,r.scope),{force:!0}),R({status:"bound",binding:c,bindingPath:u,nextAction:"guardian.hook.run",nextStep:"Start the bound host session. The hook will obtain short-lived signed attribution for the exact Cloud generation."},"Guardian exact skill session bound.",t.json,n)}async function tae(e,t,n){let r=L(e[0]??t.skill,"guardian launch requires a skill slug."),i=Qa(k(t.scope));if(i.status==="invalid")return E(i.message,t.json);let o=k(t.agent);if(o!=="codex"&&o!=="kiro-cli")return x({status:"blocked",reasonCode:"guardian_approved_launcher_unavailable",skillSlug:r,agent:o,supportedLauncherAgents:["codex","kiro-cli"],nextAction:"guardian.status",nextStep:"Use a host with verified native activation, or use the managed launcher for Codex or Kiro CLI. Cline and Cursor IDE processes do not expose a trustworthy inherited-session launcher boundary."},"A trustworthy managed Guardian launcher is unavailable for this host.",t.json,"guardian_approved_launcher_unavailable");let s=e[1];if(!s)return E("guardian launch requires `-- <codex|kiro-cli> [arguments]`.",t.json);if(!(o==="codex"?new Set(["codex","codex.exe"]):new Set(["kiro","kiro-cli","kiro.exe","kiro-cli.exe"])).has(ot(s).toLowerCase()))return x({status:"blocked",reasonCode:"guardian_launcher_executable_mismatch",agent:o,executable:ot(s),nextAction:"guardian.launch",nextStep:`Launch the real ${o} executable after --; arbitrary commands cannot receive a Guardian launch token.`},"Guardian refused to pass managed-session authority to a different executable.",t.json,"guardian_launcher_executable_mismatch");let l=(await zi(n,r)).installs[r],c=Vn(l,{scope:i.scope,agent:o}).filter(N=>N.lifecycle?.state==="active");if(c.length!==1||!c[0].lifecycle)return x({status:"blocked",reasonCode:c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous",skillSlug:r,agent:o,scope:i.scope,matchingMaterializationCount:c.length,nextAction:"installed",nextStep:"Keep exactly one active exact materialization for this agent and scope before launching a guarded session."},"Guardian could not resolve one exact installed generation for the managed launch.",t.json,c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous");let u=c[0].lifecycle,d=await Tr(u.receipt);if(d.status!=="verified")return x({status:"blocked",reasonCode:d.reasonCode,skillSlug:r,agent:o,scope:i.scope,nextAction:"install",nextStep:"Repair or reinstall the exact generation before starting a managed Guardian session."},"Guardian refused to launch from a stale or changed local generation.",t.json,d.reasonCode);let p=await Xa({backend:n,skillSlug:r,agentId:o,scope:i.scope,flags:t,enforceRequired:!0});if(p)return p;let m=await qn(n,i.scope),h=(Be(m,"hooks")??[]).filter(j).find(N=>f(N,"agent")===o&&f(N,"scope")===i.scope&&N.active===!0&&N.strictPreActionBlocking===!0&&N.exactActivationVerified===!0);if(!h)return x({status:"blocked",reasonCode:"guardian_launcher_route_unavailable",agent:o,nextAction:"guardian.hook.status",nextStep:"Install and verify the Guardian activation route before launching."},"Guardian refused to launch because the verified hook route is unavailable.",t.json,"guardian_launcher_route_unavailable");let g=k(t.hostVersion)??f(h,"hostVersion")??"unverified",y;try{y=await iz(s,n,mr(n.platform))}catch(N){return E(ke(N),t.json)}let v=Ge(32).toString("base64url"),b=n.now(),w={version:1,launchId:`guardian_launch_${Ge(12).toString("hex")}`,tokenSha256:`sha256:${Ue("sha256").update(v,"utf8").digest("hex")}`,scope:i.scope,agentId:o,hostVersion:g,skillSlug:r,generationId:u.receipt.generation.generationId,receiptSha256:Hr(u.receipt),status:"pending",createdAt:b,expiresAt:new Date(Date.parse(b)+15*6e4).toISOString()};await uae(n,i.scope,w);let _=await new Promise((N,O)=>{let X=ZM(y,e.slice(2),{cwd:n.cwd,env:{...n.env,SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN:v,SKILLS_LAYER_GUARDIAN_LAUNCH_SCOPE:i.scope},stdio:"inherit"});X.once("error",O),X.once("exit",(G,ee)=>N({exitCode:G??1,signal:ee}))}).catch(async N=>{throw await TM(n,i.scope,w.launchId).catch(()=>{}),N}),A=(await ZU(n,i.scope)).launches[w.launchId]?.status==="associated";return await TM(n,i.scope,w.launchId).catch(()=>{}),R({status:A?"managed_session_completed":"host_exited_before_association",launchId:w.launchId,skillSlug:r,agent:o,scope:i.scope,generationId:w.generationId,hostExitCode:_.exitCode,hostSignal:_.signal,associationObserved:A,nextAction:"guardian.status",nextStep:A?"The one-time launch authority was consumed by the exact host session; inspect per-target Guardian status for the resulting association.":"The host exited before its hook completed an exact active Guardian association. The one-time authority was discarded and is not strict-session evidence."},A?"Managed Guardian host session completed.":"The managed host exited without an observed Guardian session association.",t.json,n)}async function nae(e,t){let n=Qa(k(e.scope)),r=k(e.agent);if(n.status==="invalid"||!r||!kr(r))return it(r&&kr(r)?r:"codex","deny","Guardian hook configuration is invalid.");let i=Ee(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!i||i.length>512*1024)return it(r,"deny","Guardian could not read the bounded host event.");let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return it(r,"deny","Guardian could not parse the host event.")}let s=wd(r,o);if(s)return await $M({agentId:r,scope:n.scope,observation:s,rawPayload:o,flags:e,backend:t});let a=GU(r,o);if(!a)return it(r,"deny","Guardian could not bind this event to the host session.");let l=Ee(t.env.SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN);if(l){let h=await dae(t,n.scope,l,r,t.now());if(!h)return it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token.");let g=h.launch;if(h.disposition==="associated"){let y;try{y=await Go(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let v=fl(y,{agentId:r,sessionId:a,asOf:t.now()}),b=v.associations.length===1?v.associations[0]:void 0;return!b||tt(b)!==g.associationKey?it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token."):await zP({agentId:r,scope:n.scope,lookup:v,rawPayload:o,backend:t})}return await $M({agentId:r,scope:n.scope,observation:{sessionId:a,skillReference:g.skillSlug,referenceKind:"slug",source:"approved_launcher",evidence:`approved-launcher:${g.launchId}`},expectedReceiptSha256:g.receiptSha256,expectedGenerationId:g.generationId,managedLaunchId:g.launchId,qualificationCandidate:g.qualificationOnly===!0,rawPayload:o,flags:e,backend:t})}let c;try{c=await Go(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let u=fl(c,{agentId:r,sessionId:a,asOf:t.now()});if(u.status!=="unrelated")return await zP({agentId:r,scope:n.scope,lookup:u,rawPayload:o,backend:t});let d=await be(YU(t,n.scope));if(!d||d.version!==1||d.agentId!==r)return await fae(t,n.scope,r)?it(r,"deny",`Guardian requires \`skills-layer guardian launch <skill> --agent ${r} --scope ${n.scope} -- <host>\` because this host has no trustworthy native skill-activation signal.`):it(r,"allow","No Skills Layer skill session is bound; unrelated host activity remains outside Guardian.");let p=await be(VP(t,n.scope));if(!oae(p,d,a,t.now()))try{let h=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:d.skillSlug,version:d.skillVersion,...d.workspaceId?{workspaceId:d.workspaceId}:{},agentId:r,platform:t.platform,hostVersion:d.hostVersion,sessionId:a,requestedPreference:d.requestedPreference})}),g=T(h,"envelope"),y=QU(h,"publicKeys");if(!g||!y)throw new Error("Guardian session authority returned an invalid envelope.");p={version:1,envelope:g,publicKeys:y,savedAt:t.now()},await Ve(VP(t,n.scope),p)}catch{return it(r,"deny","Guardian could not obtain current signed skill-session authority.")}await sae({binding:d,sessionId:a,cache:p,backend:t}).catch(()=>{});let m=await gy({agentId:r,platform:t.platform==="darwin"||t.platform==="linux"||t.platform==="win32"?t.platform:"linux",hostVersion:d.hostVersion,rawPayload:o,attributionEnvelope:p.envelope,attributionPublicKeys:p.publicKeys,now:t.now(),evaluate:async h=>VU(h,d,t)});return{exitCode:m.exitCode,stdout:m.stdout,stderr:m.stderr}}async function $M(e){let t;try{t=await aae(e.observation,e.agentId,e.backend)}catch(c){return Oi(e.agentId,e.observation,"deny",ke(c))}let n=Hr(t.receipt);if(e.expectedReceiptSha256&&e.expectedReceiptSha256!==n||e.expectedGenerationId&&e.expectedGenerationId!==t.receipt.generation.generationId)return Oi(e.agentId,e.observation,"deny","Guardian managed launch no longer matches the exact installed generation.");if(!t.workspaceId&&(t.requestedPreference===null||t.requestedPreference==="disabled"))return Oi(e.agentId,e.observation,"allow","Guardian is not enabled for this Personal skill; no runtime association was created.");let r=t.requestedPreference??"enforce",i=Hn(e.agentId),o=lae(e.agentId,e.rawPayload,e.flags)??"unverified",s=e.backend.now(),a={version:2,revision:1,state:"pending_authority",scope:e.scope,agentId:e.agentId,hostVersion:o,sessionId:e.observation.sessionId,skillSlug:t.skillSlug,skillVersion:t.receipt.generation.semanticVersion,generationId:t.receipt.generation.generationId,receiptSha256:n,...t.workspaceId?{workspaceId:t.workspaceId}:{},requestedPreference:r,activationSource:e.observation.source,activationEvidence:e.observation.evidence,adapterRevision:i.adapterRevision,createdAt:s,updatedAt:s},l;try{l=await JU(e.backend,e.scope,a)}catch{return Oi(e.agentId,e.observation,DM(a),"Guardian could not safely record this exact skill-session association.")}try{let c=await HU(l,e.backend),u=e.backend.now(),d=dl({envelope:c.cache.envelope,publicKeys:c.cache.publicKeys,expectedAgentId:e.agentId,expectedPlatform:mr(e.backend.platform),now:u});if(d.skillSlug!==l.skillSlug||d.version!==l.skillVersion||d.generationId!==l.generationId||d.sessionId!==l.sessionId||d.workspaceId!==l.workspaceId)throw new Error("Guardian Cloud authority did not match the exact local association.");let p=await qn(e.backend,e.scope),m=Be(p,"hooks")?.filter(j).find(_=>f(_,"agent")===e.agentId&&_.active===!0),h=l.requestedPreference==="warning_only"?"warning":l.requestedPreference,g=d.workspaceRequiredMode===null?null:{requiredMode:d.workspaceRequiredMode,revision:c.policyRevision,updatedBy:"skills-layer-cloud",updatedAt:d.issuedAt},y=rae({enabled:e.qualificationCandidate===!0,managedLaunchId:e.managedLaunchId,agentId:e.agentId,exactHook:m,env:e.backend.env}),v=vl({evaluationContext:"activation_eligibility",requestedMode:h,workspacePolicy:g,hostSupported:br(e.agentId)?.maximumTier==="strict_candidate",hookInstalled:!!m,strictHookVerified:y||m?.strictPreActionBlocking===!0,exactActivationVerified:y||m?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"pending_authority",materializationState:"active"});if(!v.activationAllowed)return await No(e.backend,e.scope,tt(l),{state:"stale",reasonCode:v.reasonCode,updatedAt:s}),Oi(e.agentId,e.observation,"deny",`Guardian refused activation because verified enforcement is unavailable (${v.reasonCode}).`);let b=await No(e.backend,e.scope,tt(l),{state:"active",trustLedgerId:c.trustLedgerId,attributionExpiresAt:d.expiresAt,updatedAt:u}),w=tt(b);return await vA(e.backend,e.scope,w,c.cache),!e.managedLaunchId&&cs(e.backend.env)==="missing_attribution"?(await No(e.backend,e.scope,w,{state:"stale",reasonCode:"phase149_missing_attribution_canary",updatedAt:u}),await gae(e.backend,e.scope,w),Oi(e.agentId,e.observation,"allow","Guardian qualification removed signed attribution after exact activation.")):(e.managedLaunchId&&await pae(e.backend,e.scope,e.managedLaunchId,w),await SE(e.backend.env),e.managedLaunchId?await zP({agentId:e.agentId,scope:e.scope,lookup:{status:"active",associations:[b]},rawPayload:e.rawPayload,backend:e.backend}):Oi(e.agentId,e.observation,"allow",v.label==="warning_only"?"Guardian warning-only activation is associated with this exact installed generation; it is not counted as strict enforcement.":"Guardian associated this host session with the exact installed generation."))}catch(c){return await No(e.backend,e.scope,tt(l),{state:"pending_authority",reasonCode:"guardian_session_authority_unavailable",updatedAt:s}).catch(()=>{}),Oi(e.agentId,e.observation,qP(c)?"deny":DM(l),l.requestedPreference==="warning_only"&&!l.workspaceId&&!qP(c)?"Guardian warning-only activation continued without runtime authority; protection is diagnostic only.":`Guardian could not establish exact skill-session authority (${ke(c)}).`)}}function rae(e){if(!e.enabled||!e.managedLaunchId?.startsWith("guardian_launch_phase149_")||br(e.agentId)?.automaticAssociation!=="approved_launcher_required"||e.exactHook?.active!==!0||e.exactHook.configActive!==!0||e.exactHook.evidenceCapability!=="unverified")return!1;let t=Be(e.exactHook,"evidenceReasons");return t?.length!==1||t[0]!=="live_canary_evidence_missing"?!1:cs(e.env)!==null}async function zP(e){if(e.lookup.status==="ambiguous")return it(e.agentId,"deny","Guardian found multiple active skill associations for this host session.");let t=e.lookup.associations[0];if(!t)return it(e.agentId,"deny","Guardian expected an exact association but could not load it.");if(e.lookup.status==="terminal")return it(e.agentId,"deny","Guardian blocked a session whose exact skill was removed or detached.");if(e.lookup.status==="expected_missing_authority")return it(e.agentId,t.requestedPreference==="warning_only"&&!t.workspaceId?"allow":"deny",t.requestedPreference==="warning_only"&&!t.workspaceId?"Guardian warning only: exact runtime authority is missing; this is not strict enforcement.":"Guardian blocked an expected skill session because exact runtime authority is missing.");let n=await cae(t,e.backend);if(n.status!=="verified")return await No(e.backend,e.scope,tt(t),{state:n.state,reasonCode:n.reasonCode,updatedAt:e.backend.now()}).catch(()=>{}),it(e.agentId,"deny","Guardian blocked this session because the exact installed generation is no longer current.");let r=await hae(e.backend,e.scope,tt(t));if(e.lookup.status==="active_authority_stale"||!yae(r,t,e.backend.now()))try{let a=await HU(t,e.backend);r=a.cache;let l=dl({envelope:r.envelope,publicKeys:r.publicKeys,expectedAgentId:e.agentId,expectedPlatform:mr(e.backend.platform),now:e.backend.now()});await No(e.backend,e.scope,tt(t),{state:"active",trustLedgerId:a.trustLedgerId,attributionExpiresAt:l.expiresAt,updatedAt:e.backend.now()}),await vA(e.backend,e.scope,tt(t),r)}catch(a){let l=t.requestedPreference==="warning_only"&&!t.workspaceId&&!qP(a);return it(e.agentId,l?"allow":"deny",l?"Guardian warning only: signed runtime authority could not be refreshed.":"Guardian blocked this action because signed runtime authority could not be refreshed.")}let i={version:1,scope:t.scope,skillSlug:t.skillSlug,skillVersion:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},agentId:e.agentId,hostVersion:t.hostVersion,requestedPreference:t.requestedPreference,boundAt:t.createdAt},o=!1,s=await gy({agentId:e.agentId,platform:mr(e.backend.platform),hostVersion:t.hostVersion,rawPayload:e.rawPayload,attributionEnvelope:r.envelope,attributionPublicKeys:r.publicKeys,now:e.backend.now(),evaluate:async a=>{let l=await VU(a,i,e.backend);return o=l.delegatedExecution===!0,l}});return o&&await xE({agentId:e.agentId,scope:e.scope,skillSlug:t.skillSlug,associationKey:tt(t),env:e.backend.env}),{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr,...o?{[UU]:!0}:{}}}async function VU(e,t,n){if(e.action.actionFamily==="shell_execution"||e.action.actionFamily==="generated_code_execution"){let i=await qn(n,t.scope),o=(Be(i,"hooks")??[]).filter(j).find(c=>f(c,"agent")===t.agentId&&f(c,"scope")===t.scope&&c.active===!0&&c.configActive===!0&&typeof f(c,"absoluteCliPath")=="string"),s=o?f(o,"absoluteCliPath"):void 0,a=cs(n.env)?IE:void 0;if(s&&e.action.command&&PE({command:e.action.command,cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:mr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}))return{decision:"allow",reason:"Guardian delegated this exact shell action to the atomic guarded execution wrapper.",delegatedExecution:!0};let l=s?AE({cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:mr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}):null;return{decision:"deny",reason:l&&l.length<=800?`Use the exact guarded command prefix: ${l} <command>`:"Use the exact Skills Layer Guardian execution wrapper for one-action guarded shell or generated-code execution."}}let r=iae(e);if(r.length===0)return{decision:"deny",reason:"Guardian has no exact action mapping for this host event."};for(let i of r){let o=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({skillSlug:t.skillSlug,version:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},guardianPreference:t.requestedPreference,telemetryMode:(t.workspaceId,"cloud_managed"),action:i})});if(T(o,"enforcement")?.canExecute!==!0)return{decision:"deny",reason:`Guardian denied this exact action (${Eh(o)}).`}}return{decision:"allow",reason:"Guardian allowed the exact attributed host action."}}function iae(e){let t={strictActionSha256:e.actionSha256,toolInputSha256:e.action.toolInputSha256,adapterRevision:e.adapterRevision,host:e.action.host};switch(e.action.actionFamily){case"filesystem_read":case"filesystem_write":return e.action.fileTargets.map(n=>({type:e.action.actionFamily==="filesystem_read"?"file_read":"file_write",path:n,metadata:t}));case"network_access":return e.action.networkTargets.map(n=>({type:"network_request",url:n,metadata:t}));case"browser_access":return[{type:"browser_action",target:e.action.toolName,metadata:t}];case"device_control":return[{type:"device_action",target:e.action.toolName,metadata:t}];case"api_access":return[{type:"api_call",target:e.action.toolName,metadata:t}];default:return[]}}function it(e,t,n){let r=rs(e,{decision:t,reason:n});return{exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}}function GU(e,t){if(!j(t))return null;let n=e==="cline"?t.taskId:e==="cursor"?t.conversation_id:e==="windsurf"?t.trajectory_id:e==="antigravity"||e==="antigravity-cli"?t.conversationId:t.session_id;return typeof n=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(n)?n:null}function oae(e,t,n,r){if(!e||e.version!==1||!j(e.envelope)||!j(e.envelope.claims))return!1;let i=e.envelope.claims;return i.agentId===t.agentId&&i.sessionId===n&&i.skillSlug===t.skillSlug&&i.version===t.skillVersion&&i.workspaceId===t.workspaceId&&typeof i.expiresAt=="string"&&Date.parse(i.expiresAt)>Date.parse(r)+5e3}async function sae(e){let t=(await lt(e.backend)).installs[e.binding.skillSlug],n=Vn(t,{scope:e.binding.scope,agent:e.binding.agentId}).filter(a=>a.lifecycle?.receipt.generation.semanticVersion===e.binding.skillVersion),r=n.length===1?n[0].lifecycle:null;if(!r||r.state!=="active"||r.receipt.generation.semanticVersion!==e.binding.skillVersion||(await Tr(r.receipt)).status!=="verified")return;let o=dl({envelope:e.cache.envelope,publicKeys:e.cache.publicKeys,expectedAgentId:e.binding.agentId,expectedPlatform:mr(e.backend.platform),now:e.backend.now()});if(o.sessionId!==e.sessionId||o.generationId!==r.receipt.generation.generationId||o.skillSlug!==e.binding.skillSlug||o.version!==e.binding.skillVersion)return;let s=await JU(e.backend,e.binding.scope,{version:2,revision:1,state:"active",scope:e.binding.scope,agentId:e.binding.agentId,hostVersion:e.binding.hostVersion,sessionId:e.sessionId,skillSlug:e.binding.skillSlug,skillVersion:e.binding.skillVersion,generationId:r.receipt.generation.generationId,receiptSha256:Hr(r.receipt),...e.binding.workspaceId?{workspaceId:e.binding.workspaceId}:{},requestedPreference:e.binding.requestedPreference,activationSource:"manual_recovery",activationEvidence:`legacy-bind:${e.binding.boundAt}`,adapterRevision:Hn(e.binding.agentId).adapterRevision,trustLedgerId:e.cache.envelope.version===2?e.cache.envelope.claims.trustLedgerId:"legacy_local",attributionExpiresAt:o.expiresAt,createdAt:e.binding.boundAt,updatedAt:e.backend.now()});await vA(e.backend,e.binding.scope,tt(s),e.cache)}async function aae(e,t,n){let r=await lt(n),i=Object.entries(r.installs).flatMap(([u,d])=>Rn(d).flatMap(p=>{let m=p.lifecycle;if(!m||m.state!=="active")return[];if(!gr(p.record).includes(t))return[];if(e.referenceKind==="slug"){if(e.skillReference!==u&&e.skillReference!==m.receipt.generation.skillSlug)return[]}else{let h=Vo(m.receipt.targetDir),g=Vo(e.skillReference),y=Mu(h,g);if(y.startsWith("..")||st.isAbsolute(y)||Lt.isAbsolute(y))return[]}return[{skillSlug:u,record:hr(d,p),lifecycle:m}]}));if(i.length!==1)throw new Error(i.length===0?"Guardian activation did not resolve to an owned exact installed generation.":"Guardian activation matched more than one installed generation.");let o=i[0],s=await Tr(o.lifecycle.receipt);if(s.status!=="verified")throw new Error(`Guardian activation receipt verification failed (${s.reasonCode}).`);let a=f(o.record,"workspaceId")??f(o.record,"workingModeWorkspaceId"),l=await id(n,o.skillSlug),c=l===void 0?a?"enforce":null:XU(l);if(l!==void 0&&c===null)throw new Error("Guardian activation preference is invalid.");return{skillSlug:o.skillSlug,record:o.record,receipt:o.lifecycle.receipt,requestedPreference:c,...a?{workspaceId:a}:{}}}async function HU(e,t){let n=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:e.skillSlug,version:e.skillVersion,...e.workspaceId?{workspaceId:e.workspaceId}:{},agentId:e.agentId,platform:mr(t.platform),hostVersion:e.hostVersion,sessionId:e.sessionId,requestedPreference:e.requestedPreference})}),r=T(n,"envelope"),i=QU(n,"publicKeys"),o=T(n,"ledger"),s=o?f(o,"ledgerId"):void 0;if(!r||!i||!s)throw new Error("Guardian session authority returned an invalid exact-generation envelope.");return{cache:{version:1,envelope:r,publicKeys:i,savedAt:t.now()},trustLedgerId:s,policyRevision:r.version===2?r.claims.policyRevision:1}}function DM(e){return e.requestedPreference==="warning_only"&&!e.workspaceId?"allow":"deny"}function qP(e){return e instanceof Z?e.status<500:!ke(e).startsWith("Unable to reach ")}function Oi(e,t,n,r){return t.source==="claude_user_prompt_expansion"?n==="deny"?{exitCode:2,stdout:"",stderr:r}:{exitCode:0,stdout:"",stderr:""}:it(e,n,r)}function lae(e,t,n){let r=k(n.hostVersion);if(r)return r;if(!j(t))return null;let i=e==="cline"?t.clineVersion:e==="cursor"?t.cursor_version:t.host_version;return typeof i=="string"&&/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u.test(i)?i:null}function mr(e){return e==="darwin"||e==="win32"?e:"linux"}async function cae(e,t){let n=(await lt(t)).installs[e.skillSlug],r=Vn(n,{receiptSha256:e.receiptSha256}),i=r.length===1?r[0].lifecycle:null;if(!i)return{status:"invalid",state:"externally_removed",reasonCode:"exact_install_record_absent"};if(i.receipt.generation.semanticVersion!==e.skillVersion||i.receipt.generation.generationId!==e.generationId||Hr(i.receipt)!==e.receiptSha256)return{status:"invalid",state:"stale",reasonCode:"exact_generation_replaced"};try{await Qu(i.receipt.targetDir)}catch(s){return s.code==="ENOENT"?{status:"invalid",state:"externally_removed",reasonCode:"exact_target_absent"}:{status:"invalid",state:"stale",reasonCode:"exact_target_unreadable"}}let o=await Tr(i.receipt);return o.status==="verified"?{status:"verified"}:{status:"invalid",state:"stale",reasonCode:o.reasonCode}}function KU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-associations.json"):K(e.cwd,".skills-layer","guardian-session-associations.json")}function WU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-managed-launches.json"):K(e.cwd,".skills-layer","guardian-managed-launches.json")}async function ZU(e,t){let n=await be(WU(e,t));if(!j(n)||n.version!==1||!Number.isSafeInteger(n.revision)||Number(n.revision)<0||!j(n.launches))return{version:1,revision:0,launches:{}};let r=Object.fromEntries(Object.entries(n.launches).flatMap(([i,o])=>{if(!j(o))return[];let s=f(o,"agentId"),a=f(o,"scope"),l=f(o,"tokenSha256"),c=f(o,"receiptSha256"),u=f(o,"status"),d=o;return d.version!==1||d.launchId!==i||s!=="codex"&&s!=="kiro-cli"||a!==t||!l||!/^sha256:[a-f0-9]{64}$/u.test(l)||!c||!/^sha256:[a-f0-9]{64}$/u.test(c)||u!=="pending"&&u!=="claimed"&&u!=="associated"||o.qualificationOnly!==void 0&&o.qualificationOnly!==!0||!f(o,"hostVersion")||!f(o,"skillSlug")||!f(o,"generationId")||u==="associated"&&!f(o,"associationKey")||!f(o,"createdAt")||!f(o,"expiresAt")||!Number.isFinite(Date.parse(d.createdAt))||!Number.isFinite(Date.parse(d.expiresAt))?[]:[[i,d]]}));return{version:1,revision:Number(n.revision),launches:r}}async function nd(e,t,n){let r=WU(e,t);await Jo(Me(r));let i=`${r}.lock`,o=null;for(let s=0;s<50&&!o;s+=1)try{o=await zo(i,"wx",384)}catch(a){if(a.code!=="EEXIST"||s===49)throw a;await e.sleep(10)}if(!o)throw new Error("Guardian managed launch lock is unavailable.");try{let s=await ZU(e,t),a=n(s);return await rd(r,a.store),a.value}finally{await o.close().catch(()=>{}),await Ze(i,{force:!0}).catch(()=>{})}}async function uae(e,t,n){await nd(e,t,r=>({store:{version:1,revision:r.revision+1,launches:{...r.launches,[n.launchId]:n}},value:void 0}))}async function TM(e,t,n){await nd(e,t,r=>{let i={...r.launches};return delete i[n],{store:{version:1,revision:r.revision+1,launches:i},value:void 0}})}async function dae(e,t,n,r,i){if(n.length<32||n.length>256||!/^[A-Za-z0-9_-]+$/u.test(n))return null;let o=`sha256:${Ue("sha256").update(n,"utf8").digest("hex")}`;return await nd(e,t,s=>{let a=Object.values(s.launches).filter(d=>(d.status==="pending"||d.status==="associated")&&d.tokenSha256===o&&d.agentId===r&&(d.status==="associated"||Date.parse(d.expiresAt)>Date.parse(i))),l=a.length===1?a[0]:void 0,c=l?.status==="pending"?{...l,status:"claimed"}:l,u=Object.fromEntries(Object.entries(s.launches).flatMap(([d,p])=>p.status!=="associated"&&Date.parse(p.expiresAt)<=Date.parse(i)?[]:[[d,p.launchId===c?.launchId?c:p]]));return{store:{version:1,revision:s.revision+1,launches:u},value:c?{disposition:l?.status==="pending"?"claimed":"associated",launch:c}:null}})}async function pae(e,t,n,r){await nd(e,t,i=>{let o=i.launches[n];if(!o||o.status!=="claimed")throw new Error("Guardian managed launch is not in the claimed state.");return{store:{version:1,revision:i.revision+1,launches:{...i.launches,[n]:{...o,status:"associated",associationKey:r}}},value:void 0}})}async function fae(e,t,n){if(br(n)?.automaticAssociation!=="approved_launcher_required")return!1;let r=await lt(e);for(let[i,o]of Object.entries(r.installs)){let s=Vn(o,{scope:t,agent:n});for(let a of s){if(a.lifecycle?.state!=="active"&&a.lifecycle?.state!=="pending_activation")continue;let l=hr(o,a);if(f(l,"workspaceId")??f(l,"workingModeWorkspaceId"))return!0;let u=await id(e,i);if(u==="enforce"||u==="enabled")return!0}}return!1}function jh(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-authorities.json"):K(e.cwd,".skills-layer","guardian-session-authorities.json")}async function Go(e,t){let n=await be(KU(e,t));return n===null?rE():iE(n)}async function yA(e,t,n){let r=KU(e,t);await Jo(Me(r));let i=`${r}.lock`,o=null;try{o=await zo(i,"wx",384);let s=await Go(e,t),a=n(s);return await rd(r,a.index),a.value}finally{await o?.close().catch(()=>{}),await Ze(i,{force:!0}).catch(()=>{})}}async function JU(e,t,n){return await yA(e,t,r=>{let i=oE(r,n,r.revision),o=i.associations[tt(n)];return{index:i,value:o}})}async function No(e,t,n,r){return await yA(e,t,i=>{let o=sE(i,{key:n,expectedIndexRevision:i.revision,...r});return{index:o,value:o.associations[n]}})}async function mae(e,t){let n=0;for(let r of["project","global"]){let i=await yA(e,r,o=>{let s=aE(o,{...t,expectedIndexRevision:o.revision});return{index:s.index,value:s.removedKeys}});if(n+=i.length,i.length>0){let o=jh(e,r),s=await Nh(e,r),a=new Set(i);await rd(o,{version:1,revision:s.revision+1,authorities:Object.fromEntries(Object.entries(s.authorities).filter(([l])=>!a.has(l)))})}await nd(e,r,o=>({store:{version:1,revision:o.revision+1,launches:Object.fromEntries(Object.entries(o.launches).filter(([,s])=>s.skillSlug!==t.skillSlug||s.generationId!==t.generationId||s.receiptSha256!==t.receiptSha256))},value:void 0}))}return n}async function Nh(e,t){let n=await be(jh(e,t));return!j(n)||n.version!==1||!Number.isSafeInteger(n.revision)||!j(n.authorities)?{version:1,revision:0,authorities:{}}:{version:1,revision:Number(n.revision),authorities:Object.fromEntries(Object.entries(n.authorities).filter(r=>{let i=r[1];return j(i)&&i.version===1&&j(i.envelope)&&j(i.publicKeys)&&typeof i.savedAt=="string"}))}}async function vA(e,t,n,r){let i=jh(e,t),o=await Nh(e,t);await rd(i,{version:1,revision:o.revision+1,authorities:{...o.authorities,[n]:r}})}async function gae(e,t,n){let r=jh(e,t),i=await Nh(e,t),o={...i.authorities};delete o[n],await rd(r,{version:1,revision:i.revision+1,authorities:o})}async function hae(e,t,n){return(await Nh(e,t)).authorities[n]??null}function yae(e,t,n){if(!e||e.version!==1||!j(e.envelope)||!j(e.envelope.claims))return!1;let r=e.envelope.claims;return r.agentId===t.agentId&&r.sessionId===t.sessionId&&r.skillSlug===t.skillSlug&&r.version===t.skillVersion&&r.generationId===t.generationId&&r.workspaceId===t.workspaceId&&typeof r.expiresAt=="string"&&Date.parse(r.expiresAt)>Date.parse(n)+5e3}async function rd(e,t){let n=Me(e);await Jo(n);let r=K(n,`.${ot(e)}.${Ge(12).toString("hex")}.tmp`),i=null;try{i=await zo(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
2181
2181
  `,"utf8"),await i.sync(),await i.close(),i=null,await qo(r,e),await Yo(e,384),await PA(n)}finally{await i?.close().catch(()=>{}),await Ze(r,{force:!0}).catch(()=>{})}}function YU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-binding.json"):K(e.cwd,".skills-layer","guardian-session-binding.json")}function VP(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session.json"):K(e.cwd,".skills-layer","guardian-session.json")}function XU(e){return!e||e==="enforce"||e==="enabled"?"enforce":e==="warning"||e==="warning-only"||e==="warning_only"?"warning_only":e==="disabled"||e==="off"?"disabled":null}function QU(e,t){let n=e[t];if(!j(n))return null;let r=Object.entries(n);return r.every(([,i])=>typeof i=="string")?Object.fromEntries(r):null}async function qn(e,t){let n=t?[t]:["project","global"],r=[],i=new Set;for(let l of n){let c=lz(e,l);if(i.has(c))continue;i.add(c);let u=await cz(c);for(let d of u.hooks){let p=f(d,"hookPath"),m=p?HP(e,l,p):null,h=f(d,"configPath"),g=h?HP(e,l,h):null,y=m?await fr(m):!1,v=g?await fr(g):null,b=y?v===!1?"active_missing_config":"active":"stale_missing_hook",w=await vae({backend:e,scope:l,hook:d,absoluteHookPath:m,absoluteConfigPath:g,hookActive:y,configActive:v});r.push({hookId:f(d,"hookId")??$t,hookName:f(d,"hookName")??xt,...d,scope:f(d,"scope")??l,hookPath:m??p??null,configPath:g??h??null,active:y,configActive:v,hookState:b,strictPreActionBlocking:w.capability==="strict",exactActivationVerified:w.exactActivationVerified,activationRoute:w.activationRoute,evidenceCapability:w.capability,evidenceReasons:w.reasons,nextStep:!y||v===!1?`Run skills-layer guardian hook install --agent ${String(d.agent)} --scope ${l}.`:w.capability!=="strict"?"This hook is installed but not strict-verified. Standard workspaces permit installation with a warning. For strict workspaces, ask your Admin for an adapter with current matching real-host canary evidence; hook install does not create that evidence.":"Strict host evidence is current. Install the approved skill using this exact agent and scope.",evidencePath:w.evidencePath,qualifiedHostExecutablePath:w.qualifiedHostExecutablePath,qualifiedHostExecutableSha256:w.qualifiedHostExecutableSha256})}}let o=r.filter(l=>l.active===!0).length,s=r.filter(l=>l.active===!1).length,a=o>0?0:s;return{status:"ok",enforcementLayer:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0)?"native_hook":o>0?"native_hook_candidate":"not_installed",strictPreActionBlocking:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0),exactActivationVerified:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0&&l.exactActivationVerified===!0),activeHookCount:o,missingHookCount:a,staleHookCount:s,hooks:r,setup:await wA(e),warnings:s>0?o>0?["One or more stale Guardian hook records were found, but an active Skills Layer Security Hook is installed."]:["One or more configured Guardian hooks are missing from disk. Run skills-layer guardian hook install --agent <agent> again to repair them."]:[]}}async function vae(e){let t=f(e.hook,"agent"),n=f(e.hook,"hostVersion"),r=f(e.hook,"adapterRevision"),i=f(e.hook,"absoluteCliPath"),o=f(e.hook,"evidencePath"),s=o?HP(e.backend,e.scope,o):null;if(!t||!kr(t))return{capability:"unverified",reasons:["strict_adapter_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(br(t)?.maximumTier!=="strict_candidate")return{capability:"unverified",reasons:["host_strict_tier_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(!e.hookActive||e.configActive!==!0||!e.absoluteHookPath||!e.absoluteConfigPath)return{capability:"unverified",reasons:["hook_installation_incomplete"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(!n||!r||!i||!s)return{capability:"unverified",reasons:["hook_binding_metadata_missing"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};let a=await be(s);if(!a)return{capability:"unverified",reasons:["live_canary_evidence_missing"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};try{let l=await kE({agentId:t,platform:mr(e.backend.platform),hostVersion:n,adapterRevision:r,hookConfigPath:e.absoluteConfigPath,hookScriptPath:e.absoluteHookPath,absoluteCliPath:i}),c=vE({evidence:a,currentBinding:l,asOf:e.backend.now()}),u=br(t),d=c.capability==="strict"&&(u.automaticAssociation==="native_activation"?a.activationRoute==="native_activation":u.automaticAssociation==="approved_launcher_required"&&a.activationRoute==="approved_launcher");return{capability:d?c.capability:"unverified",reasons:d?c.reasons:[...c.reasons,"activation_route_does_not_match_host_capability"],evidencePath:s,exactActivationVerified:d,activationRoute:a.activationRoute,qualifiedHostExecutablePath:a.qualification.hostExecutablePath,qualifiedHostExecutableSha256:a.qualification.hostExecutableSha256}}catch{return{capability:"unverified",reasons:["current_installation_binding_unverifiable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null}}}async function ez(e,t){if(e.json){let c=await be(t.paths.mcpConfigPath),u=c&&Array.isArray(c.clientIds)?c.clientIds.filter(p=>typeof p=="string"):c&&f(c,"clientId")?[f(c,"clientId")]:[],d=await gz(t,u);return R({setup:await wA(t),mcp:{status:c?"mcp_configured":"mcp_not_configured",configured:!!c,clientId:u[0],clientIds:u,hosts:d,mcpUrl:c?f(c,"mcpUrl"):void 0,readiness:c?{status:"configured_needs_agent_reload",verifyCommand:u.length===1?`skills-layer mcp verify --client ${u[0]}`:"skills-layer mcp verify",nextStep:"Open a fresh agent session if Skills Layer tools are not visible yet."}:void 0,nextCommand:c?"skills-layer mcp verify":"skills-layer mcp setup"},guardian:await qn(t)},"Setup status loaded.",!0,t)}if(!t.stdoutIsTty)return R({status:"setup_needs_terminal",mcp:{nextCommand:"skills-layer mcp setup"},security:{nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Setup needs an interactive terminal. Run `skills-layer setup`, or use `skills-layer mcp setup` and `skills-layer guardian hook install --agent codex --scope project`.",!1,t);let n=await t.promptSelect("Set up Skills Layer on this machine?",[{value:"mcp",label:"Setup Skills-Layer MCP",description:"Configure Skills Layer MCP for AI tools"},{value:"security",label:"Setup Skills-Layer Security Guardian",description:"Install Guardian hooks for this workspace"},{value:"both",label:"Setup both - MCP & Security Guardian",description:"Connect supported AI tools and install Guardian hooks"},{value:"not_now",label:"Remind me Later",description:"Skip setup for now; you can run skills-layer setup later"}]);if(n==="not_now"){let c={version:1,setupChoice:"not_now",mcpChoice:"not_now",mcpPromptedAt:t.now(),guardianHookChoice:"not_now",guardianHookPromptedAt:t.now(),remindAfter:bae(t.now(),7)};return await jM(t,c),R({status:"setup_skipped",mcp:{status:"not_configured",nextCommand:"skills-layer mcp setup"},security:{status:"not_configured",nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Skills Layer setup skipped for now. Run `skills-layer setup` when you want MCP and Security hooks on this machine.",!1,t)}if(n!=="both"&&n!=="mcp"&&n!=="security")return E(`Unknown setup option "${n}".`,e.json);let r=n==="both"||n==="mcp",i=n==="both"||n==="security",o={status:"setup_complete",setupChoice:n},s={version:1,setupChoice:n,mcpChoice:r?"configured":"not_requested",mcpPromptedAt:t.now(),guardianHookChoice:i?k(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(r)if(!t.apiKey)o.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},s.mcpChoice="login_required";else{let c=await nA(e,t);if(fe(c))return c;o.mcp=c}if(i){let c={...e,json:!0,scope:k(e.scope)??"project",agent:k(e.agent)??"codex"},u=await qU(c,t);if(u.exitCode!==0)return u;let d=tle(u.stdout),p=j(d)?d:{status:"enabled",agent:k(c.agent),scope:k(c.scope)};o.security=p,o.agent=f(p,"agent")??k(c.agent),o.scope=f(p,"scope")??k(c.scope),o.enforcementLayer=f(p,"enforcementLayer")??"native_hook_candidate",o.strictPreActionBlocking=p.strictPreActionBlocking===!0,o.hookPath=f(p,"hookPath"),o.configPath=f(p,"configPath"),o.nextAction="guardian.hook.status",o.nextStep=`Run \`skills-layer guardian hook status --scope ${f(p,"scope")??"project"}\` to inspect the candidate binding. Strict pre-action blocking remains unverified until real host allow/deny canaries pass.`}await jM(t,s);let l=(j(o.mcp)?f(o.mcp,"status"):void 0)==="login_required"?"Skills Layer Security setup complete. MCP setup needs login; run `skills-layer login`, then `skills-layer setup`.":n==="security"?"Skills Layer Security Guardian setup complete.":n==="mcp"?"Skills Layer MCP setup complete. Open a fresh agent session if MCP tools are not visible yet.":"Skills Layer MCP and Security Guardian setup complete. Open a fresh agent session if MCP tools are not visible yet.";return R(o,l,e.json,t)}async function kae(e,t){let n=await qn(t),r=await wA(t),i=J(n,"activeHookCount")??0;if(t.stdoutIsTty&&i===0&&!r)return await ez(e,t);let o=i>0?"Guardian host hooks are already configured. Run `skills-layer guardian hook status` to inspect them.":"Guardian is enabled for Skills Layer runtime checks. Run `skills-layer setup` when you want MCP and Security hooks on this machine.";return{exitCode:0,stdout:`${jo(t.renderMode)}
2182
2182
 
2183
2183
  ${o}`,stderr:""}}function wae(e,t){let n=J(e,"activeHookCount")??0,r=J(e,"missingHookCount")??0,i=f(t,"status")??"unknown",o=f(t,"effectiveMode"),s=f(t,"adminPolicy"),a=f(t,"nextAction"),l=f(t,"nextStep"),c=e.strictPreActionBlocking===!0;return n>0&&r===0&&c?{id:"guardian-local-hook",title:"Guardian local hook",status:"pass",summary:`Guardian native hook active count: ${n}.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:c,measuredProtection:"verified_strict",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status"}:n>0&&r===0?{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian candidate hook active count: ${n}; live strict evidence is not current.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook_candidate",strictPreActionBlocking:!1,measuredProtection:"candidate_unverified",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status",nextStep:"Run the agent/platform live canaries and inspect Guardian hook status before relying on enforced protection."}:{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian native hook setup needs attention. Active hooks: ${n}; missing hooks: ${r}.`,enforcementLayer:f(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:c,measuredProtection:"unavailable",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook install --agent codex --scope project",nextStep:"Install a Guardian host hook for automatic checks, or route risky shell actions through `skills-layer guardian exec` for strict pre-execution blocking."}}function bae(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function tz(e){let t=rz(k(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:E(t.message,e.flags.json)};let n=await nz({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.reasonCode==="local_install_target_selection_required")return Lo({...e,context:n,reasonCode:n.reasonCode,message:"Guardian needs one exact local skill target before it can make an execution decision.",why:"This skill is installed in more than one target and the command did not identify which materialization is active.",nextAction:"guardian.check",nextStep:"Repeat the command with --agent, --scope, or --path so Guardian can bind the decision to one exact installed target."});if(n.unmanaged&&(n.unmanagedPolicy==="allow"||n.allowUnmanagedOnce))return Lo({...e,context:n,reasonCode:"guardian_unmanaged_atomic_execution_required",message:"Guardian check cannot authorize unmanaged execution.",why:"A diagnostic check cannot safely bind a one-use decision to the exact local process that would consume it.",nextAction:"install",nextStep:"Install or import the exact skill generation, then use `skills-layer guardian exec <skill-slug> -- <command>` for atomic guarded execution."});if(n.unmanaged&&n.unmanagedPolicy==="block")return Lo({...e,context:n,reasonCode:"unmanaged_skill_blocked",message:"Guardian blocked unmanaged local skill execution.",why:"The skill path is not backed by a public install index or lockfile entry and unmanaged policy is block.",nextAction:"install",nextStep:"Install or import the exact skill generation before requesting a Guardian execution decision."});let r=n.record?Yt(n.record):null;if(r&&r.state!=="active"){let s=r.state==="quarantined"?"skill_quarantined":r.state==="restore_pending"?"skill_restore_pending":r.state==="externally_removed"?"skill_externally_removed":r.state==="host_detached"?"skill_host_detached":r.state==="unreadable"?"skill_target_unreadable":r.state==="drifted"?"installed_artifact_changed":"skill_activation_pending";return Lo({...e,context:n,reasonCode:s,message:"Guardian blocked the action because this exact local generation is not active.",why:`The atomic local lifecycle state is ${r.state}.`,nextAction:r.state==="quarantined"?"guardian.incident.review":"installed",nextStep:r.state==="quarantined"?"Review the quarantine evidence and request a fresh exact-generation restore approval before re-enabling the skill.":r.state==="externally_removed"?"Reinstall the exact skill generation, or explicitly remove the retained tombstone after reviewing it.":"Complete or repair the local lifecycle transaction before running this skill."})}if(!n.installedPath)return{status:"ok",context:n};if(await Jae(n.installedPath))return Lo({...e,context:n,reasonCode:"skill_disabled",message:"Guardian blocked the action because this local skill is disabled.",why:"A local Guardian incident marker is present for this skill.",nextAction:"guardian.incident.review",nextStep:"Review the local incident report before running this skill again."});if(n.unmanaged)return{status:"ok",context:n};let i=await xae(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return Lo({...e,context:n,reasonCode:f(i,"reasonCode")??"skill_identity_mismatch",message:"Guardian blocked the action because the installed skill identity changed.",why:"The visible SKILL.md identity no longer matches the installed skill record.",nextStep:"Reinstall or re-attest the skill before running it again."});let o=await Cae(e.skillSlug,n.installedPath,e.backend,n.record);return n.driftAssessment=o,o.reattestationRequired===!0?Lo({...e,context:n,reasonCode:f(o,"reasonCode")??"installed_artifact_changed",message:"Guardian blocked the action because local runtime metadata detected installed artifact drift.",why:"The installed SKILL.md hash no longer matches the materialized runtime metadata.",nextStep:"Reinstall or re-attest the skill before running it again."}):{status:"ok",context:n}}async function Lo(e){return await Ha(e.backend,{skillSlug:e.skillSlug,version:e.version??e.context.version,action:e.action,decisionStatus:"blocked",reasonCode:e.reasonCode,telemetryMode:e.telemetryMode,path:e.context.installedPath}),{status:"blocked",result:x({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:Vu(e.context),unmanaged:e.context.unmanaged,unmanagedPolicy:e.context.unmanagedPolicy,allowUnmanagedOnce:e.context.allowUnmanagedOnce,why:e.why,nextAction:e.nextAction,nextStep:e.nextStep},e.message,e.flags.json,e.reasonCode)}}async function nz(e){let t=rz(k(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),r=k(e.flags.path),i=r?Tt(e.backend.cwd,r):void 0,o=await _ae(e.skillSlug,e.backend,{scope:k(e.flags.scope),agent:k(e.flags.agent),installedPath:i}),s=i??o?.installedPath;return{source:r?"explicit_path":o?.source??"install_index",status:r?"ok":o?.status,reasonCode:r?void 0:o?.reasonCode,installedPath:s,archivePath:r?void 0:o?.archivePath,installedPathSource:r?"explicit_path":o?.installedPathSource,version:k(e.flags.version)??o?.version,record:o?.record,unmanaged:!!(r&&!o),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function _ae(e,t,n={}){let i=(await zi(t,e)).installs[e];if(i){let o=Vn(i,{...n,platform:t.platform});if(o.length>1)return{source:"install_index",status:"degraded",reasonCode:"local_install_target_selection_required",version:f(i,"version"),record:i};if(o.length===0)return null;let s=hr(i,o[0]),a=OM(s,t);return{source:"install_index",installedPath:a.installedPath,archivePath:a.archivePath,installedPathSource:a.installedPathSource,status:a.status,reasonCode:a.reasonCode,version:f(s,"version"),record:s}}for(let o of Sae(t)){let s=await be(o);if(!j(s)||!j(s.installs))continue;let a=s.installs[e];if(j(a)){let l=OM(a,t);return{source:"lockfile",installedPath:l.installedPath,archivePath:l.archivePath,installedPathSource:l.installedPathSource,status:l.status,reasonCode:l.reasonCode,version:f(a,"version"),record:a}}}return null}function Sae(e){return Array.from(new Set([K(e.cwd,"skills-layer-lock.json"),K(e.paths.stateDir,"skills-layer-lock.json")]))}function OM(e,t){let n=f(e,"materializedSkillRoot");if(n)return{installedPath:hh(Tt(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let r=f(e,"canonicalPath");if(r)return{installedPath:hh(Tt(t.cwd,r)),installedPathSource:"canonicalPath",status:"ok"};let i=f(e,"path");if(i)return{installedPath:hh(Tt(t.cwd,i)),installedPathSource:"path",status:"ok"};let o=f(e,"materializedPath")??f(e,"bundlePath");if(o){let c=Tt(t.cwd,o),u=ot(c).toLowerCase()==="bundle.zip"||c.toLowerCase().endsWith(".zip");return{installedPath:u?Me(Me(c)):hh(c),archivePath:u?c:void 0,installedPathSource:f(e,"materializedPath")?"materializedPath":"bundlePath",status:u?"degraded":"ok",reasonCode:u?"installed_skill_root_missing":void 0}}let a=(Array.isArray(e.materializedWrites)?e.materializedWrites.filter(j):[]).find(c=>{let u=f(c,"path");return u?.toLowerCase().endsWith("/skill.md")||u?.toLowerCase()==="skill.md"}),l=a?f(a,"path"):void 0;return{installedPath:l?Me(Tt(t.cwd,l)):void 0,installedPathSource:l?"materializedWrites":void 0,status:l?"ok":void 0}}function hh(e){return ot(e).toLowerCase()==="skill.md"?Me(e):e}async function xae(e,t){let n=K(t,"SKILL.md");if(!await fr(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let r=AU(await Ui(n,"utf8"));return r?r!==e?{status:"mismatch",reasonCode:"skill_identity_mismatch",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!0}:{status:"matched",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!1}:{status:"not_checked",reasonCode:"skill_identity_metadata_unavailable",expectedSkillSlug:e,skillDocumentPath:n,reattestationRequired:!1}}catch(r){return{status:"invalid",reasonCode:"skill_identity_unreadable",expectedSkillSlug:e,skillDocumentPath:n,message:ke(r),reattestationRequired:!0}}}async function Cae(e,t,n,r){let i=r?Yt(r):null;if(i){let p=await Tr(i.receipt);return p.status==="verified"?{status:"unchanged",reasonCode:"installed_tree_manifest_matches",skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!1}:{status:"changed",reasonCode:p.reasonCode,skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!0}}let o=K(t,".skills-layer-runtime.json"),s=await be(o),a=s?T(s,"materialization"):void 0,l=a?f(a,"skillDocumentSha256"):void 0;if(!s||!l)return{status:"not_checked",reasonCode:"runtime_metadata_unavailable",skillSlug:e,reattestationRequired:!0};let c=K(t,"SKILL.md");if(!await fr(c))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,reattestationRequired:!0};let u=fz(await Ui(c,"utf8")),d=u===l;return{status:d?"unchanged":"changed",reasonCode:d?"installed_artifact_matches":"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,observedSkillDocumentSha256:u,reattestationRequired:!d}}function Vu(e){return ie({source:e.source,status:e.status,reasonCode:e.reasonCode,installedPath:e.installedPath,archivePath:e.archivePath,installedPathSource:e.installedPathSource,version:e.version,unmanaged:e.unmanaged,unmanagedPolicy:e.unmanagedPolicy,allowUnmanagedOnce:e.allowUnmanagedOnce,identityAssessment:e.identityAssessment,driftAssessment:e.driftAssessment})}function rz(e){if(e===void 0||e.trim()==="")return{status:"valid",policy:"warn"};let t=e.trim().toLowerCase();return t==="allow"||t==="warn"||t==="block"?{status:"valid",policy:t}:{status:"invalid",message:"guardian check --unmanaged-policy must be one of: allow, warn, block."}}function GP(e,t){let n=k(e)??t;return n==="cloud_managed"||n==="local_only"?{status:"valid",mode:n}:{status:"invalid",message:"guardian --telemetry-mode must be one of: cloud_managed, local_only."}}function LM(e,t){return{type:"shell_command",command:ot(t?.executableRealPath??e[0]??"command"),...t?{metadata:{executableRealPath:t.executableRealPath,executableSha256:t.executableSha256,argvSha256:oz(t.argv),cwdRealPath:t.cwdRealPath,fileTargets:t.fileTargets,networkTargets:t.networkTargets,environmentKeys:t.environmentKeys,callerActionJsonIgnored:!0,callerGrantJsonIgnored:!0}}:{}}}function Iae(e){let t=T(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:KP(e)!=="blocked"}async function Pae(e){let t=Aae(e.backend.platform);if(!t)return Lu(e,"guardian_platform_unsupported","Guardian guarded execution is unavailable on this platform.");if(t==="win32")return Lu(e,"windows_process_tree_isolation_unavailable","Guardian strict execution on Windows requires a verified Job Object process-tree adapter.");if(e.commandArgs.some(Lae))return Lu(e,"guardian_secret_in_argv","Guardian refuses likely credentials in command arguments; pass only explicitly brokered named environment secrets.");try{let[n,r]=await Promise.all([iz(e.commandArgs[0],e.backend,t),Bu(e.backend.cwd)]),i=await Ya(n);if(!i.isFile()||i.size<=0||i.size>256*1024*1024)return Lu(e,"guardian_executable_invalid","Guardian requires a bounded regular executable file.");let o=`sha256:${Ue("sha256").update(await Ui(n)).digest("hex")}`,s=Tae(e.flags,e.backend.env),a=await Eae(e.commandArgs.slice(1),r,e.backend,t),l=k(e.flags.agent)??(e.localContext.record?f(e.localContext.record,"agent")??f(e.localContext.record,"targetAgent"):void 0)??Ee(e.backend.config?.lastSelectedAgent)??"skills-layer-cli";return{status:"ok",approvedSecrets:s,request:{platform:t,actionFamily:"shell_execution",executableRealPath:n,executableSha256:o,argv:e.commandArgs.slice(1),cwdRealPath:r,fileTargets:a.fileTargets,networkTargets:a.networkTargets,immutableInputs:a.immutableInputs,environmentKeys:Oae(t,Object.keys(s)),skillSlug:e.skillSlug,version:e.version,...k(e.flags.workspaceId)?{workspaceId:k(e.flags.workspaceId)}:{},agentId:l,hostVersion:Co,sessionId:`guardian_session_${Ge(16).toString("hex")}`}}}catch(n){let r=n instanceof De?n.reasonCode:"guardian_plan_resolution_failed";return Lu(e,r,`Guardian could not resolve the exact execution plan: ${ke(n)}`)}}function Lu(e,t,n){return{status:"blocked",result:x({status:"blocked",reasonCode:t,skillSlug:e.skillSlug},n,e.flags.json,t)}}function Aae(e){return e==="darwin"||e==="linux"||e==="win32"?e:null}async function iz(e,t,n){if(!e||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Executable name is invalid.");let r=n==="win32"?st:Lt,o=r.isAbsolute(e)||e.includes("/")||e.includes("\\")?[r.isAbsolute(e)?e:r.resolve(t.cwd,e)]:Rae(e,t,n);for(let s of o.slice(0,128))try{await JM(s,n==="win32"?jB.F_OK:jB.X_OK);let a=await Bu(s);if((await Ya(a)).isFile())return a}catch{}throw new Error(`Executable ${ot(e)} was not found as an accessible regular file.`)}function Rae(e,t,n){let r=n==="win32"?st:Lt,o=(Ee(t.env.PATH)??(n==="win32"?"C:\\Windows\\System32":"/usr/local/bin:/usr/bin:/bin")).split(n==="win32"?";":":").filter(Boolean).slice(0,64),s=n==="win32"&&!st.extname(e)?(Ee(t.env.PATHEXT)??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean).slice(0,8):[""];return o.flatMap(a=>s.map(l=>r.join(a,`${e}${l}`)))}async function Eae(e,t,n,r){let i=new Set,o=new Set,s=new Map;for(let[a,l]of e.entries()){let c=l.startsWith("--")&&l.includes("=")?l.slice(l.indexOf("=")+1):l;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(c)){let p=new URL(c);if(p.protocol!=="https:")throw new Error("Guardian network targets must use HTTPS.");o.add(p.toString());continue}if(!$ae(c,r))continue;let u=await Dae(c,t,n,r);i.add(u);let d=await Ya(u).catch(()=>null);if(d?.isFile()){let p=s.get(u);p?p.argumentIndexes.push(a):s.set(u,{path:u,sha256:`sha256:${Ue("sha256").update(await Ui(u)).digest("hex")}`,size:d.size,argumentIndexes:[a]})}}return{fileTargets:[...i].sort(wh),networkTargets:[...o].sort(wh),immutableInputs:[...s.values()].sort((a,l)=>wh(a.path,l.path))}}function $ae(e,t){return!e||e.startsWith("-")?!1:(t==="win32"?st:Lt).isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.includes("/")||e.includes("\\")}async function Dae(e,t,n,r){let i=r==="win32"?st:Lt,o=r==="win32"?Ee(n.env.USERPROFILE)??Ee(n.env.HOME):Ee(n.env.HOME),s=e.startsWith("~/")&&o?i.join(o,e.slice(2)):e,a=i.normalize(i.isAbsolute(s)?s:i.resolve(t,s));try{return await Bu(a)}catch{let l=await Bu(i.dirname(a));return i.join(l,i.basename(a))}}function Tae(e,t){let n=Array.isArray(e.secretEnv)?e.secretEnv:typeof e.secretEnv=="string"?[e.secretEnv]:[],r={};for(let i of[...new Set(n)]){if(!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(i))throw new Error(`Secret environment key ${i} is invalid.`);let o=t[i];if(typeof o!="string"||o.length===0)throw new Error(`Secret environment key ${i} is unavailable.`);r[i]=o}return r}function Oae(e,t){let n=e==="win32"?["PATH","SystemRoot","TEMP","TMP","USERPROFILE"]:["HOME","PATH","TMPDIR"];return[...new Set([...n,...t])].sort(wh)}function Lae(e){return/(?:mktplace_|slg_exec_|github_pat_|gh[opusr]_|sk-)[A-Za-z0-9_-]{8,}/u.test(e)||/(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*[^\s]+/iu.test(e)||/-----BEGIN [^-\r\n]{1,64} PRIVATE KEY-----/u.test(e)}function oz(e){return`sha256:${Ue("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function wh(e,t){return e<t?-1:e>t?1:0}function jae(e){let t=[e.exitCode===0?"OK Guardian guarded execution complete.":"Guardian guarded execution finished with a command error.","","Command",` executable: ${e.executable}`,` args count: ${e.argsCount}`,` exit code: ${e.exitCode}`];return e.stdout&&t.push("","Stdout",e.stdout),e.stderr&&t.push("","Stderr",e.stderr),t.join(`
@@ -2300,7 +2300,7 @@ Delisted on ${f(l,"delistedAt")??"an unrecorded date"}; existing buyers keep acc
2300
2300
  `)}function Fu(e,t){if(j(e))return typeof e[t]=="boolean"?e[t]:void 0}function qe(e,t){return j(e)?f(e,t):void 0}function Lle(e){return e.split(/[_-]+/u).filter(Boolean).map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function GM(e){return!!(T(e,"backend")&&T(e,"auth")&&Array.isArray(e.checks))}function jle(e,t,n){let r=[`${n.ok("OK")} ${t}`,"",n.section("Readiness")],i=f(e,"summary");i&&r.push(` ${i}`);let o=T(e,"backend"),s=o?Ule(o):void 0;s&&r.push(` ${n.label("Backend")}: ${s}`);let a=T(e,"auth"),l=a?zle(a):void 0;l&&r.push(` ${n.label("Account")}: ${l}`);let c=a?J(a,"personalModeCount"):void 0,u=a?J(a,"enterpriseWorkspaceCount")??J(a,"workspaceCount"):void 0,d=a?J(a,"availableWorkingModeCount"):void 0;c!==void 0&&r.push(` ${n.label("Personal modes")}: ${c}`),u!==void 0&&r.push(` ${n.label("Enterprise workspaces")}: ${u}`),d!==void 0&&r.push(` ${n.label("Available workspace choices")}: ${d}`);let p=a?J(a,"libraryCount"):void 0;p!==void 0&&r.push(` ${n.label("Owned skills")}: ${p}`);let m=T(e,"localRuntime"),h=m?T(m,"guardian"):void 0,g=m?T(m,"mcp"):void 0;(h||g)&&(r.push("",n.section("Local runtime")),h&&r.push(` ${n.label("Guardian")}: ${qe(h,"enforcementLayer")??"not_installed"}`,` ${n.label("Strict pre-action blocking")}: ${Fu(h,"strictPreActionBlocking")===!0?"yes":"no"}`),g&&r.push(` ${n.label("MCP")}: ${Fu(g,"configured")===!0?"configured":"not configured"}`));let y=Cz(e);return y.length>0&&r.push("",n.section("Next"),...y.map(v=>` ${n.arrow} ${v}`)),r.push(` ${n.arrow} Run \`skills-layer doctor\` for diagnostics.`),r.join(`
2301
2301
  `)}function Nle(e,t,n){let r=[`${n.ok("OK")} ${t}`,"",n.section("Diagnostics")],i=f(e,"summary");i&&r.push(` ${i}`);let o=f(e,"status");o&&r.push(` ${n.label("Status")}: ${o}`);let s=Iz(e),a=s.filter(u=>qle(f(u,"status"))),l=s.filter(u=>f(u,"status")!=="pass");r.push(a.length===0?" No blocking issues found.":` ${a.length} check${a.length===1?"":"s"} need attention.`),a.length===0&&l.length>0&&r.push(` Advisory checks needing attention: ${l.length}.`),r.push("",n.section(`Checks (${s.length})`)),s.length===0&&r.push(` ${n.muted("No checks returned by the backend.")}`),s.forEach((u,d)=>{let p=f(u,"status")??"unknown",m=f(u,"title")??f(u,"id")??`Check ${d+1}`;r.push(`${d+1}. ${n.label(`[${p}] ${m}`)}`);let h=f(u,"summary");h&&r.push(` ${h}`);let g=f(u,"why");if(g&&r.push(` ${n.label("Why")}: ${g}`),p!=="pass"){let y=f(u,"nextStep");y&&r.push(` ${n.label("Fix")}: ${y}`);let v=f(u,"recommendedCommand");v&&r.push(` ${n.label("Try")}: ${v}`)}});let c=Cz(e);return c.length>0&&r.push("",n.section(a.length>0?"Recommended Fix":"Next"),...c.map(u=>` ${n.arrow} ${u}`)),r.join(`
2302
2302
  `)}function Fle(e,t,n,r){let i=[`${n.ok("OK")} ${t}`],o=zn(e,"requestedSlugs");o&&o.length>0&&i.push("",n.section("Requested"),` ${o.join(", ")}`);let s=dn(e.results);i.push("",n.section(`Comparison (${s.length})`)),s.length===0&&i.push(` ${n.muted("No comparable skills returned.")}`),s.forEach((u,d)=>{let p=JP(u)??`Skill ${d+1}`;i.push(`${d+1}. ${p}`),i.push(...ad(u).map(g=>` ${g}`));let m=Ble(u);m&&i.push(` ${m}`);let h=Ez(u);h&&i.push(` ${n.label("summary")}: ${r?h.replace(/\s+/gu," ").trim():Ja(h)}`)});let a=dn(e.missing);a.length>0&&(i.push("",n.section(`Missing (${a.length})`)),a.forEach((u,d)=>{let p=f(u,"slug")??f(u,"skillSlug")??JP(u)??`Entry ${d+1}`,m=f(u,"reason")??f(u,"status");i.push(`${d+1}. ${m?`${p} - ${m}`:p}`)}));let l=zn(e,"guidance")??Wa(e.guidance);l.length>0&&i.push("",n.section("Guidance"),...l.slice(0,3).map(u=>` ${n.arrow} ${Ja(u)}`));let c=Mle(s);return c.length>0&&i.push("",n.section("Next"),...c.map(u=>` ${n.arrow} ${u}`)),i.join(`
2303
- `)}function Ble(e){let t=T(e,"securityPosture"),n=f(e,"trust")??f(e,"trustStatus")??f(e,"trustLabel")??(t?f(t,"label"):void 0),r=e.score??e.securityScore??(t?t.securityScore:void 0),i=f(e,"risk")??f(e,"runtimeRisk")??(t?f(t,"runtimeRisk"):void 0);return[["slug",f(e,"slug")??f(e,"skillSlug")],["version",f(e,"version")??f(e,"currentVersion")],["category",f(e,"category")],["type",f(e,"type")??f(e,"skillType")],["trust",n],["score",r],["risk",i]].flatMap(([s,a])=>a==null||a===""?[]:[`${s}: ${pn(String(s),a)}`]).join("; ")}function Mle(e){let t=[];for(let n of e.slice(0,5)){let r=f(n,"slug")??f(n,"skillSlug");r&&t.push(`skills-layer show ${r}`,`skills-layer trust ${r}`,`skills-layer install ${r}`)}return t}function Ule(e){let t=f(e,"edition"),n=f(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function zle(e){let t=f(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=f(e,"email"),r=zn(e,"roles");return n&&r&&r.length>0?`${n} (${r.join(", ")})`:n??f(e,"role")}function Cz(e){let t=[],n=f(e,"recommendedCommand");n&&t.push(n);let r=f(e,"nextStep");return r&&t.push(r),t}function Iz(e){return Array.isArray(e.checks)?e.checks.filter(j):[]}function qle(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function dn(e){return Array.isArray(e)?e.filter(j):[]}function Wa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Vle(e){let t=e.commerce===!0;return{status:t?"available":"unavailable",summary:t?"Marketplace purchases, invoices, refunds, and creator commerce flows are available.":"Marketplace commerce is not available on this backend.",availableWorkflows:t?["Browse skills with `skills-layer featured` or `skills-layer search <query>`.","Start purchase handoff with `skills-layer buy <skill-slug>`.","Review account purchases with `skills-layer purchases list`."]:["Browse and install available free skills.","Use `skills-layer help topic install` for install guidance."]}}var Gle={"core.identity":"Account and sign-in","core.catalog":"Catalog discovery","core.validation":"Creator validation","core.creator":"Creator submissions","core.library":"Owned skills","core.workspace":"Workspace rollout","core.guardian":"Runtime trust checks","core.source":"Source installs","core.discovery":"Catalog discovery","marketplace.commerce":"Marketplace commerce","marketplace.reviews":"Reviews and issues","marketplace.payouts":"Creator earnings"};function Hle(e){let t=Wa(e.capabilities);return{status:"ok",edition:f(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:Gle[n]??Mh(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function Kle(e,t){let n=k(e);if(!n)return;let r=Number(n);return!Number.isInteger(r)||r<=0?E("help optimize-tokens --max-characters must be a positive integer.",t):r<120||r>4e3?E("help optimize-tokens --max-characters must be between 120 and 4000.",t):r}function Wle(e,t,n){let r=Ae(n),i=T(e,"validation")??e,o=T(i,"parsedSkill")??T(e,"parsedSkill"),s=o?T(o,"frontmatter"):void 0,a=f(e,"skillSlug")??(s?f(s,"name"):void 0),l=i.valid===!0||e.valid===!0,c=wP(i,e,"issues"),u=wP(i,e,"warnings"),d=wP(i,e,"advice"),p=T(i,"stats")??T(e,"stats"),m=[l?`${r.ok("OK")} Validation complete.`:"Validation failed.","",r.section("Bundle")];m.push(` ${r.label("Path")}: ${t}`),a&&m.push(` ${r.label("Skill")}: ${a}`),m.push(` ${r.label("Readiness")}: ${l?"ready for dry-run submission":"needs changes before submission"}`),m.push("",r.section("Checks")),m.push(` ${r.arrow} SKILL.md structure and frontmatter`),m.push(` ${r.arrow} Required bundle files and supported directories`),m.push(` ${r.arrow} Secret hygiene, unsafe script signals, and trust-review readiness`),m.push(` ${r.arrow} Trigger quality inputs for should-trigger / should-not-trigger testing`);let h=T(e,"evalReadiness");if(h){let v=T(h,"summaryEnvelope"),b=Array.isArray(v?.statuses)?v.statuses.map(P=>String(P)).join(", "):void 0,w=T(h,"score"),_=w?J(w,"effectiveScorePercent"):void 0,C=w?J(w,"overallScore"):void 0;m.push("",r.section("Effectiveness Eval")),m.push(` ${r.label("Posture")}: ${f(h,"label")??f(h,"status")??"limited"}`),m.push(` ${r.label("Origin")}: ${f(h,"origin")??"inferred"}`),_!==void 0?m.push(` ${r.label("Effective score")}: ${Dh(_)}`):C!==void 0&&m.push(` ${r.label("Effective score")}: ${Dh(C*100)}`),m.push(` ${r.label("Artifact digest")}: ${f(h,"artifactDigest")??"unavailable"}`),h.runtimeFileCount!==void 0&&m.push(` ${r.label("Runtime files")}: ${pn("runtimeFileCount",h.runtimeFileCount)}`),h.evidenceFileCount!==void 0&&m.push(` ${r.label("Evidence files excluded")}: ${pn("evidenceFileCount",h.evidenceFileCount)}`),m.push(` ${r.label("Submit envelope")}: mandatory${b?` (${b})`:""}`)}if(p){let v=p.fileCount??p.files??e.fileCount,b=p.bodyWordCount??p.bodyWords??e.bodyWordCount;m.push("",r.section("File Summary")),v!==void 0&&m.push(` ${r.label("File count")}: ${pn("fileCount",v)}`),b!==void 0&&m.push(` ${r.label("Body words")}: ${pn("bodyWordCount",b)}`)}let g=T(e,"securityReport");g&&(m.push("",r.section("Security")),m.push(` ${r.label("Recommendation")}: ${f(g,"recommendation")??"unknown"}`),m.push(...yh("Findings",Array.isArray(g.findings)?g.findings:[],r,"No security findings returned.")));let y=T(e,"aiReview");if(y){m.push("",r.section("AI Review")),m.push(` ${r.label("Status")}: ${f(y,"status")??"unknown"}`);let v=f(y,"message");v&&m.push(` ${v}`);let b=f(y,"nextStep");b&&m.push(` ${r.arrow} ${b}`)}return m.push("",...yh("Issues",c,r,"No blocking issues found.")),m.push("",...yh("Warnings",u,r,"No warnings returned.")),m.push("",...yh("Advice",d,r,"No extra advice returned.")),m.push("",r.section("Next")),l?(m.push(` ${r.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),m.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`)):m.push(` ${r.arrow} Fix the listed issues, then run skills-layer validate ${t}`),m.join(`
2303
+ `)}function Ble(e){let t=T(e,"securityPosture"),n=f(e,"trust")??f(e,"trustStatus")??f(e,"trustLabel")??(t?f(t,"label"):void 0),r=e.score??e.securityScore??(t?t.securityScore:void 0),i=f(e,"risk")??f(e,"runtimeRisk")??(t?f(t,"runtimeRisk"):void 0);return[["slug",f(e,"slug")??f(e,"skillSlug")],["version",f(e,"version")??f(e,"currentVersion")],["category",f(e,"category")],["type",f(e,"type")??f(e,"skillType")],["trust",n],["score",r],["risk",i]].flatMap(([s,a])=>a==null||a===""?[]:[`${s}: ${pn(String(s),a)}`]).join("; ")}function Mle(e){let t=[];for(let n of e.slice(0,5)){let r=f(n,"slug")??f(n,"skillSlug");r&&t.push(`skills-layer show ${r}`,`skills-layer trust ${r}`,`skills-layer install ${r}`)}return t}function Ule(e){let t=f(e,"edition"),n=f(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function zle(e){let t=f(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=f(e,"email"),r=zn(e,"roles");return n&&r&&r.length>0?`${n} (${r.join(", ")})`:n??f(e,"role")}function Cz(e){let t=[],n=f(e,"recommendedCommand");n&&t.push(n);let r=f(e,"nextStep");return r&&t.push(r),t}function Iz(e){return Array.isArray(e.checks)?e.checks.filter(j):[]}function qle(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function dn(e){return Array.isArray(e)?e.filter(j):[]}function Wa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Vle(e){let t=e.commerce===!0;return{status:t?"available":"unavailable",summary:t?"Marketplace purchases, invoices, refunds, and creator commerce flows are available.":"Marketplace commerce is not available on this backend.",availableWorkflows:t?["Browse skills with `skills-layer featured` or `skills-layer search <query>`.","Start purchase handoff with `skills-layer buy <skill-slug>`.","Review account purchases with `skills-layer purchases list`."]:["Browse and install available free skills.","Use `skills-layer help topic install` for install guidance."]}}var Gle={"core.identity":"Account and sign-in","core.catalog":"Catalog discovery","core.validation":"Creator validation","core.creator":"Creator submissions","core.library":"Owned skills","core.workspace":"Workspace rollout","core.guardian":"Runtime trust checks","core.source":"Source installs","core.discovery":"Catalog discovery","marketplace.commerce":"Marketplace commerce","marketplace.reviews":"Reviews and issues","marketplace.payouts":"Creator earnings"};function Hle(e){let t=Wa(e.capabilities);return{status:"ok",edition:f(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:Gle[n]??Mh(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function Kle(e,t){let n=k(e);if(!n)return;let r=Number(n);return!Number.isInteger(r)||r<=0?E("help optimize-tokens --max-characters must be a positive integer.",t):r<120||r>4e3?E("help optimize-tokens --max-characters must be between 120 and 4000.",t):r}function Wle(e,t,n){let r=Ae(n),i=T(e,"validation")??e,o=T(i,"parsedSkill")??T(e,"parsedSkill"),s=o?T(o,"frontmatter"):void 0,a=f(e,"skillSlug")??(s?f(s,"name"):void 0),l=i.valid===!0||e.valid===!0,c=wP(i,e,"issues"),u=wP(i,e,"warnings"),d=wP(i,e,"advice"),p=T(i,"stats")??T(e,"stats"),m=[l?`${r.ok("OK")} Validation complete.`:"Validation failed.","",r.section("Bundle")];m.push(` ${r.label("Path")}: ${t}`),a&&m.push(` ${r.label("Skill")}: ${a}`),m.push(` ${r.label("Readiness")}: ${l?"ready for dry-run submission":"needs changes before submission"}`),m.push("",r.section("Checks")),m.push(` ${r.arrow} SKILL.md structure and frontmatter`),m.push(` ${r.arrow} Required bundle files and supported directories`),m.push(` ${r.arrow} Secret hygiene, unsafe script signals, and trust-review readiness`),m.push(` ${r.arrow} Trigger quality inputs for should-trigger / should-not-trigger testing`);let h=T(e,"evalReadiness");if(h){let v=T(h,"summaryEnvelope"),b=Array.isArray(v?.statuses)?v.statuses.map(A=>String(A)).join(", "):void 0,w=T(h,"score"),_=w?J(w,"effectiveScorePercent"):void 0,C=w?J(w,"overallScore"):void 0;m.push("",r.section("Effectiveness Eval")),m.push(` ${r.label("Posture")}: ${f(h,"label")??f(h,"status")??"limited"}`),m.push(` ${r.label("Origin")}: ${f(h,"origin")??"inferred"}`),_!==void 0?m.push(` ${r.label("Effective score")}: ${Dh(_)}`):C!==void 0&&m.push(` ${r.label("Effective score")}: ${Dh(C*100)}`),m.push(` ${r.label("Artifact digest")}: ${f(h,"artifactDigest")??"unavailable"}`),h.runtimeFileCount!==void 0&&m.push(` ${r.label("Runtime files")}: ${pn("runtimeFileCount",h.runtimeFileCount)}`),h.evidenceFileCount!==void 0&&m.push(` ${r.label("Evidence files excluded")}: ${pn("evidenceFileCount",h.evidenceFileCount)}`),m.push(` ${r.label("Submit envelope")}: mandatory${b?` (${b})`:""}`)}if(p){let v=p.fileCount??p.files??e.fileCount,b=p.bodyWordCount??p.bodyWords??e.bodyWordCount;m.push("",r.section("File Summary")),v!==void 0&&m.push(` ${r.label("File count")}: ${pn("fileCount",v)}`),b!==void 0&&m.push(` ${r.label("Body words")}: ${pn("bodyWordCount",b)}`)}let g=T(e,"securityReport");g&&(m.push("",r.section("Security")),m.push(` ${r.label("Recommendation")}: ${f(g,"recommendation")??"unknown"}`),m.push(...yh("Findings",Array.isArray(g.findings)?g.findings:[],r,"No security findings returned.")));let y=T(e,"aiReview");if(y){m.push("",r.section("AI Review")),m.push(` ${r.label("Status")}: ${f(y,"status")??"unknown"}`);let v=f(y,"message");v&&m.push(` ${v}`);let b=f(y,"nextStep");b&&m.push(` ${r.arrow} ${b}`)}return m.push("",...yh("Issues",c,r,"No blocking issues found.")),m.push("",...yh("Warnings",u,r,"No warnings returned.")),m.push("",...yh("Advice",d,r,"No extra advice returned.")),m.push("",r.section("Next")),l?(m.push(` ${r.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),m.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`)):m.push(` ${r.arrow} Fix the listed issues, then run skills-layer validate ${t}`),m.join(`
2304
2304
  `)}function wP(e,t,n){let r=Array.isArray(e[n])?e[n]:[],i=Array.isArray(t[n])?t[n]:[];return r.length>0?r:i}function yh(e,t,n,r){let i=[n.section(`${e} (${t.length})`)];return t.length===0?(i.push(` ${n.muted(r)}`),i):(t.slice(0,at).forEach((o,s)=>{i.push(`${s+1}. ${Pz(o)}`)}),i)}function Pz(e){return j(e)?(f(e,"message")??f(e,"title")??f(e,"code")??f(e,"path")??Yu(e))||"Details available with --json":pn("",e)}function Zle(e,t,n){let r=Ae(n),i=Jle(e),o=Yle(e),s=[`${r.ok("OK")} Trigger preview complete.`,"",r.section("Bundle"),` ${r.label("Path")}: ${t}`],a=f(e,"skillSlug")??f(e,"slug");return a&&s.push(` ${r.label("Skill")}: ${a}`),s.push("",r.section(`Prompt Results (${i.length})`)),i.length===0&&s.push(` ${r.muted("No prompt results returned. Use --json to inspect the raw backend response.")}`),i.slice(0,at).forEach((l,c)=>{s.push(`${c+1}. ${Xle(l,c)}`)}),s.push("",r.section(`Guidance (${o.length})`)),o.length===0&&s.push(` ${r.muted("No extra trigger guidance returned.")}`),o.slice(0,at).forEach((l,c)=>{s.push(`${c+1}. ${l}`)}),s.push("",r.section("Next")),s.push(` ${r.arrow} skills-layer validate ${t}`),s.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`),s.join(`
2305
2305
  `)}function Jle(e){return[...dn(e.promptResults),...dn(e.results),...dn(e.shouldTriggerResults),...dn(e.shouldNotTriggerResults),...dn(e.paraphraseResults)]}function Yle(e){let t=Wa(e.guidance),n=dn(e.guidance).map(r=>Pz(r));return[...t,...n]}function Xle(e,t){let n=f(e,"prompt")??f(e,"text")??f(e,"input")??`Prompt ${t+1}`,r=Qle(e),i=ece(e),o=tce(e),s=e.score??e.confidence,a=f(e,"reason")??f(e,"explanation")??f(e,"message");return[`"${Ja(n)}"`,r?`expected: ${r}`:void 0,i?`actual: ${i}`:void 0,o,s!==void 0?`score: ${pn("score",s)}`:void 0,a?`reason: ${Ja(a)}`:void 0].filter(l=>!!l).join("; ")}function Qle(e){return typeof e.shouldTrigger=="boolean"?e.shouldTrigger?"should trigger":"should not trigger":typeof e.expectedTrigger=="boolean"?e.expectedTrigger?"should trigger":"should not trigger":f(e,"expected")??f(e,"kind")??f(e,"type")}function ece(e){return typeof e.triggered=="boolean"?e.triggered?"triggered":"did not trigger":typeof e.actualTrigger=="boolean"?e.actualTrigger?"triggered":"did not trigger":f(e,"actual")??f(e,"classification")??f(e,"decision")}function tce(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":f(e,"status")}function nce(e,t,n,r){let i=Ae(r),o=f(e,"skillSlug")??ot(t),s=[`${i.ok("OK")} Created ${n}.`,"",i.section("Local Skill")];s.push(` ${i.label("Path")}: ${n}`),s.push(` ${i.label("Skill")}: ${o}`);let a=f(e,"skillType"),l=f(e,"category");return a&&s.push(` ${i.label("Type")}: ${a}`),l&&s.push(` ${i.label("Category")}: ${l}`),s.push(` ${i.label("Evaluation")}: not run`),s.push("",i.section("Next")),s.push(` ${i.arrow} Edit ${n}`),s.push(` ${i.arrow} skills-layer validate ${t}`),s.push(` ${i.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),s.push(` ${i.arrow} skills-layer creator submit ${t} --dry-run`),s.join(`
2306
2306
  `)}function rce(e,t,n){let r=T(e,"profile")??e,i=_P(r,"requirementsCurrentlyDue"),o=_P(r,"requirementsPastDue"),s=_P(r,"requirementsPendingVerification"),a=["payouts","Enabled"].join(""),l=r.readyForPayouts??r[a],c=l===!0,u=r.coolingActive===!0,d=T(r,"bank"),p=[`${n.ok("OK")} ${t}`,"",n.section("Payout Profile")];return p.push(` ${n.label("Status")}: ${xP(f(r,"status"))}`),p.push(` ${n.label("Ready for payouts")}: ${HM(l)}`),p.push(` ${n.label("Account details submitted")}: ${HM(r.detailsSubmitted)}`),p.push(` ${n.label("Currency")}: ${xP(f(r,"currency")?.toUpperCase())}`),p.push(` ${n.label("Country")}: ${xP(f(r,"country")?.toUpperCase())}`),p.push(` ${n.label("Minimum withdrawal")}: ${sce(r)}`),p.push(` ${n.label("Bank")}: ${d?`ending ${f(d,"last4")} (${f(d,"currency")?.toUpperCase()})`:"No stored bank destination yet"}`),d&&p.push(` Bank changed ${Ur(f(d,"changedAt"))}`),p.push(` ${n.label("Cooling ends (UTC)")}: ${Ur(f(r,"destinationCoolingEndsAt"))}`),p.push(` ${n.label("Updated at")}: ${Ur(f(r,"updatedAt"))}`),p.push("",n.section("Requirements")),p.push(` ${n.label("Currently due")}: ${SP(i)}`),p.push(` ${n.label("Past due")}: ${SP(o)}`),p.push(` ${n.label("Pending verification")}: ${SP(s)}`),p.push("",n.section("Next")),u?(p.push(" Wait until the bank cooling period ends, then check earnings before requesting withdrawal."),p.push(` ${n.arrow} skills-layer creator earnings`)):c?(p.push(` ${n.arrow} skills-layer creator earnings`),p.push(" Check your available earnings before requesting a withdrawal."),p.push(` ${n.arrow} skills-layer creator payouts`)):(p.push(` ${n.arrow} skills-layer creator payout-link`),p.push(` ${n.arrow} skills-layer creator earnings`)),p.join(`