skills-layer 0.2.48 → 0.2.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -2
- package/public/chunks/chunk-ESQWWFG7.mjs +3 -0
- package/public/chunks/chunk-FQ7O2RXV.mjs +13 -0
- package/public/chunks/chunk-UZR7RAAD.mjs +1240 -0
- package/public/chunks/chunk-VRFARZT7.mjs +63 -0
- package/public/chunks/chunk-YT7RFIT2.mjs +3 -0
- package/public/chunks/public-cli-YKYNLV3U.mjs +1246 -0
- package/public/chunks/public-cli-help-L6QJQ53H.mjs +3 -0
- package/public/chunks/public-cli-help-audit-4QCY3NBV.mjs +3 -0
- package/public/skills-layer-public.mjs +2 -2543
|
@@ -0,0 +1,1246 @@
|
|
|
1
|
+
/* istanbul ignore file -- generated npm bundle is verified by boundary and tarball smoke tests. */
|
|
2
|
+
import { createRequire as __skillsLayerCreateRequire } from "node:module"; const require = __skillsLayerCreateRequire(import.meta.url);
|
|
3
|
+
import{A as zi,B as Uf,C as nb,D as rb,E as ib,F as Wl,G as ob,H as MT,I as jT,J as ab,K as UT,a as In,b as zl,c as Nv,d as le,e as Mv,f as jv,g as Uv,h as qv,i as Vv,j as Gv,k as zv,l as zn,m as Kv,n as Hv,o as Mf,p as Wv,q as Jv,r as Yv,s as jf,t as Zv,u as Gi,v as Kl,w as Xv,x as Qv,y as eb,z as tb}from"./chunk-VRFARZT7.mjs";import{E as _b,F as Xl,G as Ql,H as Gr,I as kb,a as k,b as lb,d as cb,e as ub,f as db,g as bs,h as fb,i as Jl,j as qf,k as Kn,l as We,m as Vr,n as Hn,o as Vf,p as Yl,q as pb,r as mb,s as gb,t as hb,u as yb,v as Zl,w as _s,x as wb,y as vb,z as bb}from"./chunk-UZR7RAAD.mjs";import{b as $t,e as Vi,g as Hl,k as sb}from"./chunk-FQ7O2RXV.mjs";import{a as qT,b as VT,c as GT}from"./chunk-ESQWWFG7.mjs";import{a as qr,b as N,d as Tt}from"./chunk-YT7RFIT2.mjs";var oe=N(Ve=>{"use strict";var hp=Symbol.for("yaml.alias"),C_=Symbol.for("yaml.document"),vc=Symbol.for("yaml.map"),A_=Symbol.for("yaml.pair"),yp=Symbol.for("yaml.scalar"),bc=Symbol.for("yaml.seq"),Rn=Symbol.for("yaml.node.type"),rL=e=>!!e&&typeof e=="object"&&e[Rn]===hp,iL=e=>!!e&&typeof e=="object"&&e[Rn]===C_,oL=e=>!!e&&typeof e=="object"&&e[Rn]===vc,sL=e=>!!e&&typeof e=="object"&&e[Rn]===A_,x_=e=>!!e&&typeof e=="object"&&e[Rn]===yp,aL=e=>!!e&&typeof e=="object"&&e[Rn]===bc;function I_(e){if(e&&typeof e=="object")switch(e[Rn]){case vc:case bc:return!0}return!1}function lL(e){if(e&&typeof e=="object")switch(e[Rn]){case hp:case vc:case yp:case bc:return!0}return!1}var cL=e=>(x_(e)||I_(e))&&!!e.anchor;Ve.ALIAS=hp;Ve.DOC=C_;Ve.MAP=vc;Ve.NODE_TYPE=Rn;Ve.PAIR=A_;Ve.SCALAR=yp;Ve.SEQ=bc;Ve.hasAnchor=cL;Ve.isAlias=rL;Ve.isCollection=I_;Ve.isDocument=iL;Ve.isMap=oL;Ve.isNode=lL;Ve.isPair=sL;Ve.isScalar=x_;Ve.isSeq=aL});var xs=N(wp=>{"use strict";var De=oe(),ft=Symbol("break visit"),R_=Symbol("skip children"),cn=Symbol("remove node");function _c(e,t){let n=P_(t);De.isDocument(e)?Xi(null,e.contents,n,Object.freeze([e]))===cn&&(e.contents=null):Xi(null,e,n,Object.freeze([]))}_c.BREAK=ft;_c.SKIP=R_;_c.REMOVE=cn;function Xi(e,t,n,r){let i=E_(e,t,n,r);if(De.isNode(i)||De.isPair(i))return D_(e,r,i),Xi(e,i,n,r);if(typeof i!="symbol"){if(De.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let s=Xi(o,t.items[o],n,r);if(typeof s=="number")o=s-1;else{if(s===ft)return ft;s===cn&&(t.items.splice(o,1),o-=1)}}}else if(De.isPair(t)){r=Object.freeze(r.concat(t));let o=Xi("key",t.key,n,r);if(o===ft)return ft;o===cn&&(t.key=null);let s=Xi("value",t.value,n,r);if(s===ft)return ft;s===cn&&(t.value=null)}}return i}async function kc(e,t){let n=P_(t);De.isDocument(e)?await Qi(null,e.contents,n,Object.freeze([e]))===cn&&(e.contents=null):await Qi(null,e,n,Object.freeze([]))}kc.BREAK=ft;kc.SKIP=R_;kc.REMOVE=cn;async function Qi(e,t,n,r){let i=await E_(e,t,n,r);if(De.isNode(i)||De.isPair(i))return D_(e,r,i),Qi(e,i,n,r);if(typeof i!="symbol"){if(De.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let s=await Qi(o,t.items[o],n,r);if(typeof s=="number")o=s-1;else{if(s===ft)return ft;s===cn&&(t.items.splice(o,1),o-=1)}}}else if(De.isPair(t)){r=Object.freeze(r.concat(t));let o=await Qi("key",t.key,n,r);if(o===ft)return ft;o===cn&&(t.key=null);let s=await Qi("value",t.value,n,r);if(s===ft)return ft;s===cn&&(t.value=null)}}return i}function P_(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function E_(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(De.isMap(t))return n.Map?.(e,t,r);if(De.isSeq(t))return n.Seq?.(e,t,r);if(De.isPair(t))return n.Pair?.(e,t,r);if(De.isScalar(t))return n.Scalar?.(e,t,r);if(De.isAlias(t))return n.Alias?.(e,t,r)}function D_(e,t,n){let r=t[t.length-1];if(De.isCollection(r))r.items[e]=n;else if(De.isPair(r))e==="key"?r.key=n:r.value=n;else if(De.isDocument(r))r.contents=n;else{let i=De.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}wp.visit=_c;wp.visitAsync=kc});var vp=N($_=>{"use strict";var T_=oe(),uL=xs(),dL={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},fL=e=>e.replace(/[!,[\]{}]/g,t=>dL[t]),Is=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[o,s]=r;return this.tags[o]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let s=/^\d+\.\d+$/.test(o);return n(6,`Unsupported YAML version ${o}`,s),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let s=t.slice(2,-1);return s==="!"||s==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),s)}let[,r,i]=t.match(/^(.*!)([^!]*)$/s);i||n(`The ${t} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(i)}catch(s){return n(String(s)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+fL(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),i;if(t&&r.length>0&&T_.isNode(t.contents)){let o={};uL.visit(t.contents,(s,a)=>{T_.isNode(a)&&a.tag&&(o[a.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,s]of r)o==="!!"&&s==="tag:yaml.org,2002:"||(!t||i.some(a=>a.startsWith(s)))&&n.push(`%TAG ${o} ${s}`);return n.join(`
|
|
4
|
+
`)}};Is.defaultYaml={explicit:!1,version:"1.2"};Is.defaultTags={"!!":"tag:yaml.org,2002:"};$_.Directives=Is});var Sc=N(Rs=>{"use strict";var L_=oe(),pL=xs();function mL(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function O_(e){let t=new Set;return pL.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function F_(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function gL(e,t){let n=[],r=new Map,i=null;return{onAnchor:o=>{n.push(o),i??(i=O_(e));let s=F_(t,i);return i.add(s),s},setAnchors:()=>{for(let o of n){let s=r.get(o);if(typeof s=="object"&&s.anchor&&(L_.isScalar(s.node)||L_.isCollection(s.node)))s.node.anchor=s.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:r}}Rs.anchorIsValid=mL;Rs.anchorNames=O_;Rs.createNodeAnchors=gL;Rs.findNewAnchor=F_});var bp=N(B_=>{"use strict";function Ps(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,o=r.length;i<o;++i){let s=r[i],a=Ps(e,r,String(i),s);a===void 0?delete r[i]:a!==s&&(r[i]=a)}else if(r instanceof Map)for(let i of Array.from(r.keys())){let o=r.get(i),s=Ps(e,r,i,o);s===void 0?r.delete(i):s!==o&&r.set(i,s)}else if(r instanceof Set)for(let i of Array.from(r)){let o=Ps(e,r,i,i);o===void 0?r.delete(i):o!==i&&(r.delete(i),r.add(o))}else for(let[i,o]of Object.entries(r)){let s=Ps(e,r,i,o);s===void 0?delete r[i]:s!==o&&(r[i]=s)}return e.call(t,n,r)}B_.applyReviver=Ps});var Xn=N(M_=>{"use strict";var hL=oe();function N_(e,t,n){if(Array.isArray(e))return e.map((r,i)=>N_(r,String(i),n));if(e&&typeof e.toJSON=="function"){if(!n||!hL.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=o=>{r.res=o,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e=="bigint"&&!n?.keep?Number(e):e}M_.toJS=N_});var Cc=N(U_=>{"use strict";var yL=bp(),j_=oe(),wL=Xn(),_p=class{constructor(t){Object.defineProperty(this,j_.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){if(!j_.isDocument(t))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=wL.toJS(this,"",s);if(typeof i=="function")for(let{count:l,res:c}of s.anchors.values())i(c,l);return typeof o=="function"?yL.applyReviver(o,{"":a},"",a):a}};U_.NodeBase=_p});var Es=N(q_=>{"use strict";var vL=Sc(),bL=xs(),eo=oe(),_L=Cc(),kL=Xn(),kp=class extends _L.NodeBase{constructor(t){super(eo.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],bL.visit(t,{Node:(o,s)=>{(eo.isAlias(s)||eo.hasAnchor(s))&&r.push(s)}}),n&&(n.aliasResolveCache=r));let i;for(let o of r){if(o===this)break;o.anchor===this.source&&(i=o)}return i}toJSON(t,n){if(!n)return{source:this.source};let{anchors:r,doc:i,maxAliasCount:o}=n,s=this.resolve(i,n);if(!s){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=r.get(s);if(a||(kL.toJS(s,null,n),a=r.get(s)),a?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Ac(i,s,r)),a.count*a.aliasCount>o)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(t,n,r){let i=`*${this.source}`;if(t){if(vL.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${i} `}return i}};function Ac(e,t,n){if(eo.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(eo.isCollection(t)){let r=0;for(let i of t.items){let o=Ac(e,i,n);o>r&&(r=o)}return r}else if(eo.isPair(t)){let r=Ac(e,t.key,n),i=Ac(e,t.value,n);return Math.max(r,i)}return 1}q_.Alias=kp});var xe=N(Sp=>{"use strict";var SL=oe(),CL=Cc(),AL=Xn(),xL=e=>!e||typeof e!="function"&&typeof e!="object",Qn=class extends CL.NodeBase{constructor(t){super(SL.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:AL.toJS(this.value,t,n)}toString(){return String(this.value)}};Qn.BLOCK_FOLDED="BLOCK_FOLDED";Qn.BLOCK_LITERAL="BLOCK_LITERAL";Qn.PLAIN="PLAIN";Qn.QUOTE_DOUBLE="QUOTE_DOUBLE";Qn.QUOTE_SINGLE="QUOTE_SINGLE";Sp.Scalar=Qn;Sp.isScalarValue=xL});var Ds=N(G_=>{"use strict";var IL=Es(),Wr=oe(),V_=xe(),RL="tag:yaml.org,2002:";function PL(e,t,n){if(t){let r=n.filter(o=>o.tag===t),i=r.find(o=>!o.format)??r[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return n.find(r=>r.identify?.(e)&&!r.format)}function EL(e,t,n){if(Wr.isDocument(e)&&(e=e.contents),Wr.isNode(e))return e;if(Wr.isPair(e)){let d=n.schema[Wr.MAP].createNode?.(n.schema,null,n);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:o,schema:s,sourceObjects:a}=n,l;if(r&&e&&typeof e=="object"){if(l=a.get(e),l)return l.anchor??(l.anchor=i(e)),new IL.Alias(l.anchor);l={anchor:null,node:null},a.set(e,l)}t?.startsWith("!!")&&(t=RL+t.slice(2));let c=PL(e,t,s.tags);if(!c){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new V_.Scalar(e);return l&&(l.node=d),d}c=e instanceof Map?s[Wr.MAP]:Symbol.iterator in Object(e)?s[Wr.SEQ]:s[Wr.MAP]}o&&(o(c),delete n.onTagObj);let u=c?.createNode?c.createNode(n.schema,e,n):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(n.schema,e,n):new V_.Scalar(e);return t?u.tag=t:c.default||(u.tag=c.tag),l&&(l.node=u),u}G_.createNode=EL});var Ic=N(xc=>{"use strict";var DL=Ds(),un=oe(),TL=Cc();function Cp(e,t,n){let r=n;for(let i=t.length-1;i>=0;--i){let o=t[i];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let s=[];s[o]=r,r=s}else r=new Map([[o,r]])}return DL.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var z_=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ap=class extends TL.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>un.isNode(r)||un.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(z_(t))this.add(n);else{let[r,...i]=t,o=this.get(r,!0);if(un.isCollection(o))o.addIn(i,n);else if(o===void 0&&this.schema)this.set(r,Cp(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let i=this.get(n,!0);if(un.isCollection(i))return i.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...i]=t,o=this.get(r,!0);return i.length===0?!n&&un.isScalar(o)?o.value:o:un.isCollection(o)?o.getIn(i,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!un.isPair(n))return!1;let r=n.value;return r==null||t&&un.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let i=this.get(n,!0);return un.isCollection(i)?i.hasIn(r):!1}setIn(t,n){let[r,...i]=t;if(i.length===0)this.set(r,n);else{let o=this.get(r,!0);if(un.isCollection(o))o.setIn(i,n);else if(o===void 0&&this.schema)this.set(r,Cp(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};xc.Collection=Ap;xc.collectionFromPath=Cp;xc.isEmptyPath=z_});var Ts=N(Rc=>{"use strict";var $L=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function xp(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var LL=(e,t,n)=>e.endsWith(`
|
|
5
|
+
`)?xp(n,t):n.includes(`
|
|
6
|
+
`)?`
|
|
7
|
+
`+xp(n,t):(e.endsWith(" ")?"":" ")+n;Rc.indentComment=xp;Rc.lineComment=LL;Rc.stringifyComment=$L});var H_=N($s=>{"use strict";var OL="flow",Ip="block",Pc="quoted";function FL(e,t,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:o=20,onFold:s,onOverflow:a}={}){if(!i||i<0)return e;i<o&&(o=0);let l=Math.max(1+o,1+i-t.length);if(e.length<=l)return e;let c=[],u={},d=i-t.length;typeof r=="number"&&(r>i-Math.max(2,o)?c.push(0):d=i-r);let p,m,g=!1,h=-1,y=-1,w=-1;n===Ip&&(h=K_(e,h,t.length),h!==-1&&(d=h+l));for(let _;_=e[h+=1];){if(n===Pc&&_==="\\"){switch(y=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(_===`
|
|
8
|
+
`)n===Ip&&(h=K_(e,h,t.length)),d=h+t.length+l,p=void 0;else{if(_===" "&&m&&m!==" "&&m!==`
|
|
9
|
+
`&&m!==" "){let I=e[h+1];I&&I!==" "&&I!==`
|
|
10
|
+
`&&I!==" "&&(p=h)}if(h>=d)if(p)c.push(p),d=p+l,p=void 0;else if(n===Pc){for(;m===" "||m===" ";)m=_,_=e[h+=1],g=!0;let I=h>w+1?h-2:y-1;if(u[I])return e;c.push(I),u[I]=!0,d=I+l,p=void 0}else g=!0}m=_}if(g&&a&&a(),c.length===0)return e;s&&s();let b=e.slice(0,c[0]);for(let _=0;_<c.length;++_){let I=c[_],x=c[_+1]||e.length;I===0?b=`
|
|
11
|
+
${t}${e.slice(0,x)}`:(n===Pc&&u[I]&&(b+=`${e[I]}\\`),b+=`
|
|
12
|
+
${t}${e.slice(I+1,x)}`)}return b}function K_(e,t,n){let r=t,i=t+1,o=e[i];for(;o===" "||o===" ";)if(t<i+n)o=e[++t];else{do o=e[++t];while(o&&o!==`
|
|
13
|
+
`);r=t,i=t+1,o=e[i]}return r}$s.FOLD_BLOCK=Ip;$s.FOLD_FLOW=OL;$s.FOLD_QUOTED=Pc;$s.foldFlowLines=FL});var Os=N(W_=>{"use strict";var Kt=xe(),er=H_(),Dc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Tc=e=>/^(%|---|\.\.\.)/m.test(e);function BL(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let o=0,s=0;o<i;++o)if(e[o]===`
|
|
14
|
+
`){if(o-s>r)return!0;if(s=o+1,i-s<=r)return!1}return!0}function Ls(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(Tc(e)?" ":""),s="",a=0;for(let l=0,c=n[l];c;c=n[++l])if(c===" "&&n[l+1]==="\\"&&n[l+2]==="n"&&(s+=n.slice(a,l)+"\\ ",l+=1,a=l,c="\\"),c==="\\")switch(n[l+1]){case"u":{s+=n.slice(a,l);let u=n.substr(l+2,4);switch(u){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:u.substr(0,2)==="00"?s+="\\x"+u.substr(2):s+=n.substr(l,6)}l+=5,a=l+1}break;case"n":if(r||n[l+2]==='"'||n.length<i)l+=1;else{for(s+=n.slice(a,l)+`
|
|
15
|
+
|
|
16
|
+
`;n[l+2]==="\\"&&n[l+3]==="n"&&n[l+4]!=='"';)s+=`
|
|
17
|
+
`,l+=2;s+=o,n[l+2]===" "&&(s+="\\"),l+=1,a=l+1}break;default:l+=1}return s=a?s+n.slice(a):n,r?s:er.foldFlowLines(s,o,er.FOLD_QUOTED,Dc(t,!1))}function Rp(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
18
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Ls(e,t);let n=t.indent||(Tc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
19
|
+
${n}`)+"'";return t.implicitKey?r:er.foldFlowLines(r,n,er.FOLD_FLOW,Dc(t,!1))}function to(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Ls;else{let i=e.includes('"'),o=e.includes("'");i&&!o?r=Rp:o&&!i?r=Ls:r=n?Rp:Ls}return r(e,t)}var Pp;try{Pp=new RegExp(`(^|(?<!
|
|
20
|
+
))
|
|
21
|
+
+(?!
|
|
22
|
+
|$)`,"g")}catch{Pp=/\n+(?!\n|$)/g}function Ec({comment:e,type:t,value:n},r,i,o){let{blockQuote:s,commentString:a,lineWidth:l}=r.options;if(!s||/\n[\t ]+$/.test(n))return to(n,r);let c=r.indent||(r.forceBlockIndent||Tc(n)?" ":""),u=s==="literal"?!0:s==="folded"||t===Kt.Scalar.BLOCK_FOLDED?!1:t===Kt.Scalar.BLOCK_LITERAL?!0:!BL(n,l,c.length);if(!n)return u?`|
|
|
23
|
+
`:`>
|
|
24
|
+
`;let d,p;for(p=n.length;p>0;--p){let x=n[p-1];if(x!==`
|
|
25
|
+
`&&x!==" "&&x!==" ")break}let m=n.substring(p),g=m.indexOf(`
|
|
26
|
+
`);g===-1?d="-":n===m||g!==m.length-1?(d="+",o&&o()):d="",m&&(n=n.slice(0,-m.length),m[m.length-1]===`
|
|
27
|
+
`&&(m=m.slice(0,-1)),m=m.replace(Pp,`$&${c}`));let h=!1,y,w=-1;for(y=0;y<n.length;++y){let x=n[y];if(x===" ")h=!0;else if(x===`
|
|
28
|
+
`)w=y;else break}let b=n.substring(0,w<y?w+1:y);b&&(n=n.substring(b.length),b=b.replace(/\n+/g,`$&${c}`));let I=(h?c?"2":"1":"")+d;if(e&&(I+=" "+a(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let x=n.replace(/\n+/g,`
|
|
29
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),C=!1,D=Dc(r,!0);s!=="folded"&&t!==Kt.Scalar.BLOCK_FOLDED&&(D.onOverflow=()=>{C=!0});let T=er.foldFlowLines(`${b}${x}${m}`,c,er.FOLD_BLOCK,D);if(!C)return`>${I}
|
|
30
|
+
${c}${T}`}return n=n.replace(/\n+/g,`$&${c}`),`|${I}
|
|
31
|
+
${c}${b}${n}${m}`}function NL(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
|
+
`)||u&&/[[\]{},]/.test(o))return to(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||u||!o.includes(`
|
|
33
|
+
`)?to(o,t):Ec(e,t,n,r);if(!a&&!u&&i!==Kt.Scalar.PLAIN&&o.includes(`
|
|
34
|
+
`))return Ec(e,t,n,r);if(Tc(o)){if(l==="")return t.forceBlockIndent=!0,Ec(e,t,n,r);if(a&&l===c)return to(o,t)}let d=o.replace(/\n+/g,`$&
|
|
35
|
+
${l}`);if(s){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:m,tags:g}=t.doc.schema;if(g.some(p)||m?.some(p))return to(o,t)}return a?d:er.foldFlowLines(d,l,er.FOLD_FLOW,Dc(t,!1))}function ML(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!==Kt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(a=Kt.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case Kt.Scalar.BLOCK_FOLDED:case Kt.Scalar.BLOCK_LITERAL:return i||o?to(s.value,t):Ec(s,t,n,r);case Kt.Scalar.QUOTE_DOUBLE:return Ls(s.value,t);case Kt.Scalar.QUOTE_SINGLE:return Rp(s.value,t);case Kt.Scalar.PLAIN:return NL(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}W_.stringifyString=ML});var Fs=N(Ep=>{"use strict";var jL=Sc(),tr=oe(),UL=Ts(),qL=Os();function VL(e,t){let n=Object.assign({blockQuote:!0,commentString:UL.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 GL(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(tr.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 zL(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let i=[],o=(tr.isScalar(e)||tr.isCollection(e))&&e.anchor;o&&jL.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 KL(e,t,n,r){if(tr.isPair(e))return e.toString(t,n,r);if(tr.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=tr.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>i=l});i??(i=GL(t.doc.schema.tags,o));let s=zL(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):tr.isScalar(o)?qL.stringifyString(o,t,n,r):o.toString(t,n,r);return s?tr.isScalar(o)||a[0]==="{"||a[0]==="["?`${s} ${a}`:`${s}
|
|
36
|
+
${t.indent}${a}`:a}Ep.createStringifyContext=VL;Ep.stringify=KL});var X_=N(Z_=>{"use strict";var Pn=oe(),J_=xe(),Y_=Fs(),Bs=Ts();function HL({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=Pn.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Pn.isCollection(e)||!Pn.isNode(e)&&typeof e=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let m=!d&&(!e||p&&t==null&&!n.inFlow||Pn.isCollection(e)||(Pn.isScalar(e)?e.type===J_.Scalar.BLOCK_FOLDED||e.type===J_.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!m&&(d||!o),indent:a+l});let g=!1,h=!1,y=Y_.stringify(e,n,()=>g=!0,()=>h=!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 g&&r&&r(),y===""?"?":m?`? ${y}`:y}else if(o&&!d||t==null&&m)return y=`? ${y}`,p&&!g?y+=Bs.lineComment(y,n.indent,c(p)):h&&i&&i(),y;g&&(p=null),m?(p&&(y+=Bs.lineComment(y,n.indent,c(p))),y=`? ${y}
|
|
37
|
+
${a}:`):(y=`${y}:`,p&&(y+=Bs.lineComment(y,n.indent,c(p))));let w,b,_;Pn.isNode(t)?(w=!!t.spaceBefore,b=t.commentBefore,_=t.comment):(w=!1,b=null,_=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!m&&!p&&Pn.isScalar(t)&&(n.indentAtStart=y.length+1),h=!1,!u&&l.length>=2&&!n.inFlow&&!m&&Pn.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let I=!1,x=Y_.stringify(t,n,()=>I=!0,()=>h=!0),C=" ";if(p||w||b){if(C=w?`
|
|
38
|
+
`:"",b){let D=c(b);C+=`
|
|
39
|
+
${Bs.indentComment(D,n.indent)}`}x===""&&!n.inFlow?C===`
|
|
40
|
+
`&&_&&(C=`
|
|
41
|
+
|
|
42
|
+
`):C+=`
|
|
43
|
+
${n.indent}`}else if(!m&&Pn.isCollection(t)){let D=x[0],T=x.indexOf(`
|
|
44
|
+
`),j=T!==-1,M=n.inFlow??t.flow??t.items.length===0;if(j||!M){let $=!1;if(j&&(D==="&"||D==="!")){let B=x.indexOf(" ");D==="&"&&B!==-1&&B<T&&x[B+1]==="!"&&(B=x.indexOf(" ",B+1)),(B===-1||T<B)&&($=!0)}$||(C=`
|
|
45
|
+
${n.indent}`)}}else(x===""||x[0]===`
|
|
46
|
+
`)&&(C="");return y+=C+x,n.inFlow?I&&r&&r():_&&!I?y+=Bs.lineComment(y,n.indent,c(_)):h&&i&&i(),y}Z_.stringifyPair=HL});var Tp=N(Dp=>{"use strict";var Q_=qr("process");function WL(e,...t){e==="debug"&&console.log(...t)}function JL(e,t){(e==="debug"||e==="warn")&&(typeof Q_.emitWarning=="function"?Q_.emitWarning(t):console.warn(t))}Dp.debug=WL;Dp.warn=JL});var Bc=N(Fc=>{"use strict";var Oc=oe(),ek=xe(),$c="<<",Lc={identify:e=>e===$c||typeof e=="symbol"&&e.description===$c,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ek.Scalar(Symbol($c)),{addToJSMap:tk}),stringify:()=>$c},YL=(e,t)=>(Lc.identify(t)||Oc.isScalar(t)&&(!t.type||t.type===ek.Scalar.PLAIN)&&Lc.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Lc.tag&&n.default);function tk(e,t,n){let r=nk(e,n);if(Oc.isSeq(r))for(let i of r.items)$p(e,t,i);else if(Array.isArray(r))for(let i of r)$p(e,t,i);else $p(e,t,r)}function $p(e,t,n){let r=nk(e,n);if(!Oc.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 nk(e,t){return e&&Oc.isAlias(t)?t.resolve(e.doc,e):t}Fc.addMergeToJSMap=tk;Fc.isMergeKey=YL;Fc.merge=Lc});var Op=N(ok=>{"use strict";var ZL=Tp(),rk=Bc(),XL=Fs(),ik=oe(),Lp=Xn();function QL(e,t,{key:n,value:r}){if(ik.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(rk.isMergeKey(e,n))rk.addMergeToJSMap(e,t,r);else{let i=Lp.toJS(n,"",e);if(t instanceof Map)t.set(i,Lp.toJS(r,i,e));else if(t instanceof Set)t.add(i);else{let o=eO(n,i,e),s=Lp.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 eO(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(ik.isNode(e)&&n?.doc){let r=XL.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)+'..."'),ZL.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)}ok.addPairToJSMap=QL});var nr=N(Fp=>{"use strict";var sk=Ds(),tO=X_(),nO=Op(),Nc=oe();function rO(e,t,n){let r=sk.createNode(e,void 0,n),i=sk.createNode(t,void 0,n);return new Mc(r,i)}var Mc=class e{constructor(t,n=null){Object.defineProperty(this,Nc.NODE_TYPE,{value:Nc.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return Nc.isNode(n)&&(n=n.clone(t)),Nc.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return nO.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?tO.stringifyPair(this,t,n,r):JSON.stringify(this)}};Fp.Pair=Mc;Fp.createPair=rO});var Bp=N(lk=>{"use strict";var Jr=oe(),ak=Fs(),jc=Ts();function iO(e,t,n){return(t.inFlow??e.flow?sO:oO)(e,t,n)}function oO({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 g=0;g<t.length;++g){let h=t[g],y=null;if(Jr.isNode(h))!d&&h.spaceBefore&&p.push(""),Uc(n,p,h.commentBefore,d),h.comment&&(y=h.comment);else if(Jr.isPair(h)){let b=Jr.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&p.push(""),Uc(n,p,b.commentBefore,d))}d=!1;let w=ak.stringify(h,u,()=>y=null,()=>d=!0);y&&(w+=jc.lineComment(w,o,c(y))),d&&y&&(d=!1),p.push(r+w)}let m;if(p.length===0)m=i.start+i.end;else{m=p[0];for(let g=1;g<p.length;++g){let h=p[g];m+=h?`
|
|
47
|
+
${l}${h}`:`
|
|
48
|
+
`}}return e?(m+=`
|
|
49
|
+
`+jc.indentComment(c(e),l),a&&a()):d&&s&&s(),m}function sO({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 g=0;g<e.length;++g){let h=e[g],y=null;if(Jr.isNode(h))h.spaceBefore&&d.push(""),Uc(t,d,h.commentBefore,!1),h.comment&&(y=h.comment);else if(Jr.isPair(h)){let b=Jr.isNode(h.key)?h.key:null;b&&(b.spaceBefore&&d.push(""),Uc(t,d,b.commentBefore,!1),b.comment&&(c=!0));let _=Jr.isNode(h.value)?h.value:null;_?(_.comment&&(y=_.comment),_.commentBefore&&(c=!0)):h.value==null&&b?.comment&&(y=b.comment)}y&&(c=!0);let w=ak.stringify(h,l,()=>y=null);c||(c=d.length>u||w.includes(`
|
|
50
|
+
`)),g<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(c||(c=d.reduce((b,_)=>b+_.length+2,2)+(w.length+2)>t.options.lineWidth)),c&&(w+=",")),y&&(w+=jc.lineComment(w,r,a(y))),d.push(w),u=d.length}let{start:p,end:m}=n;if(d.length===0)return p+m;if(!c){let g=d.reduce((h,y)=>h+y.length+2,2);c=t.options.lineWidth>0&&g>t.options.lineWidth}if(c){let g=p;for(let h of d)g+=h?`
|
|
51
|
+
${o}${i}${h}`:`
|
|
52
|
+
`;return`${g}
|
|
53
|
+
${i}${m}`}else return`${p}${s}${d.join(" ")}${s}${m}`}function Uc({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let o=jc.indentComment(t(r),e);n.push(o.trimStart())}}lk.stringifyCollection=iO});var ir=N(Mp=>{"use strict";var aO=Bp(),lO=Op(),cO=Ic(),rr=oe(),qc=nr(),uO=xe();function Ns(e,t){let n=rr.isScalar(t)?t.value:t;for(let r of e)if(rr.isPair(r)&&(r.key===t||r.key===n||rr.isScalar(r.key)&&r.key.value===n))return r}var Np=class extends cO.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(rr.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:i,replacer:o}=r,s=new this(t),a=(l,c)=>{if(typeof o=="function")c=o.call(n,l,c);else if(Array.isArray(o)&&!o.includes(l))return;(c!==void 0||i)&&s.items.push(qc.createPair(l,c,r))};if(n instanceof Map)for(let[l,c]of n)a(l,c);else if(n&&typeof n=="object")for(let l of Object.keys(n))a(l,n[l]);return typeof t.sortMapEntries=="function"&&s.items.sort(t.sortMapEntries),s}add(t,n){let r;rr.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new qc.Pair(t,t?.value):r=new qc.Pair(t.key,t.value);let i=Ns(this.items,r.key),o=this.schema?.sortMapEntries;if(i){if(!n)throw new Error(`Key ${r.key} already set`);rr.isScalar(i.value)&&uO.isScalarValue(r.value)?i.value.value=r.value:i.value=r.value}else if(o){let s=this.items.findIndex(a=>o(r,a)<0);s===-1?this.items.push(r):this.items.splice(s,0,r)}else this.items.push(r)}delete(t){let n=Ns(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let i=Ns(this.items,t)?.value;return(!n&&rr.isScalar(i)?i.value:i)??void 0}has(t){return!!Ns(this.items,t)}set(t,n){this.add(new qc.Pair(t,n),!0)}toJSON(t,n,r){let i=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(i);for(let o of this.items)lO.addPairToJSMap(n,i,o);return i}toString(t,n,r){if(!t)return JSON.stringify(this);for(let i of this.items)if(!rr.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),aO.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};Mp.YAMLMap=Np;Mp.findPair=Ns});var no=N(uk=>{"use strict";var dO=oe(),ck=ir(),fO={collection:"map",default:!0,nodeClass:ck.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return dO.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>ck.YAMLMap.from(e,t,n)};uk.map=fO});var or=N(dk=>{"use strict";var pO=Ds(),mO=Bp(),gO=Ic(),Gc=oe(),hO=xe(),yO=Xn(),jp=class extends gO.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Gc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Vc(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Vc(t);if(typeof r!="number")return;let i=this.items[r];return!n&&Gc.isScalar(i)?i.value:i}has(t){let n=Vc(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Vc(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[r];Gc.isScalar(i)&&hO.isScalarValue(n)?i.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let i=0;for(let o of this.items)r.push(yO.toJS(o,String(i++),n));return r}toString(t,n,r){return t?mO.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:i}=r,o=new this(t);if(n&&Symbol.iterator in Object(n)){let s=0;for(let a of n){if(typeof i=="function"){let l=n instanceof Set?a:String(s++);a=i.call(n,l,a)}o.items.push(pO.createNode(a,void 0,r))}}return o}};function Vc(e){let t=Gc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}dk.YAMLSeq=jp});var ro=N(pk=>{"use strict";var wO=oe(),fk=or(),vO={collection:"seq",default:!0,nodeClass:fk.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return wO.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>fk.YAMLSeq.from(e,t,n)};pk.seq=vO});var Ms=N(mk=>{"use strict";var bO=Os(),_O={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),bO.stringifyString(e,t,n,r)}};mk.string=_O});var zc=N(yk=>{"use strict";var gk=xe(),hk={identify:e=>e==null,createNode:()=>new gk.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new gk.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&hk.test.test(e)?e:t.options.nullStr};yk.nullTag=hk});var Up=N(vk=>{"use strict";var kO=xe(),wk={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new kO.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&wk.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};vk.boolTag=wk});var io=N(bk=>{"use strict";function SO({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let i=typeof r=="number"?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let a=t-(o.length-s-1);for(;a-- >0;)o+="0"}return o}bk.stringifyNumber=SO});var Vp=N(Kc=>{"use strict";var CO=xe(),qp=io(),AO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:qp.stringifyNumber},xO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():qp.stringifyNumber(e)}},IO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new CO.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:qp.stringifyNumber};Kc.float=IO;Kc.floatExp=xO;Kc.floatNaN=AO});var zp=N(Wc=>{"use strict";var _k=io(),Hc=e=>typeof e=="bigint"||Number.isInteger(e),Gp=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function kk(e,t,n){let{value:r}=e;return Hc(r)&&r>=0?n+r.toString(t):_k.stringifyNumber(e)}var RO={identify:e=>Hc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Gp(e,2,8,n),stringify:e=>kk(e,8,"0o")},PO={identify:Hc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Gp(e,0,10,n),stringify:_k.stringifyNumber},EO={identify:e=>Hc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Gp(e,2,16,n),stringify:e=>kk(e,16,"0x")};Wc.int=PO;Wc.intHex=EO;Wc.intOct=RO});var Ck=N(Sk=>{"use strict";var DO=no(),TO=zc(),$O=ro(),LO=Ms(),OO=Up(),Kp=Vp(),Hp=zp(),FO=[DO.map,$O.seq,LO.string,TO.nullTag,OO.boolTag,Hp.intOct,Hp.int,Hp.intHex,Kp.floatNaN,Kp.floatExp,Kp.float];Sk.schema=FO});var Ik=N(xk=>{"use strict";var BO=xe(),NO=no(),MO=ro();function Ak(e){return typeof e=="bigint"||Number.isInteger(e)}var Jc=({value:e})=>JSON.stringify(e),jO=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Jc},{identify:e=>e==null,createNode:()=>new BO.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Jc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Jc},{identify:Ak,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>Ak(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Jc}],UO={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},qO=[NO.map,MO.seq].concat(jO,UO);xk.schema=qO});var Jp=N(Rk=>{"use strict";var js=qr("buffer"),Wp=xe(),VO=Os(),GO={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof js.Buffer=="function")return js.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,i,o){if(!n)return"";let s=n,a;if(typeof js.Buffer=="function")a=s instanceof js.Buffer?s.toString("base64"):js.Buffer.from(s.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<s.length;++c)l+=String.fromCharCode(s[c]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Wp.Scalar.BLOCK_LITERAL),t!==Wp.Scalar.QUOTE_DOUBLE){let l=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),c=Math.ceil(a.length/l),u=new Array(c);for(let d=0,p=0;d<c;++d,p+=l)u[d]=a.substr(p,l);a=u.join(t===Wp.Scalar.BLOCK_LITERAL?`
|
|
54
|
+
`:" ")}return VO.stringifyString({comment:e,type:t,value:a},r,i,o)}};Rk.binary=GO});var Xc=N(Zc=>{"use strict";var Yc=oe(),Yp=nr(),zO=xe(),KO=or();function Pk(e,t){if(Yc.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Yc.isPair(r)){if(Yc.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let i=r.items[0]||new Yp.Pair(new zO.Scalar(null));if(r.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${r.commentBefore}
|
|
55
|
+
${i.key.commentBefore}`:r.commentBefore),r.comment){let o=i.value??i.key;o.comment=o.comment?`${r.comment}
|
|
56
|
+
${o.comment}`:r.comment}r=i}e.items[n]=Yc.isPair(r)?r:new Yp.Pair(r)}}else t("Expected a sequence for this tag");return e}function Ek(e,t,n){let{replacer:r}=n,i=new KO.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let s of t){typeof r=="function"&&(s=r.call(t,String(o++),s));let a,l;if(Array.isArray(s))if(s.length===2)a=s[0],l=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let c=Object.keys(s);if(c.length===1)a=c[0],l=s[a];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else a=s;i.items.push(Yp.createPair(a,l,n))}return i}var HO={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Pk,createNode:Ek};Zc.createPairs=Ek;Zc.pairs=HO;Zc.resolvePairs=Pk});var Qp=N(Xp=>{"use strict";var Dk=oe(),Zp=Xn(),Us=ir(),WO=or(),Tk=Xc(),Yr=class e extends WO.YAMLSeq{constructor(){super(),this.add=Us.YAMLMap.prototype.add.bind(this),this.delete=Us.YAMLMap.prototype.delete.bind(this),this.get=Us.YAMLMap.prototype.get.bind(this),this.has=Us.YAMLMap.prototype.has.bind(this),this.set=Us.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let i of this.items){let o,s;if(Dk.isPair(i)?(o=Zp.toJS(i.key,"",n),s=Zp.toJS(i.value,o,n)):o=Zp.toJS(i,"",n),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,s)}return r}static from(t,n,r){let i=Tk.createPairs(t,n,r),o=new this;return o.items=i.items,o}};Yr.tag="tag:yaml.org,2002:omap";var JO={collection:"seq",identify:e=>e instanceof Map,nodeClass:Yr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=Tk.resolvePairs(e,t),r=[];for(let{key:i}of n.items)Dk.isScalar(i)&&(r.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new Yr,n)},createNode:(e,t,n)=>Yr.from(e,t,n)};Xp.YAMLOMap=Yr;Xp.omap=JO});var Bk=N(em=>{"use strict";var $k=xe();function Lk({value:e,source:t},n){return t&&(e?Ok:Fk).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Ok={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new $k.Scalar(!0),stringify:Lk},Fk={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new $k.Scalar(!1),stringify:Lk};em.falseTag=Fk;em.trueTag=Ok});var Nk=N(Qc=>{"use strict";var YO=xe(),tm=io(),ZO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:tm.stringifyNumber},XO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():tm.stringifyNumber(e)}},QO={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new YO.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:tm.stringifyNumber};Qc.float=QO;Qc.floatExp=XO;Qc.floatNaN=ZO});var jk=N(Vs=>{"use strict";var Mk=io(),qs=e=>typeof e=="bigint"||Number.isInteger(e);function eu(e,t,n,{intAsBigInt:r}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let s=BigInt(e);return i==="-"?BigInt(-1)*s:s}let o=parseInt(e,n);return i==="-"?-1*o:o}function nm(e,t,n){let{value:r}=e;if(qs(r)){let i=r.toString(t);return r<0?"-"+n+i.substr(1):n+i}return Mk.stringifyNumber(e)}var eF={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>eu(e,2,2,n),stringify:e=>nm(e,2,"0b")},tF={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>eu(e,1,8,n),stringify:e=>nm(e,8,"0")},nF={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>eu(e,0,10,n),stringify:Mk.stringifyNumber},rF={identify:qs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>eu(e,2,16,n),stringify:e=>nm(e,16,"0x")};Vs.int=nF;Vs.intBin=eF;Vs.intHex=rF;Vs.intOct=tF});var im=N(rm=>{"use strict";var ru=oe(),tu=nr(),nu=ir(),Zr=class e extends nu.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;ru.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new tu.Pair(t.key,null):n=new tu.Pair(t,null),nu.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=nu.findPair(this.items,t);return!n&&ru.isPair(r)?ru.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=nu.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new tu.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:i}=r,o=new this(t);if(n&&Symbol.iterator in Object(n))for(let s of n)typeof i=="function"&&(s=i.call(n,s,s)),o.items.push(tu.createPair(s,null,r));return o}};Zr.tag="tag:yaml.org,2002:set";var iF={collection:"map",identify:e=>e instanceof Set,nodeClass:Zr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Zr.from(e,t,n),resolve(e,t){if(ru.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Zr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};rm.YAMLSet=Zr;rm.set=iF});var sm=N(iu=>{"use strict";var oF=io();function om(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,i=s=>t?BigInt(s):Number(s),o=r.replace(/_/g,"").split(":").reduce((s,a)=>s*i(60)+i(a),i(0));return n==="-"?i(-1)*o:o}function Uk(e){let{value:t}=e,n=s=>s;if(typeof t=="bigint")n=s=>BigInt(s);else if(isNaN(t)||!isFinite(t))return oF.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let i=n(60),o=[t%i];return t<60?o.unshift(0):(t=(t-o[0])/i,o.unshift(t%i),t>=60&&(t=(t-o[0])/i,o.unshift(t))),r+o.map(s=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var sF={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>om(e,n),stringify:Uk},aF={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>om(e,!1),stringify:Uk},qk={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(qk.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,i,o,s,a]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,c=Date.UTC(n,r-1,i,o||0,s||0,a||0,l),u=t[8];if(u&&u!=="Z"){let d=om(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};iu.floatTime=aF;iu.intTime=sF;iu.timestamp=qk});var zk=N(Gk=>{"use strict";var lF=no(),cF=zc(),uF=ro(),dF=Ms(),fF=Jp(),Vk=Bk(),am=Nk(),ou=jk(),pF=Bc(),mF=Qp(),gF=Xc(),hF=im(),lm=sm(),yF=[lF.map,uF.seq,dF.string,cF.nullTag,Vk.trueTag,Vk.falseTag,ou.intBin,ou.intOct,ou.int,ou.intHex,am.floatNaN,am.floatExp,am.float,fF.binary,pF.merge,mF.omap,gF.pairs,hF.set,lm.intTime,lm.floatTime,lm.timestamp];Gk.schema=yF});var tS=N(dm=>{"use strict";var Jk=no(),wF=zc(),Yk=ro(),vF=Ms(),bF=Up(),cm=Vp(),um=zp(),_F=Ck(),kF=Ik(),Zk=Jp(),Gs=Bc(),Xk=Qp(),Qk=Xc(),Kk=zk(),eS=im(),su=sm(),Hk=new Map([["core",_F.schema],["failsafe",[Jk.map,Yk.seq,vF.string]],["json",kF.schema],["yaml11",Kk.schema],["yaml-1.1",Kk.schema]]),Wk={binary:Zk.binary,bool:bF.boolTag,float:cm.float,floatExp:cm.floatExp,floatNaN:cm.floatNaN,floatTime:su.floatTime,int:um.int,intHex:um.intHex,intOct:um.intOct,intTime:su.intTime,map:Jk.map,merge:Gs.merge,null:wF.nullTag,omap:Xk.omap,pairs:Qk.pairs,seq:Yk.seq,set:eS.set,timestamp:su.timestamp},SF={"tag:yaml.org,2002:binary":Zk.binary,"tag:yaml.org,2002:merge":Gs.merge,"tag:yaml.org,2002:omap":Xk.omap,"tag:yaml.org,2002:pairs":Qk.pairs,"tag:yaml.org,2002:set":eS.set,"tag:yaml.org,2002:timestamp":su.timestamp};function CF(e,t,n){let r=Hk.get(t);if(r&&!e)return n&&!r.includes(Gs.merge)?r.concat(Gs.merge):r.slice();let i=r;if(!i)if(Array.isArray(e))i=[];else{let o=Array.from(Hk.keys()).filter(s=>s!=="yaml11").map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)i=i.concat(o);else typeof e=="function"&&(i=e(i.slice()));return n&&(i=i.concat(Gs.merge)),i.reduce((o,s)=>{let a=typeof s=="string"?Wk[s]:s;if(!a){let l=JSON.stringify(s),c=Object.keys(Wk).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return o.includes(a)||o.push(a),o},[])}dm.coreKnownTags=SF;dm.getTags=CF});var mm=N(nS=>{"use strict";var fm=oe(),AF=no(),xF=ro(),IF=Ms(),au=tS(),RF=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,pm=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:i,schema:o,sortMapEntries:s,toStringDefaults:a}){this.compat=Array.isArray(t)?au.getTags(t,"compat"):t?au.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=i?au.coreKnownTags:{},this.tags=au.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,fm.MAP,{value:AF.map}),Object.defineProperty(this,fm.SCALAR,{value:IF.string}),Object.defineProperty(this,fm.SEQ,{value:xF.seq}),this.sortMapEntries=typeof s=="function"?s:s===!0?RF:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};nS.Schema=pm});var iS=N(rS=>{"use strict";var PF=oe(),gm=Fs(),zs=Ts();function EF(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);l?(n.push(l),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let i=gm.createStringifyContext(e,t),{commentString:o}=i.options;if(e.commentBefore){n.length!==1&&n.unshift("");let l=o(e.commentBefore);n.unshift(zs.indentComment(l,""))}let s=!1,a=null;if(e.contents){if(PF.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let u=o(e.contents.commentBefore);n.push(zs.indentComment(u,""))}i.forceBlockIndent=!!e.comment,a=e.contents.comment}let l=a?void 0:()=>s=!0,c=gm.stringify(e.contents,i,()=>a=null,l);a&&(c+=zs.lineComment(c,"",o(a))),(c[0]==="|"||c[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(gm.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let l=o(e.comment);l.includes(`
|
|
57
|
+
`)?(n.push("..."),n.push(zs.indentComment(l,""))):n.push(`... ${l}`)}else n.push("...");else{let l=e.comment;l&&s&&(l=l.replace(/^\n+/,"")),l&&((!s||a)&&n[n.length-1]!==""&&n.push(""),n.push(zs.indentComment(o(l),"")))}return n.join(`
|
|
58
|
+
`)+`
|
|
59
|
+
`}rS.stringifyDocument=EF});var Ks=N(oS=>{"use strict";var DF=Es(),oo=Ic(),Lt=oe(),TF=nr(),$F=Xn(),LF=mm(),OF=iS(),hm=Sc(),FF=bp(),BF=Ds(),ym=vp(),wm=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Lt.NODE_TYPE,{value:Lt.DOC});let i=null;typeof n=="function"||Array.isArray(n)?i=n:r===void 0&&n&&(r=n,n=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:s}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new ym.Directives({version:s}),this.setSchema(s,r),this.contents=t===void 0?null:this.createNode(t,i,r)}clone(){let t=Object.create(e.prototype,{[Lt.NODE_TYPE]:{value:Lt.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Lt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){so(this.contents)&&this.contents.add(t)}addIn(t,n){so(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=hm.anchorNames(this);t.anchor=!n||r.has(n)?hm.findNewAnchor(n||"a",r):n}return new DF.Alias(t.anchor)}createNode(t,n,r){let i;if(typeof n=="function")t=n.call({"":t},"",t),i=n;else if(Array.isArray(n)){let y=b=>typeof b=="number"||b instanceof String||b instanceof Number,w=n.filter(y).map(String);w.length>0&&(n=n.concat(w)),i=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:o,anchorPrefix:s,flow:a,keepUndefined:l,onTagObj:c,tag:u}=r??{},{onAnchor:d,setAnchors:p,sourceObjects:m}=hm.createNodeAnchors(this,s||"a"),g={aliasDuplicateObjects:o??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:i,schema:this.schema,sourceObjects:m},h=BF.createNode(t,u,g);return a&&Lt.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,n,r={}){let i=this.createNode(t,null,r),o=this.createNode(n,null,r);return new TF.Pair(i,o)}delete(t){return so(this.contents)?this.contents.delete(t):!1}deleteIn(t){return oo.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):so(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return Lt.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return oo.isEmptyPath(t)?!n&&Lt.isScalar(this.contents)?this.contents.value:this.contents:Lt.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return Lt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return oo.isEmptyPath(t)?this.contents!==void 0:Lt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=oo.collectionFromPath(this.schema,[t],n):so(this.contents)&&this.contents.set(t,n)}setIn(t,n){oo.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=oo.collectionFromPath(this.schema,Array.from(t),n):so(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ym.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new ym.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new LF.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:i,onAnchor:o,reviver:s}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},l=$F.toJS(this.contents,n??"",a);if(typeof o=="function")for(let{count:c,res:u}of a.anchors.values())o(u,c);return typeof s=="function"?FF.applyReviver(s,{"":l},"",l):l}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return OF.stringifyDocument(this,t)}};function so(e){if(Lt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}oS.Document=wm});var Js=N(Ws=>{"use strict";var Hs=class extends Error{constructor(t,n,r,i){super(),this.name=t,this.code=r,this.message=i,this.pos=n}},vm=class extends Hs{constructor(t,n,r){super("YAMLParseError",t,n,r)}},bm=class extends Hs{constructor(t,n,r){super("YAMLWarning",t,n,r)}},NF=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let o=i-1,s=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&s.length>80){let a=Math.min(o-39,s.length-79);s="\u2026"+s.substring(a),o-=a-1}if(s.length>80&&(s=s.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(s.substring(0,o))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
60
|
+
`),s=a+s}if(/[^ ]/.test(s)){let a=1,l=n.linePos[1];l?.line===r&&l.col>i&&(a=Math.max(1,Math.min(l.col-i,80-o)));let c=" ".repeat(o)+"^".repeat(a);n.message+=`:
|
|
61
|
+
|
|
62
|
+
${s}
|
|
63
|
+
${c}
|
|
64
|
+
`}};Ws.YAMLError=Hs;Ws.YAMLParseError=vm;Ws.YAMLWarning=bm;Ws.prettifyError=NF});var Ys=N(sS=>{"use strict";function MF(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,g=!1,h=null,y=null,w=null,b=null,_=null,I=null,x=null;for(let T of e)switch(g&&(T.type!=="space"&&T.type!=="newline"&&T.type!=="comma"&&o(T.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),h&&(c&&T.type!=="comment"&&T.type!=="newline"&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),T.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&T.source.includes(" ")&&(h=T),u=!0;break;case"comment":{u||o(T,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let j=T.source.substring(1)||" ";d?d+=p+j:d=j,p="",c=!1;break}case"newline":c?d?d+=T.source:(!I||n!=="seq-item-ind")&&(l=!0):p+=T.source,c=!0,m=!0,(y||w)&&(b=T),u=!0;break;case"anchor":y&&o(T,"MULTIPLE_ANCHORS","A node can have at most one anchor"),T.source.endsWith(":")&&o(T.offset+T.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=T,x??(x=T.offset),c=!1,u=!1,g=!0;break;case"tag":{w&&o(T,"MULTIPLE_TAGS","A node can have at most one tag"),w=T,x??(x=T.offset),c=!1,u=!1,g=!0;break}case n:(y||w)&&o(T,"BAD_PROP_ORDER",`Anchors and tags must be after the ${T.source} indicator`),I&&o(T,"UNEXPECTED_TOKEN",`Unexpected ${T.source} in ${t??"collection"}`),I=T,c=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(t){_&&o(T,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),_=T,c=!1,u=!1;break}default:o(T,"UNEXPECTED_TOKEN",`Unexpected ${T.type} token`),c=!1,u=!1}let C=e[e.length-1],D=C?C.offset+C.source.length:i;return g&&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"),h&&(c&&h.indent<=s||r?.type==="block-map"||r?.type==="block-seq")&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:_,found:I,spaceBefore:l,comment:d,hasNewline:m,anchor:y,tag:w,newlineAfterProp:b,end:D,start:x??D}}sS.resolveProps=MF});var lu=N(aS=>{"use strict";function _m(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
|
+
`))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(_m(t.key)||_m(t.value))return!0}return!1;default:return!0}}aS.containsNewline=_m});var km=N(lS=>{"use strict";var jF=lu();function UF(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&jF.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}lS.flowIndentCheck=UF});var Sm=N(uS=>{"use strict";var cS=oe();function qF(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r=="function"?r:(o,s)=>o===s||cS.isScalar(o)&&cS.isScalar(s)&&o.value===s.value;return t.some(o=>i(o.key,n))}uS.mapIncludes=qF});var hS=N(gS=>{"use strict";var dS=nr(),VF=ir(),fS=Ys(),GF=lu(),pS=km(),zF=Sm(),mS="All mapping items must start at the same column";function KF({composeNode:e,composeEmptyNode:t},n,r,i,o){let s=o?.nodeClass??VF.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:g}=u,h=fS.resolveProps(d,{indicator:"explicit-key-ind",next:p??m?.[0],offset:l,onError:i,parentIndent:r.indent,startOnNewline:!0}),y=!h.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",mS)),!h.anchor&&!h.tag&&!m){c=h.end,h.comment&&(a.comment?a.comment+=`
|
|
66
|
+
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||GF.containsNewline(p))&&i(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&i(l,"BAD_INDENT",mS);n.atKey=!0;let w=h.end,b=p?e(n,p,h,i):t(n,w,d,null,h,i);n.schema.compat&&pS.flowIndentCheck(r.indent,p,i),n.atKey=!1,zF.mapIncludes(n,a.items,b)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let _=fS.resolveProps(m??[],{indicator:"map-value-ind",next:g,offset:b.range[2],onError:i,parentIndent:r.indent,startOnNewline:!p||p.type==="block-scalar"});if(l=_.end,_.found){y&&(g?.type==="block-map"&&!_.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<_.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 I=g?e(n,g,_,i):t(n,l,m,null,_,i);n.schema.compat&&pS.flowIndentCheck(r.indent,g,i),l=I.range[2];let x=new dS.Pair(b,I);n.options.keepSourceTokens&&(x.srcToken=u),a.items.push(x)}else{y&&i(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),_.comment&&(b.comment?b.comment+=`
|
|
67
|
+
`+_.comment:b.comment=_.comment);let I=new dS.Pair(b);n.options.keepSourceTokens&&(I.srcToken=u),a.items.push(I)}}return c&&c<l&&i(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,l,c??l],a}gS.resolveBlockMap=KF});var wS=N(yS=>{"use strict";var HF=or(),WF=Ys(),JF=km();function YF({composeNode:e,composeEmptyNode:t},n,r,i,o){let s=o?.nodeClass??HF.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=WF.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&&JF.flowIndentCheck(r.indent,d,i),l=m.range[2],a.items.push(m)}return a.range=[r.offset,l,c??l],a}yS.resolveBlockSeq=YF});var ao=N(vS=>{"use strict";function ZF(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}}vS.resolveEnd=ZF});var SS=N(kS=>{"use strict";var XF=oe(),QF=nr(),bS=ir(),eB=or(),tB=ao(),_S=Ys(),nB=lu(),rB=Sm(),Cm="Block collections are not allowed within flow collections",Am=e=>e&&(e.type==="block-map"||e.type==="block-seq");function iB({composeNode:e,composeEmptyNode:t},n,r,i,o){let s=r.start.source==="{",a=s?"flow map":"flow sequence",l=o?.nodeClass??(s?bS.YAMLMap:eB.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 w=r.items[y],{start:b,key:_,sep:I,value:x}=w,C=_S.resolveProps(b,{flow:a,indicator:"explicit-key-ind",next:_??I?.[0],offset:d,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!I&&!x){y===0&&C.comma?i(C.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<r.items.length-1&&i(C.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),C.comment&&(c.comment?c.comment+=`
|
|
68
|
+
`+C.comment:c.comment=C.comment),d=C.end;continue}!s&&n.options.strict&&nB.containsNewline(_)&&i(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)C.comma&&i(C.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(C.comma||i(C.start,"MISSING_CHAR",`Missing , between ${a} items`),C.comment){let D="";e:for(let T of b)switch(T.type){case"comma":case"space":break;case"comment":D=T.source.substring(1);break e;default:break e}if(D){let T=c.items[c.items.length-1];XF.isPair(T)&&(T=T.value??T.key),T.comment?T.comment+=`
|
|
69
|
+
`+D:T.comment=D,C.comment=C.comment.substring(D.length+1)}}if(!s&&!I&&!C.found){let D=x?e(n,x,C,i):t(n,C.end,I,null,C,i);c.items.push(D),d=D.range[2],Am(x)&&i(D.range,"BLOCK_IN_FLOW",Cm)}else{n.atKey=!0;let D=C.end,T=_?e(n,_,C,i):t(n,D,b,null,C,i);Am(_)&&i(T.range,"BLOCK_IN_FLOW",Cm),n.atKey=!1;let j=_S.resolveProps(I??[],{flow:a,indicator:"map-value-ind",next:x,offset:T.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(j.found){if(!s&&!C.found&&n.options.strict){if(I)for(let B of I){if(B===j.found)break;if(B.type==="newline"){i(B,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}C.start<j.found.offset-1024&&i(j.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?i(x,"MISSING_CHAR",`Missing space after : in ${a}`):i(j.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let M=x?e(n,x,j,i):j.found?t(n,j.end,I,null,j,i):null;M?Am(x)&&i(M.range,"BLOCK_IN_FLOW",Cm):j.comment&&(T.comment?T.comment+=`
|
|
70
|
+
`+j.comment:T.comment=j.comment);let $=new QF.Pair(T,M);if(n.options.keepSourceTokens&&($.srcToken=w),s){let B=c;rB.mapIncludes(n,B.items,T)&&i(D,"DUPLICATE_KEY","Map keys must be unique"),B.items.push($)}else{let B=new bS.YAMLMap(n.schema);B.flow=!0,B.items.push($);let q=(M??T).range;B.range=[T.range[0],q[1],q[2]],c.items.push(B)}d=M?M.range[2]:j.end}}let p=s?"}":"]",[m,...g]=r.end,h=d;if(m?.source===p)h=m.offset+m.source.length;else{let y=a[0].toUpperCase()+a.substring(1),w=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",w),m&&m.source.length!==1&&g.unshift(m)}if(g.length>0){let y=tB.resolveEnd(g,h,n.options.strict,i);y.comment&&(c.comment?c.comment+=`
|
|
71
|
+
`+y.comment:c.comment=y.comment),c.range=[r.offset,h,y.offset]}else c.range=[r.offset,h,h];return c}kS.resolveFlowCollection=iB});var AS=N(CS=>{"use strict";var oB=oe(),sB=xe(),aB=ir(),lB=or(),cB=hS(),uB=wS(),dB=SS();function xm(e,t,n,r,i,o){let s=n.type==="block-map"?cB.resolveBlockMap(e,t,n,r,o):n.type==="block-seq"?uB.resolveBlockSeq(e,t,n,r,o):dB.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 fB(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,g=p&&o?p.offset>o.offset?p:o:p??o;g&&(!m||m.offset<g.offset)&&i(g,"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===aB.YAMLMap.tagName&&a==="map"||s===lB.YAMLSeq.tagName&&a==="seq")return xm(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),xm(e,t,n,i,s)}let c=xm(e,t,n,i,s,l),u=l.resolve?.(c,p=>i(o,"TAG_RESOLVE_FAILED",p),t.options)??c,d=oB.isNode(u)?u:new sB.Scalar(u);return d.range=c.range,d.tag=s,l?.format&&(d.format=l.format),d}CS.composeCollection=fB});var Rm=N(xS=>{"use strict";var Im=xe();function pB(e,t,n){let r=t.offset,i=mB(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let o=i.mode===">"?Im.Scalar.BLOCK_FOLDED:Im.Scalar.BLOCK_LITERAL,s=t.source?gB(t.source):[],a=s.length;for(let h=s.length-1;h>=0;--h){let y=s[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&s.length>0?`
|
|
72
|
+
`.repeat(Math.max(1,s.length-1)):"",y=r+i.length;return t.source&&(y+=t.source.length),{value:h,type:o,comment:i.comment,range:[r,y,y]}}let l=t.indent+i.indent,c=t.offset+i.length,u=0;for(let h=0;h<a;++h){let[y,w]=s[h];if(w===""||w==="\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=h,l===0&&!e.atRoot&&n(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=y.length+w.length+1}for(let h=s.length-1;h>=a;--h)s[h][0].length>l&&(a=h+1);let d="",p="",m=!1;for(let h=0;h<u;++h)d+=s[h][0].slice(l)+`
|
|
73
|
+
`;for(let h=u;h<a;++h){let[y,w]=s[h];c+=y.length+w.length+1;let b=w[w.length-1]==="\r";if(b&&(w=w.slice(0,-1)),w&&y.length<l){let I=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;n(c-w.length-(b?2:1),"BAD_INDENT",I),y=""}o===Im.Scalar.BLOCK_LITERAL?(d+=p+y.slice(l)+w,p=`
|
|
74
|
+
`):y.length>l||w[0]===" "?(p===" "?p=`
|
|
75
|
+
`:!m&&p===`
|
|
76
|
+
`&&(p=`
|
|
77
|
+
|
|
78
|
+
`),d+=p+y.slice(l)+w,p=`
|
|
79
|
+
`,m=!0):w===""?p===`
|
|
80
|
+
`?d+=`
|
|
81
|
+
`:p=`
|
|
82
|
+
`:(d+=p+w,p=" ",m=!1)}switch(i.chomp){case"-":break;case"+":for(let h=a;h<s.length;++h)d+=`
|
|
83
|
+
`+s[h][0].slice(l);d[d.length-1]!==`
|
|
84
|
+
`&&(d+=`
|
|
85
|
+
`);break;default:d+=`
|
|
86
|
+
`}let g=r+i.length+t.source.length;return{value:d,type:o,comment:i.comment,range:[r,g,g]}}function mB({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],o=i[0],s=0,a="",l=-1;for(let p=1;p<i.length;++p){let m=i[p];if(!a&&(m==="-"||m==="+"))a=m;else{let g=Number(m);!s&&g?s=g:l===-1&&(l=e+p)}}l!==-1&&r(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let c=!1,u="",d=i.length;for(let p=1;p<t.length;++p){let m=t[p];switch(m.type){case"space":c=!0;case"newline":d+=m.source.length;break;case"comment":n&&!c&&r(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=m.source.length,u=m.source.substring(1);break;case"error":r(m,"UNEXPECTED_TOKEN",m.message),d+=m.source.length;break;default:{let g=`Unexpected token in block scalar header: ${m.type}`;r(m,"UNEXPECTED_TOKEN",g);let h=m.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:o,indent:s,chomp:a,comment:u,length:d}}function gB(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),o=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let s=1;s<t.length;s+=2)o.push([t[s],t[s+1]]);return o}xS.resolveBlockScalar=pB});var Em=N(RS=>{"use strict";var Pm=xe(),hB=ao();function yB(e,t,n){let{offset:r,type:i,source:o,end:s}=e,a,l,c=(p,m,g)=>n(r+p,m,g);switch(i){case"scalar":a=Pm.Scalar.PLAIN,l=wB(o,c);break;case"single-quoted-scalar":a=Pm.Scalar.QUOTE_SINGLE,l=vB(o,c);break;case"double-quoted-scalar":a=Pm.Scalar.QUOTE_DOUBLE,l=bB(o,c);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let u=r+o.length,d=hB.resolveEnd(s,u,t,n);return{value:l,type:a,comment:d.comment,range:[r,u,d.offset]}}function wB(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),IS(e)}function vB(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),IS(e.slice(1,-1)).replace(/''/g,"'")}function IS(e){let t,n;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
87
|
+
`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
88
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],o=" ",s=t.lastIndex;for(n.lastIndex=s;r=n.exec(e);)r[1]===""?o===`
|
|
89
|
+
`?i+=o:o=`
|
|
90
|
+
`:(i+=o+r[1],o=" "),s=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=s,r=a.exec(e),i+o+(r?.[1]??"")}function bB(e,t){let n="";for(let r=1;r<e.length-1;++r){let i=e[r];if(!(i==="\r"&&e[r+1]===`
|
|
91
|
+
`))if(i===`
|
|
92
|
+
`){let{fold:o,offset:s}=_B(e,r);n+=o,r=s}else if(i==="\\"){let o=e[++r],s=kB[o];if(s)n+=s;else if(o===`
|
|
93
|
+
`)for(o=e[r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="\r"&&e[r+1]===`
|
|
94
|
+
`)for(o=e[++r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="x"||o==="u"||o==="U"){let a=o==="x"?2:o==="u"?4:8;n+=SB(e,r+1,a,t),r+=a}else{let a=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(i===" "||i===" "){let o=r,s=e[r+1];for(;s===" "||s===" ";)s=e[++r+1];s!==`
|
|
95
|
+
`&&!(s==="\r"&&e[r+2]===`
|
|
96
|
+
`)&&(n+=r>o?e.slice(o,r+1):i)}else n+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function _B(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
97
|
+
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
98
|
+
`);)r===`
|
|
99
|
+
`&&(n+=`
|
|
100
|
+
`),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var kB={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
101
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function SB(e,t,n,r){let i=e.substr(t,n),s=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(s)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}RS.resolveFlowScalar=yB});var DS=N(ES=>{"use strict";var Xr=oe(),PS=xe(),CB=Rm(),AB=Em();function xB(e,t,n,r){let{value:i,type:o,comment:s,range:a}=t.type==="block-scalar"?CB.resolveBlockScalar(e,t,r):AB.resolveFlowScalar(t,e.options.strict,r),l=n?e.directives.tagName(n.source,d=>r(n,"TAG_RESOLVE_FAILED",d)):null,c;e.options.stringKeys&&e.atKey?c=e.schema[Xr.SCALAR]:l?c=IB(e.schema,i,l,n,r):t.type==="scalar"?c=RB(e,i,t,r):c=e.schema[Xr.SCALAR];let u;try{let d=c.resolve(i,p=>r(n??t,"TAG_RESOLVE_FAILED",p),e.options);u=Xr.isScalar(d)?d:new PS.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);r(n??t,"TAG_RESOLVE_FAILED",p),u=new PS.Scalar(i)}return u.range=a,u.source=i,o&&(u.type=o),l&&(u.tag=l),c.format&&(u.format=c.format),s&&(u.comment=s),u}function IB(e,t,n,r,i){if(n==="!")return e[Xr.SCALAR];let o=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(t))return a;let s=e.knownTags[n];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[Xr.SCALAR])}function RB({atKey:e,directives:t,schema:n},r,i,o){let s=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[Xr.SCALAR];if(n.compat){let a=n.compat.find(l=>l.default&&l.test?.test(r))??n[Xr.SCALAR];if(s.tag!==a.tag){let l=t.tagString(s.tag),c=t.tagString(a.tag),u=`Value may be parsed as either ${l} or ${c}`;o(i,"TAG_RESOLVE_FAILED",u,!0)}}return s}ES.composeScalar=xB});var $S=N(TS=>{"use strict";function PB(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let i=t[r];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++r];i?.type==="space";)e+=i.source.length,i=t[++r];break}}return e}TS.emptyScalarPosition=PB});var FS=N(Tm=>{"use strict";var EB=Es(),DB=oe(),TB=AS(),LS=DS(),$B=ao(),LB=$S(),OB={composeNode:OS,composeEmptyNode:Dm};function OS(e,t,n,r){let i=e.atKey,{spaceBefore:o,comment:s,anchor:a,tag:l}=n,c,u=!0;switch(t.type){case"alias":c=FB(e,t,r),(a||l)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=LS.composeScalar(e,t,l,r),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=TB.composeCollection(OB,e,t,n,r),a&&(c.anchor=a.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=Dm(e,t.offset,void 0,null,n,r)),a&&c.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!DB.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&r(l??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(c.spaceBefore=!0),s&&(t.type==="scalar"&&t.source===""?c.comment=s:c.commentBefore=s),e.options.keepSourceTokens&&u&&(c.srcToken=t),c}function Dm(e,t,n,r,{spaceBefore:i,comment:o,anchor:s,tag:a,end:l},c){let u={type:"scalar",offset:LB.emptyScalarPosition(t,n,r),indent:-1,source:""},d=LS.composeScalar(e,u,a,c);return s&&(d.anchor=s.source.substring(1),d.anchor===""&&c(s,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),o&&(d.comment=o,d.range[2]=l),d}function FB({options:e},{offset:t,source:n,end:r},i){let o=new EB.Alias(n.substring(1));o.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&i(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=t+n.length,a=$B.resolveEnd(r,s,e.strict,i);return o.range=[t,s,a.offset],a.comment&&(o.comment=a.comment),o}Tm.composeEmptyNode=Dm;Tm.composeNode=OS});var MS=N(NS=>{"use strict";var BB=Ks(),BS=FS(),NB=ao(),MB=Ys();function jB(e,t,{offset:n,start:r,value:i,end:o},s){let a=Object.assign({_directives:t},e),l=new BB.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=MB.resolveProps(r,{indicator:"doc-start",next:i??o?.[0],offset:n,onError:s,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&s(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=i?BS.composeNode(c,i,u,s):BS.composeEmptyNode(c,u.end,r,null,u,s);let d=l.contents.range[2],p=NB.resolveEnd(o,d,!1,s);return p.comment&&(l.comment=p.comment),l.range=[n,d,p.offset],l}NS.composeDoc=jB});var Lm=N(qS=>{"use strict";var UB=qr("process"),qB=vp(),VB=Ks(),Zs=Js(),jS=oe(),GB=MS(),zB=ao();function Xs(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function US(e){let t="",n=!1,r=!1;for(let i=0;i<e.length;++i){let o=e[i];switch(o[0]){case"#":t+=(t===""?"":r?`
|
|
102
|
+
|
|
103
|
+
`:`
|
|
104
|
+
`)+(o.substring(1)||" "),n=!0,r=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var $m=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,i,o)=>{let s=Xs(n);o?this.warnings.push(new Zs.YAMLWarning(s,r,i)):this.errors.push(new Zs.YAMLParseError(s,r,i))},this.directives=new qB.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:i}=US(this.prelude);if(r){let o=t.contents;if(n)t.comment=t.comment?`${t.comment}
|
|
105
|
+
${r}`:r;else if(i||t.directives.docStart||!o)t.commentBefore=r;else if(jS.isCollection(o)&&!o.flow&&o.items.length>0){let s=o.items[0];jS.isPair(s)&&(s=s.key);let a=s.commentBefore;s.commentBefore=a?`${r}
|
|
106
|
+
${a}`:r}else{let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
|
+
${s}`:r}}if(n){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:US(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let i of t)yield*this.next(i);yield*this.end(n,r)}*next(t){switch(UB.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,i)=>{let o=Xs(t);o[0]+=n,this.onError(o,"BAD_DIRECTIVE",r,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=GB.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new Zs.YAMLParseError(Xs(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Zs.YAMLParseError(Xs(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=zB.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
108
|
+
${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Zs.YAMLParseError(Xs(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),i=new VB.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,n,n],this.decorate(i,!1),yield i}}};qS.Composer=$m});var zS=N(cu=>{"use strict";var KB=Rm(),HB=Em(),WB=Js(),VS=Os();function JB(e,t=!0,n){if(e){let r=(i,o,s)=>{let a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(n)n(a,o,s);else throw new WB.YAMLParseError([a,a+1],o,s)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return HB.resolveFlowScalar(e,t,r);case"block-scalar":return KB.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function YB(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:o=-1,type:s="PLAIN"}=t,a=VS.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
109
|
+
`}];switch(a[0]){case"|":case">":{let c=a.indexOf(`
|
|
110
|
+
`),u=a.substring(0,c),d=a.substring(c+1)+`
|
|
111
|
+
`,p=[{type:"block-scalar-header",offset:o,indent:r,source:u}];return GS(p,l)||p.push({type:"newline",offset:-1,indent:r,source:`
|
|
112
|
+
`}),{type:"block-scalar",offset:o,indent:r,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:a,end:l};default:return{type:"scalar",offset:o,indent:r,source:a,end:l}}}function ZB(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:o=!1,type:s}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!s)switch(e.type){case"single-quoted-scalar":s="QUOTE_SINGLE";break;case"double-quoted-scalar":s="QUOTE_DOUBLE";break;case"block-scalar":{let c=e.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:s="PLAIN"}let l=VS.stringifyString({type:s,value:t},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":XB(e,l);break;case'"':Om(e,l,"double-quoted-scalar");break;case"'":Om(e,l,"single-quoted-scalar");break;default:Om(e,l,"scalar")}}function XB(e,t){let n=t.indexOf(`
|
|
113
|
+
`),r=t.substring(0,n),i=t.substring(n+1)+`
|
|
114
|
+
`;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,e.source=i}else{let{offset:o}=e,s="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:s,source:r}];GS(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:s,source:`
|
|
115
|
+
`});for(let l of Object.keys(e))l!=="type"&&l!=="offset"&&delete e[l];Object.assign(e,{type:"block-scalar",indent:s,props:a,source:i})}}function GS(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function Om(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let o of r)o.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{let i={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
116
|
+
`};delete e.items,Object.assign(e,{type:n,source:t,end:[i]});break}default:{let r="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}cu.createScalarToken=YB;cu.resolveAsScalar=JB;cu.setScalarValue=ZB});var HS=N(KS=>{"use strict";var QB=e=>"type"in e?du(e):uu(e);function du(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=du(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=uu(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=uu(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=uu(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function uu({start:e,key:t,sep:n,value:r}){let i="";for(let o of e)i+=o.source;if(t&&(i+=du(t)),n)for(let o of n)i+=o.source;return r&&(i+=du(r)),i}KS.stringify=QB});var ZS=N(YS=>{"use strict";var Fm=Symbol("break visit"),e2=Symbol("skip children"),WS=Symbol("remove item");function Qr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),JS(Object.freeze([]),e,t)}Qr.BREAK=Fm;Qr.SKIP=e2;Qr.REMOVE=WS;Qr.itemAtPath=(e,t)=>{let n=e;for(let[r,i]of t){let o=n?.[r];if(o&&"items"in o)n=o.items[i];else return}return n};Qr.parentCollection=(e,t)=>{let n=Qr.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function JS(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let i of["key","value"]){let o=t[i];if(o&&"items"in o){for(let s=0;s<o.items.length;++s){let a=JS(Object.freeze(e.concat([[i,s]])),o.items[s],n);if(typeof a=="number")s=a-1;else{if(a===Fm)return Fm;a===WS&&(o.items.splice(s,1),s-=1)}}typeof r=="function"&&i==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}YS.visit=Qr});var fu=N(pt=>{"use strict";var Bm=zS(),t2=HS(),n2=ZS(),Nm="\uFEFF",Mm="",jm="",Um="",r2=e=>!!e&&"items"in e,i2=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function o2(e){switch(e){case Nm:return"<BOM>";case Mm:return"<DOC>";case jm:return"<FLOW_END>";case Um:return"<SCALAR>";default:return JSON.stringify(e)}}function s2(e){switch(e){case Nm:return"byte-order-mark";case Mm:return"doc-mode";case jm:return"flow-error-end";case Um:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
117
|
+
`:case`\r
|
|
118
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}pt.createScalarToken=Bm.createScalarToken;pt.resolveAsScalar=Bm.resolveAsScalar;pt.setScalarValue=Bm.setScalarValue;pt.stringify=t2.stringify;pt.visit=n2.visit;pt.BOM=Nm;pt.DOCUMENT=Mm;pt.FLOW_END=jm;pt.SCALAR=Um;pt.isCollection=r2;pt.isScalar=i2;pt.prettyToken=o2;pt.tokenType=s2});var Gm=N(QS=>{"use strict";var Qs=fu();function Ht(e){switch(e){case void 0:case" ":case`
|
|
119
|
+
`:case"\r":case" ":return!0;default:return!1}}var XS=new Set("0123456789ABCDEFabcdef"),a2=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),pu=new Set(",[]{}"),l2=new Set(` ,[]{}
|
|
120
|
+
\r `),qm=e=>!e||l2.has(e),Vm=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
|
|
121
|
+
`?!0:n==="\r"?this.buffer[t+1]===`
|
|
122
|
+
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let i=this.buffer[r+t+1];if(i===`
|
|
123
|
+
`||!i&&!this.atEnd)return t+r+1}return n===`
|
|
124
|
+
`||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Ht(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
125
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Qs.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let o=t[r-1];if(o===" "||o===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let o=t[n-1];if(o===" "||o===" ")n-=1;else break}let i=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield Qs.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&Ht(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ht(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ht(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(qm),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&i[0]!=="#"||r===0&&(i.startsWith("---")||i.startsWith("..."))&&Ht(i[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Qs.FLOW_END,yield*this.parseLineStart();let o=0;for(;i[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),i[o]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(qm),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let s=this.charAt(1);if(this.flowKey||Ht(s)||s===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let o=0;for(;this.buffer[n-1-o]==="\\";)o+=1;if(o%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),i=r.indexOf(`
|
|
126
|
+
`,this.pos);if(i!==-1){for(;i!==-1;){let o=this.continueScalar(i+1);if(o===-1)break;i=r.indexOf(`
|
|
127
|
+
`,o)}i!==-1&&(n=i-(r[i-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>Ht(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let o=this.pos;r=this.buffer[o];++o)switch(r){case" ":n+=1;break;case`
|
|
128
|
+
`:t=o,n=0;break;case"\r":{let s=this.buffer[o+1];if(!s&&!this.atEnd)return this.setNext("block-scalar");if(s===`
|
|
129
|
+
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
|
|
130
|
+
`,o)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(r=this.buffer[i];r===" ";)r=this.buffer[++i];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
131
|
+
`;)r=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let o=t-1,s=this.buffer[o];s==="\r"&&(s=this.buffer[--o]);let a=o;for(;s===" ";)s=this.buffer[--o];if(s===`
|
|
132
|
+
`&&o>=this.pos&&o+1+n>a)t=o;else break}while(!0);return yield Qs.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,i;for(;i=this.buffer[++r];)if(i===":"){let o=this.buffer[r+1];if(Ht(o)||t&&pu.has(o))break;n=r}else if(Ht(i)){let o=this.buffer[r+1];if(i==="\r"&&(o===`
|
|
133
|
+
`?(r+=1,i=`
|
|
134
|
+
`,o=this.buffer[r+1]):n=r),o==="#"||t&&pu.has(o))break;if(i===`
|
|
135
|
+
`){let s=this.continueScalar(r+1);if(s===-1)break;r=Math.max(r,s-2)}}else{if(t&&pu.has(i))break;n=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Qs.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(qm),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Ht(r)||n&&pu.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!Ht(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(a2.has(n))n=this.buffer[++t];else if(n==="%"&&XS.has(this.buffer[t+1])&&XS.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
136
|
+
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
137
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let i=n-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=n),i}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};QS.Lexer=Vm});var Km=N(eC=>{"use strict";var zm=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let o=n+r>>1;this.lineStarts[o]<t?n=o+1:r=o}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let i=this.lineStarts[n-1];return{line:n,col:t-i+1}}}};eC.LineCounter=zm});var Wm=N(oC=>{"use strict";var c2=qr("process"),tC=fu(),u2=Gm();function sr(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function nC(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function iC(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function mu(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function lo(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function gu(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function rC(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!sr(t.start,"explicit-key-ind")&&!sr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,iC(t.value)?t.value.end?gu(t.value.end,t.sep):t.value.end=t.sep:gu(t.start,t.sep),delete t.sep)}var Hm=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new u2.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,c2.env.LOG_TOKENS&&console.log("|",tC.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=tC.tokenType(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&rC(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let i=r.items[r.items.length-1];if(i.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=n;else{Object.assign(i,{key:n,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=r.items[r.items.length-1];i.value?r.items.push({start:[],value:n}):i.value=n;break}case"flow-collection":{let i=r.items[r.items.length-1];!i||i.value?r.items.push({start:[],key:n,sep:[]}):i.sep?i.value=n:Object.assign(i,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let i=n.items[n.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&nC(i.start)===-1&&(n.indent===0||i.start.every(o=>o.type!=="comment"||o.indent<n.indent))&&(r.type==="document"?r.end=i.start:r.items.push({start:i.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{nC(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=mu(this.peek(2)),r=lo(n),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let o={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
|
|
138
|
+
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
139
|
+
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){gu(i,n.start),i.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,i=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",o=[];if(i&&n.sep&&!n.value){let s=[];for(let a=0;a<n.sep.length;++a){let l=n.sep[a];switch(l.type){case"newline":s.push(a);break;case"space":break;case"comment":l.indent>t.indent&&(s.length=0);break;default:s.length=0}}s.length>=2&&(o=n.sep.splice(s[1]))}switch(this.type){case"anchor":case"tag":i||n.value?(o.push(this.sourceToken),t.items.push({start:o}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):i||n.value?(o.push(this.sourceToken),t.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(sr(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(iC(n.key)&&!sr(n.sep,"newline")){let s=lo(n.start),a=n.key,l=n.sep;l.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:a,sep:l}]})}else o.length>0?n.sep=n.sep.concat(o,this.sourceToken):n.sep.push(this.sourceToken);else if(sr(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let s=lo(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||i?t.items.push({start:o,key:null,sep:[this.sourceToken]}):sr(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);i||n.value?(t.items.push({start:o,key:s,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(s):(Object.assign(n,{key:s,sep:[]}),this.onKeyLine=!0);return}default:{let s=this.startBlockValue(t);if(s){if(s.type==="block-seq"){if(!n.explicitKey&&n.sep&&!sr(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:o});this.stack.push(s);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){gu(i,n.start),i.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||sr(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:i,sep:[]}):n.sep?this.stack.push(i):Object.assign(n,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let i=mu(r),o=lo(i);rC(t);let s=t.end.splice(1,t.end.length);s.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
|
|
140
|
+
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
141
|
+
`,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=mu(t),r=lo(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=mu(t),r=lo(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};oC.Parser=Hm});var uC=N(ta=>{"use strict";var sC=Lm(),d2=Ks(),ea=Js(),f2=Tp(),p2=oe(),m2=Km(),aC=Wm();function lC(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new m2.LineCounter||null,prettyErrors:t}}function g2(e,t={}){let{lineCounter:n,prettyErrors:r}=lC(t),i=new aC.Parser(n?.addNewLine),o=new sC.Composer(t),s=Array.from(o.compose(i.parse(e)));if(r&&n)for(let a of s)a.errors.forEach(ea.prettifyError(e,n)),a.warnings.forEach(ea.prettifyError(e,n));return s.length>0?s:Object.assign([],{empty:!0},o.streamInfo())}function cC(e,t={}){let{lineCounter:n,prettyErrors:r}=lC(t),i=new aC.Parser(n?.addNewLine),o=new sC.Composer(t),s=null;for(let a of o.compose(i.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new ea.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(s.errors.forEach(ea.prettifyError(e,n)),s.warnings.forEach(ea.prettifyError(e,n))),s}function h2(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let i=cC(e,n);if(!i)return null;if(i.warnings.forEach(o=>f2.warn(i.options.logLevel,o)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function y2(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=n??t??{};if(!i)return}return p2.isDocument(e)&&!r?e.toString(n):new d2.Document(e,r,n).toString(n)}ta.parse=h2;ta.parseAllDocuments=g2;ta.parseDocument=cC;ta.stringify=y2});var ei=N(ae=>{"use strict";var w2=Lm(),v2=Ks(),b2=mm(),Jm=Js(),_2=Es(),ar=oe(),k2=nr(),S2=xe(),C2=ir(),A2=or(),x2=fu(),I2=Gm(),R2=Km(),P2=Wm(),hu=uC(),dC=xs();ae.Composer=w2.Composer;ae.Document=v2.Document;ae.Schema=b2.Schema;ae.YAMLError=Jm.YAMLError;ae.YAMLParseError=Jm.YAMLParseError;ae.YAMLWarning=Jm.YAMLWarning;ae.Alias=_2.Alias;ae.isAlias=ar.isAlias;ae.isCollection=ar.isCollection;ae.isDocument=ar.isDocument;ae.isMap=ar.isMap;ae.isNode=ar.isNode;ae.isPair=ar.isPair;ae.isScalar=ar.isScalar;ae.isSeq=ar.isSeq;ae.Pair=k2.Pair;ae.Scalar=S2.Scalar;ae.YAMLMap=C2.YAMLMap;ae.YAMLSeq=A2.YAMLSeq;ae.CST=x2;ae.Lexer=I2.Lexer;ae.LineCounter=R2.LineCounter;ae.Parser=P2.Parser;ae.parse=hu.parse;ae.parseAllDocuments=hu.parseAllDocuments;ae.parseDocument=hu.parseDocument;ae.stringify=hu.stringify;ae.visit=dC.visit;ae.visitAsync=dC.visitAsync});var Kd=N((yre,IP)=>{var E5=qr("node:tty"),D5=E5?.WriteStream?.prototype?.hasColors?.()??!1,ee=(e,t)=>{if(!D5)return i=>i;let n=`\x1B[${e}m`,r=`\x1B[${t}m`;return i=>{let o=i+"",s=o.indexOf(r);if(s===-1)return n+o+r;let a=n,l=0,u=(t===22?r:"")+n;for(;s!==-1;)a+=o.slice(l,s)+u,l=s+r.length,s=o.indexOf(r,l);return a+=o.slice(l)+r,a}},X={};X.reset=ee(0,0);X.bold=ee(1,22);X.dim=ee(2,22);X.italic=ee(3,23);X.underline=ee(4,24);X.overline=ee(53,55);X.inverse=ee(7,27);X.hidden=ee(8,28);X.strikethrough=ee(9,29);X.black=ee(30,39);X.red=ee(31,39);X.green=ee(32,39);X.yellow=ee(33,39);X.blue=ee(34,39);X.magenta=ee(35,39);X.cyan=ee(36,39);X.white=ee(37,39);X.gray=ee(90,39);X.bgBlack=ee(40,49);X.bgRed=ee(41,49);X.bgGreen=ee(42,49);X.bgYellow=ee(43,49);X.bgBlue=ee(44,49);X.bgMagenta=ee(45,49);X.bgCyan=ee(46,49);X.bgWhite=ee(47,49);X.bgGray=ee(100,49);X.redBright=ee(91,39);X.greenBright=ee(92,39);X.yellowBright=ee(93,39);X.blueBright=ee(94,39);X.magentaBright=ee(95,39);X.cyanBright=ee(96,39);X.whiteBright=ee(97,39);X.bgRedBright=ee(101,49);X.bgGreenBright=ee(102,49);X.bgYellowBright=ee(103,49);X.bgBlueBright=ee(104,49);X.bgMagentaBright=ee(105,49);X.bgCyanBright=ee(106,49);X.bgWhiteBright=ee(107,49);IP.exports=X});var LP=N((Bre,$P)=>{"use strict";$P.exports=M5;function N5(e){let t={defaultWidth:0,output:process.stdout,tty:qr("tty")};return e?(Object.keys(t).forEach(function(n){e[n]||(e[n]=t[n])}),e):t}function M5(e){let t=N5(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let n=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(n)&&n!==0)return n}return t.defaultWidth}});var FP=N((Nre,OP)=>{"use strict";OP.exports=({onlyFirst:e=!1}={})=>{let t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}});var My=N((Mre,BP)=>{"use strict";var j5=FP();BP.exports=e=>typeof e=="string"?e.replace(j5(),""):e});var MP=N((jre,jy)=>{"use strict";var NP=e=>Number.isNaN(e)?!1:e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141);jy.exports=NP;jy.exports.default=NP});var UP=N((Ure,jP)=>{"use strict";jP.exports=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}});var VP=N((qre,Uy)=>{"use strict";var U5=My(),q5=MP(),V5=UP(),qP=e=>{if(typeof e!="string"||e.length===0||(e=U5(e),e.length===0))return 0;e=e.replace(V5()," ");let t=0;for(let n=0;n<e.length;n++){let r=e.codePointAt(n);r<=31||r>=127&&r<=159||r>=768&&r<=879||(r>65535&&n++,t+=q5(r)?2:1)}return t};Uy.exports=qP;Uy.exports.default=qP});var zP=N((Vre,GP)=>{"use strict";GP.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var qy=N((Gre,HP)=>{var ml=zP(),KP={};for(let e of Object.keys(ml))KP[ml[e]]=e;var G={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};HP.exports=G;for(let e of Object.keys(G)){if(!("channels"in G[e]))throw new Error("missing channels property: "+e);if(!("labels"in G[e]))throw new Error("missing channel labels property: "+e);if(G[e].labels.length!==G[e].channels)throw new Error("channel and label counts mismatch: "+e);let{channels:t,labels:n}=G[e];delete G[e].channels,delete G[e].labels,Object.defineProperty(G[e],"channels",{value:t}),Object.defineProperty(G[e],"labels",{value:n})}G.rgb.hsl=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),o=Math.max(t,n,r),s=o-i,a,l;o===i?a=0:t===o?a=(n-r)/s:n===o?a=2+(r-t)/s:r===o&&(a=4+(t-n)/s),a=Math.min(a*60,360),a<0&&(a+=360);let c=(i+o)/2;return o===i?l=0:c<=.5?l=s/(o+i):l=s/(2-o-i),[a,l*100,c*100]};G.rgb.hsv=function(e){let t,n,r,i,o,s=e[0]/255,a=e[1]/255,l=e[2]/255,c=Math.max(s,a,l),u=c-Math.min(s,a,l),d=function(p){return(c-p)/6/u+1/2};return u===0?(i=0,o=0):(o=u/c,t=d(s),n=d(a),r=d(l),s===c?i=r-n:a===c?i=1/3+t-r:l===c&&(i=2/3+n-t),i<0?i+=1:i>1&&(i-=1)),[i*360,o*100,c*100]};G.rgb.hwb=function(e){let t=e[0],n=e[1],r=e[2],i=G.rgb.hsl(e)[0],o=1/255*Math.min(t,Math.min(n,r));return r=1-1/255*Math.max(t,Math.max(n,r)),[i,o*100,r*100]};G.rgb.cmyk=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(1-t,1-n,1-r),o=(1-t-i)/(1-i)||0,s=(1-n-i)/(1-i)||0,a=(1-r-i)/(1-i)||0;return[o*100,s*100,a*100,i*100]};function G5(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}G.rgb.keyword=function(e){let t=KP[e];if(t)return t;let n=1/0,r;for(let i of Object.keys(ml)){let o=ml[i],s=G5(e,o);s<n&&(n=s,r=i)}return r};G.keyword.rgb=function(e){return ml[e]};G.rgb.xyz=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let i=t*.4124+n*.3576+r*.1805,o=t*.2126+n*.7152+r*.0722,s=t*.0193+n*.1192+r*.9505;return[i*100,o*100,s*100]};G.rgb.lab=function(e){let t=G.rgb.xyz(e),n=t[0],r=t[1],i=t[2];n/=95.047,r/=100,i/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;let o=116*r-16,s=500*(n-r),a=200*(r-i);return[o,s,a]};G.hsl.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i,o,s;if(n===0)return s=r*255,[s,s,s];r<.5?i=r*(1+n):i=r+n-r*n;let a=2*r-i,l=[0,0,0];for(let c=0;c<3;c++)o=t+1/3*-(c-1),o<0&&o++,o>1&&o--,6*o<1?s=a+(i-a)*6*o:2*o<1?s=i:3*o<2?s=a+(i-a)*(2/3-o)*6:s=a,l[c]=s*255;return l};G.hsl.hsv=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=n,o=Math.max(r,.01);r*=2,n*=r<=1?r:2-r,i*=o<=1?o:2-o;let s=(r+n)/2,a=r===0?2*i/(o+i):2*n/(r+n);return[t,a*100,s*100]};G.hsv.rgb=function(e){let t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,o=t-Math.floor(t),s=255*r*(1-n),a=255*r*(1-n*o),l=255*r*(1-n*(1-o));switch(r*=255,i){case 0:return[r,l,s];case 1:return[a,r,s];case 2:return[s,r,l];case 3:return[s,a,r];case 4:return[l,s,r];case 5:return[r,s,a]}};G.hsv.hsl=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=Math.max(r,.01),o,s;s=(2-n)*r;let a=(2-n)*i;return o=n*i,o/=a<=1?a:2-a,o=o||0,s/=2,[t,o*100,s*100]};G.hwb.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i=n+r,o;i>1&&(n/=i,r/=i);let s=Math.floor(6*t),a=1-r;o=6*t-s,(s&1)!==0&&(o=1-o);let l=n+o*(a-n),c,u,d;switch(s){default:case 6:case 0:c=a,u=l,d=n;break;case 1:c=l,u=a,d=n;break;case 2:c=n,u=a,d=l;break;case 3:c=n,u=l,d=a;break;case 4:c=l,u=n,d=a;break;case 5:c=a,u=n,d=l;break}return[c*255,u*255,d*255]};G.cmyk.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100,o=1-Math.min(1,t*(1-i)+i),s=1-Math.min(1,n*(1-i)+i),a=1-Math.min(1,r*(1-i)+i);return[o*255,s*255,a*255]};G.xyz.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i,o,s;return i=t*3.2406+n*-1.5372+r*-.4986,o=t*-.9689+n*1.8758+r*.0415,s=t*.0557+n*-.204+r*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,i=Math.min(Math.max(0,i),1),o=Math.min(Math.max(0,o),1),s=Math.min(Math.max(0,s),1),[i*255,o*255,s*255]};G.xyz.lab=function(e){let t=e[0],n=e[1],r=e[2];t/=95.047,n/=100,r/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,o=500*(t-n),s=200*(n-r);return[i,o,s]};G.lab.xyz=function(e){let t=e[0],n=e[1],r=e[2],i,o,s;o=(t+16)/116,i=n/500+o,s=o-r/200;let a=o**3,l=i**3,c=s**3;return o=a>.008856?a:(o-16/116)/7.787,i=l>.008856?l:(i-16/116)/7.787,s=c>.008856?c:(s-16/116)/7.787,i*=95.047,o*=100,s*=108.883,[i,o,s]};G.lab.lch=function(e){let t=e[0],n=e[1],r=e[2],i;i=Math.atan2(r,n)*360/2/Math.PI,i<0&&(i+=360);let s=Math.sqrt(n*n+r*r);return[t,s,i]};G.lch.lab=function(e){let t=e[0],n=e[1],i=e[2]/360*2*Math.PI,o=n*Math.cos(i),s=n*Math.sin(i);return[t,o,s]};G.rgb.ansi16=function(e,t=null){let[n,r,i]=e,o=t===null?G.rgb.hsv(e)[2]:t;if(o=Math.round(o/50),o===0)return 30;let s=30+(Math.round(i/255)<<2|Math.round(r/255)<<1|Math.round(n/255));return o===2&&(s+=60),s};G.hsv.ansi16=function(e){return G.rgb.ansi16(G.hsv.rgb(e),e[2])};G.rgb.ansi256=function(e){let t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)};G.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let n=(~~(e>50)+1)*.5,r=(t&1)*n*255,i=(t>>1&1)*n*255,o=(t>>2&1)*n*255;return[r,i,o]};G.ansi256.rgb=function(e){if(e>=232){let o=(e-232)*10+8;return[o,o,o]}e-=16;let t,n=Math.floor(e/36)/5*255,r=Math.floor((t=e%36)/6)/5*255,i=t%6/5*255;return[n,r,i]};G.rgb.hex=function(e){let n=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return"000000".substring(n.length)+n};G.hex.rgb=function(e){let t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let n=t[0];t[0].length===3&&(n=n.split("").map(a=>a+a).join(""));let r=parseInt(n,16),i=r>>16&255,o=r>>8&255,s=r&255;return[i,o,s]};G.rgb.hcg=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.max(Math.max(t,n),r),o=Math.min(Math.min(t,n),r),s=i-o,a,l;return s<1?a=o/(1-s):a=0,s<=0?l=0:i===t?l=(n-r)/s%6:i===n?l=2+(r-t)/s:l=4+(t-n)/s,l/=6,l%=1,[l*360,s*100,a*100]};G.hsl.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=n<.5?2*t*n:2*t*(1-n),i=0;return r<1&&(i=(n-.5*r)/(1-r)),[e[0],r*100,i*100]};G.hsv.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]};G.hcg.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100;if(n===0)return[r*255,r*255,r*255];let i=[0,0,0],o=t%1*6,s=o%1,a=1-s,l=0;switch(Math.floor(o)){case 0:i[0]=1,i[1]=s,i[2]=0;break;case 1:i[0]=a,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=s;break;case 3:i[0]=0,i[1]=a,i[2]=1;break;case 4:i[0]=s,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=a}return l=(1-n)*r,[(n*i[0]+l)*255,(n*i[1]+l)*255,(n*i[2]+l)*255]};G.hcg.hsv=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t),i=0;return r>0&&(i=t/r),[e[0],i*100,r*100]};G.hcg.hsl=function(e){let t=e[1]/100,r=e[2]/100*(1-t)+.5*t,i=0;return r>0&&r<.5?i=t/(2*r):r>=.5&&r<1&&(i=t/(2*(1-r))),[e[0],i*100,r*100]};G.hcg.hwb=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t);return[e[0],(r-t)*100,(1-r)*100]};G.hwb.hcg=function(e){let t=e[1]/100,r=1-e[2]/100,i=r-t,o=0;return i<1&&(o=(r-i)/(1-i)),[e[0],i*100,o*100]};G.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]};G.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]};G.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]};G.gray.hsl=function(e){return[0,0,e[0]]};G.gray.hsv=G.gray.hsl;G.gray.hwb=function(e){return[0,100,e[0]]};G.gray.cmyk=function(e){return[0,0,0,e[0]]};G.gray.lab=function(e){return[e[0],0,0]};G.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,r=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(r.length)+r};G.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}});var JP=N((zre,WP)=>{var Hd=qy();function z5(){let e={},t=Object.keys(Hd);for(let n=t.length,r=0;r<n;r++)e[t[r]]={distance:-1,parent:null};return e}function K5(e){let t=z5(),n=[e];for(t[e].distance=0;n.length;){let r=n.pop(),i=Object.keys(Hd[r]);for(let o=i.length,s=0;s<o;s++){let a=i[s],l=t[a];l.distance===-1&&(l.distance=t[r].distance+1,l.parent=r,n.unshift(a))}}return t}function H5(e,t){return function(n){return t(e(n))}}function W5(e,t){let n=[t[e].parent,e],r=Hd[t[e].parent][e],i=t[e].parent;for(;t[i].parent;)n.unshift(t[i].parent),r=H5(Hd[t[i].parent][i],r),i=t[i].parent;return r.conversion=n,r}WP.exports=function(e){let t=K5(e),n={},r=Object.keys(t);for(let i=r.length,o=0;o<i;o++){let s=r[o];t[s].parent!==null&&(n[s]=W5(s,t))}return n}});var ZP=N((Kre,YP)=>{var Vy=qy(),J5=JP(),Qo={},Y5=Object.keys(Vy);function Z5(e){let t=function(...n){let r=n[0];return r==null?r:(r.length>1&&(n=r),e(n))};return"conversion"in e&&(t.conversion=e.conversion),t}function X5(e){let t=function(...n){let r=n[0];if(r==null)return r;r.length>1&&(n=r);let i=e(n);if(typeof i=="object")for(let o=i.length,s=0;s<o;s++)i[s]=Math.round(i[s]);return i};return"conversion"in e&&(t.conversion=e.conversion),t}Y5.forEach(e=>{Qo[e]={},Object.defineProperty(Qo[e],"channels",{value:Vy[e].channels}),Object.defineProperty(Qo[e],"labels",{value:Vy[e].labels});let t=J5(e);Object.keys(t).forEach(r=>{let i=t[r];Qo[e][r]=X5(i),Qo[e][r].raw=Z5(i)})});YP.exports=Qo});var rE=N((Hre,nE)=>{"use strict";var XP=(e,t)=>(...n)=>`\x1B[${e(...n)+t}m`,QP=(e,t)=>(...n)=>{let r=e(...n);return`\x1B[${38+t};5;${r}m`},eE=(e,t)=>(...n)=>{let r=e(...n);return`\x1B[${38+t};2;${r[0]};${r[1]};${r[2]}m`},Wd=e=>e,tE=(e,t,n)=>[e,t,n],es=(e,t,n)=>{Object.defineProperty(e,t,{get:()=>{let r=n();return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},Gy,ts=(e,t,n,r)=>{Gy===void 0&&(Gy=ZP());let i=r?10:0,o={};for(let[s,a]of Object.entries(Gy)){let l=s==="ansi16"?"ansi":s;s===t?o[l]=e(n,i):typeof a=="object"&&(o[l]=e(a[t],i))}return o};function Q5(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[i,o]of Object.entries(r))t[i]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},r[i]=t[i],e.set(o[0],o[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1B[39m",t.bgColor.close="\x1B[49m",es(t.color,"ansi",()=>ts(XP,"ansi16",Wd,!1)),es(t.color,"ansi256",()=>ts(QP,"ansi256",Wd,!1)),es(t.color,"ansi16m",()=>ts(eE,"rgb",tE,!1)),es(t.bgColor,"ansi",()=>ts(XP,"ansi16",Wd,!0)),es(t.bgColor,"ansi256",()=>ts(QP,"ansi256",Wd,!0)),es(t.bgColor,"ansi16m",()=>ts(eE,"rgb",tE,!0)),t}Object.defineProperty(nE,"exports",{enumerable:!0,get:Q5})});var sE=N((Wre,oE)=>{"use strict";var gl=VP(),eK=My(),tK=rE(),Ky=new Set(["\x1B","\x9B"]),nK=39,iE=e=>`${Ky.values().next().value}[${e}m`,rK=e=>e.split(" ").map(t=>gl(t)),zy=(e,t,n)=>{let r=[...t],i=!1,o=gl(eK(e[e.length-1]));for(let[s,a]of r.entries()){let l=gl(a);if(o+l<=n?e[e.length-1]+=a:(e.push(a),o=0),Ky.has(a))i=!0;else if(i&&a==="m"){i=!1;continue}i||(o+=l,o===n&&s<r.length-1&&(e.push(""),o=0))}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},iK=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(gl(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},oK=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i="",o,s=rK(e),a=[""];for(let[l,c]of e.split(" ").entries()){n.trim!==!1&&(a[a.length-1]=a[a.length-1].trimLeft());let u=gl(a[a.length-1]);if(l!==0&&(u>=t&&(n.wordWrap===!1||n.trim===!1)&&(a.push(""),u=0),(u>0||n.trim===!1)&&(a[a.length-1]+=" ",u++)),n.hard&&s[l]>t){let d=t-u,p=1+Math.floor((s[l]-d-1)/t);Math.floor((s[l]-1)/t)<p&&a.push(""),zy(a,c,t);continue}if(u+s[l]>t&&u>0&&s[l]>0){if(n.wordWrap===!1&&u<t){zy(a,c,t);continue}a.push("")}if(u+s[l]>t&&n.wordWrap===!1){zy(a,c,t);continue}a[a.length-1]+=c}n.trim!==!1&&(a=a.map(iK)),r=a.join(`
|
|
142
|
+
`);for(let[l,c]of[...r].entries()){if(i+=c,Ky.has(c)){let d=parseFloat(/\d[^m]*/.exec(r.slice(l,l+4)));o=d===nK?null:d}let u=tK.codes.get(Number(o));o&&u&&(r[l+1]===`
|
|
143
|
+
`?i+=iE(u):c===`
|
|
144
|
+
`&&(i+=iE(o)))}return i};oE.exports=(e,t,n)=>String(e).normalize().replace(/\r\n/g,`
|
|
145
|
+
`).split(`
|
|
146
|
+
`).map(r=>oK(r,t,n)).join(`
|
|
147
|
+
`)});var uE=N((eie,cE)=>{var aK=qr("stream"),Wy=class extends aK{#e=null;constructor(t={}){super(t),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=t.replace,this._prompt=t.prompt||null,this._hadControl=!1}#t(t,n){return this._dest?this._dest[t]:this._src?this._src[t]:n}#n(t,...n){typeof this._dest?.[t]=="function"&&this._dest[t](...n),typeof this._src?.[t]=="function"&&this._src[t](...n)}get isTTY(){return this.#e!==null?this.#e:this.#t("isTTY",!1)}set isTTY(t){this.#e=t}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(t){this._src=t}pipe(t,n){return this._dest=t,super.pipe(t,n)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(t){if(this.muted){if(!this.replace)return!0;if(t.match(/^\u001b/))return t.indexOf(this._prompt)===0&&(t=t.slice(this._prompt.length),t=t.replace(/./g,this.replace),t=this._prompt+t),this._hadControl=!0,this.emit("data",t);this._prompt&&this._hadControl&&t.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit("data",this._prompt),t=t.slice(this._prompt.length)),t=t.toString().replace(/./g,this.replace)}this.emit("data",t)}end(t){this.muted&&(t&&this.replace?t=t.toString().replace(/./g,this.replace):t=null),t&&this.emit("data",t),this.emit("end")}destroy(...t){return this.#n("destroy",...t)}destroySoon(...t){return this.#n("destroySoon",...t)}close(...t){return this.#n("close",...t)}};cE.exports=Wy});import{timingSafeEqual as l1}from"node:crypto";import{createHash as zT,timingSafeEqual as KT}from"node:crypto";function Oe(e){return`sha256:${zT("sha256").update(e).digest("hex")}`}function zr(e){return Array.isArray(e)?`[${e.map(zr).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${zr(n)}`).join(",")}}`:JSON.stringify(e)}function ec(e,t){return e.length===t.length&&KT(Buffer.from(e),Buffer.from(t))}var tc=class extends Error{issues;constructor(t){super(`Canonical bundle rejected: ${[...new Set(t.map(n=>n.code))].join(", ")}`),this.name="CanonicalBundleRejection",this.issues=HT(t)}};function HT(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):[]}var vJ=Object.freeze({error:"The source bundle contains content that must be corrected.",nextStep:"Review the listed files, remove personal data or secrets, and retry the source install."});import{createHash as Pb}from"node:crypto";function re(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(!WT(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 WT(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 Je(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")&&JT(n,new TextEncoder().encode(s)))return{content:s}}catch{}return{contentBase64:Buffer.from(n).toString("base64"),...r?{mediaType:r}:i?{mediaType:"application/pdf"}:{}}}function Ki(e){return re(e).byteLength}function Wn(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 Sb(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 JT(e,t){return e.byteLength===t.byteLength&&e.every((n,r)=>n===t[r])}var we={maxFiles:100,maxDepth:12,maxPathBytes:240,maxFileBytes:512*1024,maxRasterBytes:10*1024*1024,maxPdfBytes:20*1024*1024,maxTotalBytes:2*1024*1024},YT=[".skills-layer-install.json",".skills-layer-manifest.json",".skills-layer-quarantine","skills-lock.json"],ZT=new Set(YT),XT=new Set([".git",".hg",".next",".svn",".turbo","build","coverage","dist","node_modules"]),QT=/^(?:aux|com[1-9]|con|lpt[1-9]|nul|prn)(?:\.|$)/iu,Cb=/\b(?<local>[A-Z0-9._%+-]+)@(?<domain>[A-Z0-9.-]+\.[A-Z]{2,})\b/giu,e$=new Set(["example.com","example.net","example.org"]),t$=new Set(["abuse","admin","announce","contact","dev","help","hostmaster","info","noc","postmaster","security","support","users","webmaster"]),Ab=/(?:^|[^\p{L}\p{N}_])(?<phone>\+?[1-9]\d(?:[ \t().-]*\d){8,14})(?=$|[^\p{L}\p{N}_])/gu,xb=/\b(?:api[_-]?key|client[_-]?secret|password|private[_-]?token|secret|token)\s*[:=]\s*["']?(?<value>[A-Za-z0-9_./+=-]{20,})/giu,n$=[{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 ln(e){let t=r$(e.limits),n=[],r=[],i=e.skillsIgnore??e.files.find(m=>m.path===".skillsignore")?.content??"",o=Db(i),s=[],a=new Map;for(let m of e.files){if(typeof m?.path!="string"||typeof m.content!="string"&&typeof m.contentBase64!="string"||m.executable!==void 0&&typeof m.executable!="boolean"){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 g;try{g=re(m)}catch{n.push({severity:"error",code:"file_invalid",path:m.path,message:"Bundle entries must contain exactly one text or canonical-base64 byte payload."});continue}let h=m.path,y=ks(h);if(!y.ok){n.push({severity:"error",code:y.code,path:h,message:y.message});continue}let w=y.path,b=Eb(w);if(b){r.push({path:w,reason:b});continue}if(o(w)){r.push({path:w,reason:"skillsignore"});continue}let _=w.normalize("NFC").toLocaleLowerCase("en-US"),I=a.get(_);if(I){n.push({severity:"error",code:"path_collision",path:h,message:`Bundle path collides with ${I} after portable normalization.`});continue}a.set(_,w),s.push({path:w,file:m,bytes:g,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 m of s){let g=Buffer.byteLength(m.path,"utf8"),h=m.path.split("/").length,y=m.bytes.byteLength;if(l+=y,h>t.maxDepth&&n.push({severity:"error",code:"path_depth_exceeded",path:m.originalPath,message:"Bundle path exceeds the depth limit."}),g>t.maxPathBytes&&n.push({severity:"error",code:"path_too_long",path:m.originalPath,message:"Bundle path exceeds the byte limit."}),e.contentPolicy!=="paths_only"){let w=$b(m.path,t);y>w&&n.push({severity:"error",code:"file_too_large",path:m.originalPath,message:"Bundle file exceeds the byte limit."}),s$(m,n),e.runDlp!==!1&&typeof m.file.content=="string"&&m$(m.originalPath,m.file.content,n)}Lb("",m.path)&&n.push({severity:"error",code:"pii_path",path:m.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:m,file:g,bytes:h})=>({path:m,...g.executable===!0?{executable:!0}:{},...Kf(m)===".pdf"?Je(h,"application/pdf"):{...typeof g.content=="string"?{content:g.content}:{},...typeof g.contentBase64=="string"?{contentBase64:g.contentBase64}:{},...typeof g.mediaType=="string"?{mediaType:g.mediaType}:{}}})).sort((m,g)=>m.path.localeCompare(g.path)),u=c.map(m=>({path:m.path,bytes:re(m).byteLength,sha256:M$(re(m))})),d={fileCount:c.length,totalBytes:l,files:u,bundleSha256:j$(c)},p=e.waivePersonalData?n.filter(m=>!p$.has(m.code)):n;return{ok:p.length===0,files:c,excluded:r.sort((m,g)=>m.path.localeCompare(g.path)),issues:p,preview:d}}function Jn(e){let t=ln(e);if(!t.ok)throw new tc(t.issues.map(n=>({path:n.path??"SKILL.md",code:n.code})));return t}function Gf(e=""){let t=Db(e);return n=>{let r=ks(n);return r.ok?Eb(r.path)??(t(r.path)?"skillsignore":null):null}}function r$(e){let t={...we,...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 ks(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)||QT.test(r))return{ok:!1,code:"path_invalid",message:"Bundle path contains a reserved platform segment."};return ZT.has(t.toLocaleLowerCase("en-US"))?{ok:!1,code:"reserved_path",message:"Bundle path is reserved for Skills Layer state."}:{ok:!0,path:t}}function zf(e,t){return $b(e,t)}function Eb(e){if(e===".skillsignore")return"control_file";let t=e.split("/");if(t.some(i=>XT.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 Db(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 Tb=new Map([[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"]]),i$=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"]),o$=new Map([[".webp","image/webp"],[".wav","audio/wav"],[".ttf","font/ttf"],[".otf","font/otf"]]);function $b(e,t){let n=Kf(e);return Tb.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 s$(e,t){let n=Kf(e.path),r=e.file.mediaType?.trim().toLowerCase(),i=e.path.toLowerCase().endsWith(".tar.gz")?"application/gzip":o$.get(n);if(i){if(r&&r!==i){Ee(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&&an(s,0,4)==="RIFF"&&an(s,8,4)==="WEBP"&&Rb(s,4)===s.length-8:n===".wav"?s.length>=12&&an(s,0,4)==="RIFF"&&an(s,8,4)==="WAVE"&&Rb(s,4)===s.length-8:n===".ttf"?s.length>=12&&nc(s,0)===65536:s.length>=12&&an(s,0,4)==="OTTO")||Ee(t,"binary_transport_signature_invalid",e,"Binary signature is not valid for the requested inspection profile.");return}let o=Tb.get(n);if(o){if(r&&r!==o){Ee(t,"media_type_mismatch",e,"Raster media type does not match its approved extension.");return}a$(e,o,t);return}if(n===".pdf"){if(r&&r!=="application/pdf"){Ee(t,"media_type_mismatch",e,"PDF media type does not match its extension.");return}c$(e,t);return}if(n===".svg"){r&&r!=="image/svg+xml"&&r!=="text/plain"&&Ee(t,"media_type_mismatch",e,"SVG media type is invalid."),Ib(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)&&Ee(t,"svg_active_content",e,"SVG contains active or externally loaded content.");return}if(f$(e.bytes)||e.file.contentBase64&&!i$.has(n)){Ee(t,"unsupported_binary_type",e,"Archive, executable, or unknown binary content is not eligible for automatic publication.");return}Ib(e,t)}function Ib(e,t){if(e.file.content?.includes("\0")){Ee(t,"binary_content",e,"Bundle file is not bounded UTF-8 text.");return}try{new TextDecoder("utf-8",{fatal:!0}).decode(e.bytes)}catch{Ee(t,"invalid_utf8",e,"Text bundle file is not valid UTF-8.")}}function a$(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)||an(r,12,4)!=="IHDR"){Ee(n,"raster_malformed",e,"PNG header is malformed or truncated.");return}if(i=nc(r,16),o=nc(r,20),!l$(r)){Ee(n,"raster_malformed",e,"PNG chunk structure is malformed or truncated.");return}(Hi(r,"eXIf")||Hi(r,"tEXt")||Hi(r,"zTXt")||Hi(r,"iTXt"))&&Ee(n,"sensitive_image_metadata",e,"Raster metadata requires manual review.")}else if(t==="image/gif"){if(r.length<14||an(r,0,6)!=="GIF87a"&&an(r,0,6)!=="GIF89a"||r.at(-1)!==59){Ee(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=u$(r);if(!a){Ee(n,"raster_malformed",e,"JPEG is malformed or truncated.");return}({width:i,height:o}=a),d$(r)&&Ee(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)&&Ee(n,"raster_decompression_risk",e,"Raster dimensions or compression ratio exceed the safe policy.")}function l$(e){let t=8,n=0,r=!1;for(;t+12<=e.length;){let i=nc(e,t),o=an(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 c$(e,t){let n=e.bytes;if(n.length<12||an(n,0,5)!=="%PDF-"||!Hi(n.subarray(Math.max(0,n.length-1024)),"%%EOF")){Ee(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)&&Ee(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)&&Ee(t,"pdf_structure_limit_exceeded",e,"PDF page or object count exceeds the safe policy.")}function u$(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 d$(e){return Hi(e,"Exif\0\0")}function f$(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 Ee(e,t,n,r){e.push({severity:"error",code:t,path:n.originalPath,message:r})}function Kf(e){let t=e.split("/").at(-1).toLowerCase(),n=t.lastIndexOf(".");return n<=0?"":t.slice(n)}function Rb(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!0)}function an(e,t,n){return new TextDecoder("latin1").decode(e.subarray(t,t+n))}function Hi(e,t){return new TextDecoder("latin1").decode(e).includes(t)}function nc(e,t){return e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3]>>>0}var p$=new Set(["pii_email","pii_phone","pii_path"]);function m$(e,t,n){for(let r of n$)r.pattern.test(t)&&n.push({severity:"error",code:r.code,path:e,message:"Bundle content matched a protected-data rule."});g$(t)&&n.push({severity:"error",code:"secret_assignment",path:e,message:"Bundle content matched a protected-data rule."}),Lb(e,t)&&n.push({severity:"error",code:"pii_email",path:e,message:"Bundle content contains an email address."}),_$(e,t)&&n.push({severity:"error",code:"pii_phone",path:e,message:"Bundle content contains a phone number."})}function g$(e){xb.lastIndex=0;for(let t of e.matchAll(xb)){let n=t.groups.value;if(/^(?:process|import\.meta)\.env\.[A-Za-z_][A-Za-z0-9_]*$/u.test(n)||y$(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 Lb(e,t){Cb.lastIndex=0;for(let n of t.matchAll(Cb)){let r=n.groups.local.toLowerCase(),i=n.groups.domain.toLowerCase(),o=t.lastIndexOf(`
|
|
148
|
+
`,n.index-1)+1,s=t.indexOf(`
|
|
149
|
+
`,n.index),a=t.slice(o,s<0?t.length:s);if(!(e$.has(i)||t$.has(r)||w$(r,i)||v$(t,n.index,n[0].length,r)||h$(e,t,a,o)||b$(r,i,a)))return!0}return!1}function h$(e,t,n,r){if(!/(?:^|\/)(?:[^/]*[-_])?OFL\.txt$/iu.test(e)||r>=2048||t.slice(0,r).split(`
|
|
150
|
+
`).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 y$(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 w$(e,t){return t==="users.noreply.github.com"||/^(?:noreply|no-reply|web-flow)$/u.test(e)}function v$(e,t,n,r){return r!=="git"?!1:/^:[^\s`'"]+\.git\b/iu.test(e.slice(t+n))}function b$(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 _$(e,t){Ab.lastIndex=0;for(let n of t.matchAll(Ab)){let r=n.groups.phone,i=n[0].indexOf(r),o=n.index+i;if(k$(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(`
|
|
151
|
+
`,o-1)+1,d=t.indexOf(`
|
|
152
|
+
`,o),p=t.slice(u,d<0?t.length:d),m=t.slice(u,o),g=/(?:^|[^\p{L}\p{N}_-])X-RateLimit-Reset\s*:\s*$/iu.test(m),h=N$(t,o),y=S$(e,p,r,o-u),w=/^\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))&&!w&&!g&&!h&&!y)return!0}return!1}function k$(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(!Fb(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 S$(e,t,n,r){let i=r+n.length;return C$(n)||P$(t,n,r)||E$(t,r,i)||D$(t,r,i)||T$(t,n,r,i)||$$(t,r,i)||L$(e,t,n,r)||Se(t,r,i,/(?<![\d.])\d+\.\d+(?![\d.])/gu)||Se(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:A$(t,r,i)||x$(t,r,i)||I$(t,r,i)||R$(t,n,r,i)||O$(t,r,i)||Fb(n)||F$(t,r,i)||Se(t,r,i,/\bhresult\s+-eq\s+-?\d+\b/giu)||Se(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)||Se(t,r,i,/\bprs?\s+(?:\d+\s+){2,}\d+\b/giu)||Se(t,r,i,/\bv?\d+(?:\.\d+)*\s+\d{4}\.\d{2}\.\d{2}\s+\d{2}:\d{2}\b/giu)||Se(t,r,i,/\brun\s+`\d{9,15}`(?=[^\r\n]{0,100}\btook\b[^\r\n]{0,30}\bminutes?\b)/giu)||Se(t,r,i,/\d+\s+的\s+\d+\s+号评论/gu)||/\b(?:returnCode|unique\s+(?:code|identifier)|唯一编码)\b/iu.test(t)&&Se(t,r,i,/\b[A-Za-z][A-Za-z0-9_]*(?:_[A-Za-z0-9]+)+\/\d{9,15}\b/gu)||Se(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:B$(e,t,r,i)}function C$(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 A$(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 x$(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"||!Ob(i.timestamp))continue;let o=t-r.index;if(Se(r[0],o,n-r.index,/"timestamp"\s*:\s*(?:\d{10}|\d{13})(?=\s*[,}])/gu))return!0}catch{}return!1}function I$(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&&Ob(Number(i.groups.epoch)))return!0;return!1}function Ob(e){let t=e>=1e12?e/1e3:e;return t>=946684800&&t<=4102444800}function R$(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)||Se(e,n,r,/(?:\b(?:chromium|codex|mac|macos|release|runtime|versions?|win|windows)\b|版本(?:号)?)\s*[:=`'"(\[]*\s*\d+(?:\.\d+){1,}(?:[-~]\d+(?:\.\d+){1,})?/giu)?!0:Se(e,n,r,/["']?version["']?\s*[:=]\s*["']?\d+(?:\.\d+){1,}(?:[-~]\d+(?:\.\d+){1,})?["']?/giu):!1}function P$(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 E$(e,t,n){return Se(e,t,n,/https?:\/\/[^\s<>"']+/giu)}function D$(e,t,n){return Se(e,t,n,/\barXiv\s*:\s*\d{4}\.\d{4,5}(?:\s*\(\d{4}-\d{2}\))?/giu)||Se(e,t,n,/\b10\.\d{4,9}\/[A-Z0-9][A-Z0-9._()/:+-]*/giu)||Se(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)&&Se(e,t,n,/\b\d{4}[.-]\d{1,2}\s*[-–—~]\s*\d{4}[.-]\d{1,2}\b/gu)}function T$(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:Se(e,n,r,/\b(?:application[_ -]?number|patent(?:[_ -]?number)?)\b[^;\r\n]{0,80}?(?:CN)?\d{9,15}(?:\.\d)?(?:[A-Z]\d?)?/giu)||Se(e,n,r,/申请号[^;;\r\n]{0,160}/gu)}function $$(e,t,n){return Se(e,t,n,/@id\s*=\s*\d{9,15}/giu)}function L$(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 O$(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 Fb(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 F$(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 Se(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 B$(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 N$(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 M$(e){return`sha256:${Pb("sha256").update(e).digest("hex")}`}function j$(e){let t=Pb("sha256");return e.forEach((n,r)=>{t.update(n.path),t.update("\0"),t.update(re(n)),n.executable===!0&&t.update("\0executable-v1"),r<e.length-1&&t.update("\0")}),`sha256:${t.digest("hex")}`}import{createHash as U$}from"node:crypto";var q$=new Set(["evals","tests","test","fixtures","golden","goldens","snapshots","__snapshots__",".github",".circleci","coverage"]),V$=new Set([".gitlab-ci.yml","azure-pipelines.yml"]),G$=[".eval.json",".eval.yaml"],z$=[".golden.",".snapshot."],Bb=".skills-layer/skill.yaml",K$=new Set([".git",".hg",".svn"]),H$=new Set([".cache",".creator-tmp",".skills-layer-tmp",".tmp","node_modules"]),W$=Buffer.from([46,68,83,95,83,116,111,114,101]).toString("ascii"),J$=new Set([W$,"Thumbs.db"]);function zt(e,t){let n=Zf(e),r=Mb(t),i=Hf(n,r),[o]=i.split("/");return i===Bb?{path:n,relativePath:i,root:r,type:"control",reasonCode:"root_control_manifest"}:n.endsWith(`/${Bb}`)?{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&&K$.has(o)?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"excluded_repository_metadata"}:o&&(H$.has(o)||J$.has(o)||o.endsWith("~")||o.endsWith(".swp")||o.endsWith(".tmp"))?{path:n,relativePath:i,root:r,type:"excluded",reasonCode:"excluded_cache_or_temporary"}:o==="examples"?{path:n,relativePath:i,root:r,type:"runtime",reasonCode:"runtime_material"}:o&&q$.has(o)?{path:n,relativePath:i,root:r,type:"evidence",reasonCode:"top_level_evidence_folder"}:Q$(i)?{path:n,relativePath:i,root:r,type:"evidence",reasonCode:"evidence_test_or_spec_file"}:e1(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 rc(e){return e.map(t=>zt(t.path,e))}function Wf(e){return Jf(e,"runtime")}function Y$(e){return Jf(e,"evidence")}function ic(e){return Jf(e,"control")}function Jf(e,t){let n=Mb(e);return e.map(r=>({...r,path:Zf(r.path)})).filter(r=>zt(r.path,e).type===t).sort((r,i)=>t1(r.path,i.path,n))}function Fe(e){return Yf(Wf(e))}function Z$(e){return Yf(Y$(e))}function X$(e){return Yf(ic(e))}function Nb(e){return{runtimeDigest:Fe(e),evidenceDigest:Z$(e),controlDigest:X$(e)}}function Yf(e){let t=U$("sha256");for(let n of e)t.update(n.path),t.update("\0"),t.update(re(n)),n.executable===!0&&t.update("\0executable-v1"),t.update("\0");return`sha256:${t.digest("hex")}`}function Q$(e){let t=e.split("/"),n=t[t.length-1].toLocaleLowerCase("en-US");return/(?:^|\.)(?:test|spec)\.[^.]+$/u.test(n)}function e1(e){return e.includes("/")?!1:V$.has(e)||G$.some(t=>e.endsWith(t))||z$.some(t=>e.includes(t))}function Mb(e){let t=e.map(n=>Zf(n.path)).find(n=>n==="SKILL.md"||n.endsWith("/SKILL.md"));return!t||t==="SKILL.md"?"":t.slice(0,-9)}function Hf(e,t){return t?e===t?"":e.startsWith(`${t}/`)?e.slice(t.length+1):e:e}function t1(e,t,n){let r=Hf(e,n),i=Hf(t,n);return r==="SKILL.md"?i==="SKILL.md"?0:-1:i==="SKILL.md"?1:e.localeCompare(t)}function Zf(e){return e.replaceAll("\\","/").split("/").filter(t=>t.length>0&&t!==".").join("/")}function Wi(e){return rc(e).filter(t=>t.type!=="runtime").map(({path:t,reasonCode:n})=>({path:t,reasonCode:n}))}var n1="user_",jb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,r1=/^user_[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/u;function i1(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(n1)||r.length===0?null:{ownerUserId:n,baseSlug:r}}function Ub(e){if(/\s/u.test(e))return!1;if(jb.test(e))return!0;let t=i1(e);return t!==null&&r1.test(t.ownerUserId)&&jb.test(t.baseSlug)}function Qf(e){let t=new TextEncoder,n=[],r=[],i=0;for(let c of e){let u=t.encode(c.path),d=re(c),p=o1(d),m=new Uint8Array(30+u.length+d.length),g=new DataView(m.buffer);g.setUint32(0,67324752,!0),g.setUint16(4,20,!0),g.setUint16(6,2048,!0),g.setUint16(8,0,!0),g.setUint16(10,0,!0),g.setUint16(12,0,!0),g.setUint32(14,p,!0),g.setUint32(18,d.byteLength,!0),g.setUint32(22,d.byteLength,!0),g.setUint16(26,u.length,!0),g.setUint16(28,0,!0),m.set(u,30),m.set(d,30+u.length),n.push(m);let h=new Uint8Array(46+u.length),y=new DataView(h.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),h.set(u,46),r.push(h),i+=m.byteLength}let o=Xf(r),s=Xf(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),Xf([s,o,a])}function o1(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 Xf(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 oc(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,g=c,h=0,y=0;for(let w=0;w<a;w+=1){if(g+46>r||n.getUint32(g,!0)!==33639248)throw new Error("Artifact v1 ZIP central directory is truncated.");let b=n.getUint16(g+4,!0),_=n.getUint16(g+6,!0),I=n.getUint16(g+8,!0),x=n.getUint16(g+10,!0),C=n.getUint16(g+12,!0),D=n.getUint16(g+14,!0),T=n.getUint32(g+16,!0),j=n.getUint32(g+20,!0),M=n.getUint32(g+24,!0),$=n.getUint16(g+28,!0),B=n.getUint16(g+30,!0),q=n.getUint16(g+32,!0),Y=n.getUint16(g+34,!0),Le=n.getUint16(g+36,!0),Gt=n.getUint32(g+38,!0),He=n.getUint32(g+42,!0),Lv=g+46+$+B+q;if(b!==20||_!==20||I!==2048||x!==0||C!==0||D!==0||j!==M||j===4294967295||$===0||$>t.maxPathBytes||B!==0||q!==0||Y!==0||Le!==0||Gt!==0||He!==h||Lv>r||M>t.maxFileBytes)throw new Error("Artifact v1 ZIP central entry is invalid.");if(y+=M,y>t.maxTotalFileBytes)throw new Error("Artifact v1 ZIP exceeds its total file-byte limit.");let Lf=e.slice(g+46,g+46+$),Gl;try{Gl=d.decode(Lf)}catch{throw new Error("Artifact v1 ZIP path is not valid UTF-8.")}if(m.has(Gl))throw new Error("Artifact v1 ZIP path uniqueness is invalid.");if(m.add(Gl),He+30>c||n.getUint32(He,!0)!==67324752)throw new Error("Artifact v1 ZIP local entry is missing.");let TT=n.getUint16(He+4,!0),$T=n.getUint16(He+6,!0),LT=n.getUint16(He+8,!0),OT=n.getUint16(He+10,!0),FT=n.getUint16(He+12,!0),BT=n.getUint32(He+14,!0),Ov=n.getUint32(He+18,!0),NT=n.getUint32(He+22,!0),Of=n.getUint16(He+26,!0),Fv=n.getUint16(He+28,!0),Bv=He+30+Of+Fv,Ff=Bv+Ov;if(TT!==_||$T!==I||LT!==x||OT!==C||FT!==D||BT!==T||Ov!==j||NT!==M||Of!==$||Fv!==0||Ff>c||!a1(e.subarray(He+30,He+30+Of),Lf))throw new Error("Artifact v1 ZIP local and central entries do not match.");let Bf=e.slice(Bv,Ff);if(s1(Bf)!==T)throw new Error("Artifact v1 ZIP entry CRC-32 mismatch.");let Nf;try{Nf=d.decode(Bf)}catch{Nf=void 0}p.push({path:Gl,pathBytes:Lf,content:Nf,contentBytes:Bf}),h=Ff,g=Lv}if(g!==r||h!==c)throw new Error("Artifact v1 ZIP directory boundaries are invalid.");return p}function s1(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 a1(e,t){for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}var ac="skills-layer-artifact",c1="skills-layer-review-package",u1="skills-layer-package-binding",Ss="skills-layer-length-delimited-manifest-v1",qe=Object.freeze({id:"skills-layer-stored-zip-parser-v1",version:1,archiveFormat:"zip-stored",manifestEncoding:Ss,pathNormalization:"NFC",pathOrdering:"utf8-bytewise",caseCollisionPolicy:"unicode-lowercase-en-US",maxFiles:we.maxFiles,maxDepth:we.maxDepth,maxPathBytes:we.maxPathBytes,maxFileBytes:we.maxFileBytes,maxTotalFileBytes:20*1024*1024,maxArchiveBytes:20*1024*1024+we.maxFiles*(76+2*we.maxPathBytes)+22}),d1=Object.freeze({...qe,maxTotalFileBytes:2*1024*1024,maxArchiveBytes:2*1024*1024+we.maxFiles*(76+2*we.maxPathBytes)+22}),ep=/^sha256:[a-f0-9]{64}$/u,f1=/^(?:(?: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,p1=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,m1=/(?:^|\/)SKILL\.md$/u,g1=new TextEncoder().encode("SKILLS-LAYER-MANIFEST-V1\0"),h1=["archiveSha256","archiveDigest","manifestSha256","manifestDigest","packageBindingDigest","reviewPackageDigest","runtimePackageDigest"];function Hb(e){A1(e),Zb(e.generation,"Artifact generation identity is invalid");let n=[...Jn({files:e.reviewPackageFiles,...e.waivePersonalData?{waivePersonalData:!0}:{}}).files].sort((g,h)=>dc(g.path,h.path)),r=new Map(n.map(g=>[g.path,g])),i=zb(e.runtimeAllowlist,r,"Runtime allowlist");if(i.length===0)throw new Error("Runtime allowlist must contain at least one exact path.");let o=zb(e.deliberateRuntimeReviewMaterial??[],r,"Deliberate runtime review material"),s=new Set(i),a=new Set(o);for(let g of o){if(!s.has(g))throw new Error("Deliberate runtime review material must also be in the runtime allowlist.");if(!Kb(g,n))throw new Error("Deliberate runtime review material path is not review-only material.")}for(let g of i)if(Kb(g,n)&&!a.has(g))throw new Error(`Runtime path ${g} is review-only material and requires deliberate runtime approval.`);let l=n.filter(g=>s.has(g.path));if(l.filter(g=>m1.test(g.path)).length!==1)throw new Error("Runtime deliverable must contain exactly one SKILL.md.");let c=qb(ac,e.generation,l),u=qb(c1,e.generation,n),d=y1({generation:e.generation,reviewPackage:u,runtimePackage:c,runtimePaths:i,deliberateReviewPaths:o}),p=I1({format:ac,formatVersion:1,generation:e.generation,archive:c.envelope.archive,manifest:c.envelope.manifest,parserPolicy:qe}),m=Object.freeze(n.filter(g=>!s.has(g.path)).map(g=>g.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 qb(e,t,n){let r=n.map(C1),i=Yb(r),o=Qf([...n]),s=np({format:e,formatVersion:1,generation:t,archive:{sha256:Oe(o),sizeBytes:o.byteLength},manifest:{encoding:Ss,sha256:Oe(i),fileCount:r.length,totalFileBytes:r.reduce((a,l)=>a+l.sizeBytes,0),files:r},parserPolicy:qe});return{archiveBytes:o,manifestBytes:i,envelope:s}}function y1(e){return w1({generation:e.generation,parserPolicy:e.runtimePackage.envelope.parserPolicy,reviewPackage:Vb(e.reviewPackage),runtimePackage:Vb(e.runtimePackage),runtimePaths:e.runtimePaths,deliberateReviewPaths:e.deliberateReviewPaths})}function w1(e){let t={format:u1,formatVersion:1,generation:Xb(e.generation),parserPolicySha256:Oe(lc(JSON.stringify(e.parserPolicy))),reviewPackage:e.reviewPackage,runtimePackage:e.runtimePackage,runtimeAllowlist:Gb(e.runtimePaths),deliberateRuntimeReviewMaterial:Gb(e.deliberateReviewPaths)};return Object.freeze({...t,packageBindingDigest:Oe(lc(JSON.stringify(t)))})}function Vb(e){return Object.freeze({archiveSha256:Oe(e.archiveBytes),archiveSizeBytes:e.archiveBytes.byteLength,manifestSha256:Oe(e.manifestBytes),envelopeSha256:Oe(lc(JSON.stringify(e.envelope)))})}function Gb(e){let t=Object.freeze([...e]);return Object.freeze({sha256:Oe(v1(t)),paths:t})}function v1(e){let t=[cc(e.length)];for(let n of e){let r=lc(n);t.push(cc(r.byteLength),r)}return e_(t)}function Wb(e){return Jb(e,ac,"Artifact").envelope}function uc(e){return b1(e,ac,"Artifact")}function b1(e,t,n){let r=Jb(e,t,n),i=oc(r.archiveBytes,r.envelope.parserPolicy),o=i.map(u=>({path:u.path,...Je(u.contentBytes)})),s;try{let u=Jn({files:o,runDlp:!1,limits:{maxTotalBytes:r.envelope.parserPolicy.maxTotalFileBytes}});if(u.excluded.length>0)throw new Error("excluded path");s=[...u.files].sort((d,p)=>dc(d.path,p.path))}catch{throw new Error("Artifact archive entries do not satisfy the verified canonical manifest.")}let a=new Map(i.map(u=>[u.path,u])),l=s.map(u=>{let d=a.get(u.path);return{path:d.path,sizeBytes:d.contentBytes.byteLength,sha256:Oe(d.contentBytes)}});if(!R1(l,r.envelope.manifest.files))throw new Error("Artifact archive entries do not match the verified manifest.");let c=new Set(r.envelope.manifest.files.filter(u=>u.executable).map(u=>u.path));return s.map(u=>({...u,...c.has(u.path)?{executable:!0}:{}}))}function Jb(e,t,n){if(!(e.archiveBytes instanceof Uint8Array))throw new Error(`${n} archive bytes are invalid.`);let r=_1(e.envelope,t,n);if(e.archiveBytes.byteLength>qe.maxArchiveBytes)throw new Error(`${n} archive exceeds the v1 parser policy.`);let i=Uint8Array.from(e.archiveBytes),o=Oe(i);if(!Qb(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 _1(e,t,n){if(!Ji(e)||e.format!==t||e.formatVersion!==1)throw new Error(`${n} envelope format is invalid.`);Zb(e.generation,`${n} envelope generation identity is invalid`);let r=x1(e.parserPolicy);if(!r)throw new Error("Artifact envelope parser policy is invalid.");if(!Ji(e.archive)||typeof e.archive.sha256!="string"||!ep.test(e.archive.sha256)||!sc(e.archive.sizeBytes)||e.archive.sizeBytes>r.maxArchiveBytes)throw new Error("Artifact envelope archive metadata is invalid.");if(!Ji(e.manifest)||e.manifest.encoding!==Ss||typeof e.manifest.sha256!="string"||!ep.test(e.manifest.sha256)||!sc(e.manifest.fileCount)||e.manifest.fileCount===0||!sc(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=>k1(a));if(S1(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=Yb(i);if(!Qb(Oe(s),e.manifest.sha256))throw new Error("Artifact manifest SHA-256 mismatch.");return np({format:t,formatVersion:1,generation:e.generation,archive:{sha256:e.archive.sha256,sizeBytes:e.archive.sizeBytes},manifest:{encoding:Ss,sha256:e.manifest.sha256,fileCount:e.manifest.fileCount,totalFileBytes:e.manifest.totalFileBytes,files:i},parserPolicy:r})}function k1(e){if(!Ji(e)||typeof e.path!="string"||!sc(e.sizeBytes)||e.sizeBytes>qe.maxFileBytes||typeof e.sha256!="string"||!ep.test(e.sha256)||e.executable!==void 0&&typeof e.executable!="boolean")throw new Error("Artifact envelope manifest entry is invalid.");return{path:e.path,sizeBytes:e.sizeBytes,sha256:e.sha256,...e.executable===!0?{executable:!0}:{}}}function S1(e){let t;try{let n=Jn({files:e.map(r=>({path:r.path,content:""})),limits:{maxFiles:qe.maxFiles,maxDepth:qe.maxDepth,maxPathBytes:qe.maxPathBytes,maxFileBytes:qe.maxFileBytes,maxTotalBytes:qe.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(dc)}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 C1(e){let t=re(e);return{path:e.path,sizeBytes:t.byteLength,sha256:Oe(t),...e.executable===!0?{executable:!0}:{}}}function Yb(e){let t=[g1,cc(e.length)];for(let n of e){let r=new TextEncoder().encode(n.path);t.push(cc(r.byteLength),r,P1(n.sizeBytes),tp(n.sha256))}return e.some(n=>n.executable)&&t.push(new TextEncoder().encode("\0executable-v1\0"),Uint8Array.from(e.map(n=>n.executable?1:0))),e_(t)}function zb(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(dc)}function Kb(e,t){return zt(e,t).type==="evidence"}function A1(e){for(let t of h1)if(Object.prototype.hasOwnProperty.call(e,t))throw new Error("Caller-supplied artifact digests are forbidden; the server hashes the final ZIP bytes.")}function Zb(e,t){if(!Ji(e)||typeof e.skillSlug!="string"||!Ub(e.skillSlug)||typeof e.semanticVersion!="string"||!f1.test(e.semanticVersion)||typeof e.generationId!="string"||!p1.test(e.generationId))throw new Error(`${t}.`)}function x1(e){if(!Ji(e)||Object.keys(e).length!==Object.keys(qe).length)return null;for(let t of[qe,d1])if(Object.entries(t).every(([n,r])=>e[n]===r))return t;return null}function np(e){let t=Object.freeze(e.manifest.files.map(o=>Object.freeze({path:o.path,sizeBytes:o.sizeBytes,sha256:o.sha256,...o.executable===!0?{executable:!0}:{}}))),n=Xb(e.generation),r=Object.freeze({sha256:e.archive.sha256,sizeBytes:e.archive.sizeBytes}),i=Object.freeze({encoding:Ss,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 I1(e){return np(e)}function Xb(e){return Object.freeze({skillSlug:e.skillSlug,semanticVersion:e.semanticVersion,generationId:e.generationId})}function R1(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 dc(e,t){return Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}function lc(e){return new TextEncoder().encode(e)}function Qb(e,t){return l1(tp(e),tp(t))}function tp(e){return Buffer.from(e.slice(7),"hex")}function cc(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function P1(e){let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function e_(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 sc(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ji(e){return typeof e=="object"&&e!==null}var E1="skills-layer-artifact",D1="skills-layer-package-binding-v2",Cs=20*1024*1024,t_=Object.freeze({id:"skills-layer-stored-zip-parser-v2",version:2,archiveFormat:"zip-stored",manifestEncoding:"skills-layer-canonical-json-v1",pathNormalization:"NFC",pathOrdering:"utf8-bytewise",caseCollisionPolicy:"unicode-lowercase-en-US",maxFiles:we.maxFiles,maxDepth:we.maxDepth,maxPathBytes:we.maxPathBytes,maxFileBytes:Cs,maxTotalFileBytes:Cs,maxArchiveBytes:Cs+we.maxFiles*(76+2*we.maxPathBytes)+22});function T1(e){return{maxTotalBytes:Cs,...e?{}:{maxRasterBytes:Cs}}}function $1(e,t,n){let r=e.filter(i=>!(t&&i.code==="sensitive_image_metadata"));if(r.length)throw new Error(`Canonical Artifact V2 bundle rejected: ${[...new Set(r.map(i=>i.code))].join(", ")}`);if(n)throw new Error("Artifact V2 contains excluded paths.")}function n_(e){let t=L1(e.envelope);if(B1(e.archiveBytes,t.archive,"runtime"),!ec(rp(t.manifest),t.manifest.manifestDigest))throw new Error("Artifact V2 manifest digest is invalid.");let n={...t.packageBinding,packageBindingDigest:void 0};if(!ec(Oe(zr(n)),t.packageBinding.packageBindingDigest))throw new Error("Artifact V2 package binding digest is invalid.");let r=F1(e.archiveBytes,"runtime"),i=new Map(r.map(o=>[o.path,o]));if(r.length!==t.manifest.files.length)throw new Error("Artifact V2 runtime manifest count is invalid.");for(let o of t.manifest.files){let s=i.get(o.path);if(!s||Oe(re(s))!==o.runtimeSha256)throw new Error(`Artifact V2 runtime file binding is invalid for ${o.path}.`)}return{envelope:t,runtimeFiles:r}}function rp(e){return Oe(zr({...e,manifestDigest:void 0}))}function fc(e){return{manifestSha256:e.manifest.manifestDigest,files:e.manifest.files.map(t=>({path:t.path,sizeBytes:t.runtimeSizeBytes,sha256:t.runtimeSha256})),manifestV2:structuredClone(e.manifest)}}function L1(e){if(!e||e.format!==E1||e.formatVersion!==2||e.manifest?.format!=="skills-layer-artifact-v2"||e.manifest.formatVersion!==2||e.packageBinding?.format!==D1||e.packageBinding.formatVersion!==2||zr(e.parserPolicy)!==zr(t_))throw new Error("Artifact V2 envelope format is invalid.");return structuredClone(e)}function O1(e,t,n){let r=ln({files:e,...n.waivePersonalData?{waivePersonalData:!0}:{},...n.runDlp===!1?{runDlp:!1}:{},limits:T1(t)});return $1(r.issues,t,r.excluded.length>0),[...r.files].sort((i,o)=>Buffer.compare(Buffer.from(i.path),Buffer.from(o.path)))}function F1(e,t,n){let r;try{r=oc(e,t_)}catch{throw new Error(`Artifact V2 ${t} archive is invalid.`)}let i=r.map(o=>({path:o.path,...Je(o.contentBytes,Wn(o.path,o.contentBytes))}));return n?i.sort((o,s)=>Buffer.compare(Buffer.from(o.path),Buffer.from(s.path))):O1(i,t!=="runtime",{runDlp:!1})}function B1(e,t,n){if(e.byteLength!==t.sizeBytes||!ec(Oe(e),t.sha256))throw new Error(`Artifact V2 ${n} archive digest is invalid.`)}var Kr=class extends Error{constructor(n,r){super(r instanceof Error?r.message:String(r));this.format=n;this.failure=r;this.name="DeliveredArtifactVerificationError"}format;failure};function N1(e){return!!e&&typeof e=="object"&&e.formatVersion===2}function pc(e){if(N1(e.envelope)){let n;try{n=n_({archiveBytes:e.archiveBytes,envelope:e.envelope})}catch(r){throw new Kr("v2",r)}return{format:"v2",envelope:n.envelope,files:()=>n.runtimeFiles}}let t;try{t=Wb({archiveBytes:e.archiveBytes,envelope:e.envelope})}catch(n){throw new Kr("v1",n)}return{format:"v1",envelope:t,files:()=>{try{return uc({archiveBytes:e.archiveBytes,envelope:t})}catch(n){throw new Kr("v1",n)}}}}var nY=60*864e5;function M1(e){return e==="free_to_paid_requires_admin_review"?"a free skill is becoming paid":e==="price_change_over_50_percent"?"the change is more than 50% from the live price":e==="price_change_frequency_limit"?"the price has changed more than five times in 60 days":e}function r_(e){return e?`Why: ${M1(e)}`:void 0}var j1="Submission progress loaded.",U1="Install progress loaded.";function i_(e){return e.startsWith("processing_")?j1:U1}function Yi(e){return e&&(e.credentialStorage==="local_file_locked"||!e.credentialStorage&&e.apiKey)?"Login key stored in a local file because no OS keyring was available (mode 0600).":""}function ip(e,t,n){if(!t)return e;if(!n)return{...e,stdout:`${e.stdout.trimEnd()}
|
|
153
|
+
|
|
154
|
+
${t}
|
|
155
|
+
`};let r=JSON.parse(e.stdout);return r.summary=`${r.summary} ${t}`,{...e,stdout:JSON.stringify(r,null,2)}}var mc="Sign in again: skills-layer login";function op(e,t){let n=Date.parse(e??"");if(!Number.isFinite(n))return null;let r=n-Date.parse(t);if(r>864e5)return null;let i=e;if(r<=0)return{reasonCode:"api_key_expired",expiresAt:i,nextAction:"login",nextStep:mc,message:`Your sign-in key expired at ${i}. ${mc}`};let o=Math.floor(r/36e5),s=o<1?"less than 1 hour":`${o} hour${o===1?"":"s"}`;return{reasonCode:"api_key_expiring_soon",expiresAt:i,nextAction:"login",nextStep:mc,message:`Your sign-in key expires in ${s} (${i}). ${mc}`}}var sp=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"})]),aY=Object.freeze(sp.map(e=>e.origin)),o_=Object.freeze(sp.map(e=>e.audience));function s_(e){return sp.some(t=>t.origin===e)}function As(e){try{return s_(new URL(e).origin)}catch{return!1}}var Zi=class extends Error{constructor(){super("Skills Layer Cloud MCP requires supported OS-secure credential storage; the bearer was not saved to a local file."),this.name="SecureMcpCredentialStorageError"}};function ap(e){return`${e==="linux"?"Install libsecret secret-tool and start or unlock a Secret Service keyring in your D-Bus session.":e==="win32"?"Enable Windows PowerShell and unlock Credential Manager in your signed-in Windows session.":"Unlock the macOS login Keychain."} Then run skills-layer mcp setup --client <host-id>. No file fallback is available.`}import{spawnSync as q1}from"node:child_process";async function gc(e,t,n="",r=q1){let i=r(e,t,{input:n,encoding:"utf8",timeout:1e4,maxBuffer:65536,windowsHide:!0,stdio:["pipe","pipe","ignore"]});if(i.error)throw new Error("mcp_secure_storage_required: OS credential provider is unavailable or locked.");return{code:i.status,stdout:i.stdout}}function Yn(e){return e==="macos_keychain"||e==="linux_secret_service"||e==="windows_credential_manager"}var a_={"codex-mcp-client":"codex","visual studio code":"github-copilot","cursor-vscode":"cursor","gemini-cli-mcp-client":"gemini-cli",vscode:"github-copilot","visual-studio-code":"github-copilot",code:"github-copilot","github-copilot-cli":"github-copilot","copilot-cli":"github-copilot","github-copilot-chat":"github-copilot","claude code":"claude-code","claude-code":"claude-code","codex cli":"codex","gemini cli":"gemini-cli"};function l_(e){if(!e)return;let t=e.trim().toLowerCase();return(Object.hasOwn(a_,t)?a_[t]:void 0)??Hn(t)??void 0}function c_(e,t,n){if(e!==void 0){let r=Hn(e);return r?{agent:r}:{reasonCode:"unknown_agent"}}return{agent:l_(t)??l_(n)}}function Zn(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 u_(e,t){Zn(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"}var hc=8,f_=8,V1=128,G1=/^key_[A-Za-z0-9_-]{1,128}$/u,z1=/^user_[A-Za-z0-9_-]{1,128}$/u;function yc(e){let t=Hr(e.baseUrl);if(!t||!z1.test(e.userId)||!H1(e.createdAt))throw new Error("Pending revocation identifiers are invalid.");let n=d_(e.humanKeyIds),r=d_(e.mcpKeyIds,V1);if(e.humanKeyIds.length!==new Set(e.humanKeyIds).size||e.mcpKeyIds.length!==new Set(e.mcpKeyIds).size)throw new Error("Pending revocation credential identifiers are invalid.");if(n.length===0&&r.length===0&&!e.revokeAllMcp&&!e.revokeAdminMcp)throw new Error("Pending revocation has no server-side work.");return{version:1,baseUrl:t,userId:e.userId,humanKeyIds:n,mcpKeyIds:r,revokeAllMcp:e.revokeAllMcp,revokeAdminMcp:e.revokeAdminMcp,createdAt:e.createdAt}}function p_(e,t){let n=e.find(i=>i.baseUrl===t.baseUrl&&i.userId===t.userId),r=n?yc({baseUrl:t.baseUrl,userId:t.userId,humanKeyIds:[...new Set([...n.humanKeyIds,...t.humanKeyIds])].slice(0,f_),mcpKeyIds:[...new Set([...n.mcpKeyIds,...t.mcpKeyIds])],revokeAllMcp:n.revokeAllMcp||t.revokeAllMcp,revokeAdminMcp:n.revokeAdminMcp||t.revokeAdminMcp,createdAt:n.createdAt<t.createdAt?n.createdAt:t.createdAt}):t;return[...e.filter(i=>i.baseUrl!==t.baseUrl||i.userId!==t.userId),r].slice(-hc)}function m_(e){return{includeCurrent:!1,revokeAllMcp:e.revokeAllMcp,humanKeyIds:[...e.humanKeyIds],mcpKeyIds:[...e.mcpKeyIds]}}function K1(e,t=()=>{}){if(!cp(e)||e.version!==1||!Array.isArray(e.entries)||e.entries.length>hc)return[];let n=[];for(let i of e.entries)if(W1(i))try{n.push(yc({baseUrl:i.baseUrl,userId:i.userId,humanKeyIds:i.humanKeyIds,mcpKeyIds:i.mcpKeyIds,revokeAllMcp:i.revokeAllMcp,revokeAdminMcp:i.revokeAdminMcp,createdAt:i.createdAt}))}catch{}let r=e.entries.length-n.length;return r&&t(`Skipped ${r} invalid pending revocation entries; valid entries will still retry.`),n}function lp(e){return{version:1,entries:e.slice(-hc)}}function Hr(e){try{let t=Zn(e);return`${t.origin}${t.pathname.replace(/\/+$/u,"")}`}catch{return null}}function d_(e,t=f_){if(!Array.isArray(e)||e.length>t||e.some(n=>!G1.test(n)))throw new Error("Pending revocation credential identifiers are invalid.");return[...new Set(e)]}function H1(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))&&new Date(e).toISOString()===e}function cp(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function W1(e){return!cp(e)||Object.keys(e).sort().join("|")!=="baseUrl|createdAt|humanKeyIds|mcpKeyIds|revokeAdminMcp|revokeAllMcp|userId|version"?!1:e.version===1&&typeof e.baseUrl=="string"&&typeof e.userId=="string"&&Array.isArray(e.humanKeyIds)&&e.humanKeyIds.every(n=>typeof n=="string")&&Array.isArray(e.mcpKeyIds)&&e.mcpKeyIds.every(n=>typeof n=="string")&&typeof e.revokeAllMcp=="boolean"&&typeof e.revokeAdminMcp=="boolean"&&typeof e.createdAt=="string"}async function up(e,t){let n;try{n=await e()}catch(i){return i.code==="ENOENT"?{entries:[],preserved:!1}:(t("Pending revocation file could not be read; preserved for recovery."),{entries:[],preserved:!0})}let r;try{r=JSON.parse(n)}catch{return t("Pending revocation file has corrupt JSON; preserved for recovery. Repair it before retrying logout/login."),{entries:[],preserved:!0}}return!cp(r)||r.version!==1||!Array.isArray(r.entries)||r.entries.length>hc?(t("Pending revocation file has an unsupported envelope; preserved for recovery."),{entries:[],preserved:!0}):{entries:K1(r,t),preserved:!1}}var J1=10080*60*1e3;function dp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function fp(e,t,...n){let r=new Map;for(let i of n){let o=dp(i),s=[o,...Object.values(dp(o.tokens)),...Array.isArray(o.revocationRefs)?o.revocationRefs:[]];for(let a of s){let l=dp(a);if(typeof l.keyId!="string"||!/^key_[A-Za-z0-9_-]{1,128}$/u.test(l.keyId))continue;let c=Hr(String(l.baseUrl??o.baseUrl??e.baseUrl));if(!c)continue;let u=typeof l.userId=="string"?l.userId:typeof o.userId=="string"?o.userId:e.userId,d=typeof o.savedAt=="string"&&Number.isFinite(Date.parse(o.savedAt))?Date.parse(o.savedAt):Date.parse(t),p=typeof l.expiresAt=="string"&&Number.isFinite(Date.parse(l.expiresAt))?l.expiresAt:new Date(d+J1).toISOString();Date.parse(p)<=Date.parse(t)||r.set(`${c}\0${u}\0${l.keyId}`,{keyId:l.keyId,baseUrl:c,userId:u,expiresAt:p})}}return[...r.values()]}function g_(e,t,...n){let r=Hr(e.baseUrl);return[...new Set(fp(e,t,...n).filter(i=>i.baseUrl===r&&(!i.userId||i.userId===e.userId)).map(i=>i.keyId))]}async function pp(e,t){for(let n=0;n<Math.max(1,t.mcpKeyIds.length);n+=8){let r=n+8>=t.mcpKeyIds.length;await e({includeCurrent:r&&t.includeCurrent,revokeAllMcp:r&&t.revokeAllMcp,humanKeyIds:r?t.humanKeyIds:[],mcpKeyIds:t.mcpKeyIds.slice(n,n+8)})}}var h_="Microsoft sign-in isn't available yet. Use email, GitHub, Google or GitLab.";function mp(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function y_(e){let t=mp(mp(e.submission)?.latestFailure),n=mp(e.processing)?.status==="failed";return!t&&!n||typeof e.nextStep=="string"&&e.nextStep.trim()&&!/no further action is required/iu.test(e.nextStep)?e:{...e,nextAction:"creator.status",nextStep:"Inspect the failed update and its reported reason before retrying. A live earlier version does not mean the update succeeded."}}var Y1="Deprecated: --mfa-code is supported for this transition release only. Use the masked prompt or --totp-stdin; command-line codes can appear in process listings.";async function w_(e){let t="";for await(let n of e){if(t+=typeof n=="string"?n:new TextDecoder().decode(n),t.length>32)throw new Error("Authenticator input is too long.");if(t.includes(`
|
|
156
|
+
`))break}return t}async function v_(e,t,n){let r=e.indexOf("--"),i=r<0?e:e.slice(0,r),o=i.some(c=>c==="--mfa-code"||c.startsWith("--mfa-code=")),s=i.filter(c=>c==="--totp-stdin").length;if(!s)return{args:e,warning:o?Y1:null};if(s!==1||o)throw new Error("Choose one authenticator input: a masked prompt, --totp-stdin, or the deprecated --mfa-code.");if(n)throw new Error("Use the masked prompt on a terminal, or pipe a code to --totp-stdin.");let a=(await t()).trim();if(!/^\d{6}$/u.test(a))throw new Error("Authenticator input must be a single six-digit code.");let l=[...e];return l.splice(i.indexOf("--totp-stdin"),1,"--mfa-code",a),{args:l,warning:null}}function gp(...e){return e.find(t=>t==="community"||t==="saas")}function b_(e){return e.status!=="review_updated"?"Review added.":e.moderationStatus==="flagged"?"Review updated; awaiting moderation.":"Review updated."}var __=We({HOME:"/home/skills-layer"},"linux","/workspace").filter(e=>e.pathContracts.project.status==="supported"),xY=__.map(e=>e.id),IY=new Map(__.map(e=>[e.id,new Set(e.capabilities)]));var Z1=[...Kn],X1=["basic_skills","allowed_tools","hooks","forked_context","local_install"];function wc(e){if(e===void 0)return;if(!k_(e))throw new Error("metadata.agent_compatibility must be an object when provided");if(Object.hasOwn(e,"supported")||Object.hasOwn(e,"unsupported")){let n={};for(let r of Object.keys(e)){if(r!=="supported"&&r!=="unsupported")throw new Error(`agent_compatibility contains an unknown field: ${r}`);if(!Array.isArray(e[r]))throw new Error(`agent_compatibility.${r} must be an agent array`);for(let i of e[r]){let o=typeof i=="string"?Hn(i):null;if(!o)throw new Error(`agent_compatibility.${r} contains an unsupported agent id`);if(n[o]&&n[o].supported!==(r==="supported"))throw new Error(`agent_compatibility declares conflicting support for ${o}`);n[o]={supported:r==="supported",capabilities:[]}}}return n}let t={};for(let[n,r]of Object.entries(e)){if(!Z1.includes(n))throw new Error(`metadata.agent_compatibility contains an unsupported agent id: ${n}`);if(!k_(r))throw new Error(`metadata.agent_compatibility.${n} must be an object`);let i=nL(r,n),o=Q1(r.capabilities,`${n}.capabilities`),s=eL(r.notes,`${n}.notes`);t[n]={supported:i,capabilities:o,...s?{notes:s}:{}}}return t}function S_(e){if(!e.compatibilityMatrix)return{status:"compatible"};let t=e.compatibilityMatrix[e.agent.id];if(!t)return{status:"compatible"};if(!t.supported)return{status:"unsupported_agent"};let n=t.capabilities.filter(r=>!e.agent.capabilities.includes(r));return n.length>0?{status:"missing_capabilities",missingCapabilities:n}:{status:"compatible"}}function Q1(e,t){if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`metadata.agent_compatibility.${t} must be a string array when provided`);let n=e.map(r=>r.trim()).filter(r=>r.length>0);for(let r of n)if(!X1.includes(r))throw new Error(`metadata.agent_compatibility.${t} contains an unsupported capability: ${r}`);return[...new Set(n)]}function eL(e,t){if(e!==void 0){if(typeof e!="string"||e.trim().length===0)throw new Error(`metadata.agent_compatibility.${t} must be a non-empty string when provided`);return e.trim()}}function tL(e,t){if(typeof e!="boolean")throw new Error(`metadata.agent_compatibility.${t} must be a boolean when provided`);return e}function nL(e,t){return Object.hasOwn(e,"supported")?tL(e.supported,`${t}.supported`):!0}function k_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var eg=Tt(ei(),1);var E2="private",fC="public",pC="unlisted";function na(e){if(typeof e!="string"||e.trim().length===0)return null;let t=e.trim().toLowerCase();return t==="private"?E2:t===fC?fC:t===pC?pC:null}var Ym=["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"],D2="productivity",T2=new Set(Ym),$2={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"},L2={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 Zm(e){if(typeof e!="string")return null;let t=hC(e);return T2.has(t)?t:$2[t]??null}function mC(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 gC(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=F2(o.value);for(let[a,l]of Object.entries(L2)){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||Ym.indexOf(o[0])-Ym.indexOf(s[0]))[0];return!i||i[1].score<2?{category:O2(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 O2(e){let t=hC(e.skillType??"");return t.includes("automation")?"automation":t.includes("mcp")?"ai":D2}function hC(e){return e.trim().toLowerCase().replace(/[_\s]+/gu,"-")}function F2(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/u).map(t=>t.trim()).filter(t=>t.length>=2).flatMap(B2))}function B2(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 Xm="skills-layer.control.v3",co="skills-layer.control.v2";var N2=new Set(["private","public","unlisted"]);var M2=new Set(["schemaVersion","listing","toolContract","targets","agentCompatibility"]),j2=new Set(["visibility","priceCents","category","tags"]),U2=new Set(["visibility","category","tags"]),q2=new Set(["requestedCapabilities","requestedTools","networkDomains","fileReadScopes","fileWriteScopes","approvedCapabilities","deniedCapabilities","secretNames","shellCommands","browserOrigins","deviceKinds","apiOperations"]),V2=/^[^\s\u0000-\u001f\u007f]{1,160}$/u;function uo(e){let t;try{t=(0,eg.parse)(e,{uniqueKeys:!0})}catch(n){let r=n instanceof Error?n.message:"Invalid control YAML";throw new Error(`Invalid Creator control manifest: ${r}`)}if(!vC(t))throw new Error("Creator control manifest must be a YAML object");if(Qm(t,M2,"control manifest"),t.schemaVersion!==Xm&&t.schemaVersion!==co)throw new Error(`Creator control schemaVersion must be ${Xm} or ${co}`);return G2(t)}function G2(e){let t=e.schemaVersion;if(t!==Xm&&t!==co)throw new Error("Creator control schemaVersion is invalid");let n=e.listing===void 0?{}:yC(e.listing,"listing"),r=e.toolContract===void 0?{}:yC(e.toolContract,"toolContract");Qm(n,t===co?j2:U2,"listing"),Qm(r,q2,"toolContract");let i=n.visibility===void 0?"private":z2(n.visibility,N2,"listing.visibility"),o=n.priceCents===void 0?0:n.priceCents;if(t===co&&(!Number.isInteger(o)||Number(o)<0))throw new Error("listing.priceCents must be a non-negative integer");let s=n.category===void 0||n.category===null?null:wC(n.category,"listing.category",80).toLowerCase();return{schemaVersion:t,...e.agentCompatibility===void 0?{}:{agentCompatibility:wc(e.agentCompatibility)},listing:{visibility:i,...t===co&&n.priceCents!==void 0?{priceCents:Number(o)}:{},category:s,tags:mt(n.tags,"listing.tags",80,!0)},toolContract:{requestedCapabilities:mt(r.requestedCapabilities,"toolContract.requestedCapabilities"),requestedTools:mt(r.requestedTools,"toolContract.requestedTools"),networkDomains:mt(r.networkDomains,"toolContract.networkDomains",253,!0),fileReadScopes:mt(r.fileReadScopes,"toolContract.fileReadScopes",1024),fileWriteScopes:mt(r.fileWriteScopes,"toolContract.fileWriteScopes",1024),...r.approvedCapabilities===void 0?{}:{approvedCapabilities:mt(r.approvedCapabilities,"toolContract.approvedCapabilities",1024)},...r.deniedCapabilities===void 0?{}:{deniedCapabilities:mt(r.deniedCapabilities,"toolContract.deniedCapabilities",1024)},...r.secretNames===void 0?{}:{secretNames:mt(r.secretNames,"toolContract.secretNames",1024)},...r.shellCommands===void 0?{}:{shellCommands:mt(r.shellCommands,"toolContract.shellCommands",1024,!1,!1)},...r.browserOrigins===void 0?{}:{browserOrigins:mt(r.browserOrigins,"toolContract.browserOrigins",1024)},...r.deviceKinds===void 0?{}:{deviceKinds:mt(r.deviceKinds,"toolContract.deviceKinds",1024)},...r.apiOperations===void 0?{}:{apiOperations:mt(r.apiOperations,"toolContract.apiOperations",1024)}},targets:mt(e.targets,"targets",160,!0)}}function mt(e,t,n=160,r=!1,i=!0){if(e==null)return[];if(!Array.isArray(e))throw new Error(`${t} must be an array of bounded strings`);let o=e.map(s=>{let a=wC(s,t,n);if(i&&!V2.test(a))throw new Error(`${t} contains an invalid value`);return r?a.toLowerCase():a});return[...new Set(o)].sort((s,a)=>s.localeCompare(a))}function Qm(e,t,n){let r=Object.keys(e).filter(i=>!t.has(i));if(r.length>0)throw new Error(`${n} contains unsupported field(s): ${r.sort().join(", ")}`)}function yC(e,t){if(!vC(e))throw new Error(`${t} must be an object`);return e}function wC(e,t,n=200){if(typeof e!="string"||e.trim().length===0||e.trim().length>n)throw new Error(`${t} must be a non-empty string of at most ${n} characters`);if(/[\u0000-\u001f\u007f]/u.test(e))throw new Error(`${t} contains control characters`);return e.trim()}function z2(e,t,n){if(typeof e!="string"||!t.has(e))throw new Error(`${n} is not supported`);return e}function vC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ra=Tt(ei(),1);var tg=["claude","anthropic"];function bC(e){let t=kC(e);return t?tg.find(n=>t.includes(n))??null:null}function _C(e){let t=kC(e);return t?tg.includes(t):!1}function yu(){return`name must not use reserved ${tg.join(" or ")} terms`}function kC(e){let t=e.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").replace(/-{2,}/gu,"-");return t.length>0?t:null}var K2=1024,CC=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,H2=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function lr(e){let t=e.match(CC);if(!t)throw new Error("SKILL.md must start with YAML frontmatter delimited by ---");let[,n,r]=t,i=(0,ra.parse)(n);if(!wu(i))throw new Error("Frontmatter must parse to an object");return{frontmatter:W2(i),body:r,rawFrontmatter:n}}function AC(e,t,n){let r=e.match(CC);if(!r)throw new Error("SKILL.md must start with YAML frontmatter delimited by ---");let[,i,o]=r,s=(0,ra.parse)(i);if(!wu(s))throw new Error("Frontmatter must parse to an object");let a={...s,license:t},l=wu(s.metadata)?{...s.metadata}:void 0;return l?(delete l.license,delete l.license_file,Object.keys(l).length===0?delete a.metadata:a.metadata=l):delete a.metadata,`---
|
|
157
|
+
${(0,ra.stringify)(a,{lineWidth:0}).trimEnd()}
|
|
158
|
+
---
|
|
159
|
+
${o}`}function wu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function W2(e){let t=SC(e.name,"name"),n=SC(e.description,"description"),r=e.license,i=J2(e.compatibility,"compatibility"),o=Y2(e.metadata,"metadata");if(e.agent_compatibility!==void 0&&o?.agent_compatibility!==void 0)throw new Error("Declare agent_compatibility once, at the top level or in metadata");let s=wc(e.agent_compatibility??o?.agent_compatibility),a=s?{...o,agent_compatibility:s}:o,l=Z2(e["allowed-tools"]);if(!H2.test(t))throw new Error("name must be kebab-case");if(bC(t))throw new Error(yu());if(n.length>K2)throw new Error("description must be 1024 characters or fewer");return{name:t,description:n,...r===void 0?{}:{license:r},...i===void 0?{}:{compatibility:i},...s===void 0?{}:{compatibilityMatrix:s},...a===void 0?{}:{metadata:a},...l===void 0?{}:{"allowed-tools":l}}}function SC(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e.trim()}function J2(e,t){if(e===void 0)return;if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string when provided`);let n=e.trim();if(t==="compatibility"&&n.length>500)throw new Error("compatibility must be 500 characters or fewer");return n}function Y2(e,t){if(e!==void 0){if(!wu(e))throw new Error(`${t} must be an object when provided`);return e}}function Z2(e){if(e!==void 0){if(typeof e=="string")return e.trim();if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e.map(t=>t.trim());throw new Error("allowed-tools must be a string or string array when provided")}}function vu(e){let t=e.find(i=>i.path==="SKILL.md"),n=t?.content?lr(t.content).frontmatter.compatibilityMatrix:void 0;if(n)return n;let r=e.find(i=>i.path===".skills-layer/skill.yaml");if(typeof r?.content=="string")try{return uo(r.content).agentCompatibility}catch{return}}function bu(e){let t=S_(e);return{...t,allowed:t.status==="compatible"||e.allowIncompatible===!0,reasonCode:t.status==="unsupported_agent"?"incompatible_agent":t.status,compatibilityOverride:t.status!=="compatible"&&e.allowIncompatible===!0,compatibilityMatrix:e.compatibilityMatrix??{}}}function ia(e){let t=[];for(let n of e){let r=ng(n);r&&!t.includes(r)&&t.push(r)}return t.sort()}function ng(e){let t=e.trim().toLowerCase().replaceAll(/\s+/gu,"_").replaceAll("-","_");return X2(t)?t:Q2[t]??null}function X2(e){return["shell_execution","network_access","filesystem_read","filesystem_write","secret_handling","browser_access","device_control","api_access","generated_code_execution","model_context"].includes(e)}var Q2={secret_access:"secret_handling",secrets:"secret_handling",browser_control:"browser_access",browser:"browser_access",device:"device_control",api:"api_access",api_call:"api_access",generated_code:"generated_code_execution",generated_code_scan:"generated_code_execution",generated_code_control:"generated_code_execution",model_context_access:"model_context",model_output_context:"model_context"};function xC(e){e.skillSlug,e.version;let t={securityScore:e.securityReport.securityScore,recommendation:e.securityReport.recommendation,runtimeRisk:e.securityReport.capabilityProfile.runtimeRisk,detectedCapabilities:[...e.securityReport.capabilityProfile.detectedCapabilities],mismatches:[...e.securityReport.capabilityProfile.mismatches],...e.securityReport.securityRuleSummary?{highestRuleSeverity:e.securityReport.securityRuleSummary.highestSeverity,topRuleIds:e.securityReport.securityRuleSummary.topRuleIds,reviewDegradedReasons:e.securityReport.securityRuleSummary.review.degradedReasons,dependencyAuditStatus:e.securityReport.securityRuleSummary.dependency.status}:{}},n=ia([...e.securityReport.capabilityProfile.detectedCapabilities]);if(e.securityReport.recommendation==="blocked"||e.securityReport.recommendation==="manual_review"||e.securityReport.findings.some(o=>o.blocking))return{status:"quarantine_required",reasonCode:"security_report_not_installable",riskSummary:t,requiredConsentCapabilities:n,runtimePermissionContract:rg({skillSlug:e.skillSlug,version:e.version,securityReport:e.securityReport,runtimePolicy:e.runtimePolicy,status:"quarantine_required"})};let r=new Set(e.consentedCapabilities??[]);if(n.length>0&&e.securityReport.capabilityProfile.runtimeRisk!=="low"&&n.some(o=>!r.has(o)))return{status:"consent_required",reasonCode:"risky_capability_consent_required",riskSummary:t,requiredConsentCapabilities:n,runtimePermissionContract:rg({skillSlug:e.skillSlug,version:e.version,securityReport:e.securityReport,runtimePolicy:e.runtimePolicy,status:"policy_required"})};let i=rg({skillSlug:e.skillSlug,version:e.version,securityReport:e.securityReport,runtimePolicy:e.runtimePolicy});return{status:"ready",reasonCode:"security_checks_passed",riskSummary:t,requiredConsentCapabilities:n,runtimePermissionContract:i}}function rg(e){let t=ia(e.securityReport.capabilityProfile.declaredCapabilities),n=ia(e.securityReport.capabilityProfile.detectedCapabilities),r=ia(e.securityReport.capabilityProfile.mismatches),i=eN({detectedCapabilities:n,undeclaredCapabilities:r,runtimePolicy:e.runtimePolicy}),o=e.status??(i.some(tN)?"policy_required":"ready"),s=n.includes("network_access"),a=n.includes("filesystem_read"),l=n.includes("filesystem_write"),c=_u(e.runtimePolicy?.allowedNetworkDomains),u=_u(e.runtimePolicy?.fileScopes?.read),d=_u(e.runtimePolicy?.fileScopes?.write);return{boundary:"skills_layer_install_capability_contract",skillSlug:e.skillSlug,version:e.version,status:o,declaredCapabilities:t,detectedCapabilities:n,undeclaredCapabilities:r,defaultPolicy:"deny_until_authorized_and_scoped",requiredBeforeEnablement:i,policy:{network:{status:s?c.length>0?"scoped":"policy_required":"not_requested",allowedDomains:c},files:{readScopes:u,writeScopes:d,status:a||l?a&&u.length===0||l&&d.length===0?"policy_required":"scoped":"not_requested"},secrets:{status:n.includes("secret_handling")?e.runtimePolicy?.secretPolicy==="deny"?"denied":"brokered":"not_requested"},shell:{approvalRequired:n.includes("shell_execution")||n.includes("generated_code_execution"),generatedCodeSandboxRequired:n.includes("shell_execution")||n.includes("generated_code_execution")},browser:{confirmationRequired:n.includes("browser_access")},device:{confirmationRequired:n.includes("device_control")},api:{confirmationRequired:n.includes("api_access"),allowedTargets:_u(e.runtimePolicy?.allowedApiTargets)},modelContext:{filterRequired:n.includes("model_context")}}}}function eN(e){let t=[];return e.undeclaredCapabilities.length>0&&t.push("accept_inferred_capabilities"),e.detectedCapabilities.includes("network_access")&&!e.runtimePolicy?.allowedNetworkDomains?.length&&t.push("network_domains"),e.detectedCapabilities.includes("filesystem_read")&&!e.runtimePolicy?.fileScopes?.read?.length&&t.push("file_read_scopes"),e.detectedCapabilities.includes("filesystem_write")&&!e.runtimePolicy?.fileScopes?.write?.length&&t.push("file_write_scopes"),e.detectedCapabilities.includes("secret_handling")&&e.runtimePolicy?.secretPolicy!=="deny"&&t.push("secret_broker"),e.detectedCapabilities.includes("shell_execution")&&t.push("shell_approval","generated_code_scan_and_sandbox"),e.detectedCapabilities.includes("generated_code_execution")&&t.push("shell_approval","generated_code_scan_and_sandbox"),e.detectedCapabilities.includes("browser_access")&&t.push("browser_confirmation"),e.detectedCapabilities.includes("device_control")&&t.push("device_confirmation"),e.detectedCapabilities.includes("api_access")&&t.push("api_confirmation"),e.detectedCapabilities.includes("model_context")&&t.push("model_context_filter"),[...new Set(t)]}function tN(e){return e==="network_domains"||e==="file_read_scopes"||e==="file_write_scopes"}function _u(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort()}var nN=/\b(?:curl|wget|invoke-webrequest|requests\.(?:get|post|put|patch|delete)|axios\.(?:get|post|put|patch|delete)|httpx\.(?:get|post|put|patch|delete)|urllib\.request\.urlopen|fetch\()\b/i,rN=/\b(?:generated[-_\s]?code|generate\s+(?:and\s+)?(?:run|execute)|write\s+(?:a\s+)?(?:script|code)\s+(?:and\s+)?(?:run|execute)|execute\s+(?:the\s+)?generated\s+(?:script|code))\b/i;function IC(e,t){let n=new Set,r=new Set,i=e.parsedSkill?.frontmatter,o=i&&typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},s=sN(i?.["allowed-tools"]),a=Array.isArray(o.capabilities)?o.capabilities.filter(y=>typeof y=="string").map(y=>ig(y)):[],l=typeof o.skills_layer=="object"&&o.skills_layer!==null?o.skills_layer:{},c=Array.isArray(l.capabilities)?l.capabilities.filter(y=>typeof y=="string").map(y=>ig(y)):[],u=iN(t);for(let y of[...a,...c,...u])n.add(y);for(let y of s){let w=oN(y);w&&n.add(w)}let d=e.parsedSkill?.body??"";(/\baskuserquestion\b/i.test(d)||s.some(y=>oa(y)==="askuserquestion"))&&r.add("interactive_prompt"),s.some(y=>oa(y)==="read")&&r.add("filesystem_read"),s.some(y=>oa(y)==="write")&&r.add("filesystem_write"),s.some(y=>oa(y)==="bash")&&r.add("shell_execution");for(let y of t){let w=y.content??"";(cN(y.path)||/\bpython3?\b|\bnode\b|\bbash\b|\bsh\b/i.test(w))&&r.add("shell_execution"),rN.test(w)&&r.add("generated_code_execution"),(nN.test(w)||/\byt-dlp\b|\bgit clone\b|\bnpm install\b|\bpip install\b/i.test(w))&&r.add("network_access"),/\bwrite(file|text|binary)?\b|ffmpeg|copyfile|mkdir|remove-item|\brm\b/i.test(w)&&r.add("filesystem_write"),/\bread(file|text|binary)?\b|open\(|fs\.readfile|readfile|cat\s+|type\s+/i.test(w)&&r.add("filesystem_read"),/\b(api|sdk|request|client)\b/i.test(w)&&/\btoken|secret|key\b/i.test(w)&&r.add("secret_handling"),/\b(browser|playwright|chrome devtools|web testing|click through|page\.goto)\b/i.test(w)&&r.add("browser_access"),/\b(device|iot|smart speaker|xiaomi|mi home|air purifier|humidifier|speaker devices?)\b/i.test(w)&&r.add("device_control"),/\b(api|endpoint|graphql|rest|authorization|bearer|webhook)\b/i.test(w)&&r.add("api_access")}let p=[...r].sort(),m=[...n].sort(),g=p.filter(y=>!n.has(y)),h=r.has("network_access")||r.has("shell_execution")||r.has("generated_code_execution")||r.has("browser_access")||r.has("device_control")||r.has("api_access")?"high":r.has("filesystem_write")||r.has("filesystem_read")||r.has("secret_handling")?"elevated":"low";return{declaredCapabilities:m,detectedCapabilities:p,mismatches:g,runtimeRisk:h,executableFileCount:t.filter(lN).length}}function iN(e){try{let t=ic(e)[0];return uo(t?.content??"").toolContract.requestedCapabilities.map(ig)}catch{return[]}}function oN(e){let t=oa(e);return t==="bash"?"shell_execution":t==="write"?"filesystem_write":t==="read"?"filesystem_read":t==="askuserquestion"?"interactive_prompt":t==="browser"?"browser_access":t==="api"?"api_access":t==="device"?"device_control":null}function sN(e){return(Array.isArray(e)?e:typeof e=="string"?[e]:[]).filter(n=>typeof n=="string").flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean)}function oa(e){return e.trim().toLowerCase().replace(/\(.+\)$/u,"")}function ig(e){return ng(e)??e.trim().toLowerCase().replaceAll(/\s+/gu,"_")}var aN=/\.(?:sh|bash|zsh|fish|ps1|psm1|bat|cmd|py|pyw|js|mjs|cjs|ts|mts|cts|rb|pl|php|lua|exe|dll|so|dylib|bin|jar|wasm|app|msi|deb|rpm)$/i;function lN(e){return e.executable===!0||aN.test(e.path)||(e.content??"").startsWith("#!")}function cN(e){return/\.(sh|bash|ps1|py|js|ts)$/i.test(e)}function sa(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t=e;return t.reasonCode!=="rights_attestation_required"&&t.reasonCode!=="rights_attestation_invalid"?e:{...t,..."data"in t?{data:sa(t.data)}:{},nextAction:t.nextAction==="creator.version.submit"?"creator.submit-version":t.nextAction,nextStep:"Confirm your distribution rights, then retry with --attest-rights --rights-basis <supported-basis> --distribution-scope public_distribution (commercial_distribution for a paid release). Use --visibility private for a draft."}}function RC(e,t){if(e[0]!=="creator"||!/ requires /u.test(t))return;let n=[...lb].sort((p,m)=>m.path.length-p.path.length).find(p=>p.path.split(" ").every((m,g)=>e[g+1]===m)),r=n?`creator ${n.path}`:"creator",i={command:r,nextAction:`${r.replaceAll(" ",".")}.help`,nextStep:`Run \`skills-layer ${r} --help\` for the complete command usage.`};if(!n)return i;let s=[...(/ requires (?<argument>.+)\.$/u.exec(t)?.groups?.argument??"").split(/\b(?:from|because|outside|or)\b/u,1)[0].matchAll(/--[a-z0-9-]+/giu)].map(p=>p[0]);if(s.length===0)return i;let a=1+n.path.split(" ").length;if(n.usage[0].slice(`skills-layer ${r}`.length).trimStart().startsWith("<")&&(!e[a]||e[a].startsWith("--")))return i;let c=[...e];for(let p of s){let m=n.usage.find(y=>y.includes(`${p} `)||y.includes(`${p}]`));if(!m)return i;if(c.includes(p)||c.some(y=>y.startsWith(`${p}=`)))continue;let g=m.slice(m.indexOf(p)+p.length),h=/^\s+(<[^>]+>)/u.exec(g)?.[1];c.push(p),h&&c.push(h)}if(c.length===e.length)return i;let u=c.map((p,m)=>/^--[^=]*(?:token|secret|password|api-key|code)(?:=|$)/iu.test(p)?p.includes("=")?`${p.split("=")[0]}=<redacted>`:p:m>0&&/^--[^=]*(?:token|secret|password|api-key|code)$/iu.test(c[m-1])?"<redacted>":zl($t(p))),d=p=>/^[a-z0-9_./:@=+-]+$/iu.test(p)?p:`'${p.replaceAll("'",`'"'"'`)}'`;return{command:r,nextAction:r.replaceAll(" ","."),nextStep:`Run \`skills-layer ${u.map(d).join(" ")}\`.`}}async function PC(e){let t=k.number().int().min(1).max(120).parse(e.maximumPolls??20),n={status:"waiting_stopped",serverWorkContinues:!0};for(let r=0;;r++){if(e.signal?.aborted)return n;let i;try{i=await e.read()}catch(l){if(e.signal?.aborted)return n;throw l}if(e.signal?.aborted)return n;if(["completed","failed","cancelled","action_required","blocked","expired"].includes(String(i.status)))return i;if(r===t-1)return{...i,waitTimedOut:!0,serverWorkContinues:!0};let o=typeof i.retryAfterSeconds=="number"&&Number.isFinite(i.retryAfterSeconds)?i.retryAfterSeconds:5,s,a=new Promise(l=>{s=l,e.signal?.addEventListener("abort",s,{once:!0})});try{await Promise.race([e.sleep(Math.min(30,Math.max(2,o))*1e3),a])}finally{e.signal?.removeEventListener("abort",s)}}}var uN=["acceptedAt","sourceResolvedAt"];function og(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};for(let r of uN){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=new Date(i).toISOString().replace("T"," ").replace(/\.\d{3}Z$/u," UTC"))}let n=dN(t);return n&&(t.summary=n),t}function dN(e){let t=e.recovery;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t.nextStep;return typeof n!="string"||!n?null:`Completed through recovery${typeof e.supersededStatus=="string"?` (the run ended ${e.supersededStatus})`:""}. ${n}`}async function EC(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 DC(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(`
|
|
160
|
+
`)}var TC="Your bank is reviewing a dispute on this payment. Access is paused until it is resolved.";function ti(e){let t=e.find(n=>n.path==="SKILL.md");if(typeof t?.content!="string")throw new Error("An installed skill must contain a readable root SKILL.md. This published bundle has no SKILL.md at its root.");return lr(t.content).frontmatter.name}function $C(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}var fN=/^device_[a-f0-9]{32}$/u;function sg(e){if(typeof e!="string")return;let t=e.normalize("NFKC").replace(/[\p{C}\p{Zl}\p{Zp}]/gu," ").replace(/\s+/gu," ").trim();if(t)return[...t].slice(0,64).join("").trim()}function ag(e){if(typeof e!="string")return;let t=e.trim();return fN.test(t)?t:void 0}function LC(e){return`device_${e}`}var pN=Object.freeze({darwin:"macOS",win32:"Windows",linux:"Linux"});function OC(e){let t=sg(e.env.SKILLS_LAYER_DEVICE_NAME);if(t)return t;let n=pN[e.platform]??e.platform,r=sg(e.hostname.replace(/\.local$/iu,""));return sg(r?`${r} (${n})`:n)??""}import{createInterface as mN}from"node:readline/promises";var gN="\r\x1B[2K";function FC(e,t,n,r=0){let i=n&&n>0?Math.ceil((Zv(e)+r)/n)-1:0;return`${i>0?`\r\x1B[${i}A\x1B[J`:gN}${e}${"*".repeat(t)}`}function hN(e){let t=e;return typeof t.setRawMode=="function"&&typeof t.on=="function"&&typeof t.off=="function"}function BC(e=process.stdin,t=process.stdout,n=mN){return async r=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive secret prompt is not available in this environment.");return hN(e)?await yN(e,t,r):await wN(e,t,r,n)}}function yN(e,t,n){return new Promise((r,i)=>{let o=e.isRaw===!0,s="",a=!1,l=u=>{a||(a=!0,e.off("data",c),e.setRawMode(o),e.pause?.(),t.write(`
|
|
161
|
+
`),u())},c=u=>{let d=typeof u=="string"?u:u.toString("utf8");for(let p of d){if(p==="\r"||p===`
|
|
162
|
+
`){l(()=>r(s.trim()));return}if(p===""){l(()=>i(new Error("Interactive secret prompt cancelled.")));return}let m=[...s].length;s=p==="\b"||p==="\x7F"?[...s].slice(0,-1).join(""):s+p,t.write(FC(n,[...s].length,t.columns,m))}};t.write(n),e.resume?.(),e.on("data",c),e.setRawMode(!0)})}async function wN(e,t,n,r){let i=r({input:e,output:t,terminal:!0}),o=0;i._writeToOutput=s=>{if(s==="\r"||s===`
|
|
163
|
+
`||s===`\r
|
|
164
|
+
`)return;let a=[...i.line??""].length;t.write(FC(n,a,t.columns,o)),o=a};try{t.write(n);let s=await i.question("");return t.write(`
|
|
165
|
+
`),s.trim()}finally{i.close()}}import{hostname as yK}from"node:os";function lg(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=lg(r);n==="trust"&&delete i.score,t[n]=i}}return t}import{spawn as G0}from"node:child_process";import{createHash as me,createPublicKey as z0,randomBytes as ke}from"node:crypto";import{constants as SE}from"node:fs";import{access as K0,appendFile as wK,chmod as vK,lstat as Ml,mkdir as Ti,open as $i,readdir as $oe,readFile as on,realpath as Sl,rename as Li,rm as Ae,stat as Bi,writeFile as Jw}from"node:fs/promises";import{basename as $e,dirname as ye,join as z,posix as ct,relative as df,resolve as Gn,win32 as je}from"node:path";import{createInterface as bK}from"node:readline/promises";import{posix as vN,win32 as MC}from"node:path";import{accessSync as jC,constants as cg,lstatSync as bN,realpathSync as NC,statSync as _N}from"node:fs";function UC(e,t,n=t==="darwin"?["/opt/homebrew/bin/node","/usr/local/bin/node"]:["/usr/local/bin/node","/usr/bin/node"]){if(t==="win32")return e;let r;try{r=NC(e)}catch{return e}for(let i of n)try{if(bN(i).isSymbolicLink()&&NC(i)===r)return jC(i,cg.X_OK),i}catch{}return e}function ug(e){let t=/^runtime='(.*)'$/mu.exec(e);if(t)return t[1].replaceAll("'\\''","'");let n=/^\$runtime = '(.*)'$/mu.exec(e);return n?n[1].replaceAll("''","'"):null}function qC(e,t){let n=ug(e);if(!n||!(t==="win32"?MC:vN).isAbsolute(n))return!1;try{return jC(n,t==="win32"?cg.F_OK:cg.X_OK),_N(n).isFile()}catch{return!1}}function VC(e,t){return t==="win32"?`$runtime = '${e.replaceAll("'","''")}'
|
|
166
|
+
if (-not (Test-Path -LiteralPath $runtime -PathType Leaf)) {
|
|
167
|
+
$node = Get-Command node.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
|
168
|
+
if (-not $node) { [Console]::Error.WriteLine('mcp_runtime_missing'); exit 127 }
|
|
169
|
+
$runtime = $node.Source
|
|
170
|
+
}
|
|
171
|
+
& $runtime @args
|
|
172
|
+
exit $LASTEXITCODE
|
|
173
|
+
`:`#!/bin/sh
|
|
174
|
+
runtime=${"'"+e.replaceAll("'","'\\''")+"'"}
|
|
175
|
+
if [ ! -x "$runtime" ]; then
|
|
176
|
+
runtime=$(command -v node) || { echo mcp_runtime_missing >&2; exit 127; }
|
|
177
|
+
fi
|
|
178
|
+
exec "$runtime" "$@"
|
|
179
|
+
`}function ku(e,t){return e.endsWith("\\node.ps1")?{command:MC.join(process.env.SystemRoot??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"),args:["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",e,...t]}:{command:e,args:t}}import{lstat as dg,mkdir as kN,rm as SN}from"node:fs/promises";import{lstatSync as CN}from"node:fs";import{tmpdir as GC}from"node:os";import{dirname as AN,posix as aa}from"node:path";function zC(e,t,n,r,i){if(n==="win32")return`\\\\.\\pipe\\skills-layer-mcp-${t}`;let o=aa.join(e,"run");if(r.XDG_RUNTIME_DIR&&aa.isAbsolute(r.XDG_RUNTIME_DIR))try{let l=CN(r.XDG_RUNTIME_DIR);l.isDirectory()&&!l.isSymbolicLink()&&l.uid===i&&(l.mode&511)===448&&(o=r.XDG_RUNTIME_DIR)}catch{}let s=aa.join(o,`sl-${t}.sock`);if(Buffer.byteLength(s)<104)return s;let a=aa.join(GC(),`sl-mcp-${i}`,`sl-${t}.sock`);return Buffer.byteLength(a)<104?a:aa.join(GC(),`sl-mcp-${i}`,`sl-${t.slice(0,16)}.sock`)}async function Su(e,t=process.getuid?.()){if(e.startsWith("\\\\.\\pipe\\"))return;let n=AN(e);await kN(n,{recursive:!0,mode:448});let r=await dg(n);if(r.isSymbolicLink()||!r.isDirectory()||r.uid!==t||(r.mode&511)!==448)throw new Error("mcp_socket_directory_unsafe: MCP requires a user-owned, non-symlink directory with mode 0700.");try{let i=await dg(e);if(i.isSymbolicLink()||!i.isSocket()||i.uid!==t)throw new Error("mcp_socket_path_unsafe: Refusing the existing MCP socket path.")}catch(i){if(i.code!=="ENOENT")throw i}}async function fg(e,t=process.getuid?.()){if(!e.startsWith("\\\\.\\pipe\\"))try{let n=await dg(e);if(n.isSymbolicLink()||!n.isSocket()||n.uid!==t)return"mcp_legacy_socket_skipped: Untrusted legacy socket was left untouched.";await SN(e)}catch(n){if(n.code!=="ENOENT")return"mcp_legacy_socket_skipped: Legacy socket cleanup was unavailable."}}var pg=String.raw`async function assertPrivateMcpSocket(socketPath, uid = process.getuid?.()) {
|
|
180
|
+
if (socketPath.startsWith("\\\\.\\pipe\\")) return;
|
|
181
|
+
const directory = dirname(socketPath);
|
|
182
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
183
|
+
const info = await lstat(directory);
|
|
184
|
+
if (info.isSymbolicLink() || !info.isDirectory() || info.uid !== uid || (info.mode & 0o777) !== 0o700) {
|
|
185
|
+
throw new Error("mcp_socket_directory_unsafe: MCP requires a user-owned, non-symlink directory with mode 0700.");
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
const socket = await lstat(socketPath);
|
|
189
|
+
if (socket.isSymbolicLink() || !socket.isSocket() || socket.uid !== uid) throw new Error("mcp_socket_path_unsafe: Refusing the existing MCP socket path.");
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (error.code !== "ENOENT") throw error;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
`;var xN=String.raw`
|
|
195
|
+
$ErrorActionPreference = 'Stop'
|
|
196
|
+
[Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
197
|
+
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
198
|
+
try {
|
|
199
|
+
Add-Type -TypeDefinition @'
|
|
200
|
+
using System;
|
|
201
|
+
using System.Runtime.InteropServices;
|
|
202
|
+
public static class SkillsLayerCredentials {
|
|
203
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
204
|
+
public struct Credential {
|
|
205
|
+
public UInt32 Flags; public UInt32 Type; public string TargetName; public string Comment;
|
|
206
|
+
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
|
|
207
|
+
public UInt32 CredentialBlobSize; public IntPtr CredentialBlob; public UInt32 Persist;
|
|
208
|
+
public UInt32 AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName;
|
|
209
|
+
}
|
|
210
|
+
[DllImport("advapi32.dll", EntryPoint="CredWriteW", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
211
|
+
public static extern bool Write(ref Credential credential, UInt32 flags);
|
|
212
|
+
[DllImport("advapi32.dll", EntryPoint="CredReadW", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
213
|
+
public static extern bool Read(string target, UInt32 type, UInt32 flags, out IntPtr credential);
|
|
214
|
+
[DllImport("advapi32.dll", EntryPoint="CredDeleteW", CharSet=CharSet.Unicode, SetLastError=true)]
|
|
215
|
+
public static extern bool Delete(string target, UInt32 type, UInt32 flags);
|
|
216
|
+
[DllImport("advapi32.dll", SetLastError=true)] public static extern void CredFree(IntPtr buffer);
|
|
217
|
+
}
|
|
218
|
+
'@
|
|
219
|
+
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
220
|
+
$target = 'SkillsLayer:' + $request.service + ':' + $request.account
|
|
221
|
+
if ($request.operation -eq 'set') {
|
|
222
|
+
$bytes = [Text.Encoding]::UTF8.GetBytes([string]$request.secret)
|
|
223
|
+
if ($bytes.Length -gt 2560) { exit 1 }
|
|
224
|
+
$buffer = [Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length)
|
|
225
|
+
try {
|
|
226
|
+
[Runtime.InteropServices.Marshal]::Copy($bytes, 0, $buffer, $bytes.Length)
|
|
227
|
+
$credential = New-Object SkillsLayerCredentials+Credential
|
|
228
|
+
$credential.Type = 1; $credential.TargetName = $target; $credential.UserName = $request.account
|
|
229
|
+
$credential.CredentialBlobSize = $bytes.Length; $credential.CredentialBlob = $buffer; $credential.Persist = 2
|
|
230
|
+
if (-not [SkillsLayerCredentials]::Write([ref]$credential, 0)) { exit 1 }
|
|
231
|
+
} finally {
|
|
232
|
+
[Array]::Clear($bytes, 0, $bytes.Length)
|
|
233
|
+
[Runtime.InteropServices.Marshal]::Copy($bytes, 0, $buffer, $bytes.Length)
|
|
234
|
+
[Runtime.InteropServices.Marshal]::FreeHGlobal($buffer)
|
|
235
|
+
}
|
|
236
|
+
} elseif ($request.operation -eq 'get') {
|
|
237
|
+
$pointer = [IntPtr]::Zero
|
|
238
|
+
if (-not [SkillsLayerCredentials]::Read($target, 1, 0, [ref]$pointer)) {
|
|
239
|
+
if ([Runtime.InteropServices.Marshal]::GetLastWin32Error() -eq 1168) { exit 44 }
|
|
240
|
+
exit 1
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
$credential = [Runtime.InteropServices.Marshal]::PtrToStructure($pointer, [type][SkillsLayerCredentials+Credential])
|
|
244
|
+
$bytes = New-Object byte[] $credential.CredentialBlobSize
|
|
245
|
+
[Runtime.InteropServices.Marshal]::Copy($credential.CredentialBlob, $bytes, 0, $bytes.Length)
|
|
246
|
+
[Console]::Out.Write([Text.Encoding]::UTF8.GetString($bytes))
|
|
247
|
+
[Array]::Clear($bytes, 0, $bytes.Length)
|
|
248
|
+
} finally { [SkillsLayerCredentials]::CredFree($pointer) }
|
|
249
|
+
} elseif ($request.operation -eq 'delete') {
|
|
250
|
+
if (-not [SkillsLayerCredentials]::Delete($target, 1, 0)) {
|
|
251
|
+
if ([Runtime.InteropServices.Marshal]::GetLastWin32Error() -ne 1168) { exit 1 }
|
|
252
|
+
}
|
|
253
|
+
} else { exit 1 }
|
|
254
|
+
exit 0
|
|
255
|
+
} catch { exit 1 }
|
|
256
|
+
`,mg=["-NoLogo","-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(xN,"utf16le").toString("base64")];function KC(e=gc){async function t(n,r,i,o){try{let s=await e("powershell.exe",mg,JSON.stringify({operation:n,service:r,account:i,secret:o}));if(n==="get"&&s.code===44)return null;if(s.code!==0)throw new Error;return s.stdout||null}catch{throw new Error("mcp_secure_storage_required: Enable Windows PowerShell and unlock Credential Manager in your signed-in Windows session. No file fallback is available.")}}return{kind:"windows_credential_manager",set:async(n,r,i)=>{await t("set",n,r,i)},get:(n,r)=>t("get",n,r),delete:async(n,r)=>{await t("delete",n,r)}}}import{spawn as IN}from"node:child_process";import{existsSync as RN,readFileSync as PN}from"node:fs";import{createHash as XC}from"node:crypto";import{chmod as Cu,lstat as yg,mkdir as QC,open as EN,readFile as wg,rename as DN,rm as fo,writeFile as ca}from"node:fs/promises";import{dirname as hg,posix as TN,win32 as $N}from"node:path";var vg="skills-layer-local-broker";function LN(e){return`broker_${XC("sha256").update(`skills-layer-mcp-broker-v1\0${e}`).digest("hex").slice(0,32)}`}var HC=3e4,gt="skills-layer",ON="2025-06-18",FN=["mcp","skills-layer-mcp-proxy.mjs"],BN=["mcp","skills-layer-mcp-broker.mjs"],NN=["mcp","skills-layer-mcp-broker.lock"],MN=new Set(["universal"]);function mo(e){let t=mb(e.now),n=e.platform??process.platform,r=e.cwd??process.cwd(),i=yb({env:e.env,platform:n});RN(i)&&t.warnings.push(`mcp_legacy_cline_config: Legacy Cline configuration remains at ${i}. Review it for duplicate Skills Layer registrations; setup writes the VS Code Cline configuration and leaves the old file untouched.`);let o=e.stateDir??JN(e.env,n),s=e.mcpConfigPath??la(n,o,"mcp.json"),a=la(n,o,...FN),l=la(n,o,...BN),c=cr(s).slice(0,32),u=zC(o,c,n,e.env??{},process.getuid?.()??0),d=la(n,o,...NN),p=la(n,o,"mcp",n==="win32"?"node.ps1":"node"),m=e.nodePath&&e.nodePath!==process.execPath?e.nodePath:p,g=m===p?VC(UC(process.execPath,n),n):void 0,h=eA({mcpConfigPath:s}),y=(e.brokerSourceBuilder??tA)({mcpConfigPath:s,socketPath:u,lockPath:d}),w=cr(h),b=cr(y),_=new Set(Vf.map(C=>C.id)),x=[...Vf.map(C=>C.id),...Kn.filter(C=>!_.has(C))].map(C=>{if(_.has(C)){let D=pb(C),T=D.resolveConfigPath({env:e.env,platform:n,cwd:r});return jN({agentId:C,warnings:t.warnings,launcherSource:g,displayName:D.displayName,configPath:T,configKind:D.configKind,bridgePath:a,brokerPath:l,brokerSocketPath:u,brokerLockPath:d,mcpConfigPath:s,nodePath:m,bridgeChecksum:w,brokerChecksum:b,brokerSourceBuilder:e.brokerSourceBuilder})}return MN.has(C)?YC({agentId:C,displayName:C,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 ${C} with \`skills-layer install <skill> --agent ${C}\`.`,"MCP auto-install is not claimed for this agent yet."]}):YC({agentId:C,displayName:C,tier:"tier_2",status:"manual_handoff",verification:"manual",reason:"MCP support or the safe writable global config shape has not been verified yet.",instructions:[`Add a local stdio MCP server named ${gt}.`,`Command: ${m}`,`Args: ${a}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{...t,status:"mcp_registration_plan",serverName:gt,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:a,brokerPath:l,brokerSocketPath:u,brokerLockPath:d,nodePath:m,mcpConfigPath:s,bridgeChecksum:w,brokerChecksum:b,automaticCount:x.filter(C=>C.status==="automatic").length,manualCount:x.filter(C=>C.status==="manual_handoff").length,skillsOnlyCount:x.filter(C=>C.status==="skills_only").length,unsupportedCount:x.filter(C=>C.status==="unsupported").length,targets:x}}async function ri(e){let t=mo(e),n=YN(e.clientId),r=t.targets.find(w=>w.agentId===n),i=e.mcpConfig??await fa(t.mcpConfigPath,{allowMissing:!0});if(!i)return JC({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 ni(t.bridgePath),s=o!==null,a=o!==null&&cr(o)===t.bridgeChecksum,l=await ni(t.brokerPath),c=l!==null,u=l===null?null:cr(l),d=u===t.brokerChecksum,p=ZN(i,r.agentId),m=Ye(p,"token"),g=Ye(p,"tokenRef"),h=await zN(r,m),y=JC({plan:t,target:r,mcpConfig:i,tokenConfig:p,tokenPresent:!!m,tokenRefPresent:!!g,bridgeExists:s,checksumMatches:a,brokerExists:c,brokerChecksumMatches:d,brokerInstalledChecksum:u,targetConfigured:h.configured,rawTokenLeaked:h.rawTokenLeaked});if(/[/\\]mcp[/\\]node(?:\.ps1)?$/u.test(t.nodePath)){let w=await ni(t.nodePath),b=w===null?"mcp_runtime_missing":qC(w,e.platform??process.platform)?null:"mcp_runtime_recorded_missing";if(b)return{...y,status:"mcp_needs_repair",configured:!1,reasonCode:b,nextCommand:`skills-layer mcp repair --client ${n}`}}return y}function eA(e){return`#!/usr/bin/env node
|
|
257
|
+
import { spawn } from "node:child_process";
|
|
258
|
+
import { existsSync } from "node:fs";
|
|
259
|
+
import { randomBytes } from "node:crypto";
|
|
260
|
+
import { createConnection } from "node:net";
|
|
261
|
+
import { createInterface } from "node:readline";
|
|
262
|
+
import { readFile, lstat, mkdir } from "node:fs/promises";
|
|
263
|
+
import { dirname } from "node:path";
|
|
264
|
+
${pg}
|
|
265
|
+
|
|
266
|
+
if (process.env.SKILLS_LAYER_MCP_RUNTIME_PROBE === "1") process.stderr.write("skills_layer_runtime=" + process.execPath + "\\n");
|
|
267
|
+
const CONFIG_PATH = ${JSON.stringify(e.mcpConfigPath)};
|
|
268
|
+
const BROKER_PROTOCOL_VERSION = "1";
|
|
269
|
+
const MAX_IPC_BYTES = 1024 * 1024;
|
|
270
|
+
// RT-04: the broker accepts remote responses up to 4 MiB; its reply line adds a
|
|
271
|
+
// small envelope, so the bridge must read at least that much back.
|
|
272
|
+
const MAX_IPC_RESPONSE_BYTES = 4 * 1024 * 1024 + 64 * 1024;
|
|
273
|
+
const BROKER_CONNECT_TIMEOUT_MS = 6000;
|
|
274
|
+
const BROKER_START_RETRY_MS = 250;
|
|
275
|
+
const BROKER_REQUEST_TIMEOUT_MS = 35000;
|
|
276
|
+
const LOCAL_CLIENT_SESSION_ID = "mcp_session_" + randomBytes(16).toString("hex");
|
|
277
|
+
|
|
278
|
+
function writeMessage(message) {
|
|
279
|
+
process.stdout.write(JSON.stringify(message) + "\\n");
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function errorResponse(id, code, message, data = {}) {
|
|
283
|
+
return { jsonrpc: "2.0", id: id ?? null, error: { code, message, data } };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async function readConfig() {
|
|
287
|
+
const parsed = JSON.parse(await readFile(CONFIG_PATH, "utf8"));
|
|
288
|
+
if (!parsed || typeof parsed !== "object") {
|
|
289
|
+
throw new Error("Skills Layer MCP config is not an object.");
|
|
290
|
+
}
|
|
291
|
+
if (!parsed.brokerSocketPath || typeof parsed.brokerSocketPath !== "string") {
|
|
292
|
+
throw new Error("Skills Layer MCP broker socket is missing. Run skills-layer mcp repair.");
|
|
293
|
+
}
|
|
294
|
+
if (!parsed.brokerPath || typeof parsed.brokerPath !== "string") {
|
|
295
|
+
throw new Error("Skills Layer MCP broker is missing. Run skills-layer mcp repair.");
|
|
296
|
+
}
|
|
297
|
+
return parsed;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function requestedClientId(config) {
|
|
301
|
+
const index = process.argv.indexOf("--client");
|
|
302
|
+
if (index >= 0 && typeof process.argv[index + 1] === "string" && process.argv[index + 1].trim()) {
|
|
303
|
+
return process.argv[index + 1].trim();
|
|
304
|
+
}
|
|
305
|
+
if (typeof config.clientId === "string" && config.clientId.trim()) return config.clientId.trim();
|
|
306
|
+
if (Array.isArray(config.clientIds) && config.clientIds.length === 1 && typeof config.clientIds[0] === "string") {
|
|
307
|
+
return config.clientIds[0];
|
|
308
|
+
}
|
|
309
|
+
throw new Error("mcp_client_required");
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function requestBroker(config, payload) {
|
|
313
|
+
return new Promise((resolve, reject) => {
|
|
314
|
+
const socket = createConnection(config.brokerSocketPath);
|
|
315
|
+
let buffer = "";
|
|
316
|
+
let settled = false;
|
|
317
|
+
const finish = (callback) => {
|
|
318
|
+
if (settled) return;
|
|
319
|
+
settled = true;
|
|
320
|
+
clearTimeout(timeout);
|
|
321
|
+
callback();
|
|
322
|
+
};
|
|
323
|
+
const timeout = setTimeout(() => {
|
|
324
|
+
socket.destroy();
|
|
325
|
+
finish(() => reject(new Error("Skills Layer MCP broker timed out.")));
|
|
326
|
+
}, BROKER_REQUEST_TIMEOUT_MS);
|
|
327
|
+
socket.setEncoding("utf8");
|
|
328
|
+
socket.on("connect", () => {
|
|
329
|
+
const request = JSON.stringify({
|
|
330
|
+
type: "mcp_forward",
|
|
331
|
+
protocolVersion: BROKER_PROTOCOL_VERSION,
|
|
332
|
+
clientId: requestedClientId(config),
|
|
333
|
+
localClientSessionId: LOCAL_CLIENT_SESSION_ID,
|
|
334
|
+
payload
|
|
335
|
+
});
|
|
336
|
+
if (Buffer.byteLength(request, "utf8") > MAX_IPC_BYTES) {
|
|
337
|
+
socket.destroy();
|
|
338
|
+
finish(() => reject(new Error("Skills Layer MCP request exceeds the local IPC limit.")));
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
socket.write(request + "\\n");
|
|
342
|
+
});
|
|
343
|
+
socket.on("data", (chunk) => {
|
|
344
|
+
buffer += chunk;
|
|
345
|
+
if (Buffer.byteLength(buffer, "utf8") > MAX_IPC_RESPONSE_BYTES) {
|
|
346
|
+
socket.destroy();
|
|
347
|
+
finish(() => reject(new Error("Skills Layer MCP broker response exceeds the local IPC limit.")));
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
const newlineIndex = buffer.indexOf("\\n");
|
|
351
|
+
if (newlineIndex < 0) {
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const line = buffer.slice(0, newlineIndex);
|
|
355
|
+
socket.end();
|
|
356
|
+
try {
|
|
357
|
+
const parsed = JSON.parse(line);
|
|
358
|
+
if (parsed && parsed.ok && Object.hasOwn(parsed, "response")) {
|
|
359
|
+
finish(() => resolve(parsed.response));
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
finish(() => reject(new Error(parsed && typeof parsed.error === "string" ? parsed.error : "Skills Layer MCP broker rejected the request.")));
|
|
363
|
+
} catch (error) {
|
|
364
|
+
finish(() => reject(error));
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
socket.on("error", (cause) => {
|
|
368
|
+
const error = new Error("Skills Layer MCP broker is not available.");
|
|
369
|
+
error.code = cause && typeof cause === "object" && "code" in cause ? cause.code : "broker_unavailable";
|
|
370
|
+
finish(() => reject(error));
|
|
371
|
+
});
|
|
372
|
+
socket.on("end", () => {
|
|
373
|
+
if (!buffer.trim()) {
|
|
374
|
+
finish(() => reject(new Error("Skills Layer MCP broker closed before returning a response.")));
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function delay(ms) {
|
|
381
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async function ensureBrokerRunning(config, payload) {
|
|
385
|
+
await assertPrivateMcpSocket(config.brokerSocketPath);
|
|
386
|
+
try {
|
|
387
|
+
return await requestBroker(config, payload);
|
|
388
|
+
} catch (firstError) {
|
|
389
|
+
const deadline = Date.now() + BROKER_CONNECT_TIMEOUT_MS;
|
|
390
|
+
let lastError = firstError;
|
|
391
|
+
let nextStartAt = 0;
|
|
392
|
+
while (Date.now() < deadline) {
|
|
393
|
+
if (Date.now() >= nextStartAt) {
|
|
394
|
+
try {
|
|
395
|
+
const child = spawn(process.execPath, [config.brokerPath], {
|
|
396
|
+
detached: true,
|
|
397
|
+
stdio: "ignore"
|
|
398
|
+
});
|
|
399
|
+
child.unref();
|
|
400
|
+
} catch (error) {
|
|
401
|
+
lastError = error;
|
|
402
|
+
}
|
|
403
|
+
nextStartAt = Date.now() + BROKER_START_RETRY_MS;
|
|
404
|
+
}
|
|
405
|
+
await delay(50);
|
|
406
|
+
try {
|
|
407
|
+
return await requestBroker(config, payload);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
lastError = error;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
throw lastError;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function forward(payload) {
|
|
417
|
+
return await ensureBrokerRunning(await readConfig(), payload);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
421
|
+
for await (const line of rl) {
|
|
422
|
+
const trimmed = line.trim();
|
|
423
|
+
if (!trimmed) {
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
// RT-04: an error answers the request it belongs to, so the client never hangs.
|
|
427
|
+
let requestId = null;
|
|
428
|
+
try {
|
|
429
|
+
if (Buffer.byteLength(trimmed, "utf8") > MAX_IPC_BYTES) {
|
|
430
|
+
throw new Error("Skills Layer MCP request exceeds the local IPC limit.");
|
|
431
|
+
}
|
|
432
|
+
const payload = JSON.parse(trimmed);
|
|
433
|
+
if (payload && typeof payload === "object" && (typeof payload.id === "string" || typeof payload.id === "number")) requestId = payload.id;
|
|
434
|
+
const result = await forward(payload);
|
|
435
|
+
if (result) {
|
|
436
|
+
writeMessage(result);
|
|
437
|
+
}
|
|
438
|
+
} catch (error) {
|
|
439
|
+
writeMessage(errorResponse(requestId, -32603, error instanceof Error ? error.message : "Skills Layer MCP bridge failed."));
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
`}function tA(e){return`#!/usr/bin/env node
|
|
443
|
+
import { execFile, spawnSync } from "node:child_process";
|
|
444
|
+
import { createHash } from "node:crypto";
|
|
445
|
+
import { createServer } from "node:net";
|
|
446
|
+
import { chmod, open, readFile, rm, stat, lstat, mkdir } from "node:fs/promises";
|
|
447
|
+
import { dirname } from "node:path";
|
|
448
|
+
${pg}
|
|
449
|
+
import { promisify } from "node:util";
|
|
450
|
+
|
|
451
|
+
const execFileAsync = promisify(execFile);
|
|
452
|
+
const CONFIG_PATH = ${JSON.stringify(e.mcpConfigPath)};
|
|
453
|
+
const DEFAULT_BROKER_INSTALLATION_ID = ${JSON.stringify(LN(e.mcpConfigPath))};
|
|
454
|
+
const SOCKET_PATH = ${JSON.stringify(e.socketPath)};
|
|
455
|
+
const LOCK_PATH = ${JSON.stringify(e.lockPath??`${e.socketPath}.lock`)};
|
|
456
|
+
const SOCKET_IS_NAMED_PIPE = process.platform === "win32";
|
|
457
|
+
await assertPrivateMcpSocket(SOCKET_PATH);
|
|
458
|
+
if (!SOCKET_IS_NAMED_PIPE) process.umask(0o077);
|
|
459
|
+
const BROKER_PROTOCOL_VERSION = "1";
|
|
460
|
+
const MCP_PROTOCOL_VERSION = ${JSON.stringify(ON)};
|
|
461
|
+
const MAX_IPC_BYTES = 1024 * 1024;
|
|
462
|
+
const MAX_REMOTE_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
463
|
+
const MAX_CONCURRENT_REQUESTS = 16;
|
|
464
|
+
const REMOTE_REQUEST_TIMEOUT_MS = 30000;
|
|
465
|
+
const IDLE_SHUTDOWN_MS = 15000;
|
|
466
|
+
const LOCK_STARTUP_GRACE_MS = 1200;
|
|
467
|
+
const APPROVED_CLOUD_MCP_ENDPOINTS = new Set(${JSON.stringify(o_)});
|
|
468
|
+
let activeRequests = 0;
|
|
469
|
+
let idleTimer = null;
|
|
470
|
+
let lockHandle = null;
|
|
471
|
+
|
|
472
|
+
async function readConfig() {
|
|
473
|
+
const parsed = JSON.parse(await readFile(CONFIG_PATH, "utf8"));
|
|
474
|
+
if (!parsed || typeof parsed !== "object") {
|
|
475
|
+
throw new Error("Skills Layer MCP config is not an object.");
|
|
476
|
+
}
|
|
477
|
+
return parsed;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function selectClientConfig(config, requestedClientId) {
|
|
481
|
+
const clientId = typeof requestedClientId === "string" && requestedClientId.trim()
|
|
482
|
+
? requestedClientId.trim()
|
|
483
|
+
: typeof config.clientId === "string" && config.clientId.trim()
|
|
484
|
+
? config.clientId.trim()
|
|
485
|
+
: Array.isArray(config.clientIds) && config.clientIds.length === 1 && typeof config.clientIds[0] === "string"
|
|
486
|
+
? config.clientIds[0]
|
|
487
|
+
: null;
|
|
488
|
+
if (!clientId) throw new Error("mcp_client_required");
|
|
489
|
+
if (Array.isArray(config.clientIds) && !config.clientIds.includes(clientId)) {
|
|
490
|
+
throw new Error("mcp_client_not_configured");
|
|
491
|
+
}
|
|
492
|
+
const tokenConfig = config.tokens && typeof config.tokens === "object" && config.tokens[clientId] && typeof config.tokens[clientId] === "object"
|
|
493
|
+
? config.tokens[clientId]
|
|
494
|
+
: config;
|
|
495
|
+
return { ...config, ...tokenConfig, clientId };
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function brokerInstallationId(config) {
|
|
499
|
+
if (typeof config.brokerInstallationId === "string" && /^broker_[A-Za-z0-9_-]{16,80}$/u.test(config.brokerInstallationId)) {
|
|
500
|
+
return config.brokerInstallationId;
|
|
501
|
+
}
|
|
502
|
+
return DEFAULT_BROKER_INSTALLATION_ID;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
async function readKeychainSecret(service, account) {
|
|
506
|
+
try {
|
|
507
|
+
const { stdout } = await execFileAsync("/usr/bin/security", ["find-generic-password", "-a", account, "-s", service, "-w"]);
|
|
508
|
+
const secret = stdout.trim();
|
|
509
|
+
return secret.length > 0 ? secret : null;
|
|
510
|
+
} catch {
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
async function resolveToken(config) {
|
|
516
|
+
if (typeof config.token === "string" && config.token.length > 0) {
|
|
517
|
+
return config.token;
|
|
518
|
+
}
|
|
519
|
+
if (["linux_secret_service", "windows_credential_manager"].includes(config.credentialStorage) && typeof config.tokenRef === "string") {
|
|
520
|
+
const service = config.credentialService || "Skills Layer CLI";
|
|
521
|
+
const windows = config.credentialStorage === "windows_credential_manager";
|
|
522
|
+
const result = spawnSync(windows ? "powershell.exe" : "secret-tool", windows ? ${JSON.stringify(mg)} : ["lookup", "service", service, "account", config.tokenRef], {
|
|
523
|
+
input: windows ? JSON.stringify({ operation: "get", service, account: config.tokenRef }) : "",
|
|
524
|
+
encoding: "utf8", timeout: 10000, maxBuffer: 65536, windowsHide: true, stdio: ["pipe", "pipe", "ignore"]
|
|
525
|
+
});
|
|
526
|
+
if (!result.error && result.status === 0 && result.stdout) return result.stdout;
|
|
527
|
+
throw new Error("mcp_secure_storage_required: Unlock the OS credential store and run skills-layer mcp repair.");
|
|
528
|
+
}
|
|
529
|
+
if (config.credentialStorage === "macos_keychain" && typeof config.tokenRef === "string" && config.tokenRef.length > 0) {
|
|
530
|
+
const secret = await readKeychainSecret(config.credentialService || "Skills Layer CLI", config.tokenRef);
|
|
531
|
+
if (secret) {
|
|
532
|
+
return secret;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
throw new Error("Skills Layer MCP token is unavailable. Run skills-layer mcp repair from Terminal.");
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function assertExactMcpEndpoint(config) {
|
|
539
|
+
if (typeof config.mcpUrl !== "string" || typeof config.baseUrl !== "string") {
|
|
540
|
+
throw new Error("Skills Layer MCP endpoint configuration is incomplete. Run skills-layer mcp repair.");
|
|
541
|
+
}
|
|
542
|
+
const url = new URL(config.mcpUrl);
|
|
543
|
+
const base = new URL(config.baseUrl);
|
|
544
|
+
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
|
545
|
+
if (url.protocol !== "https:" && !(loopback && url.protocol === "http:")) {
|
|
546
|
+
throw new Error("Skills Layer MCP endpoint must use HTTPS (except loopback development).");
|
|
547
|
+
}
|
|
548
|
+
if (url.origin !== base.origin || url.pathname !== "/mcp" || url.search || url.hash || url.username || url.password) {
|
|
549
|
+
throw new Error("Skills Layer MCP endpoint does not exactly match the configured API origin and /mcp path.");
|
|
550
|
+
}
|
|
551
|
+
const exact = url.origin + "/mcp";
|
|
552
|
+
const approvedCloud = APPROVED_CLOUD_MCP_ENDPOINTS.has(exact);
|
|
553
|
+
const secureCustom = url.protocol === "https:" && config.allowCustomMcpOrigin === true;
|
|
554
|
+
if (!approvedCloud && !loopback && !secureCustom) {
|
|
555
|
+
throw new Error("Skills Layer MCP endpoint is not an approved Cloud origin. Run skills-layer mcp repair.");
|
|
556
|
+
}
|
|
557
|
+
return exact;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function parseMcpHttpResponse(text) {
|
|
561
|
+
if (!text.trim()) return null;
|
|
562
|
+
if (!text.trimStart().startsWith("data:")) return JSON.parse(text);
|
|
563
|
+
const dataLine = text.split(/\\r?\\n/u).find((line) => line.startsWith("data:"));
|
|
564
|
+
if (!dataLine) return null;
|
|
565
|
+
const data = dataLine.slice("data:".length).trim();
|
|
566
|
+
return data ? JSON.parse(data) : null;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function parseRemoteErrorResponse(text, payload, status, retryAfterHeader) {
|
|
570
|
+
const retryAfterSeconds = Number.parseInt(retryAfterHeader || "", 10);
|
|
571
|
+
try {
|
|
572
|
+
const parsed = JSON.parse(text);
|
|
573
|
+
if (parsed && parsed.jsonrpc === "2.0" && parsed.error && typeof parsed.error === "object") {
|
|
574
|
+
const remoteData = parsed.error.data && typeof parsed.error.data === "object" ? parsed.error.data : {};
|
|
575
|
+
const data = { status };
|
|
576
|
+
for (const key of ["requestId", "reasonCode", "retryAfterSeconds", "nextAction", "nextStep"]) {
|
|
577
|
+
const value = remoteData[key];
|
|
578
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") data[key] = value;
|
|
579
|
+
}
|
|
580
|
+
if (!Object.hasOwn(data, "retryAfterSeconds") && Number.isFinite(retryAfterSeconds)) {
|
|
581
|
+
data.retryAfterSeconds = Math.max(1, retryAfterSeconds);
|
|
582
|
+
}
|
|
583
|
+
const remoteMessage = typeof parsed.error.message === "string"
|
|
584
|
+
? parsed.error.message.replace(/[\\u0000-\\u001f\\u007f]/gu, " ").trim().slice(0, 500)
|
|
585
|
+
: "";
|
|
586
|
+
return {
|
|
587
|
+
jsonrpc: "2.0",
|
|
588
|
+
id: payload && Object.hasOwn(payload, "id") ? payload.id : null,
|
|
589
|
+
error: {
|
|
590
|
+
code: typeof parsed.error.code === "number" ? parsed.error.code : -32000,
|
|
591
|
+
message: remoteMessage || "Skills Layer MCP request failed with HTTP " + status + ".",
|
|
592
|
+
data
|
|
593
|
+
}
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
} catch {
|
|
597
|
+
// Non-JSON upstream errors are projected to a bounded generic MCP error.
|
|
598
|
+
}
|
|
599
|
+
return {
|
|
600
|
+
jsonrpc: "2.0",
|
|
601
|
+
id: payload && Object.hasOwn(payload, "id") ? payload.id : null,
|
|
602
|
+
error: {
|
|
603
|
+
code: status === 429 ? -32029 : -32000,
|
|
604
|
+
message: "Skills Layer MCP request failed with HTTP " + status + ".",
|
|
605
|
+
data: {
|
|
606
|
+
status,
|
|
607
|
+
...(Number.isFinite(retryAfterSeconds) ? { retryAfterSeconds: Math.max(1, retryAfterSeconds) } : {})
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
async function forwardMcp(config, payload, localClientSessionId) {
|
|
614
|
+
const token = await resolveToken(config);
|
|
615
|
+
const mcpUrl = assertExactMcpEndpoint(config);
|
|
616
|
+
const controller = new AbortController();
|
|
617
|
+
const timeout = setTimeout(() => controller.abort(), REMOTE_REQUEST_TIMEOUT_MS);
|
|
618
|
+
try {
|
|
619
|
+
const response = await fetch(mcpUrl, {
|
|
620
|
+
method: "POST",
|
|
621
|
+
redirect: "error",
|
|
622
|
+
signal: controller.signal,
|
|
623
|
+
headers: {
|
|
624
|
+
accept: "application/json, text/event-stream",
|
|
625
|
+
"content-type": "application/json",
|
|
626
|
+
"mcp-protocol-version": MCP_PROTOCOL_VERSION,
|
|
627
|
+
"x-skills-layer-client": config.clientId,
|
|
628
|
+
"x-skills-layer-mcp-client": config.clientId,
|
|
629
|
+
"x-skills-layer-mcp-broker": brokerInstallationId(config),
|
|
630
|
+
"x-skills-layer-mcp-session": localClientSessionId,
|
|
631
|
+
authorization: \`Bearer \${token}\`
|
|
632
|
+
},
|
|
633
|
+
body: JSON.stringify(payload)
|
|
634
|
+
});
|
|
635
|
+
const declaredLength = Number(response.headers.get("content-length") || "0");
|
|
636
|
+
if (declaredLength > MAX_REMOTE_RESPONSE_BYTES) {
|
|
637
|
+
throw new Error("Skills Layer MCP response exceeds the broker limit.");
|
|
638
|
+
}
|
|
639
|
+
const text = await response.text();
|
|
640
|
+
if (Buffer.byteLength(text, "utf8") > MAX_REMOTE_RESPONSE_BYTES) {
|
|
641
|
+
throw new Error("Skills Layer MCP response exceeds the broker limit.");
|
|
642
|
+
}
|
|
643
|
+
if (!response.ok) {
|
|
644
|
+
return parseRemoteErrorResponse(text, payload, response.status, response.headers.get("retry-after"));
|
|
645
|
+
}
|
|
646
|
+
return parseMcpHttpResponse(text);
|
|
647
|
+
} finally {
|
|
648
|
+
clearTimeout(timeout);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function writeJsonLine(socket, payload) {
|
|
653
|
+
socket.write(JSON.stringify(payload) + "\\n");
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
async function cleanup() {
|
|
657
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
658
|
+
const ownsLock = await ownsBrokerLock();
|
|
659
|
+
if (!ownsLock) {
|
|
660
|
+
if (lockHandle) await lockHandle.close().catch(() => undefined);
|
|
661
|
+
lockHandle = null;
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
if (!SOCKET_IS_NAMED_PIPE) await rm(SOCKET_PATH, { force: true });
|
|
665
|
+
if (lockHandle) await lockHandle.close().catch(() => undefined);
|
|
666
|
+
lockHandle = null;
|
|
667
|
+
await rm(LOCK_PATH, { force: true });
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function parseLockPid(value) {
|
|
671
|
+
const pid = Number.parseInt(value.trim(), 10);
|
|
672
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function processIsAlive(pid) {
|
|
676
|
+
try {
|
|
677
|
+
process.kill(pid, 0);
|
|
678
|
+
return true;
|
|
679
|
+
} catch (error) {
|
|
680
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code !== "ESRCH");
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function delay(ms) {
|
|
685
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
async function ownsBrokerLock() {
|
|
689
|
+
const value = await readFile(LOCK_PATH, "utf8").catch(() => "");
|
|
690
|
+
return parseLockPid(value) === process.pid;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
async function acquireBrokerLock() {
|
|
694
|
+
const deadline = Date.now() + LOCK_STARTUP_GRACE_MS;
|
|
695
|
+
while (Date.now() <= deadline) {
|
|
696
|
+
try {
|
|
697
|
+
const handle = await open(LOCK_PATH, "wx", 0o600);
|
|
698
|
+
await handle.writeFile(String(process.pid) + "\\n", "utf8");
|
|
699
|
+
return handle;
|
|
700
|
+
} catch (error) {
|
|
701
|
+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") throw error;
|
|
702
|
+
const ownerPid = parseLockPid(await readFile(LOCK_PATH, "utf8").catch(() => ""));
|
|
703
|
+
if (ownerPid !== null) {
|
|
704
|
+
if (processIsAlive(ownerPid)) return null;
|
|
705
|
+
await rm(LOCK_PATH, { force: true });
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
const lockStat = await stat(LOCK_PATH).catch(() => null);
|
|
709
|
+
if (!lockStat || Date.now() - lockStat.mtimeMs >= LOCK_STARTUP_GRACE_MS) {
|
|
710
|
+
await rm(LOCK_PATH, { force: true });
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
await delay(50);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
return null;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function scheduleIdleShutdown(server) {
|
|
720
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
721
|
+
idleTimer = setTimeout(() => {
|
|
722
|
+
if (activeRequests === 0) {
|
|
723
|
+
server.close(() => {
|
|
724
|
+
void cleanup().finally(() => process.exit(0));
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
}, IDLE_SHUTDOWN_MS);
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
lockHandle = await acquireBrokerLock();
|
|
731
|
+
if (!lockHandle) process.exit(0);
|
|
732
|
+
|
|
733
|
+
if (!SOCKET_IS_NAMED_PIPE) await rm(SOCKET_PATH, { force: true });
|
|
734
|
+
|
|
735
|
+
const server = createServer((socket) => {
|
|
736
|
+
if (activeRequests >= MAX_CONCURRENT_REQUESTS) {
|
|
737
|
+
writeJsonLine(socket, { ok: false, error: "Skills Layer MCP broker is busy. Retry shortly." });
|
|
738
|
+
socket.end();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
let buffer = "";
|
|
742
|
+
let handled = false;
|
|
743
|
+
socket.setEncoding("utf8");
|
|
744
|
+
socket.on("data", async (chunk) => {
|
|
745
|
+
if (handled) return;
|
|
746
|
+
buffer += chunk;
|
|
747
|
+
if (Buffer.byteLength(buffer, "utf8") > MAX_IPC_BYTES) {
|
|
748
|
+
handled = true;
|
|
749
|
+
writeJsonLine(socket, { ok: false, error: "Skills Layer MCP request exceeds the local IPC limit." });
|
|
750
|
+
socket.end();
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
const newlineIndex = buffer.indexOf("\\n");
|
|
754
|
+
if (newlineIndex < 0) {
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
handled = true;
|
|
758
|
+
activeRequests += 1;
|
|
759
|
+
try {
|
|
760
|
+
const request = JSON.parse(buffer.slice(0, newlineIndex) || "{}");
|
|
761
|
+
if (request.protocolVersion !== BROKER_PROTOCOL_VERSION) {
|
|
762
|
+
throw new Error("protocol_version_unsupported");
|
|
763
|
+
}
|
|
764
|
+
if (request.type === "broker_shutdown") {
|
|
765
|
+
await cleanup();
|
|
766
|
+
writeJsonLine(socket, { ok: true, active: false });
|
|
767
|
+
socket.end();
|
|
768
|
+
server.close(() => process.exit(0));
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
if (request.type !== "mcp_forward") {
|
|
772
|
+
throw new Error("unsupported_broker_request");
|
|
773
|
+
}
|
|
774
|
+
if (!request.payload || typeof request.payload !== "object") {
|
|
775
|
+
throw new Error("invalid_mcp_payload");
|
|
776
|
+
}
|
|
777
|
+
if (typeof request.localClientSessionId !== "string" || !/^mcp_session_[A-Za-z0-9_-]{16,80}$/u.test(request.localClientSessionId)) {
|
|
778
|
+
throw new Error("invalid_mcp_client_session");
|
|
779
|
+
}
|
|
780
|
+
const config = selectClientConfig(await readConfig(), request.clientId);
|
|
781
|
+
const response = await forwardMcp(config, request.payload, request.localClientSessionId);
|
|
782
|
+
writeJsonLine(socket, {
|
|
783
|
+
ok: true,
|
|
784
|
+
response
|
|
785
|
+
});
|
|
786
|
+
} catch (error) {
|
|
787
|
+
writeJsonLine(socket, {
|
|
788
|
+
ok: false,
|
|
789
|
+
error: error instanceof Error ? error.message : "Skills Layer MCP broker failed."
|
|
790
|
+
});
|
|
791
|
+
} finally {
|
|
792
|
+
activeRequests -= 1;
|
|
793
|
+
socket.end();
|
|
794
|
+
scheduleIdleShutdown(server);
|
|
795
|
+
}
|
|
796
|
+
});
|
|
797
|
+
});
|
|
798
|
+
|
|
799
|
+
await assertPrivateMcpSocket(SOCKET_PATH);
|
|
800
|
+
server.listen(SOCKET_PATH, async () => {
|
|
801
|
+
if (SOCKET_IS_NAMED_PIPE) {
|
|
802
|
+
scheduleIdleShutdown(server);
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
try {
|
|
806
|
+
await chmod(SOCKET_PATH, 0o600);
|
|
807
|
+
} catch {
|
|
808
|
+
// Some platforms do not support chmod on sockets.
|
|
809
|
+
}
|
|
810
|
+
scheduleIdleShutdown(server);
|
|
811
|
+
});
|
|
812
|
+
|
|
813
|
+
process.once("SIGTERM", () => server.close(() => void cleanup().finally(() => process.exit(0))));
|
|
814
|
+
process.once("SIGINT", () => server.close(() => void cleanup().finally(() => process.exit(0))));
|
|
815
|
+
`}async function bg(e){let t=[e.bridgePath,...e.clientId?["--client",e.clientId]:[]],n=ku(e.nodePath,t),r=n.command!==e.nodePath,i=await WC(e,n,e.timeoutMs??(r?HC:5e3));if(i.status==="ok"||!r)return i;let o=null;try{o=ug(PN(e.nodePath,"utf8"))}catch{o=null}if(!o)return i;let s=await WC(e,{command:o,args:t},e.timeoutMs??HC),a={status:s.status,responseReceived:s.responseReceived,reasonCode:s.reasonCode,toolCount:s.toolCount};return s.status!=="ok"?{...i,directProbe:a}:{...i,reasonCode:i.reasonCode==="probe_timeout"?"mcp_launcher_timeout":"mcp_launcher_failed",message:"The MCP bridge answers when started with Node directly, but not through the Windows PowerShell launcher (node.ps1). Run skills-layer mcp repair, then verify again; if it still fails, send this result to Skills Layer support.",directProbe:a}}async function WC(e,t,n){let r=e.requestId??1,i=IN(t.command,t.args,{stdio:["pipe","pipe","pipe"],env:{...process.env,SKILLS_LAYER_MCP_RUNTIME_PROBE:"1"}}),o="",s=new Promise(p=>{i.once("error",()=>p({ok:!1,message:"MCP Node launcher is unavailable. Run skills-layer mcp repair.",reasonCode:"mcp_runtime_missing"}))});i.stdin.on("error",()=>{});let a=new Promise(p=>i.once("close",()=>p())),l=WN(i.stdout).then(async p=>(p.ok||await a,p));i.stderr.on("data",p=>{o+=String(p)});let c,u=new Promise(p=>{c=setTimeout(()=>p("timeout"),n)});i.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:r,method:"tools/list",params:{}})}
|
|
816
|
+
`);let d=await Promise.race([l,u,s]);if(clearTimeout(c),i.kill(),d==="timeout")return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_timeout",message:"MCP bridge did not respond before the verification timeout."};if(!d.ok)return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"reasonCode"in d?d.reasonCode:o.includes("mcp_runtime_missing")?"mcp_runtime_missing":"probe_failed",message:o.trim()?"MCP bridge failed before returning a response.":d.message};try{let p=JSON.parse(d.line);if(Ze(p)&&Ze(p.error)){let h=Ze(p.error.data)?p.error.data:null;return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:null,reasonCode:Ye(h,"reasonCode")??"remote_mcp_error",message:Ye(p.error,"message")??"Skills Layer MCP returned an error."}}let m=Ze(p)&&Ze(p.result)&&Array.isArray(p.result.tools)?p.result.tools:null,g=m&&e.expectedToolName?m.some(h=>Ze(h)&&Ye(h,"name")===e.expectedToolName):void 0;return{status:"ok",resolvedInterpreter:o.match(/^skills_layer_runtime=(.+)$/mu)?.[1],method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:m?m.length:null,...g===void 0?{}:{expectedToolPresent:g},reasonCode:null,message:m?`MCP bridge responded with ${m.length} tool${m.length===1?"":"s"}.`:"MCP bridge responded."}}catch{return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:null,reasonCode:"invalid_probe_response",message:"MCP bridge returned a response that was not valid JSON."}}}function JC(e){let t=e.target.status==="automatic",n=e.tokenPresent||e.tokenRefPresent,r=Ye(e.mcpConfig,"brokerIntegrityProfile")==="extended_v1",i=Ye(e.mcpConfig,"brokerChecksum"),o=r&&i!==null&&i===e.brokerInstalledChecksum,s=!n||e.brokerExists&&e.brokerChecksumMatches,a=(e.tokenPresent||e.tokenRefPresent)&&e.bridgeExists&&e.checksumMatches&&s&&t&&e.targetConfigured&&!e.rawTokenLeaked,l=a?"mcp_configured":r?"mcp_extension_verification_required":e.mcpConfig?"mcp_needs_repair":"mcp_not_configured",c=r?`npm run skills-layer -- mcp verify --client ${e.target.agentId}`:`skills-layer mcp verify --client ${e.target.agentId}`;return{status:l,configured:a,evidenceStale:e.plan.evidenceStale,warnings:e.plan.warnings,clientId:e.target.agentId,environment:Ye(e.tokenConfig,"environment")??Ye(e.mcpConfig,"environment")??e.plan.environment,baseUrl:Ye(e.mcpConfig,"baseUrl"),mcpUrl:Ye(e.mcpConfig,"mcpUrl"),tokenPrefix:Ye(e.tokenConfig,"tokenPrefix")??Ye(e.mcpConfig,"tokenPrefix"),scopes:Array.isArray(e.tokenConfig?.scopes)?e.tokenConfig.scopes:Array.isArray(e.mcpConfig?.scopes)?e.mcpConfig.scopes:[],configuredClients:XN(e.mcpConfig),tokenPresent:e.tokenPresent||e.tokenRefPresent,tokenStorage:Yn(Ye(e.tokenConfig,"credentialStorage"))?Ye(e.tokenConfig,"credentialStorage"):e.tokenPresent?"local_file_locked":"unknown",bridge:{path:e.plan.bridgePath,exists:e.bridgeExists,checksumMatches:e.checksumMatches},broker:{path:e.plan.brokerPath,socketPath:e.plan.brokerSocketPath,required:n,exists:e.brokerExists,checksumMatches:e.brokerChecksumMatches,integrityStatus:e.brokerChecksumMatches?"verified":o?"extended_verification_required":"mismatch"},target:{agentId:e.target.agentId,displayName:e.target.displayName,tier:e.target.tier,status:e.target.status,configPath:e.target.configPath,configured:e.targetConfigured,rawTokenLeaked:e.rawTokenLeaked,reason:e.target.reason,restartRequired:e.target.restartRequired,instructions:e.target.instructions},liveProbe:{status:"not_run",method:"tools/list",reasonCode:"use_mcp_verify",message:`Live MCP tools/list was not run by status. Run \`${c}\` to verify remote MCP reachability through the local bridge.`,nextCommand:c},nextCommand:a?null:r?`npm run skills-layer -- mcp verify --client ${e.target.agentId}`:`skills-layer mcp repair --client ${e.target.agentId}`}}function jN(e){return{agentId:e.agentId,displayName:e.displayName,tier:"tier_1",status:"automatic",serverName:gt,configPath:e.configPath,restartRequired:!0,verification:"bridge_config_written",transport:"stdio_bridge",bridgePath:e.bridgePath,nodePath:e.nodePath,configKind:e.configKind,reason:"MCP support and a safe local config shape are known.",instructions:[`Skills Layer will install the local MCP bridge at ${e.bridgePath}.`,`Skills Layer will update ${e.configPath} to launch the bridge with ${e.nodePath}.`,"The raw MCP token stays in Skills Layer local storage and is not written to the agent config.","Open a fresh agent session or restart the agent to load the MCP server."],preflight:async()=>{await Su(e.brokerSocketPath);let t=await fg(`/tmp/skills-layer-mcp-${cr(e.mcpConfigPath).slice(0,32)}.sock`);t&&!e.warnings.includes(t)&&e.warnings.push(t),await GN({configPath:e.configPath,configKind:e.configKind,bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId})},apply:async()=>{let t=await UN({bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,brokerLockPath:e.brokerLockPath,mcpConfigPath:e.mcpConfigPath,nodePath:e.nodePath,launcherSource:e.launcherSource,brokerSourceBuilder:e.brokerSourceBuilder});return await qN({configPath:e.configPath,configKind:e.configKind,bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId}),t},disconnect:async()=>{await VN({configPath:e.configPath,configKind:e.configKind,bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId})}}}function YC(e){return{agentId:e.agentId,displayName:e.displayName,tier:e.tier,status:e.status,serverName:gt,configPath:null,restartRequired:!0,verification:e.verification,transport:"manual",bridgePath:null,nodePath:null,configKind:null,reason:e.reason,instructions:e.instructions}}async function UN(e){await Su(e.brokerSocketPath);let t=eA({mcpConfigPath:e.mcpConfigPath}),n=(e.brokerSourceBuilder??tA)({mcpConfigPath:e.mcpConfigPath,socketPath:e.brokerSocketPath,lockPath:e.brokerLockPath});if(await QC(hg(e.bridgePath),{recursive:!0}),e.launcherSource){if((await yg(e.nodePath).catch(i=>{if(i.code!=="ENOENT")throw i;return null}))?.isSymbolicLink())throw new Error("mcp_runtime_unsafe: Refusing a symlink launcher.");await ca(e.nodePath,e.launcherSource,{mode:448}),await Cu(e.nodePath,448)}return await ca(e.bridgePath,t,"utf8"),await ca(e.brokerPath,n,"utf8"),await gg(hg(e.bridgePath),448),await gg(e.bridgePath,448),await gg(e.brokerPath,448),{bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,brokerLockPath:e.brokerLockPath,mcpConfigPath:e.mcpConfigPath,checksum:cr(t),brokerChecksum:cr(n),nodePath:e.nodePath}}async function qN(e){if(await Sg(e.configPath),e.configKind==="codex_toml"){await HN(e);return}await KN(e)}async function VN(e){if(await Sg(e.configPath),e.configKind==="codex_toml"){let s=await ni(e.configPath);if(s===null)return;let a=po(e),l=ua(e),c=da(e);if(!s.includes(a.trimEnd())&&!s.includes(l.trimEnd())&&!s.includes(c.trimEnd()))return;await Au(e.configPath,rA(s));return}let t=await fa(e.configPath,{allowMissing:!0}),n=xu(e.configKind),r=t?.[n];if(!t||!Ze(r))return;let i=r[gt];if(!kg(i,e))return;let o={...r};delete o[gt],await Au(e.configPath,`${JSON.stringify({...t,[n]:o},null,2)}
|
|
817
|
+
`)}async function GN(e){if(await Sg(e.configPath),e.configKind==="codex_toml"){let i=await ni(e.configPath);if(i===null)return;let o=nA(i);if(o!==null&&o!==po(e).trimEnd()&&o!==ua(e).trimEnd()&&o!==da(e).trimEnd()&&![po,ua,da].some(s=>o===s({...e,nodePath:process.execPath}).trimEnd()))throw new Error(`mcp_registration_ownership_ambiguous: ${e.configPath} already contains an unowned ${gt} block`);return}let n=(await fa(e.configPath,{allowMissing:!0}))?.[xu(e.configKind)],r=Ze(n)?n[gt]:void 0;if(r!==void 0&&!kg(r,e))throw new Error(`mcp_registration_ownership_ambiguous: ${e.configPath} already contains an unowned ${gt} entry`)}async function zN(e,t){if(!e.configPath||!e.configKind||!e.bridgePath||!e.nodePath)return{configured:!1,rawTokenLeaked:!1};if(e.configKind==="codex_toml"){let a=await ni(e.configPath);return a===null?{configured:!1,rawTokenLeaked:!1}:{configured:a.includes(po({bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId}).trimEnd())||a.includes("[mcp_servers.skills-layer]")&&a.includes(`command = ${JSON.stringify(e.nodePath)}`)&&(a.includes(`args = [${JSON.stringify(e.bridgePath)}, "--client", ${JSON.stringify(e.agentId)}]`)||a.includes(`args = [${JSON.stringify(e.bridgePath)}]`)),rawTokenLeaked:!!(t&&a.includes(t))}}let n=await fa(e.configPath,{allowMissing:!0}),r=n?.[xu(e.configKind)],i=Ze(r)?r[gt]:void 0,o=e.configKind==="json_opencode_mcp"&&Ze(i)&&Array.isArray(i.command)?{command:i.command[0],args:i.command.slice(1)}:Ze(i)?{command:i.command,args:i.args}:{command:void 0,args:void 0};return{configured:JSON.stringify(i)===JSON.stringify(_g({configKind:e.configKind,bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId}))||o.command===e.nodePath&&Array.isArray(o.args)&&o.args[0]===e.bridgePath&&(o.args.length===1||o.args[1]==="--client"&&o.args[2]===e.agentId),rawTokenLeaked:!!(t&&JSON.stringify(n??{}).includes(t))}}async function KN(e){let t=await fa(e.configPath,{allowMissing:!0})??{},n=xu(e.configKind),r=t[n],i=Ze(r)?{...r}:{},o=_g(e),s=i[gt];if(s!==void 0&&!kg(s,e))throw new Error(`mcp_registration_ownership_ambiguous: ${e.configPath} already contains an unowned ${gt} entry`);i[gt]=o,await Au(e.configPath,`${JSON.stringify({...t,[n]:i},null,2)}
|
|
818
|
+
`)}function _g(e){let t=ku(e.nodePath,[e.bridgePath,"--client",e.agentId]);return e.configKind==="json_opencode_mcp"?{type:"local",command:[t.command,...t.args],enabled:!0}:e.configKind==="json_copilot_mcp_servers"?{type:"local",...t,env:{},tools:["*"]}:t}function kg(e,t){return[t.nodePath,process.execPath].some(n=>JSON.stringify(e)===JSON.stringify(_g({...t,nodePath:n})))}function xu(e){return e==="json_servers"?"servers":e==="json_opencode_mcp"?"mcp":"mcpServers"}async function HN(e){let t=await ni(e.configPath)??"",n=po(e),r=nA(t);if(r!==null&&r.trimEnd()!==n.trimEnd()&&r.trimEnd()!==ua(e).trimEnd()&&r.trimEnd()!==da(e).trimEnd()&&![po,ua,da].some(o=>r.trimEnd()===o({...e,nodePath:process.execPath}).trimEnd()))throw new Error(`mcp_registration_ownership_ambiguous: ${e.configPath} already contains an unowned ${gt} block`);let i=`${rA(t).trimEnd()}${t.trim().length>0?`
|
|
819
|
+
|
|
820
|
+
`:""}${n}`;await Au(e.configPath,i)}function po(e){let t=ku(e.nodePath,[e.bridgePath,"--client",e.agentId]);return["[mcp_servers.skills-layer]",'# skills-layer-owner = "skills-layer"',`command = ${JSON.stringify(t.command)}`,`args = [${t.args.map(n=>JSON.stringify(n)).join(", ")}]`,""].join(`
|
|
821
|
+
`)}function ua(e){return["[mcp_servers.skills-layer]",`command = ${JSON.stringify(e.nodePath)}`,`args = [${JSON.stringify(e.bridgePath)}, "--client", ${JSON.stringify(e.agentId)}]`,""].join(`
|
|
822
|
+
`)}function da(e){return["[mcp_servers.skills-layer]",`command = ${JSON.stringify(e.nodePath)}`,`args = [${JSON.stringify(e.bridgePath)}]`,""].join(`
|
|
823
|
+
`)}function nA(e){let t=e.split(/\r?\n/u),n=t.findIndex(i=>i.trim()==="[mcp_servers.skills-layer]");if(n<0)return null;let r=t.length;for(let i=n+1;i<t.length;i+=1)if(/^\s*\[.+\]\s*$/u.test(t[i])){r=i;break}return t.slice(n,r).join(`
|
|
824
|
+
`).trimEnd()}function rA(e){let t=e.split(/\r?\n/u),n=[],r=!1;for(let i of t){if(i.trim()==="[mcp_servers.skills-layer]"){r=!0;continue}r&&/^\s*\[.+\]\s*$/u.test(i)&&(r=!1),r||n.push(i)}return n.join(`
|
|
825
|
+
`).trimEnd()}async function Au(e,t){await QC(hg(e),{recursive:!0,mode:448});let n=await yg(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink())throw new Error(`mcp_config_symlink_rejected: ${e}`);let r=`${e}.skills-layer.lock`,i=`${e}.skills-layer-stage-${process.pid}`,o=`${e}.skills-layer-backup`,s;try{s=await EN(r,"wx",384)}catch(a){throw a.code==="EEXIST"?new Error(`mcp_config_locked: ${e}`):a}try{n?.isFile()&&(await ca(o,await wg(e),{mode:384}),await Cu(o,384)),await fo(i,{force:!0}),await ca(i,t,{encoding:"utf8",flag:"wx",mode:384}),await DN(i,e),await Cu(e,384)}finally{await s.close(),await Promise.all([fo(i,{force:!0}),fo(r,{force:!0})])}}async function Sg(e){if((await yg(e).catch(n=>{if(n.code==="ENOENT")return null;throw n}))?.isSymbolicLink())throw new Error(`mcp_config_symlink_rejected: ${e}`)}async function fa(e,t){try{let n=JSON.parse(await wg(e,"utf8"));return Ze(n)?n:{}}catch(n){if(t.allowMissing&&n.code==="ENOENT")return null;throw n}}async function ni(e){try{return await wg(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function gg(e,t){try{await Cu(e,t)}catch{}}async function Cg(e){await fo(e,{force:!0})}async function Ag(e,t,n=`${t}.lock`){await Su(t);let r=fg(t);await Promise.all([fo(e,{force:!0}),r,fo(n,{force:!0})])}function WN(e){return e?new Promise(t=>{let n="";e.on("data",r=>{n+=String(r);let i=n.indexOf(`
|
|
826
|
+
`);i>=0&&t({ok:!0,line:n.slice(0,i)})}),e.on("error",r=>{t({ok:!1,message:r instanceof Error?r.message:"MCP bridge stdout failed."})}),e.on("end",()=>{t({ok:!1,message:"MCP bridge exited before returning a response."})})}):Promise.resolve({ok:!1,message:"MCP bridge stdout was not available."})}function JN(e,t){let n=iA(t),r=e??process.env,i=t==="win32"?ZC(r.APPDATA,r.USERPROFILE,r.HOME):ZC(r.XDG_CONFIG_HOME,r.HOME?n.join(r.HOME,".skills-layer"):void 0);return i?t==="win32"||r.XDG_CONFIG_HOME?.trim()?n.join(i,"skills-layer"):i:n.join(process.cwd(),".skills-layer")}function YN(e){let t=Yl(e);if(t.status==="unknown")throw new Error(`unknown MCP host: ${e}`);return t.hostId}function ZN(e,t){let n=e.tokens;return Ze(n)&&Ze(n[t])?n[t]:e}function XN(e){if(!e)return[];let t=e.clientIds;if(Array.isArray(t))return t.filter(i=>typeof i=="string"&&i.trim().length>0);let n=e.tokens;if(Ze(n))return Object.keys(n);let r=Ye(e,"clientId");return r?[r]:[]}function la(e,...t){return iA(e).join(...t)}function iA(e){return e==="win32"?$N:TN}function ZC(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Ye(e,t){let n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function cr(e){return XC("sha256").update(e).digest("hex")}function Ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{chmod as oA,lstat as lA,mkdir as QN,open as eM,readFile as Ig,rename as tM,rm as xg,writeFile as sA}from"node:fs/promises";import{dirname as nM,join as aA}from"node:path";var rM=[{hostId:"claude-code",relativePath:".mcp.json",containerKey:"mcpServers"},{hostId:"cursor",relativePath:".cursor/mcp.json",containerKey:"mcpServers"},{hostId:"cline",relativePath:".cline/mcp.json",containerKey:"mcpServers"},{hostId:"gemini-cli",relativePath:".gemini/settings.json",containerKey:"mcpServers"},{hostId:"windsurf",relativePath:".windsurf/mcp.json",containerKey:"mcpServers"}];async function cA(e){let t=aA(e.stateDir,"mcp","skills-layer-mcp-proxy.mjs"),n=[];for(let r of rM){let i=aA(e.projectRoot,r.relativePath),o=await lA(i).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(!o){n.push(pa(r,i,"absent","No legacy project configuration file exists.",t,e.nodePath));continue}if(o.isSymbolicLink()||!o.isFile()){n.push(pa(r,i,"ambiguous","The legacy target is not a regular owned file and was left unchanged.",t,e.nodePath));continue}let s;try{let u=JSON.parse(await Ig(i,"utf8"));if(!ma(u))throw new Error("not an object");s=u}catch{n.push(pa(r,i,"malformed","The legacy project configuration is not a JSON object and was left unchanged.",t,e.nodePath));continue}let a=s[r.containerKey],l=ma(a)?a["skills-layer"]:void 0;if(l===void 0){n.push(pa(r,i,"absent","No Skills Layer project registration exists in this file.",t,e.nodePath));continue}let c=dA(l,e.nodePath,t,r.hostId)?"owned":"ambiguous";n.push(pa(r,i,c,c==="owned"?"An exact legacy Skills Layer project registration was found.":"A Skills Layer-named entry exists but exact ownership could not be proved.",t,e.nodePath))}return n}async function uA(e){let t=new Set(e.verifiedGlobalHostIds),n=e.discovery.filter(o=>o.status==="owned"&&t.has(o.hostId)),r=e.discovery.filter(o=>o.status!=="absent"&&!n.includes(o)).map(o=>({configPath:o.configPath,hostId:o.hostId,reason:o.status==="owned"?"The replacement global registration is not verified.":o.reason}));if(!e.apply)return{applied:!1,plannedPaths:n.map(o=>o.configPath),cleanedPaths:[],skipped:r};let i=[];for(let o of n){let s=await lA(o.configPath);if(s.isSymbolicLink()||!s.isFile()){r.push({configPath:o.configPath,hostId:o.hostId,reason:"The target changed after discovery and is no longer a regular file."});continue}let a=JSON.parse(await Ig(o.configPath,"utf8"));if(!ma(a)||!ma(a[o.containerKey])){r.push({configPath:o.configPath,hostId:o.hostId,reason:"The target changed after discovery and no longer has the expected container."});continue}let l=a[o.containerKey];if(!dA(l["skills-layer"],o.nodePath,o.bridgePath,o.hostId)){r.push({configPath:o.configPath,hostId:o.hostId,reason:"Ownership no longer matches the discovery receipt."});continue}let c={...l};delete c["skills-layer"],await iM(o.configPath,JSON.stringify({...a,[o.containerKey]:c},null,2)+`
|
|
827
|
+
`),i.push(o.configPath)}return{applied:!0,plannedPaths:n.map(o=>o.configPath),cleanedPaths:i,skipped:r}}function dA(e,t,n,r){return!ma(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 iM(e,t){await QN(nM(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 eM(n,"wx",384).catch(s=>{throw s.code==="EEXIST"?new Error(`mcp_legacy_migration_locked: ${e}`):s});try{await sA(i,await Ig(e),{mode:384}),await oA(i,384),await xg(r,{force:!0}),await sA(r,t,{encoding:"utf8",flag:"wx",mode:384}),await tM(r,e),await oA(e,384)}finally{await o.close(),await Promise.all([xg(r,{force:!0}),xg(n,{force:!0})])}}function pa(e,t,n,r,i,o){return{hostId:e.hostId,configPath:t,containerKey:e.containerKey,status:n,reason:r,bridgePath:i,nodePath:o}}function ma(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{createHmac as BM,sign as gX,timingSafeEqual as NM,verify as MM}from"node:crypto";import{createHash as oM}from"node:crypto";import{posix as wA,win32 as vA}from"node:path";var St=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"}),fA=256*1024,sM=16,aM=4096,lM=1024,cM=512,ha=65536,Xe=4096,uM=1024,bA=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,dM=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,fM=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,pM=new Set(["__proto__","constructor","prototype"]),pA=Object.freeze({codex:Object.freeze({agentId:"codex",adapterRevision:St.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:St["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:St.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:St["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:St.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:St["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:St.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:St.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:St.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:St["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:St["kiro-cli"],eventName:"preToolUse",sourceUrl:"https://kiro.dev/docs/hooks/types/",sourceCheckedAt:"2026-09-25",blockingContract:"non-zero command exit blocks"})}),mM=new Set(["bash","exec_command","shell","shell_command","execute_command","run_shell_command","run_command","execute_bash"]),gM=new Set(["read","read_file","view","glob","grep","list_files","search_files","list_code_definition_names","view_file","fs_read"]),hM=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"]),yM=new Set(["webfetch","websearch","web_fetch","web_search","google_web_search"]),wM=new Set(["browser","browser_action","computer"]),vM=new Set(["device","device_action","computer_use"]);function Wt(e){return Object.prototype.hasOwnProperty.call(pA,e)?pA[e]:null}function Jt(e){return Wt(e)!==null}function _A(e){let t=Wt(e.agentId);if(!t)throw new Error(`No strict hook adapter is implemented for ${e.agentId}.`);LM(e.platform),SA(e.hostVersion,"host version"),ga(e.expectedSessionId,"expected session id");let n=DM(e.attribution),r=TM(e.payload),i=e.agentId==="cline"?_M(r,e):e.agentId==="gemini-cli"?kM(r,e):e.agentId==="cursor"?SM(r,e):e.agentId==="github-copilot"?CM(r,e):e.agentId==="opencode"?AM(r,e):e.agentId==="windsurf"?xM(r,e):e.agentId==="antigravity"||e.agentId==="antigravity-cli"?IM(r,e):e.agentId==="kiro-cli"?RM(r,e):bM(r,e),o=PM({agentId:e.agentId,platform:e.platform,cwd:i.cwd,toolName:i.toolName,toolInput:i.toolInput}),s=Pg(FM(i.toolInput)),a=Pg({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:hA(go(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:hA(go(a))})}function ur(e,t){if(!Wt(e))throw new Error(`No strict hook adapter is implemented for ${e}.`);if(t.decision!=="allow"&&t.decision!=="warn"&&t.decision!=="deny")throw new Error("Strict hook decision must be allow, warn or deny.");OM(t.reason,"decision reason",uM);let n=i=>Object.freeze({exitCode:0,stdout:JSON.stringify(i),stderr:""});if(t.decision==="deny")return e==="kiro-cli"||e==="opencode"||e==="windsurf"||e==="github-copilot"?Object.freeze({exitCode:2,stdout:"",stderr:t.reason}):n(e==="cline"?{cancel:!0,errorMessage:t.reason}:e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"?{decision:"deny",reason:t.reason}:e==="cursor"?{permission:"deny",user_message:t.reason,agent_message:t.reason}:t.eventName==="UserPromptExpansion"?{decision:"block",reason:t.reason}:{hookSpecificOutput:{hookEventName:mA(t.eventName),permissionDecision:"deny",permissionDecisionReason:t.reason}});if(t.decision==="allow")return e==="cline"?n({cancel:!1}):Object.freeze({exitCode:0,stdout:"",stderr:""});let r=`Guardian warning: ${t.reason}`;return e==="claude-code"?t.eventName==="UserPromptExpansion"?n({systemMessage:r}):n({hookSpecificOutput:{hookEventName:mA(t.eventName),permissionDecision:"ask",permissionDecisionReason:t.reason}}):e==="cursor"?n({permission:"ask",user_message:t.reason,agent_message:t.reason}):e==="cline"?n({cancel:!1,errorMessage:r}):Object.freeze({exitCode:0,stdout:"",stderr:r})}function mA(e){return e&&/^[A-Za-z]{1,64}$/u.test(e)?e:"PreToolUse"}function bM(e,t){if(e.hook_event_name!=="PreToolUse")throw new Error("Strict host hook accepts only the PreToolUse event.");let n=J(e.session_id,"hook session id",256);if(n!==t.expectedSessionId)throw new Error("Hook session does not match the bound session.");let r=En(J(e.cwd,"hook cwd",Xe),t.platform),i=J(e.tool_name,"hook tool name",256),o=J(e.tool_use_id,"hook tool use id",256),s=ht(e.tool_input,"hook tool input");return{sessionId:n,cwd:r,toolName:i,toolUseId:o,toolInput:s}}function _M(e,t){if(e.hookName!=="PreToolUse")throw new Error("Strict Cline hook accepts only the PreToolUse event.");let n=J(e.taskId,"Cline task id",256);if(n!==t.expectedSessionId)throw new Error("Cline task does not match the bound session.");J(e.clineVersion,"Cline version",128);let r=J(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.");J(e.userId,"Cline user id",256);let i=ht(e.model,"Cline model");if(J(i.provider,"Cline model provider",256),J(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=>En(J(c,"Cline workspace root",Xe),t.platform)),s=ht(e.preToolUse,"Cline preToolUse"),a=J(s.tool,"Cline tool name",256),l=ht(s.parameters,"Cline tool parameters");return{sessionId:n,cwd:o[0],toolName:a,toolUseId:null,toolInput:l}}function kM(e,t){if(e.hook_event_name!=="BeforeTool")throw new Error("Strict Gemini CLI hook accepts only the BeforeTool event.");let n=J(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=En(J(e.cwd,"Gemini CLI cwd",Xe),t.platform),i=J(e.tool_name,"Gemini CLI tool name",256),o=ht(e.tool_input,"Gemini CLI tool input"),s=Iu(e.tool_use_id,"Gemini CLI tool use id");return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function SM(e,t){if(e.hook_event_name!=="preToolUse")throw new Error("Strict Cursor hook accepts only the preToolUse event.");let n=J(e.conversation_id,"Cursor conversation id",256);if(n!==t.expectedSessionId)throw new Error("Cursor conversation does not match the bound session.");J(e.cursor_version,"Cursor version",128);let r=kA(e.workspace_roots,"Cursor workspace roots",t.platform),i=typeof e.cwd=="string"?e.cwd:r[0],o=En(J(i,"Cursor cwd",Xe),t.platform),s=J(e.tool_name,"Cursor tool name",256),a=ht(e.tool_input,"Cursor tool input"),l=Iu(e.tool_use_id,"Cursor tool use id");return{sessionId:n,cwd:o,toolName:s,toolUseId:l,toolInput:a}}function CM(e,t){if(e.hook_event_name!=="PreToolUse")throw new Error("Guardian accepts only GitHub Copilot's PascalCase PreToolUse event.");let n=J(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=En(J(e.cwd,"GitHub Copilot cwd",Xe),t.platform),i=J(e.tool_name,"GitHub Copilot tool name",256),o=ht(e.tool_input,"GitHub Copilot tool input");return{sessionId:n,cwd:r,toolName:i,toolUseId:null,toolInput:o}}function AM(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=J(e.session_id,"OpenCode session id",256);if(n!==t.expectedSessionId)throw new Error("OpenCode session does not match the bound session.");let r=En(J(e.cwd,"OpenCode cwd",Xe),t.platform),i=J(e.tool_name,"OpenCode tool name",256),o=ht(e.tool_input,"OpenCode tool input"),s=J(e.call_id,"OpenCode call id",256);return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function xM(e,t){let n=J(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=J(e.trajectory_id,"Windsurf trajectory id",256);if(i!==t.expectedSessionId)throw new Error("Windsurf trajectory does not match the bound session.");let o=J(e.execution_id,"Windsurf execution id",256),s=ht(e.tool_info,"Windsurf tool info"),a=n==="pre_run_command"&&typeof s.cwd=="string"?s.cwd:e.cwd,l=En(J(a,"Windsurf cwd",Xe),t.platform);if(n==="pre_read_code"||n==="pre_write_code"){let p=J(s.file_path,"Windsurf file path",Xe);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:J(s.command_line,"Windsurf command",ha)}};let c=J(s.mcp_server_name,"Windsurf MCP server",256),u=J(s.mcp_tool_name,"Windsurf MCP tool",256),d=ht(s.mcp_tool_arguments,"Windsurf MCP arguments");return{sessionId:i,cwd:l,toolName:`mcp__${c}__${u}`,toolUseId:o,toolInput:d}}function IM(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=J(e.conversationId,"Antigravity conversation id",256);if(n!==t.expectedSessionId)throw new Error("Antigravity conversation does not match the bound session.");let r=kA(e.workspacePaths,"Antigravity workspace paths",t.platform),i=ht(e.toolCall,"Antigravity tool call"),o=J(i.name,"Antigravity tool name",256),s=ht(i.args,"Antigravity tool arguments"),a=Iu(i.id,"Antigravity tool call id");return{sessionId:n,cwd:r[0],toolName:o,toolUseId:a,toolInput:s}}function RM(e,t){if(e.hook_event_name!=="preToolUse")throw new Error("Strict Kiro hook accepts only the preToolUse event.");let n=J(e.session_id,"Kiro session id",256);if(n!==t.expectedSessionId)throw new Error("Kiro session does not match the bound session.");let r=En(J(e.cwd,"Kiro cwd",Xe),t.platform),i=J(e.tool_name,"Kiro tool name",256),o=ht(e.tool_input,"Kiro tool input"),s=Iu(e.tool_use_id,"Kiro tool use id");return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function PM(e){let t=e.toolName.toLowerCase();if(mM.has(t)){let n=e.toolInput.command??e.toolInput.cmd??e.toolInput.CommandLine,r=J(n,`${e.toolName} command`,ha);if(r.trim().length===0)throw new Error(`${e.toolName} command cannot be empty.`);return{actionFamily:"shell_execution",command:r,fileTargets:[],networkTargets:[]}}if(gM.has(t)){let n=Rg(e.toolInput,e.cwd,e.platform);return n.length===0&&n.push(e.cwd),{actionFamily:"filesystem_read",command:null,fileTargets:yA(n),networkTargets:[]}}if(hM.has(t)){let n=t==="apply_patch"?EM(e.toolInput,e.cwd,e.platform):Rg(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:yA(n),networkTargets:[]}}if(yM.has(t)){let n=e.toolInput.url,r=e.toolInput.query;if(t==="webfetch"||t==="web_fetch"){let i=AA(J(n,`${e.toolName} URL`,Xe));return{actionFamily:"network_access",command:null,fileTargets:[],networkTargets:[i]}}return J(r,`${e.toolName} query`,ha),{actionFamily:"network_access",command:null,fileTargets:[],networkTargets:[]}}if(wM.has(t)||t.startsWith("browser__"))return{actionFamily:"browser_access",command:null,fileTargets:[],networkTargets:gA(e.toolInput)};if(vM.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:Rg(e.toolInput,e.cwd,e.platform),networkTargets:gA(e.toolInput)};throw new Error(`Tool ${e.toolName} has no strict mapping for ${e.agentId}.`)}function Rg(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(J(e[o],`${o} path`,Xe));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(J(o,"tool path",Xe))}return r.map(o=>CA(o,t,n))}function EM(e,t,n){let r=J(e.patch??e.command,"apply_patch payload",ha),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(CA(a,t,n))}if(i.length===0)throw new Error("apply_patch payload has no recognized file targets.");return i}function gA(e){return e.url===void 0?[]:[AA(J(e.url,"tool URL",Xe))]}function DM(e){if(!e||typeof e!="object")throw new Error("Strict hook attribution is required.");if(!fM.test(e.skillSlug))throw new Error("Strict hook attribution skill slug is invalid.");return SA(e.version,"attribution version"),ga(e.generationId,"attribution generation id"),ga(e.actorId,"attribution actor id"),ga(e.tenantId,"attribution tenant id"),e.workspaceId!==void 0&&ga(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 TM(e){let t=e;if(typeof e=="string"){if(Buffer.byteLength(e,"utf8")>fA)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.")}}$M(t);let n=go(t);if(Buffer.byteLength(n,"utf8")>fA)throw new Error("Host hook payload exceeds the maximum 256 KiB size.");return ht(t,"host hook payload")}function $M(e){let t=0,n=new Set,r=(i,o)=>{if(t+=1,t>aM)throw new Error("Host hook JSON contains too many values.");if(o>sM)throw new Error("Host hook JSON exceeds the maximum depth.");if(!(i===null||typeof i=="boolean")){if(typeof i=="string"){if(i.length>ha)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>lM)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>cM)throw new Error("Host hook JSON object has too many keys.");for(let[l,c]of a){if(pM.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 ht(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object.`);return e}function J(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 Iu(e,t){if(e==null)return null;let n=J(e,t,256);if(!bA.test(n))throw new Error(`${t} is invalid.`);return n}function kA(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=>En(J(r,t,Xe),n))}function ga(e,t){if(typeof e!="string"||!bA.test(e))throw new Error(`${t} is invalid.`)}function SA(e,t){if(typeof e!="string"||!dM.test(e))throw new Error(`${t} is invalid.`)}function LM(e){if(e!=="darwin"&&e!=="linux"&&e!=="win32")throw new Error("Strict hook platform is unsupported.")}function OM(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 En(e,t){if(e.length>Xe||e.includes("\0"))throw new Error("Hook path is invalid.");let n=t==="win32"?vA:wA;if(!n.isAbsolute(e))throw new Error(`Hook path must be absolute for ${t}.`);return n.normalize(e)}function CA(e,t,n){let r=n==="win32"?vA:wA;if(e.length>Xe||e.includes("\0"))throw new Error("Tool path is invalid.");return r.normalize(r.isAbsolute(e)?e:r.resolve(t,e))}function AA(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 FM(e){return JSON.parse(go(e))}function Pg(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))Pg(t)}return e}function go(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(n=>go(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${go(t[n])}`).join(",")}}`}function hA(e){return`sha256:${oM("sha256").update(e).digest("hex")}`}function yA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}var jM=32,UM=1024,qM=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,xA=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,VM=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,GM=/^hmac-sha256:[a-f0-9]{64}$/u,zM=/^ed25519:[A-Za-z0-9_-]{86}$/u,KM=/^(?:sha256:)?[a-f0-9]{64}$/u,HM=/^[a-f0-9]{64}$/u,IA=Object.freeze({disabled:0,warning:1,enforce:2});function wa(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"||!zM.test(t.signature))throw new Error("Guardian attribution signature is invalid.");dr(t.keyId,"Guardian attribution key id");let s=e.publicKeys?.[t.keyId];if(!s)throw new Error("Guardian attribution key is unknown.");let a=WM(t.claims),l={version:2,algorithm:"ed25519",keyId:t.keyId,issuer:t.issuer,claims:a},c=Buffer.from(t.signature.slice(8),"base64url");if(!MM(null,Buffer.from(Ru(l),"utf8"),s,c))throw new Error("Guardian attribution signature verification failed.");return RA(a,e)}if(!e.key)throw new Error("Guardian attribution key is required.");if(ZM(e.key),dr(t.keyId,"Guardian attribution key id"),typeof t.signature!="string"||!GM.test(t.signature))throw new Error("Guardian attribution signature is invalid.");let n=EA(t.claims),r=YM({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||!NM(i,o))throw new Error("Guardian attribution signature verification failed.");return RA(n,e)}async function Eg(e){try{if(!e.attributionEnvelope||!e.attributionKey&&!e.attributionPublicKeys)throw new Error("Signed Guardian attribution is required.");let t=wa({...e.attributionKey?{key:e.attributionKey}:{},...e.attributionPublicKeys?{publicKeys:e.attributionPublicKeys}:{},envelope:e.attributionEnvelope,expectedAgentId:e.agentId,expectedPlatform:e.platform,now:e.now}),n=_A({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,expectedSessionId:t.sessionId,attribution:t,payload:e.rawPayload}),r=JM(t.requestedMode,t.workspaceRequiredMode),i=await e.evaluate(n,{effectiveMode:r});return XM(i),r==="disabled"&&i.decision!=="deny"?ur(e.agentId,{decision:"allow",reason:"Guardian is disabled for this personal skill session."}):ur(e.agentId,{decision:i.decision,reason:DA(i.reason)})}catch{return ur(e.agentId,{decision:"deny",reason:"Guardian could not verify this action."})}}function EA(e){if(!e||typeof e!="object")throw new Error("Guardian attribution claims are required.");if(!Jt(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(!xA.test(e.hostVersion))throw new Error("Guardian attribution host version is invalid.");if(dr(e.sessionId,"Guardian attribution session id"),!VM.test(e.skillSlug))throw new Error("Guardian attribution skill slug is invalid.");if(!xA.test(e.version))throw new Error("Guardian attribution skill version is invalid.");return dr(e.generationId,"Guardian attribution generation id"),dr(e.actorId,"Guardian attribution actor id"),dr(e.tenantId,"Guardian attribution tenant id"),e.workspaceId!==void 0&&dr(e.workspaceId,"Guardian attribution workspace id"),PA(e.requestedMode,"Guardian requested mode"),e.workspaceRequiredMode!==null&&PA(e.workspaceRequiredMode,"Guardian workspace-required mode"),ya(e.issuedAt,"Guardian attribution issuedAt"),ya(e.expiresAt,"Guardian attribution expiresAt"),Dg({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 WM(e){let t=EA(e);if(!KM.test(e.contractDigest))throw new Error("Guardian attribution contract digest is invalid.");if(!HM.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 dr(e.trustLedgerId,"Guardian attribution Trust Ledger id"),Dg({...t,contractDigest:e.contractDigest,archiveSha256:e.archiveSha256,policyRevision:e.policyRevision,trustLedgerId:e.trustLedgerId})}function RA(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=ya(t.now,"Guardian runtime timestamp"),r=ya(e.issuedAt,"Guardian attribution issuedAt"),i=ya(e.expiresAt,"Guardian attribution expiresAt");if(i.getTime()<=r.getTime())throw new Error("Guardian attribution expiry must follow issuance.");if(n.getTime()<r.getTime()-QM)throw new Error("Guardian attribution is not valid yet.");if(n.getTime()>i.getTime())throw new Error("Guardian attribution has expired.");return e}function JM(e,t){return t!==null&&IA[t]>IA[e]?t:e}function YM(e,t){return`hmac-sha256:${BM("sha256",t).update(Ru(e)).digest("hex")}`}function ZM(e){if(!(e instanceof Uint8Array)||e.byteLength<jM||e.byteLength>UM)throw new Error("Guardian attribution key must contain between 32 and 1024 bytes.")}function dr(e,t){if(typeof e!="string"||!qM.test(e))throw new Error(`${t} is invalid.`)}function PA(e,t){if(e!=="enforce"&&e!=="warning"&&e!=="disabled")throw new Error(`${t} is invalid.`)}function ya(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 XM(e){if(!e||e.decision!=="allow"&&e.decision!=="warn"&&e.decision!=="deny")throw new Error("Guardian policy evaluator returned an invalid decision.");DA(e.reason)}var QM=2*6e4;function DA(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 Ru(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Ru).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ru(t[n])}`).join(",")}}`}function Dg(e){if(e&&typeof e=="object"){for(let t of Object.values(e))Dg(t);Object.freeze(e)}return e}import{createHash as TA}from"node:crypto";var $A=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,ej=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,ii=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,LA=/^sha256:[a-f0-9]{64}$/u,OA=4096;function FA(){return Object.freeze({version:2,revision:0,associations:Object.freeze({})})}function BA(e){if(!dn(e)||e.version!==2||!Number.isSafeInteger(e.revision)||Number(e.revision)<0||!dn(e.associations))throw new Error("Guardian session association index is invalid.");let t={};for(let[n,r]of Object.entries(e.associations)){if(!dn(r))throw new Error("Guardian session association record is invalid.");let i=r;if($g(i),Be(i)!==n)throw new Error("Guardian session association key does not match its exact identity.");t[n]=Dn({...i})}return Dn({version:2,revision:Number(e.revision),associations:t})}function pr(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)=>Lg(n.path,r.path))};return Tg(ba(t))}function Be(e){return qA(e),`association_${TA("sha256").update(ba({scope:e.scope,agentId:e.agentId,sessionId:e.sessionId,skillSlug:e.skillSlug,skillVersion:e.skillVersion,generationId:e.generationId}),"utf8").digest("hex")}`}function NA(e,t,n){if(Eu(e),e.revision!==n)throw new Error("Guardian association compare-and-swap revision changed.");$g(t);let r=Be(t),i=e.associations[r],o=Dn({...t,revision:i?i.revision+1:1,createdAt:i?.createdAt??t.createdAt});return Dn({version:2,revision:e.revision+1,associations:{...e.associations,[r]:o}})}function MA(e,t){if(Eu(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.");yo(t.updatedAt,"Guardian association update timestamp"),t.attributionExpiresAt!==void 0&&yo(t.attributionExpiresAt,"Guardian attribution expiry"),t.trustLedgerId!==void 0&&fr(t.trustLedgerId,"Guardian Trust Ledger id"),t.reasonCode!==void 0&&ho(t.reasonCode,"Guardian association reason code");let r=Dn({...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 Dn({version:2,revision:e.revision+1,associations:{...e.associations,[t.key]:r}})}function _a(e,t){Eu(e),fr(t.sessionId,"Guardian host session id");let n=yo(t.asOf,"Guardian association lookup timestamp"),r=Object.values(e.associations).filter(a=>a.agentId===t.agentId&&a.sessionId===t.sessionId).sort((a,l)=>Lg(Be(a),Be(l)));if(r.length===0)return{status:"unrelated",associations:[]};let i=r.filter(a=>a.state==="refused");if(i.length>0)return{status:"terminal",associations:i};let o=r.filter(a=>a.state==="active");if(o.length>1)return{status:"ambiguous",associations:o};if(o.length===1){let a=o[0],l=a.attributionExpiresAt?Date.parse(a.attributionExpiresAt):Number.NaN;return Number.isFinite(l)&&l>n?{status:"active",associations:[a]}:{status:"active_authority_stale",associations:[a]}}let s=r.filter(a=>a.state==="pending_authority"||a.state==="stale");return s.length>0?{status:"expected_missing_authority",associations:s}:{status:"terminal",associations:r}}function jA(e,t){if(Eu(e),e.revision!==t.expectedIndexRevision)throw new Error("Guardian association compare-and-swap revision changed.");if(!ii.test(t.skillSlug)||!$A.test(t.generationId)||!LA.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:Dn({version:2,revision:e.revision+1,associations:Object.fromEntries(Object.entries(e.associations).filter(([i])=>!r.has(i)))}),removedKeys:[...n]}}function UA(e){let t=ba({referenceKind:e.observation.referenceKind,skillReference:e.observation.skillReference}),n={version:2,revision:1,state:"refused",scope:e.scope,agentId:e.agentId,hostVersion:e.hostVersion,sessionId:e.observation.sessionId,skillSlug:e.observation.referenceKind==="slug"&&ii.test(e.observation.skillReference)?e.observation.skillReference:"unresolved-skill",skillVersion:"unresolved",generationId:`refused_${Tg(t).slice(7,39)}`,receiptSha256:Tg(`refused
|
|
828
|
+
${t}`),requestedPreference:"enforce",activationSource:e.observation.source,activationEvidence:e.observation.evidence,adapterRevision:e.adapterRevision,reasonCode:e.reasonCode,createdAt:e.now,updatedAt:e.now};return $g(n),Dn(n)}function Pu(e,t){if(!dn(t))return null;if(e==="claude-code"){let n=Yt(t.session_id);if(t.hook_event_name==="UserPromptExpansion"&&t.expansion_type==="slash_command"){let r=Yt(t.command_name);if(n&&r&&ii.test(r))return va(n,r,"slug","claude_user_prompt_expansion",`UserPromptExpansion:${r}`)}if(t.hook_event_name==="PreToolUse"&&t.tool_name==="Skill"){let r=dn(t.tool_input)?t.tool_input:null,i=r?Yt(r.skill)??Yt(r.name):null;if(n&&i&&ii.test(i))return va(n,i,"slug","claude_skill_tool",`Skill:${i}`)}return null}if(e==="gemini-cli"){let n=Yt(t.session_id),r=dn(t.tool_input)?t.tool_input:null,i=r?Yt(r.name):null;return t.hook_event_name==="BeforeTool"&&t.tool_name==="activate_skill"&&n&&i&&ii.test(i)?va(n,i,"slug","gemini_activate_skill",`activate_skill:${i}`):null}if(e==="antigravity"||e==="antigravity-cli"){let n=Yt(t.conversationId),r=dn(t.toolCall)?t.toolCall:null,i=r&&dn(r.args)?r.args:null,o=i?Yt(i.AbsolutePath):null;if(r?.name==="view_file"&&i?.IsSkillFile===!0&&n&&o)return va(n,o,"path","antigravity_skill_file",`view_file:${o}`)}if(e==="opencode"){let n=Yt(t.session_id),r=dn(t.tool_input)?t.tool_input:null,i=r?Yt(r.name)??Yt(r.skill):null;if(t.hook_event_name==="tool.execute.before"&&t.tool_name==="skill"&&n&&i&&ii.test(i))return va(n,i,"slug","opencode_skill_tool",`skill:${i}`)}return null}function va(e,t,n,r,i){return fr(e,"Guardian activation session id"),ho(t,"Guardian activation skill reference"),ho(i,"Guardian activation evidence"),Object.freeze({sessionId:e,skillReference:t,referenceKind:n,source:r,evidence:i})}function Eu(e){if(!e||e.version!==2||!Number.isSafeInteger(e.revision)||e.revision<0||!dn(e.associations))throw new Error("Guardian session association index is invalid.")}function $g(e){if(!e||e.version!==2||!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Guardian session association version is invalid.");if(qA(e),!LA.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","refused"].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.");ho(e.activationEvidence,"Guardian activation evidence"),ho(e.adapterRevision,"Guardian adapter revision"),yo(e.createdAt,"Guardian association creation timestamp"),yo(e.updatedAt,"Guardian association update timestamp"),e.attributionExpiresAt!==void 0&&yo(e.attributionExpiresAt,"Guardian attribution expiry"),e.trustLedgerId!==void 0&&fr(e.trustLedgerId,"Guardian Trust Ledger id"),e.workspaceId!==void 0&&fr(e.workspaceId,"Guardian workspace id"),e.reasonCode!==void 0&&ho(e.reasonCode,"Guardian association reason code")}function qA(e){if(e.scope!=="project"&&e.scope!=="global")throw new Error("Guardian association scope is invalid.");if(fr(e.agentId,"Guardian association agent id"),fr(e.sessionId,"Guardian association session id"),!ii.test(e.skillSlug))throw new Error("Guardian association skill slug is invalid.");if(!ej.test(e.skillVersion))throw new Error("Guardian association skill version is invalid.");fr(e.generationId,"Guardian association generation id")}function fr(e,t){if(typeof e!="string"||!$A.test(e))throw new Error(`${t} is invalid.`)}function ho(e,t){if(typeof e!="string"||e.length===0||e.length>OA||/[\u0000-\u001f\u007f]/u.test(e))throw new Error(`${t} is invalid.`)}function yo(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 Yt(e){return typeof e=="string"&&e.length>0&&e.length<=OA?e:null}function dn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Tg(e){return`sha256:${TA("sha256").update(e,"utf8").digest("hex")}`}function ba(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(ba).join(",")}]`;let t=e;return`{${Object.keys(t).sort(Lg).map(n=>`${JSON.stringify(n)}:${ba(t[n])}`).join(",")}}`}function Lg(e,t){return e<t?-1:e>t?1:0}function Dn(e){if(e&&typeof e=="object"){for(let t of Object.values(e))Dn(t);Object.freeze(e)}return e}import{constants as VA}from"node:fs";import{lstat as tj,open as nj}from"node:fs/promises";import{createHash as rj}from"node:crypto";import{posix as HA,win32 as WA}from"node:path";var ij=/^sha256:[a-f0-9]{64}$/u,GA=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,JA=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,oj=4096,YA=6;function sj(e){return Du(ka(e))}function ZA(e){let t=cj(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};lj(r.sourceUrl)||n.push("evidence_source_not_https");let i=Ng(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()+YA),t.getTime()>l.getTime()&&n.push("evidence_stale")}zA(r.binding,"evidence",n),zA(e.currentBinding,"current",n);let o=r.binding&&typeof r.binding=="object"?sj(r.binding):null;(!wo(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"||ka(KA(r.binding))!==ka(KA(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];mr(r.allowCanary,"allow","allowed",!0,!1,r.bindingDigest,i,t,n),mr(r.denyCanary,"deny","denied",!1,!1,r.bindingDigest,i,t,n),mr(r.argumentMutationCanary,"argument_mutation","denied",!1,!1,r.bindingDigest,i,t,n),mr(r.missingAttributionCanary,"missing_attribution","denied",!1,!1,r.bindingDigest,i,t,n),mr(r.enterpriseNonDowngradeCanary,"enterprise_non_downgrade","denied",!1,!1,r.bindingDigest,i,t,n),mr(r.handlerFailureCanary,"handler_failure","denied",!1,!1,r.bindingDigest,i,t,n),mr(r.handlerTimeoutCanary,"handler_timeout","denied",!1,!1,r.bindingDigest,i,t,n),mr(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"||!Bg(r.qualification.hostExecutablePath,l))&&n.push("qualification_host_executable_not_absolute"),wo(r.qualification.hostExecutableSha256)||n.push("qualification_host_digest_invalid"),wo(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 XA(e){if(!Wt(e.agentId))throw new Error(`No strict hook adapter exists for ${e.agentId}.`);if(e.adapterRevision!==St[e.agentId])throw new Error("Strict hook adapter revision does not match the implemented adapter.");if(!JA.test(e.hostVersion))throw new Error("Strict hook host version is invalid.");aj(e.platform);let n=Fg(e.hookConfigPath,e.platform,"hook config path"),r=Fg(e.hookScriptPath,e.platform,"hook script path"),i=Fg(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([Og(n,!1),Og(r,e.platform!=="win32"),Og(i,e.platform!=="win32")]);return Object.freeze({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,adapterRevision:e.adapterRevision,hookConfigPath:n,hookConfigSha256:Du(o),hookScriptPath:r,hookScriptSha256:Du(s),absoluteCliPath:i,cliSha256:Du(a)})}function zA(e,t,n){if(!e||typeof e!="object"){n.push(`${t}_binding_missing`);return}let r=Wt(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}JA.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())Bg(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())wo(s)||n.push(`${t}_digest_${o}_invalid`)}function KA(e){let{hostVersion:t,...n}=e;return n}function mr(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`),GA.test(e.observationId)||l.push(`${t}_observation_id_invalid`),GA.test(e.fixtureId)||l.push(`${t}_fixture_id_invalid`);let c=Ng(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()+YA),a.getTime()>u.getTime()&&l.push(`${t}_canary_stale`)}e.realHostExecution||l.push(`${t}_not_real_host_execution`),(!wo(e.bindingDigest)||e.bindingDigest!==o)&&l.push(`${t}_binding_digest_mismatch`),wo(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 Og(e,t){let n=await tj(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 nj(e,VA.O_RDONLY|VA.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 Fg(e,t,n){if(!Bg(e,t))throw new Error(`Strict ${n} must be absolute for ${t}.`);return(t==="win32"?WA:HA).normalize(e)}function Bg(e,t){return typeof e!="string"||e.length===0||e.length>oj||e.includes("\0")?!1:(t==="win32"?WA:HA).isAbsolute(e)}function aj(e){if(e!=="darwin"&&e!=="linux"&&e!=="win32")throw new Error("Strict hook platform is unsupported.")}function wo(e){return typeof e=="string"&&ij.test(e)}function lj(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 cj(e,t){let n=Ng(e);if(!n)throw new Error(`${t} must be a valid ISO date.`);return n}function Ng(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 ka(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(ka).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${ka(t[n])}`).join(",")}}`}function Du(e){return`sha256:${rj("sha256").update(e).digest("hex")}`}import{createHash as uj}from"node:crypto";import{constants as gr}from"node:fs";import{open as ex}from"node:fs/promises";import{isAbsolute as dj}from"node:path";var Ca="skills-layer-real-host-canary-v1",fj=new Set(["allow","deny","argument_mutation","missing_attribution","enterprise_non_downgrade","handler_failure","handler_timeout","activation_association"]),pj=/^[A-Za-z0-9_-]{43}$/u,tx=/^association_[a-f0-9]{64}$/u,mj=4096,gj=512*1024,hj=16*1024;function bo(e){return Aa(e)?.scenario??null}async function jg(e){let t=Aa(e.env);if(!t||e.activationEvent&&t.scenario!=="activation_association")return!1;let n=e.reportingSource??"hook";if(n==="hook"&&(e.delegatedExecution===!0||QA(e.agentId,e.result)?.value?.includes("atomic guarded execution wrapper")||t.scenario!=="activation_association"&&t.sideEffectPath&&!yj(e.rawPayloadBase64,t.sideEffectPath)))return!1;let r="invalid";try{let i=e.rawPayloadBase64??"";if(Buffer.byteLength(i,"utf8")>gj)throw new Error("Guardian canary payload is too large.");if(r=n==="guarded_execution"?e.result.exitCode===0?"allowed":"denied":vj(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=Tu(t.challenge),s=Tu(`${t.scenario}\0${i}`);try{await $u(t.resultPath,{challenge:t.challenge,driver:Ca,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=QA(e.agentId,e.result);throw await $u(t.diagnosticPath,{schemaVersion:"skills-layer.guardian-canary-diagnostic.v1",challengeDigest:Tu(t.challenge),driver:Ca,agentId:e.agentId,scenario:t.scenario,associationState:e.associationState,activationEvent:e.activationEvent,hostOutcome:r,failureCode:wj(i),...o?{decisionReasonCode:o.code,decisionReasonSha256:Tu(o.value)}:{}}).catch(()=>{}),i}}async function nx(e){let t=Aa(e);return!t||t.scenario!=="activation_association"?!1:(await $u(t.associationPath,{challenge:t.challenge,associationEstablished:!0}),!0)}async function rx(e){let t=Aa(e.env);if(!t)return!1;if(!tx.test(e.associationKey))throw new Error("Guardian canary delegation association key is invalid.");try{await $u(t.delegationPath,{challenge:t.challenge,driver:Ca,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 ix(e){let t=Aa(e.env);if(!t)return null;let n;try{n=await bj(t.delegationPath)}catch(r){if(r.code==="ENOENT")return null;throw r}if(!vo(n)||n.challenge!==t.challenge||n.driver!==Ca||typeof n.agentId!="string"||typeof n.scope!="string"||typeof n.skillSlug!="string"||typeof n.associationKey!="string"||!tx.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 Aa(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!==Ca||!n||!fj.has(n)||!r||!pj.test(r)||!Sa(i)||!Sa(o)||!Sa(s)||!Sa(a)||l!==void 0&&!Sa(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 yj(e,t){if(!e)return!1;try{let n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return Mg(n,t,0)}catch{return!1}}function Mg(e,t,n){return n>16?!1:typeof e=="string"?e.includes(t):Array.isArray(e)?e.some(r=>Mg(r,t,n+1)):vo(e)?Object.values(e).some(r=>Mg(r,t,n+1)):!1}function wj(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 QA(e,t){let n=t.exitCode===0?void 0:t.stderr;if(t.exitCode===0)try{let o=JSON.parse(t.stdout);vo(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=(vo(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 vj(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"||t.stdout==="")return"allowed";let n;try{n=JSON.parse(t.stdout)}catch{throw new Error("Guardian canary hook decision output is invalid.")}if(!vo(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"||n.permission==="ask")return"allowed"}else{let r=vo(n.hookSpecificOutput)?n.hookSpecificOutput:null;if(r?.permissionDecision==="deny")return"denied";if(r?.permissionDecision==="allow"||r?.permissionDecision==="ask")return"allowed"}throw new Error("Guardian canary hook decision output is invalid.")}async function $u(e,t){let n=typeof gr.O_NOFOLLOW=="number"?gr.O_NOFOLLOW:0,r=await ex(e,gr.O_CREAT|gr.O_EXCL|gr.O_WRONLY|n,384);try{await r.writeFile(`${JSON.stringify(t)}
|
|
829
|
+
`,"utf8"),await r.sync()}finally{await r.close()}}async function bj(e){let t=typeof gr.O_NOFOLLOW=="number"?gr.O_NOFOLLOW:0,n=await ex(e,gr.O_RDONLY|t);try{let r=await n.stat();if(!r.isFile()||r.size>hj)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 Sa(e){return typeof e=="string"&&Buffer.byteLength(e,"utf8")<=mj&&dj(e)}function Tu(e){return`sha256:${uj("sha256").update(e,"utf8").digest("hex")}`}function vo(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}var ox=Object.freeze(["SKILLS_LAYER_GUARDIAN_CANARY_DRIVER","SKILLS_LAYER_GUARDIAN_CANARY_SIDE_EFFECT_PATH"]);function sx(e){let t=_j(e.command,e.platform);if(!t)return!1;let n;try{n=lx(e)}catch{return!1}return t.length>n.length&&n.every((r,i)=>t[i]===r)}function ax(e){return lx(e).map(n=>kj(n,e.platform)).join(" ")}function lx(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 _j(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 kj(e,t){return t==="win32"&&e==="&"||/^[A-Za-z0-9_./:\\-]+$/u.test(e)?e:t==="win32"?`"${e.replaceAll('"','\\"')}"`:`'${e.replaceAll("'",`'"'"'`)}'`}var cx={disabled:0,warning:1,enforce:2},Sj=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u;function ux(e){dx(e.requestedMode),e.workspacePolicy!==null&&Cj(e.workspacePolicy);let t=e.workspacePolicy?.requiredMode,n=t!==void 0&&cx[t]>cx[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 Cj(e){if(dx(e.requiredMode),!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Workspace Guardian policy revision is invalid.");if(!Sj.test(e.updatedBy))throw new Error("Workspace Guardian policy updater is invalid.");if(!Aj(e.updatedAt))throw new Error("Workspace Guardian policy timestamp is invalid.")}function dx(e){if(e!=="enforce"&&e!=="warning"&&e!=="disabled")throw new Error("Guardian host mode is invalid.")}function Aj(e){let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}var xj=Object.freeze([Zt("codex",["cli"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","explicit deny","https://github.com/openai/codex","exact_activation_signal_unverified"),Zt("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"),Zt("cline",["ide"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","cancel=true","https://docs.cline.bot/customization/hooks","exact_activation_signal_unverified"),Zt("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"),Zt("antigravity",["ide"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny","https://antigravity.google/docs/hooks?tab=ide","failure_timeout_canary_required"),Zt("antigravity-cli",["cli"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny","https://antigravity.google/docs/hooks?tab=cli","failure_timeout_canary_required"),Zt("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"),Zt("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"),Zt("windsurf",["local_ide"],!0,"unavailable","best_effort","warning_audit","event-specific exit 2","https://docs.windsurf.com/windsurf/cascade/hooks","privileged_surface_incomplete"),Zt("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"),Zt("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 fn(e){return xj.find(t=>t.agentId===e)??null}function Ug(e,t){let n=fn(e);return n?n.maximumTier==="warning_audit"?{capabilityTier:"warning_audit",maximumTier:"warning_audit",supportStatus:"warning_only",supportReasonCode:n.reasonCode,supportLabel:"warning only"}:t?{capabilityTier:"strict_verified",maximumTier:n.maximumTier,supportStatus:"strict_verified",supportReasonCode:null,supportLabel:"can block, verified on this device"}:{capabilityTier:n.maximumTier,maximumTier:n.maximumTier,supportStatus:"candidate_unverified",supportReasonCode:n.reasonCode,supportLabel:"can block, not yet verified"}:{capabilityTier:"unsupported",maximumTier:"unsupported",supportStatus:"unsupported",supportReasonCode:"guardian_host_unknown",supportLabel:"not supported"}}function xa(e){if(e.materializationState==="externally_removed"||e.associationState==="externally_removed")return hr("externally_removed","exact_target_absent");if(e.materializationState==="host_detached"||e.associationState==="host_detached")return hr("host_detached","host_registration_detached");if(e.materializationState==="unreadable"||e.materializationState==="drifted"||e.associationState==="stale")return hr("stale_binding","exact_local_authority_stale");let t=ux({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?hr("candidate_unverified","no_verified_exact_activation_route"):e.hookInstalled&&!e.strictHookVerified&&!e.completeWrapperVerified?hr("candidate_unverified",t.reasonCode):t.activationAllowed?e.evaluationContext==="runtime"&&!e.completeWrapperVerified&&e.associationState!=="active"?hr("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}):hr("unavailable",t.reasonCode):hr("host_unsupported","host_has_no_supported_guardian_route")}function Zt(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 hr(e,t){return Object.freeze({label:e,countedAsEnforced:!1,activationAllowed:!1,runtimeGuardian:!1,reasonCode:t})}import{createHash as Ij,randomBytes as Rj}from"node:crypto";import{constants as yt}from"node:fs";import{chmod as fx,lstat as gx,open as Ra,realpath as Pj,rename as px,unlink as Ia}from"node:fs/promises";import{basename as Lu,dirname as Ej,isAbsolute as hx,join as Ou,posix as Fu}from"node:path";var Dj=1024*1024,Tj=32,$j=2e4,Hg=4096,Lj=/^sha256:[a-f0-9]{64}$/u,Oj=new Set(["__proto__","constructor","prototype"]);function Fj(e){let t=_x(e.agentId),n=Mj(t,e.eventName);qj(e.absoluteScriptPath),e.portableCommand!==void 0&&Uj(t,e.portableCommand);let r=Pa(e.existingJson),i=Jg(r,n),o=Nj(t,n,e.portableCommand??e.absoluteScriptPath),s=_o(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=kx(e.previousOwnership,t,n),d=i.flatMap((m,g)=>_o(m)===u.entrySha256?[g]:[]);if(d.length===0&&e.operation==="restore")return Vg(r,n,[...i,o]),{json:`${JSON.stringify(r,null,2)}
|
|
830
|
+
`,changed:!0,ownership:a};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,g]of i.entries())m===p&&l.push(o),d.includes(m)||l.push(g)}Vg(r,n,l);let c=Ea(Pa(e.existingJson))!==Ea(r);return{json:c?`${JSON.stringify(r,null,2)}
|
|
831
|
+
`:e.existingJson,changed:c,ownership:a}}function Bj(e){let t=_x(e.agentId),n=kx(e.ownership,t,e.ownership.eventName),r=Pa(e.existingJson),i=Jg(r,n.eventName);if(i.filter(a=>_o(a)===n.entrySha256).length===0)throw new Error("Skills Layer hook ownership could not be proven; refusing to remove host config.");let s=i.filter(a=>_o(a)!==n.entrySha256);return Vg(r,n.eventName,s),{json:`${JSON.stringify(r,null,2)}
|
|
832
|
+
`,changed:!0,ownership:n}}async function Nu(e){return await wx(e.configPath,t=>Fj({...e.update,existingJson:t}),e.checkpoint)}async function yx(e){return await wx(e.configPath,t=>Bj({agentId:e.agentId,existingJson:t,ownership:e.ownership}))}async function wx(e,t,n){let r={configPath:e,checkpoint:n};if(!hx(r.configPath)||r.configPath.length>Hg||r.configPath.includes("\0"))throw new Error("Host hook config path must be an absolute bounded path.");let i=Ej(r.configPath),o=await gx(i);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("Host hook config parent must be a real directory, not a symbolic link.");let s=await Pj(i),a=Ou(s,Lu(r.configPath)),l=Rj(12).toString("hex"),c=Ou(s,`.${Lu(a)}.skills-layer.lock`),u=Ou(s,`.${Lu(a)}.skills-layer-stage-${l}`),d=Ou(s,`.${Lu(a)}.skills-layer-backup-${l}`),p=null,m=!1,g=null,h=null,y=384,w=!1,b=!1;try{p=await Ra(c,yt.O_CREAT|yt.O_EXCL|yt.O_WRONLY,384),m=!0,await p.writeFile(`${process.pid}
|
|
833
|
+
`,"utf8"),await p.sync();let _=await Gg(a);h=_?.bytes??null,y=_?.mode??384;let I=h===null?"{}":Buffer.from(h).toString("utf8"),x=t(I);if(!x.changed)return{...x,configPath:a,configSha256:Kg(h)};let C=new TextEncoder().encode(x.json);if(g=await Ra(u,yt.O_CREAT|yt.O_EXCL|yt.O_WRONLY|yt.O_NOFOLLOW,384),await g.writeFile(C),await g.sync(),await g.close(),g=null,h!==null){let j=await Ra(d,yt.O_CREAT|yt.O_EXCL|yt.O_WRONLY|yt.O_NOFOLLOW,384);try{await j.writeFile(h),await j.sync()}finally{await j.close()}w=!0}await Bu(s),await r.checkpoint?.("after_backup");let D=await Gg(a);if(!Gj(h,D?.bytes??null))throw new Error("Host hook config changed concurrently; refusing to overwrite it.");await px(u,a),b=!0,await fx(a,384),await Bu(s),await r.checkpoint?.("after_replace");let T=await mx(a);if(!zg(T.bytes,C))throw new Error("Atomic host hook config verification failed after replacement.");return w&&(await Ia(d),w=!1),await Bu(s),{...x,configPath:a,configSha256:Kg(T.bytes)}}catch(_){if(b)try{if(h===null)await Ia(a).catch(I=>{if(I.code!=="ENOENT")throw I});else{if(!w)throw new Error("Host hook rollback backup is unavailable.");await fx(d,y&511),await px(d,a),w=!1;let I=await mx(a);if(!zg(I.bytes,h))throw new Error("Host hook rollback verification failed.")}await Bu(s)}catch(I){throw new AggregateError([_,I],"Host hook config update and exact rollback both failed.")}throw _}finally{g&&await g.close().catch(()=>{}),p&&await p.close(),await Ia(u).catch(qg),w&&await Ia(d).catch(qg),m&&await Ia(c).catch(qg)}}function Nj(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,...e==="claude-code"?{onFailure:"block"}:{}}]}}function vx(e){if(e.ownerships.length===0)return null;let t;try{return t=Pa(e.configJson),e.ownerships.every(n=>Jg(t,n.eventName).some(r=>_o(r)===n.entrySha256))}catch{return null}}function Wg(e){if(e.agentId==="cursor")return"block";if(e.agentId!=="claude-code")return"host_default";let t;try{t=Pa(e.configJson)}catch{return"unknown"}let n=oi(t.hooks)?t.hooks:{},r=e.ownerships.map(i=>(Array.isArray(n[i.eventName])?n[i.eventName]:[]).find(s=>_o(s)===i.entrySha256));return r.length===0||r.some(i=>i===void 0)?"unknown":r.every(i=>{let o=oi(i)&&Array.isArray(i.hooks)?i.hooks:[];return o.length>0&&o.every(s=>oi(s)&&s.onFailure==="block")})?"block":"continue"}function bx(e){if(e.agentId!=="claude-code"||e.scope!=="project"||e.platform==="win32")return;let t=Fu.dirname(Fu.dirname(Fu.dirname(e.hookPath)));return`"$CLAUDE_PROJECT_DIR"/${Fu.relative(t,e.hookPath)}`}function _x(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 Mj(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 kx(e,t,n){if(!e||e.owner!=="skills-layer"||e.agentId!==t||e.eventName!==n||!Lj.test(e.entrySha256))throw new Error("Valid prior Skills Layer hook ownership evidence is required.");return e}var jj=/^"\$CLAUDE_PROJECT_DIR"(?!.*\/\.{1,2}(?:\/|$))(?:\/[A-Za-z0-9._-]+)+$/u;function Uj(e,t){if(e!=="claude-code"||t.length>Hg||!jj.test(t))throw new Error('A portable Guardian hook command must be "$CLAUDE_PROJECT_DIR"/<relative path> for Claude Code.')}function qj(e){if(!hx(e)||e.length===0||e.length>Hg||e.includes("\0"))throw new Error("Guardian hook script path must be absolute and bounded.")}function Pa(e){if(typeof e!="string"||Buffer.byteLength(e,"utf8")>Dj)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(Vj(t),!oi(t))throw new Error("Host hook config root must be a JSON object.");return t}function Vj(e){let t=0,n=(r,i)=>{if(t+=1,t>$j)throw new Error("Host hook config contains too many JSON values.");if(i>Tj)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(!oi(r))throw new Error("Host hook config contains a non-JSON value.");for(let[o,s]of Object.entries(r)){if(Oj.has(o))throw new Error(`Host hook config contains unsafe key ${o}.`);n(s,i+1)}}};n(e,0)}function Jg(e,t){if(e.hooks===void 0&&(e.hooks={}),!oi(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 Vg(e,t,n){let r=e.hooks;if(!oi(r))throw new Error("Host hook config hooks field must be an object.");r[t]=n}function oi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}async function Gg(e){let t;try{t=await gx(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 Ra(e,yt.O_RDONLY|yt.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 mx(e){let t=await Gg(e);if(!t)throw new Error(`Host hook config disappeared: ${e}`);return t}async function Bu(e){let t=await Ra(e,yt.O_RDONLY);try{await t.sync()}finally{await t.close()}}function Gj(e,t){return e===null||t===null?e===t:zg(e,t)}function zg(e,t){return e.byteLength===t.byteLength&&Buffer.from(e).equals(Buffer.from(t))}function qg(e){if(e.code!=="ENOENT")throw e}function _o(e){return Kg(Ea(e))}function Ea(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Ea).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ea(t[n])}`).join(",")}}`}function Kg(e){return`sha256:${Ij("sha256").update(e).digest("hex")}`}import{createHash as zj,randomBytes as Kj}from"node:crypto";import{constants as wt}from"node:fs";import{chmod as Sx,lstat as xx,open as Da,realpath as Hj,rename as Cx,unlink as ko}from"node:fs/promises";import{basename as Mu,dirname as Wj,isAbsolute as Jj,join as ju}from"node:path";var Ix=1024*1024,Yj=4096,Rx=/^sha256:[a-f0-9]{64}$/u;async function Yg(e){Px(e.filePath);let t=Xj(e.content),n=Xg(t),r=Object.freeze({owner:"skills-layer",fileSha256:n}),i=Wj(e.filePath),o=await xx(i);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("Owned hook parent must be a real directory, not a symbolic link.");let s=await Hj(i),a=ju(s,Mu(e.filePath)),l=Kj(12).toString("hex"),c=ju(s,`.${Mu(a)}.skills-layer.lock`),u=ju(s,`.${Mu(a)}.skills-layer-stage-${l}`),d=ju(s,`.${Mu(a)}.skills-layer-backup-${l}`),p=null,m=null,g=null,h=!1,y=!1;try{if(p=await Da(c,wt.O_CREAT|wt.O_EXCL|wt.O_WRONLY,384),await p.writeFile(`${process.pid}
|
|
834
|
+
`,"utf8"),await p.sync(),g=await Gu(a),Zj(e,g),g!==null&&Vu(g,t))return{filePath:a,fileSha256:n,changed:!1,ownership:r};if(m=await Da(u,wt.O_CREAT|wt.O_EXCL|wt.O_WRONLY|wt.O_NOFOLLOW,448),await m.writeFile(t),await m.sync(),await m.close(),m=null,g!==null){let _=await Da(d,wt.O_CREAT|wt.O_EXCL|wt.O_WRONLY|wt.O_NOFOLLOW,448);try{await _.writeFile(g),await _.sync()}finally{await _.close()}h=!0}await Uu(s),await e.checkpoint?.("after_backup");let w=await Gu(a);if(!Qj(g,w))throw new Error("Owned hook changed concurrently; refusing to overwrite it.");await Cx(u,a),y=!0,await Sx(a,448),await Uu(s),await e.checkpoint?.("after_replace");let b=await Ax(a);if(!Vu(b,t))throw new Error("Atomic owned hook verification failed after replacement.");return h&&(await ko(d),h=!1),await Uu(s),{filePath:a,fileSha256:n,changed:!0,ownership:r}}catch(w){if(y)try{if(g===null)await ko(a).catch(qu);else{if(!h)throw new Error("Owned hook rollback backup is unavailable.");await Cx(d,a),h=!1,await Sx(a,448);let b=await Ax(a);if(!Vu(b,g))throw new Error("Owned hook rollback verification failed.")}await Uu(s)}catch(b){throw new AggregateError([w,b],"Owned hook update and exact rollback both failed.")}throw w}finally{m&&await m.close().catch(()=>{}),p&&await p.close(),await ko(u).catch(qu),h&&await ko(d).catch(qu),await ko(c).catch(qu)}}async function Zg(e){if(Px(e.filePath),e.ownership?.owner!=="skills-layer"||!Rx.test(e.ownership.fileSha256))throw new Error("Owned hook file ownership is invalid.");let t=await Gu(e.filePath);if(t===null)return"missing";if(Xg(t)!==e.ownership.fileSha256)throw new Error("The hook file changed after Skills Layer installed it; refusing to remove it.");return await ko(e.filePath),"removed"}function Zj(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"||!Rx.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(Xg(t)!==n.fileSha256)throw new Error("Owned hook changed outside Skills Layer; ownership digest does not match.")}function Px(e){if(!Jj(e)||e.includes("\0")||Buffer.byteLength(e,"utf8")>Yj)throw new Error("Owned hook path must be an absolute bounded path.")}function Xj(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>Ix)throw new Error("Owned hook content exceeds the 1 MiB maximum.");return t}async function Gu(e){let t;try{t=await xx(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 Da(e,wt.O_RDONLY|wt.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>Ix)throw new Error("Owned hook target exceeds the 1 MiB maximum.");return new Uint8Array(await n.readFile())}finally{await n.close()}}async function Ax(e){let t=await Gu(e);if(t===null)throw new Error(`Owned hook disappeared: ${e}`);return t}async function Uu(e){let t=await Da(e,wt.O_RDONLY);try{await t.sync()}finally{await t.close()}}function Qj(e,t){return e===null||t===null?e===t:Vu(e,t)}function Vu(e,t){return e.byteLength===t.byteLength&&Buffer.from(e).equals(Buffer.from(t))}function Xg(e){return`sha256:${zj("sha256").update(e).digest("hex")}`}function qu(e){if(e.code!=="ENOENT")throw e}var Qg=["Sample input:","Expected output:","## Success criteria"];function Ex(e){return/release notes?/iu.test(e)&&/bullet|plain.?english|customer/iu.test(e)?{input:`Task: Rewrite the following release notes into exactly three short plain-English bullets for customers.
|
|
835
|
+
|
|
836
|
+
Input: Version 2.4 adds CSV export to the reports page, reduces dashboard loading time from six seconds to two, and fixes duplicate email notifications when an invoice is paid.`,output:`- Download your reports as CSV files.
|
|
837
|
+
- Open your dashboard faster.
|
|
838
|
+
- Receive one email when your invoice is paid.`,criteria:"Return exactly three short customer-facing bullets. Preserve all three supplied changes without adding unsupported claims or technical jargon."}:/release/iu.test(e)&&/check|review/iu.test(e)?{input:"Release 2.4: automated tests pass; migration rehearsal passes; rollback instructions are missing; owner approval is pending.",output:`- [x] Confirm passing automated tests.
|
|
839
|
+
- [x] Confirm the migration rehearsal.
|
|
840
|
+
- [ ] Document and review rollback instructions.
|
|
841
|
+
- [ ] Obtain owner approval.
|
|
842
|
+
Decision: hold release until the two open items are resolved.`,criteria:"Account for every supplied release condition. Leave missing evidence and pending approval unresolved, and do not claim the release is ready."}:/plan.*project|project.*plan/iu.test(e)?{input:"Plan a small website launch for Friday. The copy is approved. Sam must build the page before Lee can test it. Deployment follows testing.",output:`1. Sam builds the page using the approved copy.
|
|
843
|
+
2. Lee tests the completed page.
|
|
844
|
+
3. Deploy after testing passes, targeting Friday.
|
|
845
|
+
Confirm available time with Sam and Lee before committing to the date.`,criteria:"Preserve the named owners, dependencies and Friday target. Do not invent estimates or promise a date without availability."}:null}function Dx(e){return`${Qg[0]}
|
|
846
|
+
${e.input}
|
|
847
|
+
|
|
848
|
+
${Qg[1]}
|
|
849
|
+
${e.output}
|
|
850
|
+
|
|
851
|
+
${Qg[2]}
|
|
852
|
+
|
|
853
|
+
${e.criteria}`}var ah=Tt(ei(),1);import{createHash as Fx}from"node:crypto";import{posix as rh}from"node:path";import{createHash as eU}from"node:crypto";var eh=["LICENSE","LICENCE","LICENSE.md","LICENCE.md","LICENSE.txt","COPYING","COPYING.txt"];var WX=256*1024;var zu=`MIT License
|
|
854
|
+
|
|
855
|
+
Copyright (c) <year> <copyright holders>
|
|
856
|
+
|
|
857
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
858
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
859
|
+
in the Software without restriction, including without limitation the rights
|
|
860
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
861
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
862
|
+
furnished to do so, subject to the following conditions:
|
|
863
|
+
|
|
864
|
+
The above copyright notice and this permission notice shall be included in all
|
|
865
|
+
copies or substantial portions of the Software.
|
|
866
|
+
|
|
867
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
868
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
869
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
870
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
871
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
872
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
873
|
+
SOFTWARE.
|
|
874
|
+
`,th={MIT:zu},$x=/^LicenseRef-[A-Za-z0-9](?:[A-Za-z0-9.-]{0,126}[A-Za-z0-9])?$/u,tU=/^[A-Za-z0-9][A-Za-z0-9.+-]*(?:\s+(?:AND|OR|WITH)\s+[A-Za-z0-9][A-Za-z0-9.+-]*)*$/u,Lx=/^LICENSES\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;function So(e){return th[e]}function La(e){return Object.hasOwn(th,e)}function yr(e){let t=e.trim();if(t.length===0||t.length>200)throw new Error("license identifier must be between 1 and 200 characters");if(!$x.test(t)&&!tU.test(t))throw new Error("license identifier must be an SPDX identifier/expression or a namespaced LicenseRef-* identifier");return t}function nh(e){let t=e.trim().replaceAll("\\","/");if(!eh.includes(t)&&!Lx.test(t))throw new Error("license file must be a recognised root licence file or a single bounded LICENSES/* path");return t}function Ku(e,t,n){if(n?.mode==="source_capture")return nU(e,t,n.additionalEvidence??[]);let r=t.license;if(r!==void 0&&(typeof r!="string"||r.trim().length===0))return Tn("license_invalid","license must be a non-empty SPDX or LicenseRef-* string when supplied.");let i=typeof r=="string"?r.trim():void 0,o=i,s=i?"canonical":null;if(o)try{yr(o)}catch(d){let p=d instanceof Error?d.message:"The supplied licence identifier is invalid.";return Tn("license_invalid",p)}let a=aU(e);if(a.status==="invalid")return Tn("license_invalid",a.message);let l=a.file;if(!o&&!l)return Tn("license_missing","Licence not supplied by creator.");if(!o&&l){let d=lU(l.content);return d?{status:"confirmation_required",identifier:null,detectedIdentifier:d,declarationSource:null,filePath:l.path,text:l.content,textSha256:$a(l.content),issues:[si("license_confirmation_required",`A known ${d} licence file was found, but the creator must confirm the identifier before Skills Layer records it.`,"Confirm the detected identifier interactively or set top-level license explicitly; validation-only operation will not change the bundle.")]}:Tn("license_invalid","Licence text exists without a creator-supplied identifier; Skills Layer will not guess custom or ambiguous terms.")}if(o&&!l)return Tn("license_missing","A licence identifier is declared, but the corresponding in-bundle licence text is missing.");let c=o,u=l;if(La(c)){if(oU(u.content))return{status:"recognized_template",identifier:c,detectedIdentifier:null,declarationSource:s,filePath:u.path,text:u.content,textSha256:$a(u.content),issues:[si("license_template_incomplete",`The ${c} template is recognized, but its year and copyright-holder placeholders are incomplete.`,"This does not block publication: the licence is recorded as declared with an incomplete notice. To complete it, replace <year> and <copyright holders> in the licence file.")]};if(!sU(c,u.content))return Tn("license_mismatch",`The supplied ${c} declaration does not match the approved template with a completed copyright line.`)}else if(!$x.test(c))return Tn("license_invalid","This standard licence is not in the approved exact-template set, so Skills Layer cannot verify that its declaration and text agree.");return{status:"verified",identifier:c,detectedIdentifier:null,declarationSource:s,filePath:u.path,text:u.content,textSha256:$a(u.content),issues:[]}}function nU(e,t,n){let r=t.license,i=null,o=[];if(r!==void 0)if(typeof r=="string"&&r.trim())try{i=yr(r)}catch(g){o.push(si("license_invalid",g instanceof Error?g.message:"The supplied licence identifier is invalid.","Review the source declaration and every retained licence evidence location."))}else o.push(si("license_invalid","license must be a non-empty SPDX or LicenseRef-* string when supplied.","Review the source declaration and every retained licence evidence location."));let s=[...e,...n].filter(g=>rU(g.path)&&typeof g.content=="string"&&g.content.length>0).filter((g,h,y)=>y.findIndex(w=>Ta(w.path)===Ta(g.path)&&w.content===g.content)===h),a=s.map(g=>({file:g,identifier:iU(g.content)})),l=a.map(g=>g.identifier).filter(g=>g!==null).filter((g,h,y)=>y.indexOf(g)===h),c=[...i?[i]:[],...l].filter((g,h,y)=>y.indexOf(g)===h),u=s.map(g=>Ta(g.path)).sort((g,h)=>g.localeCompare(h)),d=[...i?["SKILL.md#license"]:[],...u];if(c.length===0)return u.length===0&&o.length===0?Tn("license_missing","Licence not supplied by source."):{status:"unspecified",identifier:null,detectedIdentifier:null,declarationSource:null,filePath:u[0]??null,text:s[0]?.content??null,textSha256:s[0]?$a(s[0].content):null,evidencePaths:d,detectedIdentifiers:l,issues:o.length>0?o:[si("license_invalid","Licence text was found, but no supported SPDX or LicenseRef identifier could be captured.","Review every retained licence evidence location.")]};let p=[...c].sort((g,h)=>Tx(g)-Tx(h)||g.localeCompare(h))[0],m=a.find(g=>g.identifier===p)?.file??null;return c.length>1&&o.push(si("license_conflict_resolved",`Conflicting licence evidence declared ${c.join(", ")}; selected ${p} using the documented permissiveness order while retaining every evidence location.`,"Review all retained licence evidence; the selected display licence does not remove or override other applicable terms.")),{status:"declared",identifier:p,detectedIdentifier:m?p:null,declarationSource:p===i?"canonical":"detected",filePath:m?Ta(m.path):null,text:m?.content??null,textSha256:m?$a(m.content):null,evidencePaths:d,detectedIdentifiers:l,issues:o}}function rU(e){let t=Ta(e),n=t.split("/").at(-1)?.toUpperCase()??"";return eh.includes(n)||/^(?:LICENSE|LICENCE|COPYING)(?:[._-].+)?$/u.test(n)||/(?:^|\/)LICENSES\/[^/]+$/iu.test(t)}function Ta(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function iU(e){let t=/(?:^|\n)\s*(?:#|\/\/|\/\*|\*)?\s*SPDX-License-Identifier:\s*([^\r\n*]+?)(?:\s*\*\/)?\s*$/imu.exec(e)?.[1]?.trim();if(t)try{return yr(t)}catch{}return/CC0 1\.0 Universal|Creative Commons Zero v?1\.0/iu.test(e)?"CC0-1.0":/free and unencumbered software released into the public domain/iu.test(e)?"Unlicense":/Zero-Clause BSD|BSD Zero Clause/iu.test(e)?"0BSD":/^MIT License\s*$/imu.test(e)&&/Permission is hereby granted, free of charge/iu.test(e)?"MIT":/Apache License\s+Version 2\.0, January 2004/iu.test(e)?"Apache-2.0":/Mozilla Public License\s+Version 2\.0/iu.test(e)?"MPL-2.0":/GNU AFFERO GENERAL PUBLIC LICENSE/iu.test(e)?"AGPL-3.0-only":/GNU LESSER GENERAL PUBLIC LICENSE/iu.test(e)?"LGPL-3.0-only":/GNU GENERAL PUBLIC LICENSE[\s\S]{0,80}Version 3/iu.test(e)?"GPL-3.0-only":/GNU GENERAL PUBLIC LICENSE[\s\S]{0,80}Version 2/iu.test(e)?"GPL-2.0-only":/Redistribution and use in source and binary forms/iu.test(e)&&/Neither the name/iu.test(e)?"BSD-3-Clause":/Redistribution and use in source and binary forms/iu.test(e)?"BSD-2-Clause":/Permission to use, copy, modify, and\/or distribute this software for any purpose with or without fee/iu.test(e)?"ISC":null}function Tx(e){let t=e.toUpperCase();return t==="CC0-1.0"||t==="UNLICENSE"?0:t==="0BSD"?1:t==="MIT"||t==="ISC"||t.startsWith("BSD-")?2:t==="APACHE-2.0"?3:t==="MPL-2.0"?4:t.startsWith("LGPL-")?5:t.startsWith("GPL-")?6:t.startsWith("AGPL-")?7:50}function oU(e){let t="Copyright (c) <year> <copyright holders>",n=zu.indexOf(t),r=zu.slice(0,n),i=zu.slice(n+t.length).trimEnd(),o=e.replace(/\r\n?/gu,`
|
|
875
|
+
`).trim();return o.startsWith(r)&&o.endsWith(i)&&/<(?:year|copyright holders)>/u.test(o.slice(r.length,o.length-i.length))}function sU(e,t){if(e!=="MIT")return!1;let n="Copyright (c) <year> <copyright holders>",r=So(e),i=r.indexOf(n),o=r.slice(0,i),s=r.slice(i+n.length);if(!t.startsWith(o)||!t.endsWith(s))return!1;let a=t.slice(o.length,t.length-s.length);return/^Copyright \(c\) \d{4}(?:-\d{4})? [^\r\n<>]+$/u.test(a)}function aU(e){let t=e.map(i=>({...i,path:i.path.replaceAll("\\","/").replace(/^\.\//u,"")})),n=new Set(eh),r=t.filter(i=>(n.has(i.path)||Lx.test(i.path))&&typeof i.content=="string"&&i.content.length>0);return r.length>1?{status:"invalid",message:"Multiple licence files are present; keep exactly one supported root or LICENSES/* file so Skills Layer does not guess which terms apply."}:{status:"ok",file:r[0]?{path:r[0].path,content:r[0].content}:null}}function lU(e){for(let t of Object.keys(th))if(e===So(t))return t;return null}function Tn(e,t){return{status:"unspecified",identifier:null,detectedIdentifier:null,declarationSource:null,filePath:null,text:null,textSha256:null,issues:[si(e,t,"Run interactive `skills-layer validate <path>` or `skills-layer creator init` to select a template, import exact terms, or explicitly skip.")]}}function si(e,t,n){return{severity:"warning",code:e,message:t,nextAction:"creator.license",nextStep:n}}function $a(e){return eU("sha256").update(e,"utf8").digest("hex")}var cU=64,uU=5e3,dU=1200,oh="release_strict",fU=/(^|\/)SKILL\.md$/,pU=[/(^|\n)#+\s+examples?\b/i,/(^|\n)#+\s+usage examples?\b/i,/(^|\n)#+\s+\u793A\u4F8B(?=$|\s)/u,/(^|\n)#+\s+\u4F8B\u5B50(?=$|\s)/u,/(^|\n)#+\s+\u7528\u4F8B(?=$|\s)/u],mU=[/(^|\n)#+\s+troubleshooting\b/i,/(^|\n)#+\s+trouble shooting\b/i,/(^|\n)#+\s+\u6545\u969C\u6392\u9664(?=$|\s)/u,/(^|\n)#+\s+\u95EE\u9898\u6392\u67E5(?=$|\s)/u,/(^|\n)#+\s+\u6392\u9519(?=$|\s)/u],gU=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+|[\p{L}\p{N}_-]+/gu,hU=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;function Ie(e,t={}){let n=t.profile??"legacy_v1",r=[],i=e.filter(p=>fU.test(p.path)),o=e.some(p=>p.path.includes("/references/")||p.path.startsWith("references/"));if(i.length===0)return r.push(pn("skill-missing","Bundle must contain exactly one SKILL.md file")),ih(n,!1,r,e.length,0,o);i.length>1&&r.push(pn("skill-duplicate","Bundle must not contain more than one SKILL.md file"));let s=i[0];if(!s||typeof s.content!="string")return r.push(pn("skill-content-missing","SKILL.md content must be available for validation")),ih(n,!1,r,e.length,0,o);let a;try{a=lr(s.content)}catch(p){let m=p instanceof Error?p.message:"Unknown frontmatter parsing error";return r.push(pn("frontmatter-invalid",m)),n==="external_ingest_tolerant"&&r.push($n("external-normalisation-needed","The external skill is recognizable but must be normalized before release")),ih(n,n==="external_ingest_tolerant",r,e.length,0,o)}/^Helps with [^.]+\.$/u.test(a.frontmatter.description.trim())&&r.push($n("scaffold-description-placeholder","Replace the scaffold description with the skill's concrete purpose and when to use it."));let l=new Set(rc(e).filter(p=>p.type==="runtime").map(p=>p.path));for(let p of e)if(!(!l.has(p.path)||!p.path.endsWith(".md")||!p.content))for(let m of p.content.matchAll(/\]\(([^)\s]+)(?:\s+[^)]*)?\)/gu)){let g=m[1].split("#",1)[0];if(!g||/^(?:[a-z][a-z0-9+.-]*:|\/)/iu.test(g))continue;let h=rh.normalize(rh.join(rh.dirname(p.path),g));l.has(h)||r.push($n("runtime-reference-missing",`Runtime reference ${h} from ${p.path} is absent or excluded from the installed artifact.`))}let c=yU(a.body),u=wU(a.frontmatter.metadata);u&&r.push(u);let d=Ku(e,a.frontmatter);return r.push(...d.issues),r.push(...vU({files:e,skillFilePath:s.path,parsedSkill:a,profile:n})),Ox(a.body,pU)||r.push($n("examples-missing","Consider adding an Examples section to improve skill usability")),Ox(a.body,mU)||r.push($n("troubleshooting-missing","Consider adding a Troubleshooting section for common failure cases")),c>uU&&r.push($n("skill-body-too-long","SKILL.md body should stay under 5000 words for progressive disclosure")),c>dU&&!o&&r.push($n("references-missing","Large skills should move detailed material into references/")),{profile:n,ingestible:i.length===1,valid:r.every(p=>p.severity!=="error"),issues:r,parsedSkill:a,excludedFromRuntime:Wi(e),license:d,stats:{fileCount:e.length,bodyWordCount:c,hasReferences:o}}}function yU(e){let t=e.trim();if(t.length===0)return 0;let n=t.match(gU);return n?n.reduce((r,i)=>r+(hU.test(i)?i.length:1),0):0}function pn(e,t){return{severity:"error",code:e,message:t}}function $n(e,t){return{severity:"warning",code:e,message:t}}function Ox(e,t){return t.some(n=>n.test(e))}function wU(e){return e?.price_cents===void 0?null:$n("price-cents-non-authoritative","metadata.price_cents is ignored; marketplace pricing is stored in the version pricing authority")}function ih(e,t,n,r,i,o){return{profile:e,ingestible:t,valid:!1,issues:n,stats:{fileCount:r,bodyWordCount:i,hasReferences:o}}}function vU(e){let t=[],n=rc(e.files),r=n.find(p=>p.type==="control");if(r){let p=e.files.find(m=>m.path.replaceAll("\\","/").replace(/^\.\//u,"")===r.path);try{let m=uo(p?.content??"");if(m.agentCompatibility){let g=e.parsedSkill.frontmatter.compatibilityMatrix;g&&JSON.stringify(g)!==JSON.stringify(m.agentCompatibility)?t.push(pn("compatibility-declaration-conflict","agentCompatibility in .skills-layer/skill.yaml differs from agent_compatibility in SKILL.md; declare it in one place.")):(e.parsedSkill.frontmatter.compatibilityMatrix=m.agentCompatibility,e.parsedSkill.frontmatter.metadata={...e.parsedSkill.frontmatter.metadata,agent_compatibility:m.agentCompatibility})}}catch(m){t.push(pn("control-manifest-invalid",m.message))}}if(e.profile==="legacy_v1")return t;let o=e.profile!=="external_ingest_tolerant"?pn:$n,s=e.parsedSkill.frontmatter.name;s.length>cU&&t.push(o("portable-name-too-long","Portable skill names must be 64 characters or fewer"));let l=e.skillFilePath.replaceAll("\\","/").split("/").filter(Boolean),c=l.length>1?l.at(-2):void 0;c&&c!==s&&t.push(o("portable-directory-name-mismatch","Portable skill name must match the directory containing SKILL.md")),e.parsedSkill.frontmatter.compatibility!==void 0&&t.push(o("unverified-compatibility-claim","Compatibility claims belong in evidence-backed control data, not portable runtime frontmatter"));let u=e.parsedSkill.frontmatter.metadata,d=["category","license","license_file","price_cents","skills_layer","tags","visibility"].filter(p=>u&&Object.hasOwn(u,p));return d.length>0&&t.push(o("runtime-control-metadata",`Skills Layer control metadata must not be stored in portable runtime frontmatter: ${d.join(", ")}`)),n.some(p=>p.reasonCode==="misplaced_control_manifest")&&t.push(pn("control-manifest-misplaced","The Skills Layer control manifest is allowed only at the skill root")),n.some(p=>p.reasonCode==="unsupported_control_material")&&t.push(pn("control-material-unsupported","Only root .skills-layer/skill.yaml is supported as control material")),n.filter(p=>p.type==="control").length>1&&t.push(pn("control-manifest-duplicate","A skill bundle may contain only one root control manifest")),t}var Co=["general","software-engineering","data-and-analytics","documents-and-content","research-and-knowledge","business-operations","security-and-compliance","custom"],bU={general:wr("general","General",["inputs","decisions","outputs","success","failures"],[],["repetition","size"]),"software-engineering":wr("software-engineering","Software engineering",["repository_context","languages","test_commands","failure_recovery","change_boundaries"],["shell_execution","source_mutation","secrets"],["deterministic_scripts","project_conventions","target_adapters"]),"data-and-analytics":wr("data-and-analytics","Data and analytics",["data_sources","schema","quality_checks","statistical_limits","output_shape"],["sensitive_data","query_cost","misleading_inference"],["schema_references","repeatable_transform","output_templates"]),"documents-and-content":wr("documents-and-content","Documents and content",["audience","source_material","tone","layout","review_criteria"],["private_content","copyright","unsafe_claims"],["style_references","document_templates","render_checks"]),"research-and-knowledge":wr("research-and-knowledge","Research and knowledge",["research_question","source_quality","recency","citation_style","uncertainty"],["source_injection","personal_data","unsupported_claims"],["source_policy","reference_corpus","citation_template"]),"business-operations":wr("business-operations","Business operations",["business_event","approvals","systems_of_record","exceptions","handoffs"],["external_mutation","financial_action","identity"],["process_reference","repeatable_checklist","system_adapter"]),"security-and-compliance":wr("security-and-compliance","Security and compliance",["control_objective","threat_model","evidence","severity","escalation"],["credential_exposure","destructive_action","policy_bypass"],["control_catalog","deterministic_scanner","evidence_template"]),custom:wr("custom","Custom",["domain_definition","special_terms","decision_rules","success","failures"],["domain_specific_risks"],["domain_knowledge","repeatability","target_mapping"])};function sh(e){let t=bU[e];return{...t,questionIds:[...t.questionIds],questions:t.questions.map(n=>({...n})),riskPrompts:[...t.riskPrompts],resourceSignals:[...t.resourceSignals]}}function wr(e,t,n,r,i){return{id:e,label:t,questionIds:n,questions:n.map(o=>({id:o,prompt:_U(o)})),riskPrompts:r,resourceSignals:i}}function _U(e){return{inputs:"What inputs will the skill receive, and which are required?",decisions:"Which decisions must the skill make, and what rules govern them?",outputs:"What exact output should a successful run produce?",success:"What observable evidence proves the outcome is correct?",failures:"Which failures must stop, redirect, or be reported explicitly?",repository_context:"Which repository structure, conventions, and boundaries must the skill inspect?",languages:"Which languages, runtimes, and supported versions are in scope?",test_commands:"Which exact validation commands prove the change works?",failure_recovery:"How should partial failures be recovered without damaging user work?",change_boundaries:"Which files, systems, and side effects are permitted or forbidden?",data_sources:"Which data sources are authoritative, and how are they accessed?",schema:"Which schemas, keys, types, and relationships must be preserved?",quality_checks:"Which deterministic checks establish data quality?",statistical_limits:"Which assumptions, uncertainty, or statistical limits must be disclosed?",output_shape:"What exact tables, fields, charts, or file formats are required?",audience:"Who will use the output, and what do they already understand?",source_material:"Which source material is authoritative and how large is it?",tone:"Which tone, terminology, and style constraints must be followed?",layout:"Which layout, template, rendering, or accessibility requirements apply?",review_criteria:"Which review checks must pass before the artifact is complete?",research_question:"What precise question should the research answer?",source_quality:"Which source types are acceptable, preferred, or forbidden?",recency:"How current must the evidence be, and when is browsing required?",citation_style:"How must claims, citations, and links be represented?",uncertainty:"How should conflicting or incomplete evidence be communicated?",business_event:"Which event starts the process and which outcome closes it?",approvals:"Which approvals are required before each consequential action?",systems_of_record:"Which systems are authoritative for reading and writing state?",exceptions:"Which exceptions require a stop, escalation, or alternate path?",handoffs:"Who receives each handoff and what evidence must accompany it?",control_objective:"Which control objective and protected asset are in scope?",threat_model:"Which actors, attack paths, and trust boundaries must be considered?",evidence:"Which evidence is sufficient, reproducible, and safe to retain?",severity:"How are likelihood, impact, confidence, and severity determined?",escalation:"Which findings require blocking, escalation, or emergency handling?",domain_definition:"Define the specialist domain and the boundary of this skill.",special_terms:"Which domain terms need precise definitions?",decision_rules:"Which domain rules drive decisions and exceptions?",domain_specific_risks:"Which domain-specific harms or misuse cases must be prevented?"}[e]}var kU="skills-layer.creator.draft-plan.v1";function Bx(e){CU(e.skillSlug);let t=e.outcome.trim().replace(/\s+/gu," ");if(!t)throw new Error("Quick Creator outcome must not be empty");let n=SU(e.description??`${t.replace(/[.!?]+$/u,"")}. Use when the user explicitly requests this outcome.`),r=Ex(e.description??t),i=(0,ah.stringify)({name:e.skillSlug,description:n,...e.license?{license:e.license}:{}},{lineWidth:0}).trimEnd(),o=[{path:".skills-layer/skill.yaml",content:(0,ah.stringify)({schemaVersion:"skills-layer.control.v2",listing:{visibility:"private"},toolContract:{requestedCapabilities:[],requestedTools:[],networkDomains:[],fileReadScopes:[],fileWriteScopes:[]},targets:[]},{lineWidth:0})},{path:"SKILL.md",content:`---
|
|
876
|
+
${i}
|
|
877
|
+
---
|
|
878
|
+
|
|
879
|
+
# ${AU(e.skillSlug)}
|
|
880
|
+
|
|
881
|
+
## Procedure
|
|
882
|
+
|
|
883
|
+
1. Confirm the request explicitly matches this outcome: ${t}
|
|
884
|
+
2. Ask for any missing inputs or constraints before acting.
|
|
885
|
+
3. Perform the smallest safe workflow that produces the requested outcome.
|
|
886
|
+
4. Check the result and clearly report any unresolved condition.
|
|
887
|
+
|
|
888
|
+
## Examples
|
|
889
|
+
|
|
890
|
+
${r?Dx(r):"Supply a realistic example input, its expected output, and a success criterion for this task before validation."}
|
|
891
|
+
|
|
892
|
+
## Troubleshooting
|
|
893
|
+
|
|
894
|
+
- If intent or authority is unclear, stop and ask for clarification.
|
|
895
|
+
- If a required tool or resource is unavailable, report it instead of inventing a result.
|
|
896
|
+
`}];if(!Ie(o,{profile:"native_creator_strict"}).valid)throw new Error("Quick Creator generated an invalid portable draft");let a=o.map(l=>({path:l.path,action:"create",previousDigest:null,nextDigest:Nx(l)}));return{schemaVersion:kU,skillSlug:e.skillSlug,files:o,changes:a,workspaceDigest:Hu(o),planDigest:Hu(o),planeDigests:Nb(o),placeholderCount:0,defaultCapabilityCount:0}}function SU(e){let t=e.trim().replace(/\s+/gu," ");if(!t)throw new Error("Creator description must not be empty");if(t.length>1024)throw new Error("Creator description must be 1024 characters or fewer");return t}function CU(e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(e)||e.length>64)throw new Error("Creator skill slug must be kebab-case and 64 characters or fewer")}function AU(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Nx(e){return`sha256:${Fx("sha256").update(re(e)).digest("hex")}`}function Hu(e){return`sha256:${Fx("sha256").update(JSON.stringify(e.map(t=>({path:t.path,digest:Nx(t)})))).digest("hex")}`}var lh=Tt(ei(),1);var xU=["standalone","workflow_automation","mcp_enhanced"];function Mx(e){let t=e?.trim();if(!t)return"standalone";if(t==="workflow")return"workflow_automation";if(!xU.includes(t))throw new Error(`Unsupported skill type "${t}". Supported types: standalone, workflow, workflow_automation, mcp_enhanced.`);return t}function jx(e){RU(e);let t=PU(e.licenseSelection??{mode:"skip"}),n={path:".skills-layer/skill.yaml",content:EU(e)};return[...[{path:"SKILL.md",content:e.quickOutcome===void 0?IU(e):Bx({skillSlug:e.skillSlug,outcome:e.quickOutcome,description:e.description,...e.licenseSelection&&e.licenseSelection.mode!=="skip"?{license:e.licenseSelection.identifier}:{}}).files.find(i=>i.path==="SKILL.md").content},...t],n]}function IU(e){let t=e.licenseSelection??{mode:"skip"},n=t.mode==="skip"?{}:{license:t.identifier},r=(0,lh.stringify)({name:e.skillSlug,description:e.description,...n},{lineWidth:0}).trimEnd(),i=e.description.replace(/\s+/gu," ").trim().toLowerCase();return`---
|
|
897
|
+
${r}
|
|
898
|
+
---
|
|
899
|
+
# ${DU(e.skillSlug)}
|
|
900
|
+
|
|
901
|
+
## Procedure
|
|
902
|
+
|
|
903
|
+
1. Confirm the request explicitly matches this outcome: ${i}
|
|
904
|
+
2. Ask for missing inputs, constraints, or authority before acting.
|
|
905
|
+
3. Perform the smallest safe workflow that produces the requested outcome.
|
|
906
|
+
4. Validate the result and report any unresolved condition.
|
|
907
|
+
|
|
908
|
+
## Example
|
|
909
|
+
|
|
910
|
+
- Help me with ${TU(e.skillSlug)}
|
|
911
|
+
|
|
912
|
+
## Troubleshooting and Stop Conditions
|
|
913
|
+
|
|
914
|
+
- If intent or authority is unclear, stop and ask for clarification.
|
|
915
|
+
- If a required tool or resource is unavailable, report it instead of inventing a result.
|
|
916
|
+
`}function RU(e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(e.skillSlug))throw new Error("skillSlug must be kebab-case");if(e.skillSlug.length>64)throw new Error("skillSlug must be 64 characters or fewer");if(e.description.trim().length===0)throw new Error("description must be a non-empty string");if(e.description.length>1024)throw new Error("description must be 1024 characters or fewer");if(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(e.description))throw new Error("description contains unsupported control characters");let t=e.licenseSelection;if(!t||t.mode==="skip")return;let n=yr(t.identifier);if(t.mode==="template"&&!La(n))throw new Error(`No approved immutable licence template is available for ${n}`);if(t.mode!=="template"){if(t.text.length===0)throw new Error("creator-supplied licence text must not be empty");if(Buffer.byteLength(t.text,"utf8")>256*1024)throw new Error("creator-supplied licence text must be 256 KiB or smaller");nh(t.filePath??"LICENSE")}}function PU(e){return e.mode==="skip"?[]:e.mode==="template"?[{path:"LICENSE",content:So(e.identifier)}]:[{path:nh(e.filePath??"LICENSE"),content:e.text}]}function EU(e){return(0,lh.stringify)({schemaVersion:"skills-layer.control.v2",listing:{visibility:"private",priceCents:0,category:$U(e)},toolContract:{requestedCapabilities:[],requestedTools:[],networkDomains:[],fileReadScopes:[],fileWriteScopes:[]},targets:[]},{lineWidth:0})}function DU(e){return Ux(e).split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ").replaceAll("\0","-")}function TU(e){return Ux(e).replaceAll("-"," ").replaceAll("\0","-")}function Ux(e){return e.replace(/-(?=\d{9,}(?:-|$))/gu,"\0")}function $U(e){let t=Zm(e.category);return t||gC({name:e.skillSlug,slug:e.skillSlug,description:e.description,skillType:e.skillType}).category}async function qx(e){let t=await LU(e.suggestedDomain,e.promptText),n=sh(t),r=[];for(let o of n.questions){let s=Wu(await e.promptText(`${o.prompt}
|
|
917
|
+
> `));s&&r.push(`Domain context (${o.id}): ${s}`)}let i=n.riskPrompts.length===0?[]:Ao(await e.promptText(`What safeguards address these ${n.label} risks: ${n.riskPrompts.join(", ")}? Separate multiple safeguards with " | ".
|
|
918
|
+
> `));return{selectedDomain:t,domainConfirmed:!0,representativeTasks:[await Ln(e.promptText,"Give one representative request that should activate this skill.")],negativeExamples:[await Ln(e.promptText,"Give one out-of-scope request that must not activate this skill.")],paraphrases:[await Ln(e.promptText,"Give one alternate phrasing of the representative request.")],nearMisses:[await Ln(e.promptText,"Give one near-miss request that should stop or redirect safely.")],successCriteria:Oa(await Ln(e.promptText,'What observable criteria prove success? Separate multiple criteria with " | ".')),failureConditions:Oa(await Ln(e.promptText,'Which known conditions mean the workflow cannot safely complete? Separate multiple conditions with " | ".')),expectedOutputs:Oa(await Ln(e.promptText,'What exact output should a successful run produce? Separate multiple outputs with " | ".')),safetyConstraints:[...Oa(await Ln(e.promptText,'Which safety constraints must always hold? Separate multiple constraints with " | ".')),...i],constraints:[...Oa(await Ln(e.promptText,'Which input, authority, time, cost, or scope constraints apply? Separate multiple constraints with " | ".')),...r],reusableKnowledge:Ao(await e.promptText(`What reusable knowledge could move to references/? Leave blank for none; separate items with " | ".
|
|
919
|
+
> `)),repeatedSteps:Ao(await e.promptText(`Which repeated deterministic steps could become a script? Leave blank for none; separate items with " | ".
|
|
920
|
+
> `)),fragileSteps:Ao(await e.promptText(`Which fragile steps need deterministic validation? Leave blank for none; separate items with " | ".
|
|
921
|
+
> `)),targetAgents:Ao(await e.promptText(`Which agents have actually been verified? Leave blank for none; separate IDs with " | ".
|
|
922
|
+
> `)),referenceMaterialBytes:await ch(e.promptText,"Approximate reusable reference-material size in bytes (blank if unknown):"),assetPayloadBytes:await ch(e.promptText,"Approximate reusable asset size in bytes (blank if none/unknown):"),expectedRunsPerMonth:await ch(e.promptText,"Expected runs per month (blank if unknown):")}}function Vx(e){if(!e||typeof e!="object")return"general";let t=e.data;if(!t||typeof t!="object")return"general";let n=t.domainProfile,r=t.session,i=r&&typeof r=="object"?r.domainSuggestion:void 0,o=n&&typeof n=="object"?n.id:i&&typeof i=="object"?i.profileId:void 0;return typeof o=="string"&&Co.includes(o)?o:"general"}function Gx(e){if(!e||typeof e!="object")return null;let t=e.data;if(!t||typeof t!="object")return null;let n=t.session;if(!n||typeof n!="object")return null;let r=n.skillSlug;return typeof r=="string"&&r.trim()?r:null}async function LU(e,t){let n=Wu(await t(`Suggested domain: ${e}. Press Enter to accept, or enter one of: ${Co.join(", ")}.
|
|
923
|
+
> `));if(!n)return e;if(!Co.includes(n))throw new Error(`Unknown Creator domain profile: ${n}`);return n}async function Ln(e,t){let n=Wu(await e(`${t}
|
|
924
|
+
> `));if(!n)throw new Error("Interactive Creator interview answers must not be empty");return n}async function ch(e,t){let n=Wu(await e(`${t}
|
|
925
|
+
> `));if(!n)return null;let r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new Error(`${t} requires a non-negative safe integer`);return r}function Oa(e){let t=Ao(e);if(t.length===0)throw new Error("Interactive Creator interview answers must not be empty");return t}function Ao(e){return e.split("|").map(t=>t.trim()).filter(Boolean)}function Wu(e){return e.trim().replace(/\s+/gu," ")}var RQ={domain:mn("domain","Confirm or change the suggested domain.","The domain selects the relevant safeguards and terminology.",{type:"string",enum:Co}),activation:mn("activation","Give a representative request that should activate this skill.","A positive example defines when the skill is useful.",{type:"string",minLength:1}),boundaries:mn("boundaries","Describe an out-of-scope request, a near miss, and an alternate activation phrasing.","Boundaries prevent accidental activation.",Fa(["negativeExamples","nearMisses","paraphrases"])),outputs:mn("outputs","Describe the expected output and observable success criteria.","The workflow needs a testable result.",Fa(["expectedOutputs","successCriteria"])),failures:mn("failures","Which known conditions mean the workflow cannot safely complete?","Known failure conditions make stopping behaviour explicit.",Ju()),safety:mn("safety","Describe safety constraints and operating constraints.","Authority, cost, time and scope boundaries must be explicit.",Fa(["safetyConstraints","constraints"])),domain_requirements:mn("domain_requirements","Describe domain-specific requirements and safeguards.","Domain context keeps the skill accurate without opening extra questions.",Fa(["constraints","safetyConstraints"])),resources:mn("resources","Identify reusable knowledge and approximate reference or asset sizes.","This drives the explainable resource recommendation.",{type:"object",required:["reusableKnowledge"],properties:{reusableKnowledge:Ju(!0),referenceMaterialBytes:uh(),assetPayloadBytes:uh()},additionalProperties:!1}),repeatability:mn("repeatability","Identify repeatable and fragile steps.","Repeated or fragile work may need scripts and deterministic validation.",Fa(["repeatedSteps","fragileSteps"],!0)),confirmation:mn("confirmation","Confirm the normalized interview and provide verified target agents and expected monthly use.","Confirmation prevents Creator from inventing missing intent.",{type:"object",required:["confirmed"],properties:{confirmed:{const:!0},targetAgents:Ju(!0),expectedRunsPerMonth:uh()},additionalProperties:!1})};function Yu(e,t){let n=t.trim();if(!n)throw new Error("Creator interview answer must not be empty");if(e==="domain"||e==="activation")return n;if(n.startsWith("{")||n.startsWith("["))try{return JSON.parse(n)}catch{throw new Error("Creator interview answer must be valid JSON")}let r=OU(n);return e==="failures"?r:e==="domain_requirements"?{constraints:[r[0]],safetyConstraints:r.slice(1)}:e==="boundaries"?{negativeExamples:[r[0]],nearMisses:[r[1]],paraphrases:[r[2]]}:e==="outputs"?{expectedOutputs:[r[0]],successCriteria:[r[1]]}:e==="safety"?{safetyConstraints:[r[0]],constraints:r.slice(1)}:e==="repeatability"?{repeatedSteps:[r[0]],fragileSteps:r.slice(1)}:e==="resources"?{reusableKnowledge:r,referenceMaterialBytes:null,assetPayloadBytes:null}:{confirmed:/^(?:y|yes|confirm|confirmed)$/iu.test(n),targetAgents:[],expectedRunsPerMonth:null}}function mn(e,t,n,r){return{id:e,prompt:t,whyAsked:n,required:!0,answerSchema:r}}function Ju(e=!1){return{type:"array",minItems:e?0:1,items:{type:"string",minLength:1}}}function uh(){return{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}function Fa(e,t=!1){return{type:"object",required:e,properties:Object.fromEntries(e.map(n=>[n,Ju(t)])),additionalProperties:!1}}function OU(e){let t=e.split("|").map(n=>n.trim()).filter(Boolean);if(t.length===0)throw new Error("Creator interview answer must not be empty");return t}var Ba=class extends Error{constructor(n,r){super(n);this.reasonCode=r}reasonCode};function zx(e,t){if(!dh(e)||!dh(e.workspace))throw ai("Creator materialization response is missing its workspace.");let n=BU(t??e.skillSlug);if(!n)throw new Ba("Creator materialization response is missing a portable skill slug; rerun with --dir or inspect the session.","creator_materialization_slug_missing");if(!Array.isArray(e.workspace.files)||e.workspace.files.length===0)throw ai("Creator materialization response contains no files.");let r=e.workspace.files.map((s,a)=>FU(s,a)),i=e.workspace.digest;if(typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i))throw ai("Creator materialization response is missing a valid workspace digest.");if(Hu(r)!==i)throw new Ba("Creator materialization workspace digest does not match the returned files.","creator_materialization_digest_mismatch");return{skillSlug:n,files:r,workspaceDigest:i}}function FU(e,t){if(!dh(e)||typeof e.path!="string")throw ai(`Creator materialization file ${t+1} is malformed.`);let n=typeof e.content=="string",r=typeof e.contentBase64=="string";if(n===r)throw ai(`Creator materialization file ${e.path} must contain exactly one byte representation.`);if(e.mediaType!==void 0&&typeof e.mediaType!="string")throw ai(`Creator materialization file ${e.path} has an invalid media type.`);let i={path:e.path,...n?{content:e.content}:{contentBase64:e.contentBase64},...typeof e.mediaType=="string"?{mediaType:e.mediaType}:{}};try{re(i)}catch(o){throw ai(o instanceof Error?o.message:`Creator materialization file ${e.path} is invalid.`)}return i}function BU(e){if(typeof e!="string")return null;let t=e.trim();return/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(t)&&t.length<=64?t:null}function ai(e){return new Ba(e,"creator_materialization_snapshot_invalid")}function dh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomUUID as NU}from"node:crypto";import{constants as On}from"node:fs";import{lstat as Xt,mkdir as Zu,mkdtemp as MU,open as fh,realpath as Xu,readdir as jU,rename as Na,rm as Kx}from"node:fs/promises";import{basename as UU,dirname as Ma,isAbsolute as qU,join as gn,parse as ph,posix as Wx,resolve as ed,sep as Qu}from"node:path";var Hx=16*1024*1024,VU=64*1024*1024,mh=typeof On.O_NOFOLLOW=="number"?On.O_NOFOLLOW:0;async function Jx(e){let t=await Qx(e);await vr(t);let n=await hh(t);return{exists:n.exists,files:n.files.map(r=>({path:r.relativePath,...Je(r.bytes)}))}}async function Yx(e){return(await Zx(e)).plan}async function td(e){let t=await Zx(e);if(t.plan.confirmationRequired&&!e.confirmed)return{status:"confirmation_required",plan:t.plan};let n=t.targetDir,r=Ma(n);await vr(r),await Zu(r,{recursive:!0}),await vr(r);let i=[...t.tree.files.map(c=>c.relativePath),...e.files.map(c=>c.path)].reduce((c,u)=>Math.max(c,u.length),0),o=GU({parentDir:r,longestRelativePath:i,platform:process.platform});await vr(o);let s=await MU(gn(o,".skills-layer-stage-")),a=null,l=!0;try{t.tree.exists&&await WU(t.tree,s);for(let c of e.files)await JU(s,c);if(await ZU(n,t.tree),!t.tree.exists)return await li(()=>Na(s,n)),l=!1,{status:"created",plan:t.plan};a=gn(o,`.skills-layer-backup-${NU()}`),await li(()=>Na(n,a));try{await li(()=>Na(s,n)),l=!1}catch(c){throw await li(()=>Na(a,n)),a=null,c}return await li(()=>Kx(a,{recursive:!0,force:!0})),a=null,{status:"replaced",plan:t.plan}}finally{l&&await li(()=>Kx(s,{recursive:!0,force:!0})),a&&await XU(n,a)}}function GU(e){if(e.platform!=="win32")return e.parentDir;let t=ph(e.parentDir).root,n=Qu.length+26+Qu.length+e.longestRelativePath,r=e.parentDir;for(;r!==t&&r.length+n>tq;)r=Ma(r);return r}async function gh(e,t=256*1024){let n=await eI(ed(e));if(await vr(n),(await Xt(n)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${n}`);let i=await Xu(n);await vr(i);let o=await Xx(i,t);return Buffer.from(o).toString("utf8")}async function Zx(e){zU(e.files);let t=ed(e.targetDir),n=await Qx(t);await vr(n);let r=await hh(n),i=new Map(r.files.map(l=>[l.relativePath,l])),o=new Set(r.directories.map(l=>l.relativePath)),s=e.files.map(l=>{let c=i.get(l.path);if(o.has(l.path))throw new Error(`Scaffold file ${l.path} conflicts with an existing directory.`);let u=re(l),d=u.byteLength;if(!c)return{path:l.path,action:"create",previousBytes:null,nextBytes:d};let p=Buffer.from(c.bytes).equals(Buffer.from(u));return{path:l.path,action:p?"unchanged":"replace",previousBytes:c.bytes.byteLength,nextBytes:d}}),a=r.files.length+r.directories.length;return{tree:r,targetDir:n,plan:{targetDir:t,targetExists:r.exists,confirmationRequired:r.exists&&a>0,preservedEntryCount:a,changes:s}}}function zU(e){let t=new Set,n=new Map,r=new Set(e.map(o=>o.path));for(let o of e){if(KU(o.path),t.has(o.path))throw new Error(`Scaffold contains duplicate generated path ${o.path}.`);t.add(o.path);let s=o.path.normalize("NFC").toLocaleLowerCase("en-US"),a=n.get(s);if(a&&a!==o.path)throw new Error(`Scaffold contains a cross-platform path collision: ${a} and ${o.path}.`);n.set(s,o.path);let l=o.path.split("/");for(let c=1;c<l.length;c+=1){let u=l.slice(0,c).join("/");if(r.has(u))throw new Error(`Scaffold file ${u} conflicts with generated descendant ${o.path}.`)}}let i=Ie(e);if(!i.valid)throw new Error(`Scaffold bundle validation failed: ${i.issues.filter(o=>o.severity==="error").map(o=>`${o.code}: ${o.message}`).join("; ")}`)}function KU(e){let t=e.split("/");if(e.length===0||e.includes("\\")||e.includes("\0")||qU(e)||Wx.normalize(e)!==e||e===".."||e.startsWith("../")||e!==e.normalize("NFC")||e.length>1024||t.some(n=>!HU(n)))throw new Error(`Unsafe scaffold path: ${e}`)}function HU(e){if(!e||e.length>255||/[<>:"|?*\u0000-\u001f]/u.test(e)||/[ .]$/u.test(e))return!1;let t=e.split(".")[0].toUpperCase();return!nq.has(t)}async function hh(e){let t;try{t=await Xt(e,{bigint:!0})}catch(s){if(xo(s))return{exists:!1,identity:null,files:[],directories:[]};throw s}if(t.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${e}`);if(!t.isDirectory())throw new Error(`Scaffold target must be a directory: ${e}`);let n=[],r=[],i=0,o=async(s,a)=>{let l=await Xt(s,{bigint:!0});if(l.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${s}`);if(!l.isDirectory())throw new Error(`Scaffold target changed while it was inspected: ${s}`);let c=(await jU(s,{withFileTypes:!0})).sort((d,p)=>d.name.localeCompare(p.name));for(let d of c){let p=gn(s,d.name),m=a?Wx.join(a,d.name):d.name,g=await Xt(p,{bigint:!0});if(g.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${p}`);if(g.isDirectory()){r.push({relativePath:m,absolutePath:p}),await o(p,m);continue}if(!g.isFile())throw new Error(`Scaffold transaction refuses non-regular filesystem entries: ${p}`);let h=Number(g.size);if(h>Hx||i+h>VU)throw new Error("Existing scaffold target exceeds the bounded transaction copy limit.");let y=await Xx(p,Hx);i+=y.byteLength,n.push({relativePath:m,absolutePath:p,bytes:y})}let u=await Xt(s,{bigint:!0});if(u.dev!==l.dev||u.ino!==l.ino||!u.isDirectory())throw new Error(`Scaffold target changed while it was inspected: ${s}`)};return await o(e,""),{exists:!0,identity:{dev:t.dev,ino:t.ino},files:n,directories:r}}async function Xx(e,t){let n=await fh(e,On.O_RDONLY|mh);try{let r=await n.stat();if(!r.isFile())throw new Error(`Expected a regular file: ${e}`);if(r.size>t)throw new Error(`File exceeds the bounded read limit: ${e}`);return new Uint8Array(await n.readFile())}finally{await n.close()}}async function WU(e,t){for(let n of e.directories)await Zu(gn(t,...n.relativePath.split("/")),{recursive:!0});for(let n of e.files){let r=gn(t,...n.relativePath.split("/"));await Zu(Ma(r),{recursive:!0}),await YU(r,n.bytes)}}async function JU(e,t){let n=gn(e,...t.path.split("/"));await Zu(Ma(n),{recursive:!0});let r=await fh(n,On.O_WRONLY|On.O_CREAT|On.O_TRUNC|mh,384);try{await r.writeFile(re(t)),await r.sync()}finally{await r.close()}}async function YU(e,t){let n=await fh(e,On.O_WRONLY|On.O_CREAT|On.O_EXCL|mh,384);try{await n.writeFile(t)}finally{await n.close()}}async function vr(e){let t=ed(e),n=ph(t).root,r=t.slice(n.length).split(Qu).filter(Boolean),i=n;for(let o of r){i=gn(i,o);try{if((await Xt(i)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${i}`)}catch(s){if(xo(s))return;throw s}}}async function Qx(e){let t=await eI(ed(e));await vr(t);try{if((await Xt(t)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${t}`);return await Xu(t)}catch(o){if(!xo(o))throw o}let n=[],r=t;for(;;)try{await Xt(r);break}catch(o){if(!xo(o))throw o;let s=Ma(r);if(s===r)throw new Error(`Unable to resolve scaffold target parent: ${t}`);n.unshift(UU(r)),r=s}let i=await Xu(r);return gn(i,...n)}async function eI(e){let t=ph(e).root,n=e.slice(t.length).split(Qu).filter(Boolean);if(n.length===0)return e;let r=gn(t,n[0]);return(await Xt(r)).isSymbolicLink()?gn(await Xu(r),...n.slice(1)):e}async function ZU(e,t){let n=await hh(e);if(n.exists!==t.exists)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");if(!t.exists)return;if(!t.identity||!n.identity||n.identity.dev!==t.identity.dev||n.identity.ino!==t.identity.ino)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");let r=t.directories.map(o=>o.relativePath),i=n.directories.map(o=>o.relativePath);if(r.join("\0")!==i.join("\0"))throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");if(n.files.length!==t.files.length)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");for(let o=0;o<t.files.length;o+=1){let s=t.files[o],a=n.files[o];if(s.relativePath!==a.relativePath||!Buffer.from(s.bytes).equals(Buffer.from(a.bytes)))throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.")}}async function XU(e,t){try{await Xt(t)}catch(n){if(xo(n))return;throw n}try{await Xt(e)}catch(n){if(xo(n)){await li(()=>Na(t,e));return}throw n}throw new Error(`Scaffold backup requires manual recovery: ${t}`)}async function li(e,t={}){let n=t.maximumAttempts??5;if(!Number.isInteger(n)||n<1||n>10)throw new Error("Filesystem retry maximumAttempts must be between 1 and 10.");let r=t.wait??(i=>new Promise(o=>setTimeout(o,i)));for(let i=1;;i+=1)try{return await e()}catch(o){if(!QU(o)||i>=n)throw o;await r(Math.min(160,10*2**(i-1)))}}function QU(e){return typeof e=="object"&&e!==null&&"code"in e&&eq.has(String(e.code))}function xo(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}var eq=new Set(["EPERM","EBUSY","ENOTEMPTY","EACCES"]),tq=240,nq=new Set(["CON","PRN","AUX","NUL","CLOCK$",...Array.from({length:9},(e,t)=>`COM${t+1}`),...Array.from({length:9},(e,t)=>`LPT${t+1}`)]);var tI="skills-layer.creator.platform-telemetry.v1";function nI(e){return e==="darwin"?"macos":e==="linux"?"linux":e==="win32"?"windows":"other"}function rI(e){let t={schemaVersion:tI,...e};if(!iI(t))throw new Error("Creator platform telemetry event is invalid or contains unsupported fields");return t}function iI(e){return!rq(e)||Object.keys(e).sort().join("\0")!==["nodeMajor","occurredAt","operation","operationId","osFamily","outcome","schemaVersion"].sort().join("\0")?!1:e.schemaVersion===tI&&(e.osFamily==="macos"||e.osFamily==="linux"||e.osFamily==="windows"||e.osFamily==="other")&&Number.isInteger(e.nodeMajor)&&Number(e.nodeMajor)>=18&&Number(e.nodeMajor)<=99&&(e.operation==="plan"||e.operation==="materialize"||e.operation==="patch"||e.operation==="recover")&&(e.outcome==="succeeded"||e.outcome==="failed"||e.outcome==="recovered")&&typeof e.operationId=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.operationId)&&typeof e.occurredAt=="string"&&Number.isFinite(Date.parse(e.occurredAt))}async function oI(e){if(!iI(e.event))throw new Error("Creator platform telemetry event is invalid");try{return await e.publish(e.event),"accepted"}catch{return"ignored"}}function rq(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{resolve as sI}from"node:path";function yh(e,t){let n=e.filter(o=>/(^|\/)SKILL\.md$/u.test(o.path)&&typeof o.content=="string");if(n.length!==1||!n[0]?.content)throw new Error("Licence remediation requires exactly one readable SKILL.md file.");let r=t.mode==="template"?"LICENSE":t.filePath??"LICENSE",i=t.mode==="template"?So(t.identifier):t.text;return[{path:n[0].path,content:AC(n[0].content,t.identifier,r)},{path:r,content:i}]}async function nd(e){if((e.explicitCopyrightHolder!==void 0||e.explicitYear!==void 0)&&(e.skip||e.explicitLicenseFile||e.explicitIdentifier!=="MIT"))throw new Error("creator validate template completion requires --license MIT without --license-file or --skip-license.");if(e.skip&&(e.explicitIdentifier||e.explicitLicenseFile))throw new Error("--skip-license cannot be combined with --license or --license-file.");if(e.explicitLicenseFile&&!e.explicitIdentifier)throw new Error("--license-file requires --license <SPDX-or-LicenseRef-identifier>.");if(e.skip)return{selection:{mode:"skip"},source:"skip"};if(e.explicitIdentifier){let i=yr(e.explicitIdentifier);if(e.explicitLicenseFile)return{selection:{mode:"custom",identifier:i,text:await gh(sI(e.cwd,e.explicitLicenseFile)),filePath:"LICENSE"},source:"explicit_import"};if(!La(i))throw new Error(`--license ${i} requires --license-file because Skills Layer will not invent or guess terms.`);return{selection:{mode:"template",identifier:i,...e.explicitCopyrightHolder===void 0?{}:{copyrightHolder:e.explicitCopyrightHolder},...e.explicitYear===void 0?{}:{year:e.explicitYear}},source:"explicit_template"}}let t=iq(e.files??[]);if(t?.status==="verified"||t?.status==="recognized_template")return{selection:aI(t),source:"existing"};if(!e.interactive||!e.prompt)return{selection:{mode:"skip"},source:"skip"};let n=[];t?.status==="confirmation_required"&&t.detectedIdentifier&&t.text&&t.filePath&&n.push({value:`existing:${t.detectedIdentifier}`,label:`Confirm detected ${t.detectedIdentifier} terms`,description:`Preserve ${t.filePath} byte-for-byte and bind its detected identifier.`}),n.push({value:"template:MIT",label:"Use the approved MIT template",description:"Creator-selected immutable standard template; review and replace placeholders before publication."},{value:"import",label:"Import my exact terms",description:"Supply an SPDX/LicenseRef identifier and a local text file; Skills Layer will not alter it."},{value:"skip",label:"Skip for now",description:"Continue with a visible, non-blocking license_missing warning."});let r=await e.prompt.select("Choose optional creator licence terms:",n);if(!r||r==="skip")return{selection:{mode:"skip"},source:"skip"};if(r.startsWith("existing:")&&t?.text&&t.filePath)return{selection:aI(t),source:"existing"};if(r==="template:MIT")return{selection:{mode:"template",identifier:"MIT"},source:"interactive_template"};if(r==="import"){let i=yr(await e.prompt.text("SPDX or LicenseRef-* identifier: ")),o=(await e.prompt.text("Path to the exact licence terms file: ")).trim();if(!o)throw new Error("A licence terms file path is required for import.");return{selection:{mode:"custom",identifier:i,text:await gh(sI(e.cwd,o)),filePath:"LICENSE"},source:"interactive_import"}}throw new Error("Unsupported creator licence selection.")}function iq(e){let t=e.filter(n=>/(^|\/)SKILL\.md$/u.test(n.path)&&typeof n.content=="string");if(t.length!==1||!t[0]?.content)return null;try{return Ku(e,lr(t[0].content).frontmatter)}catch{return null}}function aI(e){if(!e.identifier&&!e.detectedIdentifier)throw new Error("Existing licence selection requires a creator-confirmed identifier.");if(!e.text||!e.filePath)throw new Error("Existing licence selection requires exact in-bundle terms.");return{mode:"existing",identifier:e.identifier??e.detectedIdentifier,text:e.text,filePath:e.filePath}}var lI={maxPatternBytes:512,maxWildcards:8},oq=new Set(["[","]","(",")","{","}","+","?","|"]);function ja(e,t=lI){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>t.maxPatternBytes||!Number.isSafeInteger(t.maxWildcards)||t.maxWildcards<0)return Io();let n=e.startsWith("^"),r=e.endsWith("$")&&!sq(e,e.length-1),i=n?1:0,o=r?e.length-1:e.length;if(i>=o)return Io();let s=[""],a=0,l=!1;for(let c=i;c<o;c+=1){let u=e[c];if(l){s[s.length-1]+=u,l=!1;continue}if(u==="\\"){l=!0;continue}if(u==="*"){if(s[s.length-1]===""&&s.length>1)continue;if(a+=1,a>t.maxWildcards)return Io();s.push("");continue}if(oq.has(u)||u==="^"||u==="$"||u.charCodeAt(0)<32||u.charCodeAt(0)===127)return Io();s[s.length-1]+=u}return l||s.every(c=>c.length===0)?Io():{valid:!0,anchoredStart:n,anchoredEnd:r,segments:s,wildcardCount:a}}function cI(e,t,n=lI){let r=ja(t,n);if(!r.valid)return{matched:!1,reasonCode:"unsafe_pattern"};let{segments:i,anchoredStart:o,anchoredEnd:s,wildcardCount:a}=r;if(a===0){let c=i[0];return o&&s?{matched:e===c}:o?{matched:e.startsWith(c)}:s?{matched:e.endsWith(c)}:{matched:e.includes(c)}}let l=0;for(let c=0;c<i.length;c+=1){let u=i[c];if(u.length===0)continue;let d=c===0,p=c===i.length-1;if(d&&o){if(!e.startsWith(u))return{matched:!1};l=u.length;continue}if(p&&s)return{matched:e.length-u.length>=l&&e.endsWith(u)};let m=e.indexOf(u,l);if(m<0)return{matched:!1};l=m+u.length}return{matched:!0}}function sq(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function Io(){return{valid:!1,reasonCode:"unsafe_pattern"}}var br=Object.freeze({schemaVersion:"skills-layer.eval.resource-policy.v1",maxPackBytes:256*1024,maxNestingDepth:16,maxObjectKeys:4096,maxCases:64,maxAssertions:512,maxPatternBytes:512,maxPatternWildcards:8,maxPathBytes:512,maxFiles:256,maxFileBytes:1024*1024,maxScannedBytes:8*1024*1024,maxOpaqueFileBytes:20*1024*1024,maxOpaqueBytes:20*1024*1024,maxJsonDepth:32,maxJsonKeys:4096,maxDurationMs:5e3,maxResultBytes:256*1024});function rd(e,t=br){let n=dI(e,{maxBytes:t.maxPackBytes,maxDepth:t.maxNestingDepth,maxKeys:t.maxObjectKeys,rootPath:"$"});if(!n.valid)return n;if(!wh(e))return Qe("invalid_pack","eval-pack-invalid","$","Eval pack must be an object");let r=e.cases;if(Array.isArray(r)&&r.length>t.maxCases)return Qe("resource_limit","eval-pack-case-limit","$.cases","Eval case count exceeds the checked resource policy.");let i=0;if(Array.isArray(r))for(let o=0;o<r.length;o+=1){let s=r[o];if(!(!wh(s)||!Array.isArray(s.assertions))){if(i+=s.assertions.length,i>t.maxAssertions)return Qe("resource_limit","eval-pack-assertion-limit",`$.cases[${o}].assertions`,"Eval assertion count exceeds the checked resource policy.");for(let a=0;a<s.assertions.length;a+=1){let l=s.assertions[a];if(!wh(l))continue;let c=`$.cases[${o}].assertions[${a}]`;if(l.type==="regex_match"&&!ja(l.pattern,{maxPatternBytes:t.maxPatternBytes,maxWildcards:t.maxPatternWildcards}).valid)return Qe("unsafe_pattern","eval-pack-unsafe-pattern",`${c}.pattern`,"Eval pattern is outside the bounded literal/glob language.");if(l.path!==void 0&&!fI(l.path,t.maxPathBytes))return Qe("invalid_pack","eval-pack-target-path-invalid",`${c}.path`,"Eval target must be a bounded portable relative path.")}}}return{valid:!0,outcome:"valid",issues:[]}}function id(e,t=br){if(!Array.isArray(e)||e.length>t.maxFiles)return Qe("resource_limit","eval-file-count-limit","$files","Eval file count exceeds the checked resource policy.");let n=0,r=0,i=new Set;for(let o=0;o<e.length;o+=1){let s=e[o];if(!s||!fI(s.path,t.maxPathBytes)||i.has(uI(s.path)))return Qe("invalid_pack","eval-file-path-invalid",`$files[${o}].path`,"Eval file paths must be unique bounded portable relative paths.");i.add(uI(s.path));let a;try{a=Ki(s)}catch{return Qe("invalid_pack","eval-file-content-invalid",`$files[${o}]`,"Eval file content must use one canonical byte representation.")}if(aq(s)){if(a>t.maxOpaqueFileBytes)return Qe("resource_limit","eval-opaque-file-byte-limit",`$files[${o}]`,"Eval opaque asset exceeds the per-file byte limit.");if(r+=a,r>t.maxOpaqueBytes)return Qe("resource_limit","eval-opaque-byte-limit","$files","Eval opaque asset bytes exceed the cumulative byte limit.")}else{if(a>t.maxFileBytes)return Qe("resource_limit","eval-file-byte-limit",`$files[${o}]`,"Eval target file exceeds the per-file byte limit.");if(n+=a,n>t.maxScannedBytes)return Qe("resource_limit","eval-scan-byte-limit","$files","Eval target bytes exceed the cumulative scan limit.")}}return{valid:!0,outcome:"valid",issues:[]}}function vh(e,t=br){return dI(e,{maxBytes:t.maxFileBytes,maxDepth:t.maxJsonDepth,maxKeys:t.maxJsonKeys,rootPath:"$json"})}function dI(e,t){let n=new WeakSet,r=[{value:e,depth:0,path:t.rootPath}],i=0,o=0;for(;r.length>0;){let s=r.pop();if(s.depth>t.maxDepth)return Qe("resource_limit","eval-nesting-limit",s.path,"Eval input exceeds the nesting-depth limit.");if(typeof s.value=="string")i+=Buffer.byteLength(s.value,"utf8");else if(typeof s.value=="number"||typeof s.value=="boolean")i+=String(s.value).length;else if(s.value===null)i+=4;else if(typeof s.value=="object"){if(n.has(s.value))return Qe("invalid_pack","eval-cycle-invalid",s.path,"Eval input must be acyclic JSON data.");if(n.add(s.value),Array.isArray(s.value)){o+=s.value.length;for(let a=s.value.length-1;a>=0;a-=1)r.push({value:s.value[a],depth:s.depth+1,path:`${s.path}[${a}]`})}else for(let[a,l]of Object.entries(s.value))o+=1,i+=Buffer.byteLength(a,"utf8"),r.push({value:l,depth:s.depth+1,path:`${s.path}.${a}`})}else if(s.value!==void 0)return Qe("invalid_pack","eval-json-type-invalid",s.path,"Eval input must contain JSON-compatible values only.");if(o>t.maxKeys||i>t.maxBytes)return Qe("resource_limit","eval-byte-or-key-limit",s.path,"Eval input exceeds the checked byte or key limit.")}return{valid:!0,outcome:"valid",issues:[]}}function fI(e,t){return typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>t||e.includes("\\")||e.includes("\0")||e.startsWith("/")||/^[A-Za-z]:/u.test(e)?!1:e.split("/").every(r=>r.length>0&&r!=="."&&r!=="..")}function uI(e){return e.normalize("NFC").toLowerCase()}function aq(e){return typeof e.contentBase64=="string"&&typeof e.content!="string"}function wh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qe(e,t,n,r){return{valid:!1,outcome:e,issues:[{code:t,path:n,message:r}]}}function pI(e={}){let t=e.maxScannedBytes??br.maxScannedBytes;if(!Number.isSafeInteger(t)||t<0)throw new Error("Eval scan budget must be a non-negative safe integer.");return{maxScannedBytes:t,scannedBytes:0}}function sd(e,t){switch(e.type){case"file_exists":return bh(t.files,ci(e.path))?Ro("file_exists"):Ot("file_missing");case"json_valid":return lq(e,t);case"section_exists":return cq(e,t);case"regex_match":return uq(e,t);case"schema_match":return dq(e,t);case"artifact_valid":return fq(e,t);case"max_duration_ms":return Ct("runner_unavailable");case"command_exit":return Ct("runner_unavailable");default:return Ct("assertion_type_unsupported")}}function lq(e,t){let n=bh(t.files,ci(e.path));if(!n)return Ot("file_missing");let r=Ua(n,t);if(!r.ok)return Ct(r.reasonCode);try{let i=JSON.parse(r.content);return vh(i).valid?Ro("json_valid"):Ct("resource_limit")}catch{return Ot("json_invalid")}}function cq(e,t){let n=ci(e.target);if(!n)return Ot("section_target_missing");for(let r of t.files){let i=Ua(r,t);if(!i.ok){if(i.reasonCode==="opaque_asset_not_text")continue;return Ct(i.reasonCode)}if(i.content.split(/\r?\n/u).some(o=>pq(o,n)))return Ro("section_exists")}return Ot("section_missing")}function uq(e,t){let n=ci(e.pattern);if(!n)return Ot("regex_missing");if(!ja(n).valid)return Ct("unsafe_pattern");let r=ci(e.path),i=r?t.files.filter(s=>od(s.path)===od(r)):t.files,o=!1;for(let s of i){let a=Ua(s,t);if(!a.ok){if(a.reasonCode==="opaque_asset_not_text"){o=!0;continue}return Ct(a.reasonCode)}if(cI(a.content,n).matched)return Ro("regex_matched")}return r&&o?Ct("opaque_asset_not_text"):Ot("regex_not_matched")}function dq(e,t){let n=bh(t.files,ci(e.path));if(!n)return Ot("file_missing");let r=Ua(n,t);if(!r.ok)return Ct(r.reasonCode);let i;try{i=JSON.parse(r.content)}catch{return Ot("json_invalid")}return vh(i).valid?mq(i)?(Array.isArray(e.requiredKeys)?e.requiredKeys.map(String):[]).every(s=>Object.prototype.hasOwnProperty.call(i,s))?Ro("schema_matched"):Ot("schema_required_key_missing"):Ot("schema_target_not_object"):Ct("resource_limit")}function fq(e,t){let n=id(t.files);if(!n.valid)return Ct(n.outcome);for(let r of t.files){let i=Ua(r,t);if(!i.ok&&i.reasonCode!=="opaque_asset_not_text")return Ct(i.reasonCode)}return Fe(t.files)===ci(e.artifactDigest)?Ro("artifact_digest_matched"):Ot("artifact_digest_mismatch")}function bh(e,t){if(!t)return;let n=od(t);return e.find(r=>od(r.path)===n)}function ci(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function od(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function Ua(e,t){if(typeof e.contentBase64=="string"&&typeof e.content!="string")return{ok:!1,reasonCode:"opaque_asset_not_text"};let n=e.content??"",r=Buffer.byteLength(n,"utf8");if(r>br.maxFileBytes)return{ok:!1,reasonCode:"resource_limit"};if(t.scanBudget){if(t.scanBudget.scannedBytes+r>t.scanBudget.maxScannedBytes)return{ok:!1,reasonCode:"resource_limit"};t.scanBudget.scannedBytes+=r}return{ok:!0,content:n}}function pq(e,t){let n=e.trimStart(),r=0;for(;n[r]==="#";)r+=1;return r===0||n[r]!==" "?!1:n.slice(r+1).trim().localeCompare(t.trim(),void 0,{sensitivity:"accent"})===0}function mq(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ro(e){return{status:"passed",reasonCode:e}}function Ot(e){return{status:"failed",reasonCode:e}}function Ct(e){return{status:"skipped",reasonCode:e}}import{createHash as gq}from"node:crypto";var hq=["submitted","inferred","submitted_plus_inferred"],yq=["starter","reviewed","verified"],wq=["file_exists","json_valid","schema_match","section_exists","regex_match","command_exit","artifact_valid","max_duration_ms"],vq=new Set(hq),bq=new Set(yq),_q=new Set(wq);function ld(e){let t=rd(e);if(!t.valid)return{valid:!1,issues:t.issues};let n=[],r=e;return r.schemaVersion!=="skills-layer.eval.pack.v1"&&n.push(Ft("eval-pack-schema-invalid","$.schemaVersion","Eval pack schemaVersion is unsupported")),(typeof r.artifactDigest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(r.artifactDigest))&&n.push(Ft("eval-pack-artifact-digest-invalid","$.artifactDigest","Eval pack must target a sha256 artifact digest")),(typeof r.origin!="string"||!vq.has(r.origin))&&n.push(Ft("eval-pack-origin-invalid","$.origin","Eval pack origin is not canonical")),(typeof r.confidence!="string"||!bq.has(r.confidence))&&n.push(Ft("eval-pack-confidence-invalid","$.confidence","Eval pack confidence is not canonical")),typeof r.creatorReviewed!="boolean"&&n.push(Ft("eval-pack-review-invalid","$.creatorReviewed","Eval pack must state whether the creator reviewed it")),(!ad(r.redaction)||r.redaction.mode!=="content_free")&&n.push(Ft("eval-pack-redaction-invalid","$.redaction.mode","Eval pack must use content_free redaction by default")),!Array.isArray(r.cases)||r.cases.length===0?n.push(Ft("eval-pack-cases-invalid","$.cases","Eval pack must include at least one case")):kq(r.cases,n),{valid:n.length===0,issues:n}}function Po(e){return`sha256:${gq("sha256").update(Sq(e)).digest("hex")}`}function kq(e,t){let n=new Set;e.forEach((r,i)=>{let o=`$.cases[${i}]`;if(!ad(r)){t.push(Ft("eval-pack-case-invalid",o,"Eval case must be an object"));return}if(typeof r.id!="string"||r.id.trim().length===0?t.push(Ft("eval-pack-case-id-invalid",`${o}.id`,"Eval case id is required")):n.has(r.id)?t.push(Ft("eval-pack-case-id-duplicate",`${o}.id`,"Eval case ids must be unique")):n.add(r.id),!Array.isArray(r.assertions)||r.assertions.length===0){t.push(Ft("eval-pack-assertions-invalid",`${o}.assertions`,"Eval case must include assertions"));return}r.assertions.forEach((s,a)=>{let l=`${o}.assertions[${a}]`;(!ad(s)||typeof s.type!="string"||!_q.has(s.type))&&t.push(Ft("eval-pack-assertion-type-invalid",`${l}.type`,"Eval assertion type is not supported"))})})}function Sq(e){return JSON.stringify(_h(e))}function _h(e){return Array.isArray(e)?e.map(_h).sort(Cq):ad(e)?Object.fromEntries(Object.entries(e).filter(([t])=>t!=="evalPackDigest").sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,_h(n)])):e}function Cq(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}function ad(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ft(e,t,n){return{code:e,path:t,message:n}}function gI(e){let t=e.assertionsPassed+e.assertionsFailed,n={coverageRatio:mI(e.evaluatedCapabilities,e.declaredCapabilities),passRate:t===0?0:mI(e.assertionsPassed,t),freshnessFactor:xq(e),evidenceConfidence:e.evidenceConfidenceOverride===void 0?Aq(e):cd(qa(e.evidenceConfidenceOverride)),baselineDelta:qa(Math.max(0,e.baselineDelta??0)),telemetrySignal:qa(e.aggregationThresholdMet?e.telemetrySignal??0:0)},r=cd(n.coverageRatio*.25+n.passRate*.25+n.freshnessFactor*.15+n.evidenceConfidence*.2+n.baselineDelta*.05+n.telemetrySignal*.1);return{components:n,overallScore:r,effectiveScorePercent:Rq(r*100),assertionsFailed:e.assertionsFailed,executedAssertions:t,aggregationThresholdMet:e.aggregationThresholdMet}}function hI(e){return e.executedAssertions===0&&e.components.coverageRatio===0?"unknown":e.components.freshnessFactor===0?"stale":e.assertionsFailed>0&&e.components.passRate<.8?"failing":e.overallScore>=.8&&e.components.coverageRatio>=.8&&e.components.passRate>=.9&&e.components.evidenceConfidence>=.7?"strong":e.aggregationThresholdMet&&e.components.telemetrySignal>=.7?"telemetry-backed":"limited"}function Aq(e){let t=e.origin==="submitted"?.65:e.origin==="submitted_plus_inferred"?.55:.25,n=e.creatorReviewed?.15:0,r=Math.min(e.runCount*.03,.15),i=Math.min(new Set(e.runnerTypes).size*.04,.1),o=e.aggregationThresholdMet?.1:0;return cd(qa(t+n+r+i+o))}function xq(e){if(e.freshnessPolicy==="never")return 1;if(!e.generatedAt||!e.now)return 0;let t=Date.parse(e.generatedAt),n=Date.parse(e.now);if(!Number.isFinite(t)||!Number.isFinite(n)||n<t)return 0;let r=Iq(e.freshnessPolicy);return n-t<=r?1:0}function Iq(e){return e==="3_months"?2160*60*60*1e3:e==="6_months"?4392*60*60*1e3:365*24*60*60*1e3}function mI(e,t){return t<=0?0:cd(qa(e/t))}function qa(e){return Math.max(0,Math.min(1,e))}function cd(e){return Math.round(e*1e4)/1e4}function Rq(e){return Math.round(e*10)/10}var kh=["passed","failed","not_run","generated_only","policy_skipped","runner_unavailable"],lee=new Set(kh);function Eo(e){return{schemaVersion:"skills-layer.eval.summary.v1",status:e.status,skillSlug:e.skillSlug,version:e.version,...e.generationId?{generationId:e.generationId}:{},artifactDigest:e.artifactDigest,...e.evalPackDigest?{evalPackDigest:e.evalPackDigest}:{},...e.runnerVersion?{runnerVersion:e.runnerVersion}:{},generatedAt:e.generatedAt,...e.counts?{counts:e.counts}:{},redaction:{mode:"content_free",rawContentIncluded:!1}}}function Pq(e){return e==="limited"||e==="unknown"?"attention_needed":"ready"}function Sh(e){let t=Fe(e),n=Wf(e),r=e.map(l=>zt(l.path,e)).filter(l=>l.type==="evidence"),i=Eq(e),o=i?"submitted":"inferred",s=gI({declaredCapabilities:4,evaluatedCapabilities:i?2:1,assertionsPassed:0,assertionsFailed:0,assertionsSkipped:0,origin:o,creatorReviewed:!1,runCount:0,runnerTypes:["dry"],aggregationThresholdMet:!1,freshnessPolicy:"never"}),a=hI(s);return{schemaVersion:"skills-layer.eval.readiness.v1",status:Pq(a),label:a,artifactDigest:t,origin:o,confidence:"starter",creatorReviewed:!1,runtimeFileCount:n.length,evidenceFileCount:r.length,excludedEvidencePaths:r.map(l=>l.path),evaluation:"not_run",summaryEnvelope:{requiredOnSubmit:!0,statuses:[...kh]},nextAction:"creator.submit",nextStep:"Add representative Eval cases, preview trigger behavior, then submit with the mandatory redacted Eval summary.",improvements:["Add representative should-trigger, should-not-trigger, and paraphrase cases.","Review the generated assertions and cover every advertised core capability."],recommendedCommands:["skills-layer preview-trigger <path>","skills-layer validate <path>"]}}function Eq(e){return e.map(t=>zt(t.path,e)).some(t=>t.type==="evidence"&&(t.relativePath.startsWith("evals/")||t.relativePath.endsWith(".eval.json")||t.relativePath.endsWith(".eval.yaml")))}import{mkdir as Dq,readFile as Tq,writeFile as $q}from"node:fs/promises";import{join as Lq}from"node:path";var yI="Local Eval: its content-free summary (status, pass/fail counts and digests; no skill files, prompts or output) was sent to Skills Layer as effectiveness evidence for this version.",Oq="About local Eval evidence: after each install the CLI runs the skill's Eval on this device and, when you are signed in, sends that summary. It counts towards the skill's Platform Score. This notice is shown once; each result still says when a summary was sent.",Fq="local-eval-evidence-notice.json";async function wI(e){if(!e.submitted)return{evidenceSubmitted:!1};let t=Lq(e.stateDir,Fq);return await Tq(t,"utf8").then(r=>typeof JSON.parse(r).shownAt=="string",()=>!1).catch(()=>!1)?{evidenceSubmitted:!0,message:yI}:(await Dq(e.stateDir,{recursive:!0}),await $q(t,`${JSON.stringify({version:1,shownAt:e.now})}
|
|
926
|
+
`,"utf8"),{evidenceSubmitted:!0,message:yI,firstNotice:Oq})}function vI(e){if(!e||typeof e!="object")return[];let t=e;return[t.message,t.firstNotice].filter(n=>typeof n=="string")}function bI(e){if(e.activationState!=="inactive_staging")return ud("invalid_pack","inactive_staging_required","$activationState","Static Eval must run before activation in an inactive staging tree.");let t=rd(e.pack);if(!t.valid)return{outcome:t.outcome,reasonCode:t.issues[0]?.code??t.outcome,issues:t.issues};let n=ld(e.pack);if(!n.valid)return{outcome:"invalid_pack",reasonCode:n.issues[0]?.code??"invalid_pack",issues:n.issues};let r=id(e.files);if(!r.valid)return{outcome:r.outcome,reasonCode:r.issues[0]?.code??r.outcome,issues:r.issues};let i=e.pack,o=Fe(e.files);if(i.artifactDigest!==o)return ud("invalid_pack","artifact_digest_mismatch","$.artifactDigest","Eval pack is not bound to the staged runtime artifact.");let s=pI(),a=i.cases.map(d=>({id:d.id,assertions:d.assertions.map(p=>sd(p,{files:e.files,scanBudget:s}))})),l=a.flatMap(d=>d.assertions).find(d=>d.reasonCode==="resource_limit"||d.reasonCode==="unsafe_pattern");if(l){let d=l.reasonCode;return ud(d,d,"$cases","Static Eval stopped at the checked security boundary.")}let c=Bq(a),u=Eo({status:c.failed>0?"failed":c.passed>0?"passed":"not_run",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:o,evalPackDigest:Po(e.pack),generatedAt:e.generatedAt,runnerVersion:e.runnerVersion,counts:{cases:a.length,assertions:c.total,passed:c.passed,failed:c.failed,skipped:c.skipped}});return Buffer.byteLength(JSON.stringify(u),"utf8")>br.maxResultBytes?ud("resource_limit","eval-result-byte-limit","$result","Static Eval result exceeds the checked byte limit."):{outcome:"completed",result:{summary:u,cases:a}}}function Bq(e){let t={total:0,passed:0,failed:0,skipped:0};for(let n of e)for(let r of n.assertions)t.total+=1,r.status==="passed"?t.passed+=1:r.status==="failed"?t.failed+=1:t.skipped+=1;return t}function ud(e,t,n,r){return{outcome:e,reasonCode:t,issues:[{code:t,path:n,message:r}]}}import{createHash as Nq}from"node:crypto";var vt="1.0",At=["security_safety","runtime_access_control","effectiveness_outcomes","trust_integrity"],Ge={platformScore:"skills-layer-platform-score-v1",engine:"skills-layer-platform-score-engine-v1",policy:"skills-layer-platform-score-policy-v1",intake:"skills-layer-platform-intake-v1",intakeReceipt:"skills-layer-platform-intake-receipt-v1",authorityAdapter:"skills-layer-platform-authority-adapter-v1",report:"skills-layer-platform-score-report-v1",audienceProjection:"skills-layer-platform-score-projection-v1",machineReport:"skills-layer-platform-score-json-v1",parityManifest:"skills-layer-platform-score-parity-v1",securitySarif:"skills-layer-security-sarif-v1",signedPassport:"skills-layer-skill-passport-v1",signedProvenance:"skills-layer-source-process-artifact-provenance-v1",authorityReference:"skills-layer-platform-authority-reference-v1",statusRegistry:"skills-layer-platform-score-status-v1",compositionCatalogue:"skills-layer-platform-score-controls-v1",dimensionResults:{security_safety:"skills-layer-security-score-v1",runtime_access_control:"skills-layer-runtime-access-score-v1",effectiveness_outcomes:"skills-layer-effectiveness-score-v1",trust_integrity:"skills-layer-trust-integrity-score-v1"}},Do=["ready","ready_with_findings","provisional_evidence","action_required","blocked"],To=["available","withheld","unscored"],Mq=["passed","passed_with_findings","pending","unavailable","failed","blocked","not_performed","not_applicable"],jq=["mandatory","conditional","supplementary"],Uq=["applicable","conditional","not_applicable","unknown"],dd=["current","stale","unknown","not_applicable"],qq=["scored","evidence_only","composition_control"],Ah=["green","amber","red"];var Vq=[{controlId:"SL-PS-INPUT-001",family:"input_integrity",title:"Exact subject parity"},{controlId:"SL-PS-INPUT-002",family:"input_integrity",title:"Compatible score and policy versions"},{controlId:"SL-PS-INPUT-003",family:"input_integrity",title:"Dimension revision and digest verification"},{controlId:"SL-PS-INPUT-004",family:"input_integrity",title:"Latest eligible dimension heads"},{controlId:"SL-PS-INPUT-005",family:"input_integrity",title:"Mandatory baseline completeness"},{controlId:"SL-PS-ROUTE-001",family:"signal_routing",title:"One primary scoring owner"},{controlId:"SL-PS-ROUTE-002",family:"signal_routing",title:"Canonical signal and finding identity"},{controlId:"SL-PS-ROUTE-003",family:"signal_routing",title:"Cross-reference without duplicate deduction"},{controlId:"SL-PS-ROUTE-004",family:"signal_routing",title:"Cap linked to originating signal"},{controlId:"SL-PS-CALC-001",family:"calculation",title:"Four equal dimension weights"},{controlId:"SL-PS-CALC-002",family:"calculation",title:"Deterministic arithmetic and rounding"},{controlId:"SL-PS-CALC-003",family:"calculation",title:"Green eligibility ordering"},{controlId:"SL-PS-CALC-004",family:"calculation",title:"Safety and authority cap ordering"},{controlId:"SL-PS-CALC-005",family:"calculation",title:"Final decision and band consistency"},{controlId:"SL-PS-PUBLISH-001",family:"publication",title:"Immutable revision and supersession"},{controlId:"SL-PS-PUBLISH-002",family:"publication",title:"Canonical and audience projection digest parity"},{controlId:"SL-PS-PUBLISH-003",family:"publication",title:"Cross-surface report and revision parity"},{controlId:"SL-PS-PUBLISH-004",family:"publication",title:"Current acquisition authority"}];var Gq=[{reasonCode:"platform_score_ready",availability:"available",decision:"ready",nextActor:null},{reasonCode:"platform_score_ready_with_findings",availability:"available",decision:"ready_with_findings",nextActor:null},{reasonCode:"platform_score_required_dimension_withheld",availability:"withheld",decision:"provisional_evidence",nextActor:"platform"},{reasonCode:"score_rebuild_in_progress",availability:"withheld",decision:"provisional_evidence",nextActor:"platform"},{reasonCode:"platform_score_action_required",availability:"available",decision:"action_required",nextActor:"owner"},{reasonCode:"platform_score_blocked",availability:"withheld",decision:"blocked",nextActor:"operator"},{reasonCode:"unscored_local_source",availability:"unscored",decision:null,nextActor:null}],Va={contractVersion:vt,policyId:Ge.policy,policyVersion:vt,dimensionWeightsBasisPoints:{security_safety:2500,runtime_access_control:2500,effectiveness_outcomes:2500,trust_integrity:2500},rounding:"half_up",bands:{greenMinimum:90,amberMinimum:70},greenEligibility:{minimumRawScore:90,minimumSecurityScore:90,minimumRuntimeScore:90,minimumEffectivenessScore:70,minimumTrustScore:90,failedGateMaximumScore:89},compositionControlIds:Vq.map(e=>e.controlId)},Aee=di(Va),Bt=k.string().regex(/^sha256:[a-f0-9]{64}$/u),Q=k.string().min(1),Ga=k.string().datetime({offset:!0}),ui=k.number().min(0).max(100),_r=k.object({skillId:Q,slug:Q,skillVersionId:Q,version:Q,generationId:Q,archiveSha256:Bt,artifactDigest:Bt,runtimeArtifactDigest:Bt}).strict(),xt=k.object({authorityType:Q,authorityId:Q,revision:k.number().int().positive(),digest:Bt,observedAt:Ga}).strict(),xh=k.object({controlId:k.string().regex(/^SL-[A-Z0-9]+(?:-[A-Z0-9]+)*-[0-9]{3}$/u),title:Q,status:k.enum(Mq),nativeStatus:Q.optional(),requirementClass:k.enum(jq),applicability:k.enum(Uq),freshness:k.enum(dd),freshnessDetails:k.object({verifiedAt:Ga.nullable(),validUntil:Ga.nullable(),invalidationTriggers:k.array(Q).min(1),authorityRevision:k.number().int().positive(),trustRootPolicyVersion:Q,staleEffect:k.enum(["withhold","cap","limitation"])}).strict().optional(),reasonCode:Q,scoringRole:k.enum(qq),signalIds:k.array(Q),scoreContribution:k.number().optional(),authorityReferences:k.array(xt),limitations:k.array(Q)}).strict(),Ih=k.object({policyId:Q,policyVersion:Q,policyDigest:Bt,policyEpoch:Q}).strict(),Rh=k.object({capId:Q,reasonCode:Q,maximumScore:ui,sourceSignalId:Q}).strict(),Ph=k.object({kind:k.enum(["deduction","weighted","blend"]),formula:Q,rawScore:ui.nullable(),rounding:Q,components:k.array(k.object({key:Q,label:Q,value:k.number().nullable(),weight:k.number().min(0).max(1).optional()}).strict()),deductions:k.array(k.object({sourceId:Q,amount:k.number().nonnegative()}).strict()),outcomes:k.object({confidence:k.enum(["platform_baseline","corroborated","strong"]).nullable(),baselineDelta:k.number().finite().nullable(),eligibleObservationCount:k.number().int().nonnegative(),effectiveSampleSize:k.number().nonnegative(),sourceConcentration:k.number().min(0).max(1).nullable(),coreClaimCount:k.number().int().nonnegative(),coreTaskCount:k.number().int().nonnegative(),unsupportedCount:k.number().int().nonnegative(),inconclusiveCount:k.number().int().nonnegative()}).strict().optional()}).strict(),zq=k.object({contractVersion:k.literal(vt),contractId:k.enum([Ge.dimensionResults.security_safety,Ge.dimensionResults.runtime_access_control,Ge.dimensionResults.effectiveness_outcomes,Ge.dimensionResults.trust_integrity]),dimensionId:k.enum(At),subject:_r,revision:k.number().int().positive(),generatedAt:Ga,policy:Ih,availability:k.enum(To),decision:k.enum(Do).nullable(),score:ui.nullable(),reasonCode:Q,freshness:k.enum(dd),items:k.array(xh),appliedCaps:k.array(Rh),calculation:Ph.optional(),integrity:k.object({inputDigest:Bt,canonicalDigest:Bt}).strict()}).strict().superRefine((e,t)=>{e.contractId!==Ge.dimensionResults[e.dimensionId]&&t.addIssue({code:"custom",message:"platform_score_dimension_contract_mismatch"}),e.availability==="available"&&e.score===null&&t.addIssue({code:"custom",message:"platform_score_available_dimension_requires_score"}),e.availability!=="available"&&e.score!==null&&t.addIssue({code:"custom",message:"platform_score_non_available_dimension_forbids_score"}),e.availability==="unscored"&&e.decision!==null&&t.addIssue({code:"custom",message:"platform_score_unscored_dimension_forbids_decision"}),e.availability!=="unscored"&&e.decision===null&&t.addIssue({code:"custom",message:"platform_score_dimension_requires_decision"})}),Kq=k.discriminatedUnion("kind",[k.object({constraintId:Q,kind:k.literal("ceiling"),sourceDimension:k.enum(At),sourceSignalId:Q,reasonCode:Q,maximumScore:ui,decisionImpact:k.enum(["ready_with_findings","action_required"])}).strict(),k.object({constraintId:Q,kind:k.literal("block"),sourceDimension:k.enum(At),sourceSignalId:Q,reasonCode:Q,decisionImpact:k.literal("blocked")}).strict()]),_I=k.enum(Ah),fd=k.object({contractVersion:k.literal(vt),contractId:k.literal(Ge.platformScore),engineId:k.literal(Ge.engine),policyId:k.literal(Ge.policy),policyVersion:k.literal(vt),policyDigest:Bt,subject:_r,availability:k.enum(To),decision:k.enum(Do).nullable(),rawScore:ui.nullable(),score:ui.nullable(),band:_I.nullable(),badge:k.object({icon:k.literal("double_tick"),label:k.literal("Quality Assured"),tone:_I}).strict().nullable(),statusReasonCode:Q,reasonCodes:k.array(Q),limitingDimensions:k.array(k.enum(At)),appliedConstraints:k.array(Kq),dimensionReferences:k.array(k.object({dimensionId:k.enum(At),revision:k.number().int().positive(),canonicalDigest:Bt,score:ui.nullable()}).strict()).length(4)}).strict().superRefine((e,t)=>{e.availability==="available"&&(e.decision===null||e.decision==="provisional_evidence"||e.decision==="blocked"||e.rawScore===null||e.score===null||e.band===null||e.badge===null)&&t.addIssue({code:"custom",message:"platform_score_available_result_incomplete"}),e.availability==="withheld"&&(e.score!==null||e.band!==null||e.badge!==null)&&t.addIssue({code:"custom",message:"platform_score_withheld_result_exposes_numeric_band"}),e.availability==="unscored"&&e.decision!==null&&t.addIssue({code:"custom",message:"platform_score_unscored_result_forbids_decision"}),e.availability==="unscored"&&(e.rawScore!==null||e.score!==null||e.band!==null||e.badge!==null)&&t.addIssue({code:"custom",message:"platform_score_unscored_result_exposes_numeric_band"}),e.score!==null&&e.band!==null&&e.band!==Hq(e.score)&&t.addIssue({code:"custom",message:"platform_score_band_mismatch"}),(e.band===null!=(e.badge===null)||e.band!==null&&e.badge?.tone!==e.band)&&t.addIssue({code:"custom",message:"platform_score_badge_mismatch"});let n=Gq.find(r=>r.reasonCode===e.statusReasonCode);(!n||n.availability!==e.availability||n.decision!==e.decision)&&t.addIssue({code:"custom",message:"platform_score_status_reason_mismatch"})});function Hq(e){return e>=Va.bands.greenMinimum?"green":e>=Va.bands.amberMinimum?"amber":"red"}var pd=k.object({passed:k.number().int().nonnegative(),passed_with_findings:k.number().int().nonnegative(),pending:k.number().int().nonnegative(),unavailable:k.number().int().nonnegative(),failed:k.number().int().nonnegative(),blocked:k.number().int().nonnegative(),not_performed:k.number().int().nonnegative(),not_applicable:k.number().int().nonnegative()}).strict(),Eh=k.object({findingId:Q,dimensionId:k.enum(At),controlId:Q,severity:k.enum(["note","low","medium","high","critical"]),status:k.enum(["open","resolved","accepted","false_positive"]),title:Q,summary:Q,remediation:Q,locations:k.array(k.object({uri:k.literal("SKILL.md"),startLine:k.number().int().positive()}).strict()).optional()}).strict(),Dh=k.object({platformTrustLedger:xt,distributionAuthority:xt}).strict(),xee=k.object({contractVersion:k.literal(vt),contractId:k.literal(Ge.report),reportId:Q,revision:k.number().int().positive(),generatedAt:Ga,subject:_r,inputDigest:Bt,authorityVectorDigest:Bt,finalization:Dh,dimensionResults:k.array(zq).length(4),platformScore:fd,statusCounts:pd,findings:k.array(Eh),limitations:k.array(Q),integrity:k.object({canonicalDigest:Bt}).strict()}).strict().superRefine((e,t)=>{let n=new Set(e.dimensionResults.map(r=>r.dimensionId));(n.size!==At.length||At.some(r=>!n.has(r)))&&t.addIssue({code:"custom",message:"platform_score_report_dimension_set_invalid"}),(Qt(e.subject)!==Qt(e.platformScore.subject)||e.dimensionResults.some(r=>Qt(r.subject)!==Qt(e.subject)))&&t.addIssue({code:"custom",message:"platform_score_report_subject_mismatch"}),e.integrity.canonicalDigest!==Wq(e)&&t.addIssue({code:"custom",message:"platform_score_report_digest_mismatch"})});function Wq(e){let{integrity:t,...n}=e;return di(n)}function Qt(e){return JSON.stringify(Ch(e))}function di(e){return`sha256:${Nq("sha256").update(Qt(e),"utf8").digest("hex")}`}function Ch(e){return Array.isArray(e)?e.map(Ch):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Ch(n)])):e}var fe=k.string().min(1),it=k.string().regex(/^sha256:[a-f0-9]{64}$/u),Th=k.string().datetime({offset:!0}),$h=k.number().min(0).max(100),md=k.string().url(),Jq=xh.omit({authorityReferences:!0}),Yq=k.object({dimensionId:k.enum(At),revision:k.number().int().positive(),availability:k.enum(To),decision:k.enum(Do).nullable(),score:$h.nullable(),reasonCode:fe,freshness:k.enum(dd),items:k.array(Jq),calculation:Ph.optional(),appliedCaps:k.array(Rh).optional(),policy:Ih.optional()}).strict(),Zq=k.object({reportId:fe,revision:k.number().int().positive(),reportDigest:it,generatedAt:Th,subject:_r,authorityVectorDigest:it,finalization:Dh,platformScore:fd,dimensions:k.array(Yq).length(4),statusCounts:pd,findings:k.array(Eh),limitations:k.array(fe),verificationLinks:k.array(md)}).strict(),Xq=k.object({controlId:fe,concern:fe,authorityReferences:k.array(xt)}).strict(),Qq=k.object({controlId:fe,governanceDecision:fe,authorityReferences:k.array(xt)}).strict(),eV=k.object({controlId:fe,diagnosticCode:fe,authorityReferences:k.array(xt)}).strict(),gd={contractVersion:k.literal(vt),contractId:k.literal(Ge.audienceProjection),projectionPolicyVersion:k.literal(vt),projectionDigest:it,report:Zq},tV=k.object({...gd,projectionProfile:k.literal("public"),profileDetails:k.object({kind:k.literal("public")}).strict()}).strict(),nV=k.object({...gd,projectionProfile:k.literal("owner_manager"),profileDetails:k.object({kind:k.literal("owner_manager"),remediationEvidence:k.array(Xq)}).strict()}).strict(),rV=k.object({...gd,projectionProfile:k.literal("tenant_admin"),profileDetails:k.object({kind:k.literal("tenant_admin"),governanceEvidence:k.array(Qq)}).strict()}).strict(),iV=k.object({...gd,projectionProfile:k.literal("platform_operator"),profileDetails:k.object({kind:k.literal("platform_operator"),operationalEvidence:k.array(eV)}).strict()}).strict(),kI=k.discriminatedUnion("projectionProfile",[tV,nV,rV,iV]).superRefine((e,t)=>{let{projectionDigest:n,...r}=e;n!==SI(r)&&t.addIssue({code:"custom",message:"platform_score_projection_digest_mismatch"});let i=new Set(e.report.dimensions.map(o=>o.dimensionId));(i.size!==At.length||At.some(o=>!i.has(o)))&&t.addIssue({code:"custom",message:"platform_score_projection_dimension_set_invalid"})});function SI(e){return di(e)}var Lh=k.object({contractVersion:k.literal(vt),contractId:k.literal(Ge.machineReport),projection:kI,deterministicJsonDigest:it,presentation:k.object({badge:k.object({displayLabel:k.enum(["Limited Confidence","Moderate Confidence","Strong Confidence"]),tone:k.enum(["green","amber","red"])}).strict().nullable()}).strict().optional()}).strict().superRefine((e,t)=>{e.deterministicJsonDigest!==di(e.projection)&&t.addIssue({code:"custom",message:"platform_score_machine_report_digest_mismatch"})}),$o=k.object({contractVersion:k.literal(vt),contractId:k.literal(Ge.signedPassport),passportId:fe,issuedAt:Th,expiresAt:Th,subject:_r,authorityVectorDigest:it,report:k.object({reportId:fe,revision:k.number().int().positive(),digest:it}).strict(),platformScore:k.object({availability:k.enum(To),decision:k.enum(Do).nullable(),score:$h.nullable(),band:k.enum(Ah).nullable()}).strict(),platformTrustLedger:xt,distributionAuthority:xt,sourceProvenance:xt,issuer:k.object({keyId:fe,algorithm:k.literal("Ed25519")}).strict(),signature:fe,verificationUrl:md}).strict(),oV=k.object({id:fe,name:fe.optional(),shortDescription:k.object({text:fe}).strict().optional()}).strict(),sV=k.object({ruleId:fe,level:k.enum(["none","note","warning","error"]),message:k.object({text:fe}).strict(),partialFingerprints:k.object({"skills-layer/findingId":fe}).strict(),locations:k.array(k.object({physicalLocation:k.object({artifactLocation:k.object({uri:fe}).strict(),region:k.object({startLine:k.number().int().positive().optional()}).strict().optional()}).strict()}).strict()).optional(),properties:k.object({dimensionId:k.literal("security_safety"),findingId:fe,severity:k.enum(["note","low","medium","high","critical"]),status:k.enum(["open","resolved","accepted","false_positive"]),remediation:fe}).strict()}).strict(),aV=k.object({$schema:md.optional(),version:k.literal("2.1.0"),runs:k.array(k.object({tool:k.object({driver:k.object({name:k.literal("Skills Layer"),informationUri:md,rules:k.array(oV)}).strict()}).strict(),results:k.array(sV),properties:k.object({contractVersion:k.literal(vt),contractId:k.literal(Ge.securitySarif),reportId:fe,reportRevision:k.number().int().positive(),reportDigest:it,subject:_r}).strict()}).strict()).min(1)}).strict(),Oh=k.object({contractVersion:k.literal(vt),contractId:k.literal(Ge.parityManifest),projectionProfile:k.enum(["public","owner_manager","tenant_admin","platform_operator"]),report:k.object({reportId:fe,revision:k.number().int().positive(),digest:it}).strict(),factsDigest:it,facts:k.object({subject:_r,authorityVectorDigest:it,platformScore:fd,dimensions:k.array(k.object({dimensionId:k.enum(At),revision:k.number().int().positive(),score:$h.nullable(),availability:k.enum(To),decision:k.enum(Do).nullable(),reasonCode:fe}).strict()).length(4),statusCounts:pd,findingIds:k.array(fe),platformTrustLedger:xt,distributionAuthority:xt,sourceProvenance:xt}).strict(),artifacts:k.object({projectionDigest:it,machineReportDigest:it,securitySarifDigest:it,passportDigest:it,markdownDigest:it}).strict()}).strict().superRefine((e,t)=>{e.factsDigest!==di(e.facts)&&t.addIssue({code:"custom",message:"platform_score_parity_facts_digest_mismatch"})});var Dee=Object.freeze({passed:{label:"Passed",tone:"green",meaning:"Requirement met without findings."},passed_with_findings:{label:"Passed with Findings",tone:"amber",meaning:"Requirement met, with caveats or limitations."},failed:{label:"Failed",tone:"red",meaning:"Requirement not met, including a required control being missing."},blocked:{label:"Blocked",tone:"red",meaning:"A blocking condition prevents proceeding."},pending:{label:"Pending",tone:"blue",meaning:"Awaiting assessment or completion."},unavailable:{label:"Unavailable",tone:"grey",meaning:"Evidence needed to determine the result is unavailable."},not_performed:{label:"Not Performed",tone:"grey",meaning:"The check was not carried out."},not_applicable:{label:"Not Applicable",tone:"grey",meaning:"The check does not apply to this skill."}}),Tee=Object.freeze({community_evidence_not_yet_collected:"Not yet collected",trust_transparency_maturity_not_yet_available:"Evidence only; does not reduce the score"});var Lo=".skills-layer/skill.yaml",Fn=(e,t,n)=>({detected:e,howToFix:`Declare toolContract.${t} in ${Lo} (or run skills-layer creator tool-contract), or add ${n} to toolContract.deniedCapabilities if the skill does not need it.`}),lV=Object.freeze({runtime_access_file_read_scope_missing:Fn("The skill's instructions or scripts read files, and no file read scope is declared.","fileReadScopes","filesystem_read"),runtime_access_file_write_scope_missing:Fn("The skill's instructions or scripts write files, and no file write scope is declared.","fileWriteScopes","filesystem_write"),runtime_access_network_scope_missing:Fn("The skill uses the network, and no allowed network domains are declared.","networkDomains","network_access"),runtime_access_secret_scope_missing:Fn("The skill handles secrets, and no secret names are declared.","secretNames","secret_handling"),runtime_access_secret_broker_missing:Fn("The skill handles secrets, and secret handling is not approved for brokered use.","approvedCapabilities (secret_handling) with toolContract.secretNames","secret_handling"),runtime_access_shell_scope_missing:Fn("The skill runs shell commands, and no allowed commands are declared.","shellCommands","shell_execution"),runtime_access_browser_scope_missing:Fn("The skill drives a browser, and no allowed browser origins are declared.","browserOrigins","browser_access"),runtime_access_device_scope_missing:Fn("The skill controls a device, and no device kinds are declared.","deviceKinds","device_control"),runtime_access_api_scope_missing:Fn("The skill calls external APIs, and no API operations are declared.","apiOperations","api_access"),runtime_access_generated_code_sandbox_missing:{detected:"The skill runs code it generates, and generated-code execution is not denied.",howToFix:`Add generated_code_execution to toolContract.deniedCapabilities in ${Lo} if the skill does not need it.`},runtime_access_dependency_mutation_policy_missing:{detected:"The skill can run commands that could install or change dependencies.",howToFix:`Prepare dependencies beforehand and add shell_execution and generated_code_execution to toolContract.deniedCapabilities in ${Lo}.`},runtime_access_decision_incomplete:{detected:"A capability the security scan detected is neither declared nor denied.",howToFix:`List every detected capability in toolContract.requestedCapabilities or toolContract.deniedCapabilities in ${Lo}.`},runtime_access_capability_mismatch:{detected:"The declared capabilities do not match what the security scan detected.",howToFix:`Update toolContract.requestedCapabilities in ${Lo} to match what the skill does.`},runtime_access_purpose_or_target_missing:{detected:"A capability is allowed without binding each operation to its purpose and target.",howToFix:`Deny the capabilities the skill does not need in toolContract.deniedCapabilities (${Lo}); scope the rest to exact targets.`}});function cV(e){return e.reasonCode==="trust_bundle_quality_advisories_present"?{detected:"The bundle is missing recommended documentation, such as examples or troubleshooting.",howToFix:"Add the missing sections to SKILL.md and submit a new version. Each advisory lowers the artifact family score; none blocks publication.",whoCanFix:"creator"}:e.controlId.startsWith("SL-TI-SOURCE-")?e.reasonCode==="trust_source_reverification_required"?{detected:"The source verification is out of date.",howToFix:"Re-verify the source connection or ownership claim so the current revision is verified again.",whoCanFix:"creator_or_claimed_owner"}:{detected:"The source is disclosed, but its owner is not verified. A pinned commit records exactly what was published; it does not verify who published it.",howToFix:"Connect the source through a GitHub App or OAuth source connection (skills-layer source connection start), or verify ownership of the listing (skills-layer creator claim).",whoCanFix:"creator_or_claimed_owner"}:null}function uV(e){if(e.status==="passed_with_findings")return cV(e);if(e.status!=="failed"&&e.status!=="blocked")return null;let t=lV[e.reasonCode];return t?{...t,whoCanFix:"creator_or_claimed_owner"}:null}function dV(e){return e==="creator"?"the creator":e==="platform"?"Skills Layer":"the creator (for an imported skill, its owner after a verified claim)"}function Fh(e){return e.flatMap(t=>{let n=uV(t);return n?[`${t.controlId}: Detected: ${n.detected} How to fix: ${n.howToFix} Who can fix this: ${dV(n.whoCanFix)}.`]:[]})}function Bh(e){if(e.dimensionId==="effectiveness_outcomes"&&e.reasonCode==="effectiveness_not_evaluated"){let t=(o,s)=>e.items.filter(a=>a.status===o&&s(a.requirementClass)).length,n=t("unavailable",o=>o==="mandatory"),r=t("not_applicable",o=>o!=="mandatory"),i=(o,s,a)=>`${o} ${o===1?s:a}`;return["Not evaluated: there are no verified task outcomes for this exact version, so Effectiveness contributes 0 under the current scoring policy. This does not mean the skill ran and failed.",...e.items.some(o=>o.status==="passed")?["A Pass on a preparation or attestation check means the test was prepared and signed as required; it does not show that the task succeeded."]:[],...n+r>0?[`${i(n,"required check has","required checks have")} no evidence yet (Unavailable); ${i(r,"optional check does","optional checks do")} not apply (Not Applicable).`]:[]].join(" ")}if(e.dimensionId==="effectiveness_outcomes"&&e.reasonCode==="effectiveness_no_core_task_succeeds"){let t=e.calculation?.outcomes,n=t&&t.coreTaskCount>0?` (${t.coreTaskCount} of ${t.coreTaskCount} claim-linked task${t.coreTaskCount===1?"":"s"} did not succeed)`:"";return`${e.score??0}/100 because the advertised core task did not succeed in the platform test${n}. A "Pass" below means that check ran as required, not that the task succeeded.`}return e.score===0&&!e.items.some(t=>t.status==="failed"||t.status==="blocked")?`0/100 because of ${e.reasonCode.replaceAll("_"," ")}; no single check below failed.`:null}var fV={red:"Limited Confidence",amber:"Moderate Confidence",green:"Strong Confidence"};function za(e){return fV[e]}var CI=[{title:"Runtime Analysis",text:"Execution or detonation.",limitations:["Security check not performed: Sandbox runtime execution.","Security check not performed: Malware detonation."]},{title:"Supply-chain attestation",text:"dependencies and build provenance were not independently attested.",limitations:["Security check not performed: Supply chain attestation."]},{title:"Human review",text:"no manual security code review was performed.",limitations:["Security check not performed: Manual code review."]}],pV="Antivirus and YARA scanning cover binary files only (images, audio, fonts and PDFs). Every file, including text and code, gets the static security rules and AI review.";function mV(e){let t=new Set(CI.flatMap(r=>r.limitations)),n=CI.filter(r=>r.limitations.some(i=>e.includes(i))).map(({title:r,text:i})=>({title:r,text:i}));return{outOfScope:n,scanCoverage:n.length>0?[pV]:[],other:e.filter(r=>!t.has(r))}}function Nh(e,t){let n=mV(e),r=(i,o)=>o.length===0?[]:t==="markdown"?[`## ${i}`,"",...o.map(s=>`- ${s}`),""]:[`${i}:`,...o.map(s=>`- ${s}`)];return[...r("Out of Scope",n.outOfScope.map(({title:i,text:o})=>t==="markdown"?`**${i}:** ${o}`:`${i}: ${o}`)),...r("Scan coverage",n.scanCoverage),...r("Other limitations",n.other)]}function hd(e){return Lh.safeParse(e).success}function AI(e){return e.appliedConstraints.some(t=>t.reasonCode==="effectiveness_not_evaluated")}var gV="Not evaluated: Skills Layer could not build a test for this exact version, so Effectiveness counts as 0 and the overall score is capped.";function jh(e){let t=e.projection.report,n=t.platformScore,r=AI(n),i=[`Platform Score \u2014 ${t.subject.slug} ${t.subject.version}`,`Report: ${t.reportId} revision ${t.revision}`,`Overall: ${n.score===null?"Withheld":`${n.score}/100 (${n.band}) \u2014 ${za(n.band)}${r?" \xB7 Not evaluated":""}`}`,`Decision: ${n.decision??"unscored"} (${n.statusReasonCode})`,...xI(n),"Dimensions:"];for(let o of t.dimensions){let s=o.policy?` \xB7 rules v${o.policy.policyVersion}`:"";i.push(r&&o.dimensionId==="effectiveness_outcomes"?`- ${Mh(o.dimensionId)}: Not evaluated (counts as 0)${s}`:`- ${Mh(o.dimensionId)}: ${o.score===null?"Withheld":`${o.score}/100`} \u2014 ${o.decision??o.availability}${s}`);let a=Bh(r&&o.dimensionId==="effectiveness_outcomes"?{...o,reasonCode:"effectiveness_not_evaluated"}:o);a&&i.push(` ${a}`),i.push(...II(o).slice(o.policy?1:0).map(l=>` ${l}`));for(let l of o.items)for(let c of Fh([l]))i.push(` ${l.status==="passed_with_findings"?"Check with findings":"Failed check"} ${c}`)}return i.push(...Nh(t.limitations,"text")),i.push(`Checks: ${Object.entries(t.statusCounts).map(([o,s])=>`${o}=${s}`).join(", ")}`,`Report digest: ${t.reportDigest}`),i.join(`
|
|
927
|
+
`)}function xI(e){let t=Va.greenEligibility,n=e.limitingDimensions.filter(r=>e.reasonCodes.includes(`platform_score_green_gate_failed:${r}`));return[...AI(e)?[gV]:[],"Formula: equal-weight average of the four dimension scores (25% each).",`Overall formula policy: ${e.policyId}, version ${e.policyVersion}. Each dimension shows its own rules version.`,`Canonical average before eligibility limits: ${e.rawScore===null?"Withheld":`${e.rawScore}/100`}.`,`Published Platform Score: ${e.score===null?"Withheld":`${e.score}/100`}.`,"Rounding: half-up once after eligibility limits and safety caps.",`Green requires an average of at least ${t.minimumRawScore}, Security ${t.minimumSecurityScore}, Runtime ${t.minimumRuntimeScore}, Effectiveness ${t.minimumEffectivenessScore}, Trust ${t.minimumTrustScore}, and no material cap or evidence gap.`,...n.map(r=>`Green eligibility limit: ${Mh(r)}; maximum ${t.failedGateMaximumScore}/100.`),...e.appliedConstraints.map(r=>r.kind==="ceiling"?`${r.sourceDimension==="security_safety"?"Safety cap":"Score ceiling"} ${r.constraintId}: maximum ${r.maximumScore}/100; ${r.reasonCode}.`:`Safety block ${r.constraintId}: ${r.reasonCode}.`)]}function II(e){let t=e.calculation,n=e.policy?[`Scored under rules v${e.policy.policyVersion} (${e.policy.policyId}).`]:[];return t?[...n,t.formula,`Pre-cap score: ${t.rawScore??"Withheld"}. Rounding: ${t.rounding}.`,...t.components.map(r=>`${r.label}: ${r.value??"No eligible input"}${r.weight===void 0?"":`; weight ${r.weight}`}`),...t.deductions.map(r=>`${r.sourceId}: \u2212${r.amount}`),...t.outcomes?[`Evidence confidence: ${t.outcomes.confidence??"Withheld"}.`,`Without-skill comparison delta: ${t.outcomes.baselineDelta??"Not measured"}.`,`Core coverage: ${t.outcomes.coreClaimCount} claims, ${t.outcomes.coreTaskCount} claim-linked tasks; unsupported ${t.outcomes.unsupportedCount}, inconclusive ${t.outcomes.inconclusiveCount}.`,`Eligible independent observations: ${t.outcomes.eligibleObservationCount}; effective sample ${t.outcomes.effectiveSampleSize}; source concentration ${t.outcomes.sourceConcentration??"No field evidence"}.`]:[],...(e.appliedCaps??[]).map(r=>`Cap ${r.capId}: maximum ${r.maximumScore}; ${r.reasonCode}`)]:n}function Mh(e){return e==="security_safety"?"Security & Safety":e==="runtime_access_control"?"Runtime Access & Control":e==="effectiveness_outcomes"?"Effectiveness & Outcomes":"Trust & Integrity"}import{sign as qee,verify as hV}from"node:crypto";function yV(e,t){let n=$o.safeParse(e);if(!n.success)return{valid:!1,reasonCode:"passport_schema_invalid"};let{signature:r,...i}=n.data;return hV(null,Buffer.from(Qt(i),"utf8"),t,Buffer.from(r,"base64url"))?{valid:!0,reasonCode:"passport_signature_valid"}:{valid:!1,reasonCode:"passport_signature_invalid"}}function Uh(e){let t=$o.safeParse(e.passport);if(!t.success||!Number.isFinite(Date.parse(e.now)))return{valid:!1,reasonCode:"passport_schema_invalid"};let n=t.data,r=e.publicKeys instanceof Map?e.publicKeys.get(n.issuer.keyId):e.publicKeys[n.issuer.keyId];return r?Date.parse(n.issuedAt)>Date.parse(e.now)?{valid:!1,reasonCode:"passport_not_yet_valid"}:Date.parse(n.expiresAt)<=Date.parse(e.now)?{valid:!1,reasonCode:"passport_expired"}:e.currentPassportId&&n.passportId!==e.currentPassportId?{valid:!1,reasonCode:"passport_superseded"}:e.expectedSubject&&Qt(n.subject)!==Qt(e.expectedSubject)?{valid:!1,reasonCode:"passport_subject_mismatch"}:e.expectedReport&&Qt(n.report)!==Qt(e.expectedReport)?{valid:!1,reasonCode:"passport_report_mismatch"}:yV(n,r).valid?{valid:!0,reasonCode:"passport_valid"}:{valid:!1,reasonCode:"passport_signature_invalid"}:{valid:!1,reasonCode:"passport_unknown_key"}}var wV=/^github:([^/]+)\/([^/#]+)(?:\/([^#]+))?(?:#(.+))?$/,vV=/^gitlab:([^/#]+(?:\/[^/#]+)*?)\/([^/#]+)(?:\/([^/#]+))?(?:#(.+))?$/,bV=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.+?))?(?:#([^@]+))?$/,_V=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/.+)?(?:#[^@]+)?$/,kV=/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/,SV=/^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/,CV=/^(?:ssh:\/\/)?git@gitlab\.com[:/]([^/]+(?:\/[^/]+)*)\/([^/]+?)(?:\.git)?$/;function en(e){let t=e.trim();if(t.length===0)throw new Error("import requires a non-empty source.");let{sourceInput:n,skillFilter:r}=xV(t),i=n.match(wV);if(i){let[,d,p,m,g]=i;return yd({input:t,owner:d,repo:p,ref:g?.trim()||"main",subpath:m,skillFilter:r})}let o=n.match(vV);if(o){let[,d,p,m,g]=o;return qh({input:t,host:"gitlab.com",namespace:d,repo:p,ref:g?.trim()||"main",subpath:m,skillFilter:r})}let s=IV(t);if(s)return s;let a=RV(t);if(a)return a;let l=n.match(SV);if(l){let[,d,p]=l;return yd({input:t,owner:d,repo:hn(p),ref:"main",subpath:"SKILL.md"})}let c=n.match(CV);if(c){let[,d,p]=c;return qh({input:t,host:"gitlab.com",namespace:d,repo:hn(p),ref:"main",subpath:"SKILL.md"})}if(/^(?:git\+)?https?:\/\//u.test(n)){if(/[?&]skill=/u.test(n)){let d=new URL(n.replace(/^git\+/u,"")),p=d.searchParams.get("skill")?.trim();return d.searchParams.delete("skill"),{kind:"url",input:t,url:d.toString(),canonicalSource:d.toString(),...p?{skillFilter:p}:{}}}return{kind:"url",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,"")}}let u=n.match(bV);if(u&&!kV.test(n)){let[,d,p,m,g]=u;return yd({input:t,owner:d,repo:hn(p),ref:g?.trim()||"main",subpath:m,skillFilter:r})}return/^(?:ssh:\/\/)?git@/u.test(n)||/^(?:git\+)?ssh:\/\//u.test(n)?{kind:"git",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,""),...r?{skillFilter:r}:{}}:{kind:"local",input:t,location:n,canonicalSource:n,...r?{skillFilter:r}:{}}}var AV='Source references must not contain ".", ".." or empty path segments';function Bn(e,t){if(t===void 0)return;let n=t;for(let r=0;r<4;r+=1){let i;try{i=decodeURIComponent(n)}catch{break}if(i===n)break;n=i}if(n.split(/[\\/]/u).some(r=>r===""||r==="."||r===".."))throw new Error(`${AV} (${e}).`)}function RI(e){let t=e.replace(/^https?:\/\/[^/?#]*/u,"").split(/[?#]/u)[0].replace(/^\//u,"").replace(/\/$/u,"");t.length>0&&Bn("url path",t)}function wd(e){let t=e?.trim();return t&&t.length>0?t:"SKILL.md"}function xV(e){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("git@")||e.startsWith("ssh://"))return{sourceInput:e};let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return{sourceInput:e};let n=e.slice(0,t),r=e.slice(t+1).trim();return r.match(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u)?n.includes("#")?{sourceInput:n,skillFilter:r}:n.startsWith("github:")||n.startsWith("gitlab:")||_V.test(n)?{sourceInput:n,skillFilter:r}:{sourceInput:n,skillFilter:r}:{sourceInput:e}}function PI(e,t,n,r){return`${e}://${t}@${n}/${r}`}function hn(e){return e.replace(/\.git$/u,"")}function IV(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return null;let t=new URL(e);if(t.hostname!=="github.com")return null;RI(e);let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error("GitHub URLs must include an owner and repository.");let r=n[0],i=hn(n[1]),o="main",s="SKILL.md";(n[2]==="tree"||n[2]==="blob")&&(o=n[3]?.trim()||"main",s=wd(n.slice(4).join("/")));let a=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),yd({input:e,owner:r,repo:i,ref:o,subpath:s,skillFilter:a})}function RV(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return null;let t=new URL(e);if(t.hostname==="github.com")return null;let n=t.pathname.split("/").filter(Boolean),r=n.indexOf("-");if(t.hostname!=="gitlab.com"&&r!==-1)throw new Error("Self-hosted GitLab sources are not supported for the public launch; use GitLab.com.");if(t.hostname!=="gitlab.com")return null;RI(e);let i=r===-1?n:n.slice(0,r);if(i.length<2)throw new Error("GitLab URLs must include a namespace and repository.");let o=hn(i[i.length-1]),s=i.slice(0,-1).join("/"),a=r===-1?void 0:n[r+1],l=r===-1?[]:n.slice(r+2),c=(a==="tree"||a==="blob")&&l[0]?.trim()||"main",u=a==="tree"||a==="blob"?wd(l.slice(1).join("/")):"SKILL.md",d=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),qh({input:e,host:t.hostname,namespace:s,repo:o,ref:c,subpath:u,skillFilter:d})}function yd(e){Bn("owner",e.owner),Bn("repository",e.repo),Bn("ref",e.ref),Bn("subpath",e.subpath?.trim()||void 0);let t=wd(e.subpath);return{kind:"github",input:e.input,owner:e.owner,repo:hn(e.repo),ref:e.ref,subpath:t,repoUrl:`https://github.com/${e.owner}/${hn(e.repo)}`,rawUrl:`https://raw.githubusercontent.com/${e.owner}/${hn(e.repo)}/${e.ref}/${t}`,canonicalSource:PI("github",`${e.owner}/${hn(e.repo)}`,e.ref,t),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function qh(e){Bn("namespace",e.namespace),Bn("repository",e.repo),Bn("ref",e.ref),Bn("subpath",e.subpath?.trim()||void 0);let t=hn(e.repo),n=wd(e.subpath);return{kind:"gitlab",input:e.input,host:e.host,namespace:e.namespace,repo:t,ref:e.ref,subpath:n,repoUrl:`https://${e.host}/${e.namespace}/${t}`,rawUrl:`https://${e.host}/${e.namespace}/${t}/-/raw/${e.ref}/${n}`,canonicalSource:PI("gitlab",`${e.namespace}/${t}`,e.ref,n),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}import{createHash as Ad}from"node:crypto";import{readdir as YI,readFile as Zh,stat as Xh}from"node:fs/promises";import{dirname as ZI,posix as Ne,win32 as JV}from"node:path";var Ha=Tt(ei(),1);import{createHash as PV}from"node:crypto";var $I=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/u,vd=/(^|\/)SKILL\.md$/u,EV=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,DV=/^#\s+(.+?)\s*$/mu,TV=/^Skill ID:\s*`?([^`\s]+)`?\s*$/imu,$V=new Set(["name must be a non-empty string","name must be kebab-case",yu()]),LI=1024,LV="description must be 1024 characters or fewer",EI=/^(description:[ \t]*)(\S[^\r\n]*)$/gmu,OV="phase131-v2";function bd(e){let t=Ie(e.files);if(t.parsedSkill)return{files:e.files,validation:t,skillSlug:t.parsedSkill.frontmatter.name,description:t.parsedSkill.frontmatter.description,originalSkillName:t.parsedSkill.frontmatter.name,normalizationApplied:!1,normalizationIssues:[]};if(!e.allowNormalization)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let n=e.files,r=t,i=[],o=FV(n);o&&(n=o.files,r=o.validation,i.push(o.issue));let s=BV(n,r);if(s&&(n=s.files,r=s.validation,i.push(s.issue)),r.parsedSkill){let h=TI(r,i);return{files:n,validation:h,skillSlug:h.parsedSkill.frontmatter.name,description:h.parsedSkill.frontmatter.description,originalSkillName:h.parsedSkill.frontmatter.name,normalizationApplied:!0,normalizationIssues:i,normalizationProvenance:Vh(e.files,n,i)}}if(!jV(r)){let h=NV(e.files,e.fallbackSkillSlug);return h||{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]}}let a=n.find(h=>vd.test(h.path));if(!a||typeof a.content!="string")return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let l=OI(a.content);if(!l)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let c=UV({fallbackSkillSlug:e.fallbackSkillSlug,originalSkillName:l.frontmatter.name});if(!c)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let u=qV(l,c),d=n.map(h=>h.path===a.path?{...h,content:u}:h),p=TI(Ie(d),i);if(!p.parsedSkill)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let m=l.frontmatter.name||void 0,g=[...i,m?Ka("frontmatter-name-normalized","Source name was normalized to a portable skill slug for ingestion."):Ka("frontmatter-name-synthesized","Missing source name was deterministically synthesized from the immutable source directory for ingestion.")];return{files:d,validation:p,skillSlug:p.parsedSkill.frontmatter.name,description:p.parsedSkill.frontmatter.description,originalSkillName:m,normalizationApplied:!0,normalizationIssues:g,normalizationProvenance:Vh(e.files,d,g)}}function FV(e){let t=e.find(g=>vd.test(g.path));if(!t||typeof t.content!="string")return null;let n=t.content.match($I);if(!n)return null;let[,r,i]=n,o=[...r.matchAll(EI)];if(o.length!==1)return null;let[,s,a]=o[0],l=a.trim(),c=/^\[[A-Za-z0-9._-]{1,32}\][ \t]+\S/u.test(l),u=l.includes(": ");if(!c&&!u||l.startsWith('"')||l.startsWith("'"))return null;let p=`---
|
|
928
|
+
${r.replace(EI,()=>`${s}${JSON.stringify(l)}`)}
|
|
929
|
+
---
|
|
930
|
+
${i}`,m=e.map(g=>g===t?{...g,content:p}:g);return{files:m,validation:Ie(m),issue:Ka("frontmatter-description-repaired","Source description used invalid YAML and was quoted automatically for ingestion.")}}function BV(e,t){if(!t.issues.some(s=>s.code==="frontmatter-invalid"&&s.message===LV))return null;let n=e.find(s=>vd.test(s.path));if(!n||typeof n.content!="string")return null;let r=OI(n.content);if(!r||r.frontmatter.description.length<=LI)return null;let i=FI(r,{description:BI(r.frontmatter.description)}),o=e.map(s=>s===n?{...s,content:i}:s);return{files:o,validation:Ie(o),issue:Ka("description-truncated","Source description exceeded 1024 characters and was truncated automatically for ingestion.")}}function NV(e,t){let n=e.find(p=>vd.test(p.path));if(!n||typeof n.content!="string")return null;let r=n.content;if(r.trimStart().startsWith("---"))return null;let i=r.match(DV)?.[1]?.trim();if(!i)return null;let o=r.match(TV)?.[1]?.trim(),s=[o,t,i].map(p=>p?fi(p):null).find(p=>!!p),a=MV(r);if(!s||!a)return null;let l=`---
|
|
931
|
+
${(0,Ha.stringify)({name:s,description:a},{lineWidth:0}).trimEnd()}
|
|
932
|
+
---
|
|
933
|
+
${r}`,c=e.map(p=>p===n?{...p,content:l}:p),u=Ie(c);if(!u.parsedSkill)return null;let d=[Ka("frontmatter-synthesized","Missing source frontmatter was synthesized from deterministic Markdown fields.")];return{files:c,validation:u,skillSlug:s,description:a,originalSkillName:o??i,normalizationApplied:!0,normalizationIssues:d,normalizationProvenance:Vh(e,c,d)}}function Vh(e,t,n){return{schemaVersion:"skills-layer-source-normalization-v1",rulesetVersion:OV,originalBundleSha256:DI(e),normalizedBundleSha256:DI(t),appliedRules:Array.from(new Set(n.map(r=>r.code))).sort()}}function DI(e){let t=PV("sha256");return[...e].sort((n,r)=>n.path.localeCompare(r.path)).forEach((n,r,i)=>{t.update(n.path),t.update("\0"),t.update(re(n)),r<i.length-1&&t.update("\0")}),`sha256:${t.digest("hex")}`}function MV(e){let n=e.trim().split(/\r?\n\s*\r?\n/u).map(i=>i.trim()).filter(Boolean).filter(i=>!i.startsWith("#")&&!/^Skill ID:/iu.test(i)&&!i.startsWith("```")&&!/^[-*]\s/u.test(i)),r=n.find(i=>/^Use this skill\b/iu.test(i))??n[0];return r?BI(r.replace(/\s+/gu," ").trim()):null}function fi(e){let t=e.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"");if(t.length===0)return null;let n=t.split("-").filter(r=>r.length>0&&!_C(r)).join("-");return n.length===0||!EV.test(n)?null:n}function jV(e){return e.issues.length===1&&e.issues[0]?.code==="frontmatter-invalid"&&$V.has(e.issues[0].message)}function UV(e){let t=[e.fallbackSkillSlug,e.originalSkillName].map(n=>n?.trim()).filter(n=>!!n);for(let n of t){let r=fi(n);if(r)return r}return null}function OI(e){let t=e.match($I);if(!t)return null;let[,n,r]=t,i=(0,Ha.parse)(n);if(!VV(i))return null;let o=typeof i.name=="string"?i.name.trim():"",s=typeof i.description=="string"?i.description.trim():"";return s?{frontmatter:{...i,name:o,description:s},body:r}:null}function qV(e,t){return FI(e,{name:t})}function FI(e,t){return`---
|
|
934
|
+
${(0,Ha.stringify)({...e.frontmatter,...t}).trimEnd()}
|
|
935
|
+
---
|
|
936
|
+
${e.body}`}function BI(e){let t=e.slice(0,LI),n=t.charCodeAt(t.length-1);return n>=55296&&n<=56319?t.slice(0,-1):t}function Ka(e,t){return{severity:"warning",code:e,message:t,nextAction:"review-normalized-source",nextStep:"Review the normalized frontmatter and improve the upstream SKILL.md when practical."}}function TI(e,t){if(t.length===0)return e;let n=[...e.issues,...t];return{...e,valid:e.valid&&n.every(r=>r.severity!=="error"),issues:n}}function VV(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function NI(e){if(!yn(e))throw new Error("Well-known search response must be a JSON object.");if(e.version!==1)throw new Error("Well-known search response version must be 1.");let t=Gh(e.provider),n=HV(e.query,"query"),r=UI(e.limit,"limit");if(!Array.isArray(e.results))throw new Error("results must be an array.");return{version:1,provider:t,query:n,limit:r,results:e.results.map((i,o)=>GV(i,`results[${o}]`))}}function MI(e){if(!yn(e))throw new Error("Well-known skill manifest must be a JSON object.");if(e.version!==1)throw new Error("Well-known skill manifest version must be 1.");let t=Gh(e.provider);if(!yn(e.skill))throw new Error("skill must be an object.");if(!Array.isArray(e.skill.files))throw new Error("skill.files must be an array.");let n=e.skill.files.map((i,o)=>zV(i,`skill.files[${o}]`));if(!n.some(i=>i.path==="SKILL.md"))throw new Error("skill.files must include SKILL.md.");let r=WV(e.skill.sourceUrl,"skill.sourceUrl")??n.find(i=>i.path==="SKILL.md").url;return{version:1,provider:t,skill:{slug:Nt(e.skill.slug,"skill.slug"),name:Nt(e.skill.name,"skill.name"),description:Nt(e.skill.description,"skill.description"),skillVersion:Nt(e.skill.skillVersion,"skill.skillVersion"),compatibility:qI(e.skill.compatibility,"skill.compatibility"),featured:e.skill.featured===!0,tags:VI(e.skill.tags,"skill.tags"),files:n,sourceUrl:pi(r,"skill.sourceUrl")}}}function jI(e){if(!yn(e))throw new Error("Well-known index must be a JSON object.");if(!yn(e.provider))throw new Error("Well-known index provider must be an object.");let t=Gh(e.provider);if(e.version!==2)throw new Error("Well-known service manifest version must be 2.");if(!yn(e.capabilities))throw new Error("capabilities must be an object.");if(e.capabilities.directSkillManifest!==!0)throw new Error("capabilities.directSkillManifest must be true.");if(e.capabilities.search!==!0)throw new Error("capabilities.search must be true.");let n=UI(e.capabilities.maxSearchResults,"capabilities.maxSearchResults");if(!yn(e.routes))throw new Error("routes must be an object.");return{version:2,provider:t,capabilities:{directSkillManifest:!0,search:!0,maxSearchResults:n},routes:{search:pi(e.routes.search,"routes.search"),skillManifest:pi(e.routes.skillManifest,"routes.skillManifest"),skillFile:pi(e.routes.skillFile,"routes.skillFile")}}}function GV(e,t){if(!yn(e))throw new Error(`${t} must be an object.`);return{slug:Nt(e.slug,`${t}.slug`),name:Nt(e.name,`${t}.name`),description:Nt(e.description,`${t}.description`),skillVersion:Nt(e.skillVersion,`${t}.skillVersion`),compatibility:qI(e.compatibility,`${t}.compatibility`),featured:e.featured===!0,tags:VI(e.tags,`${t}.tags`),skillManifestUrl:pi(e.skillManifestUrl,`${t}.skillManifestUrl`)}}function zV(e,t){if(!yn(e))throw new Error(`${t} must be an object.`);return{path:KV(Nt(e.path,`${t}.path`)),url:pi(e.url,`${t}.url`)}}function Gh(e){if(!yn(e))throw new Error("Well-known index provider must be an object.");return{name:Nt(e.name,"provider.name"),baseUrl:pi(e.baseUrl,"provider.baseUrl")}}function KV(e){return e.trim().replaceAll("\\","/").replace(/^\/+/u,"").split("/").filter(t=>t.length>0&&t!=="."&&t!=="..").join("/")}function UI(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<1||e>5)throw new Error(`${t} must be between 1 and 5.`);return e}function HV(e,t){if(typeof e!="string")throw new Error(`${t} must be a string.`);return e.trim()}function Nt(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string.`);return e.trim()}function qI(e,t){if(e==null)return"";if(typeof e!="string")throw new Error(`${t} must be a string.`);return e.trim()}function WV(e,t){if(e!==void 0)return Nt(e,t)}function pi(e,t){let n=Nt(e,t);if(!/^https?:\/\//u.test(n))throw new Error(`${t} must be an absolute http(s) URL.`);return n}function VI(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be a string array.`);return e.map(n=>n.trim()).filter(n=>n.length>0)}function yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Oo=class extends Error{constructor(t){super(t instanceof Error?t.message:"Source files could not be read completely.",{cause:t}),this.name="SourceReadUnavailableError"}};var Cd=100,No=class extends Error{},YV=40;async function XI(e){if(e.source.kind==="local")return c6({source:e.source,cwd:e.cwd,platform:e.platform});if(e.source.kind==="git")return{source:e.source,results:[],issues:[{severity:"warning",code:"git-remote-not-inspectable",message:"Generic git remotes are normalized, but inspection currently requires a local checkout or GitHub/GitLab raw access."}]};if(e.source.kind==="well-known"&&Array.isArray(e.source.files)&&e.source.files.length>0)return Hh({source:e.source,fetchFn:e.fetchFn});if(e.source.kind==="url"){let t=await ZV({source:e.source,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug});if(t!==null)return t}if(e.source.kind==="github"||e.source.kind==="gitlab")try{return await e6({source:e.source,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug})}catch(t){if(t instanceof Oo)throw t;let n=t instanceof mi?t:null;if(!(iR(e.source.subpath)&&(n===null||n.status===404||n.status===403))){if(n===null)throw t;let i=e.source.kind==="github"?"GitHub":"GitLab";throw new Oo(new Error(`${i} source inspection failed (HTTP ${n.status}): ${n.message}. This is a source-provider failure, not a Skills Layer login failure.`))}}return XV({source:e.source,fetchFn:e.fetchFn})}async function ZV(e){if(iR(e.source.url))return null;let t=await I6(e.source.url,e.fetchFn);if(t===null)return null;let n=e.source.skillFilter??e.requestedSkillSlug??E6(e.source.url),r=[],i=[];if(n){let o=WI(t.index.routes.skillManifest,{slug:n}),s=await KI(o,e.fetchFn);if(s===null)i.push({severity:"warning",code:"well-known-skill-not-found",message:`Well-known provider did not expose "${n}".`});else{let a=await Hh({source:HI({inputSource:e.source,detectedIndex:t,manifest:s,manifestUrl:o,skillFilter:n}),fetchFn:e.fetchFn});r.push(...a.results),i.push(...a.issues)}}else{let o=WI(t.index.routes.search,{query:P6(e.source.url),limit:"5"}),s=await R6(o,e.fetchFn);if(s!==null)for(let a of s.results.slice(0,t.index.capabilities.maxSearchResults)){let l=await KI(a.skillManifestUrl,e.fetchFn);if(l===null){i.push({severity:"warning",code:"well-known-manifest-not-found",message:`Well-known provider advertised "${a.slug}" but its manifest was unavailable.`});continue}let c=await Hh({source:HI({inputSource:e.source,detectedIndex:t,manifest:l,manifestUrl:a.skillManifestUrl}),fetchFn:e.fetchFn});r.push(...c.results),i.push(...c.issues)}}return{source:e.source,results:r,issues:i}}async function XV(e){let t=await e.fetchFn(w6(e.source));if(!t.ok)throw await Sr(t);let r=[{path:"SKILL.md",content:await t.text()}];return QI(e.source,r)}async function Hh(e){let t=await l6(e.source,e.fetchFn);return QI(e.source,t)}function QI(e,t){let n=[],r=bd({files:t,allowNormalization:!0}),i=r.validation,o=r.skillSlug??Za(i,e);if(!o||!Mo(e.skillFilter,o)){let s=t.find(a=>f6.test(a.path));return s&&jo(n,i,s.path),{source:e,results:[],issues:n}}return{source:e,results:[{skillSlug:o,description:r.description??(i.parsedSkill?i.parsedSkill.frontmatter.description:o),...r.originalSkillName?{originalSkillName:r.originalSkillName}:{},sourceKind:e.kind,relativeSkillRoot:".",relativeSkillFile:"SKILL.md",discoveryRoute:"remote_file",validation:{valid:i.valid,issueCount:i.issues.length},...r.normalizationIssues.length>0?{normalizationIssues:r.normalizationIssues}:{},...r.normalizationProvenance?{normalizationProvenance:r.normalizationProvenance}:{},files:r.files,losslessImport:QV(e,t)}],issues:n}}function QV(e,t){let n=Ad("sha256"),r=t.slice().sort((l,c)=>l.path.localeCompare(c.path));r.forEach((l,c)=>{n.update(l.path),n.update("\0"),n.update(re(l)),c<r.length-1&&n.update("\0")});let i=n.digest("hex"),o=e.kind==="github"||e.kind==="gitlab"?e.kind:"url",s=e.kind==="github"?`${e.owner}/${e.repo}`:e.kind==="gitlab"?`${e.namespace}/${e.repo}`:e.canonicalSource,a=e.kind==="github"||e.kind==="gitlab"?e.ref:"fetched-content";return{source:{provider:o,repository:s,ref:a,commitSha:/^[a-f0-9]{40}$/iu.test(a)?a.toLowerCase():i,treeSha:null},files:r.map(l=>({path:l.path,bytes:re(l),...l.executable?{executable:!0}:{}}))}}async function e6(e){let t=await t6(e.source,e.fetchFn),n=[],r=e.requestedSkillSlug??e.source.skillFilter,i,o=new Map;if(r){let d=await n6({source:e.source,fetchFn:e.fetchFn,context:t});n.push(...d.issues);let p=d.results.filter(m=>Mo(r,m.skillSlug));if(p.length===0)return{source:e.source,results:d.results,issues:n};i=new Set(p.map(m=>m.relativeSkillRoot));for(let m of p){let g=m.files.find(h=>h.path==="SKILL.md");g?.content!==void 0&&o.set(m.relativeSkillFile,g.content)}}let s=new Map([...o].map(([d,p])=>[d,{content:p}])),a=await u6({fileSet:t.fileSet,fetchFile:async d=>{let p=s.get(d);if(p!==void 0)return{...typeof p=="string"?{content:p}:p,...t.relativeFileEntries.find(h=>h.path===d)?.executable?{executable:!0}:{}};let m=await e.fetchFn(nR(e.source,Ja(t.sourceRoot,d)));if(!m.ok)throw await Sr(m);let g={...Je(new Uint8Array(await m.arrayBuffer()),m.headers.get("content-type")),...t.relativeFileEntries.find(h=>h.path===d)?.executable?{executable:!0}:{}};return s.set(d,g),g},onlySkillRoots:i},n),l=new Map;for(let d of a){let p=l.get(d.skillSlug);(!p||ty(d,p)<0)&&l.set(d.skillSlug,d)}let c=[...l.values()].filter(d=>Mo(r,d.skillSlug)),u=c.length===0?{commitSha:e.source.ref,treeSha:null}:await S6(e.source,e.fetchFn,C6(c));return{source:e.source,results:c.map(d=>({skillSlug:d.skillSlug,description:d.description,...d.originalSkillName?{originalSkillName:d.originalSkillName}:{},sourceKind:e.source.kind,relativeSkillRoot:d.relativeSkillRoot,relativeSkillFile:d.relativeSkillFile,discoveryRoute:d.discoveryRoute,...d.pluginName?{pluginName:d.pluginName}:{},...d.pluginManifestPath?{pluginManifestPath:d.pluginManifestPath}:{},validation:{valid:d.validation.valid,issueCount:d.validation.issues.length},...d.normalizationIssues&&d.normalizationIssues.length>0?{normalizationIssues:d.normalizationIssues}:{},...d.normalizationProvenance?{normalizationProvenance:d.normalizationProvenance}:{},files:d.files,providerFileAttestations:a6(d,t.providerBlobByPath),losslessImport:{source:{provider:e.source.kind,repository:e.source.kind==="github"?`${e.source.owner}/${e.source.repo}`:`${e.source.namespace}/${e.source.repo}`,ref:e.source.ref,commitSha:u.commitSha,treeSha:u.treeSha},files:d.originalFiles.map(p=>{let m=Ja(d.relativeSkillRoot,p.path);return{path:m,bytes:re(p),...p.executable?{executable:!0}:{},providerObjectId:t.providerBlobByPath.get(m)??void 0}})}})).sort((d,p)=>d.skillSlug.localeCompare(p.skillSlug)||d.relativeSkillRoot.localeCompare(p.relativeSkillRoot)),issues:n}}async function t6(e,t){let n=ny(e.subpath),i=(await b6(e,t)).map(s=>{let a=kr(s.path,n);return a===null?null:{...s,path:a}}).filter(s=>s!==null),o=i.map(s=>s.path);if(o.length===0)throw new Error(`Remote repository path "${e.subpath}" did not expose any files.`);return{sourceRoot:n,relativeFileEntries:i,fileSet:new Set(o),providerBlobByPath:new Map(i.map(s=>[s.path,s.providerBlobSha]))}}async function n6(e){let t=F6([...e.context.fileSet],".");if(t.length>YV&&!e.requestedSkillSlug&&!e.source.skillFilter)return{source:e.source,results:t.map(o=>r6({entry:o,source:e.source})).sort((o,s)=>o.skillSlug.localeCompare(s.skillSlug)||o.relativeSkillRoot.localeCompare(s.relativeSkillRoot)),issues:[{severity:"warning",code:"remote-source-large-index",message:`Found ${t.length} Skills Layer-compatible entries; listing uses repository paths to stay within source host request limits. Select a specific skill or subfolder for full validation details.`}]};let n=[],i=(await s6(t,8,async o=>o6({entry:o,source:e.source,sourceRoot:e.context.sourceRoot,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug??e.source.skillFilter,issues:n}))).filter(o=>o!==null).sort((o,s)=>o.skillSlug.localeCompare(s.skillSlug)||o.relativeSkillRoot.localeCompare(s.relativeSkillRoot));return{source:e.source,results:i,issues:n}}function r6(e){let t=i6(e.entry),n=eR(e.entry.skillRoot);return{skillSlug:t,description:`Discovered at ${e.entry.skillRoot}. Select this skill or subfolder for full details.`,sourceKind:e.source.kind,relativeSkillRoot:e.entry.skillRoot,relativeSkillFile:e.entry.skillFilePath,discoveryRoute:n,fileCount:e.entry.bundleFileCount,validation:{valid:!0,issueCount:0},files:[]}}function i6(e){let t=e.skillRoot==="."?Ne.basename(Ne.dirname(e.skillFilePath)):Ne.basename(e.skillRoot);return fi(t)??fi(e.skillRoot.replace(/\//gu,"-"))??`source-skill-${Ad("sha256").update(e.skillRoot).digest("hex").slice(0,12)}`}async function o6(e){let t=await e.fetchFn(nR(e.source,Ja(e.sourceRoot,e.entry.skillFilePath)));if(!t.ok)return e.issues.push({severity:"warning",code:"remote-skill-unreadable",message:(await Sr(t)).message,path:e.entry.skillFilePath}),null;let n=await t.text(),r=e.entry.skillRoot!=="."?fi(Ne.basename(e.entry.skillRoot))??void 0:void 0,i=bd({files:[{path:"SKILL.md",content:n}],fallbackSkillSlug:r,allowNormalization:!0}),o=i.validation,s=i.skillSlug??Za(o,null);if(!s)return jo(e.issues,o,e.entry.skillFilePath),null;if(!Mo(e.requestedSkillSlug,s))return null;if(!o.parsedSkill)return jo(e.issues,o,e.entry.skillFilePath),null;let a=eR(e.entry.skillRoot);return{skillSlug:s,description:i.description??o.parsedSkill.frontmatter.description,...i.originalSkillName?{originalSkillName:i.originalSkillName}:{},sourceKind:e.source.kind,relativeSkillRoot:e.entry.skillRoot,relativeSkillFile:e.entry.skillFilePath,discoveryRoute:a,fileCount:e.entry.bundleFileCount,validation:{valid:o.valid,issueCount:o.issues.length},...i.normalizationIssues.length>0?{normalizationIssues:i.normalizationIssues}:{},...i.normalizationProvenance?{normalizationProvenance:i.normalizationProvenance}:{},files:i.files}}function eR(e){return Qh().find(n=>n.absolutePath===e)?.discoveryRoute??(e==="."?"root":"recursive")}async function s6(e,t,n){let r=new Array(e.length),i=0,o=Math.min(Math.max(t,1),e.length);return await Promise.all(Array.from({length:o},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}})),r}function a6(e,t){return e.files.map(n=>{let r=Ja(e.relativeSkillRoot,n.path);return{path:n.path,providerBlobSha:t.get(r)??null,contentSha256:A6(re(n))}})}async function l6(e,t){let n=D6(e.files);return(await Promise.all(n.map(async i=>{let o=await t(e.fileUrls?.[i]??T6(e.sourceUrl,i));if(!o.ok)throw await Sr(o);return{path:i,...Je(new Uint8Array(await o.arrayBuffer()),o.headers.get("content-type"))}}))).sort((i,o)=>i.path.localeCompare(o.path))}async function c6(e){let t=Cr(e.platform),n=t.resolve(e.cwd,e.source.location);if(!(await Xh(n)).isDirectory()){let l=[{path:t.basename(n),...Je(new Uint8Array(await Zh(n)))}],c=Ie(l),u=Za(c,e.source);if(!u||!Mo(e.source.skillFilter,u)){let d=$6(c,t.basename(n));return{source:e.source,results:[],issues:d}}return{source:e.source,results:[{skillSlug:u,description:c.parsedSkill?.frontmatter.description??u,sourceKind:"local",relativeSkillRoot:".",relativeSkillFile:t.basename(n),discoveryRoute:"remote_file",validation:{valid:c.valid,issueCount:c.issues.length},files:l}],issues:[]}}let i=[],o=await d6(n,e.platform,i),s=new Map;for(let l of o){let c=s.get(l.skillSlug);(!c||ty(l,c)<0)&&s.set(l.skillSlug,l)}let a=[...s.values()].filter(l=>Mo(e.source.skillFilter,l.skillSlug)).map(l=>({skillSlug:l.skillSlug,description:l.description,sourceKind:"local",relativeSkillRoot:l.relativeSkillRoot,relativeSkillFile:l.relativeSkillFile,discoveryRoute:l.discoveryRoute,...l.pluginName?{pluginName:l.pluginName}:{},...l.pluginManifestPath?{pluginManifestPath:l.pluginManifestPath}:{},validation:{valid:l.validation.valid,issueCount:l.validation.issues.length},files:l.files})).sort((l,c)=>l.skillSlug.localeCompare(c.skillSlug)||l.relativeSkillRoot.localeCompare(c.relativeSkillRoot));return{source:e.source,results:a,issues:i}}async function u6(e,t){let n=new Map,r=new Set,i=Qh();for(let s of i){let a=s.discoveryRoute==="root"?e.fileSet.has("SKILL.md")?["SKILL.md"]:[]:Wa(e.fileSet,s.absolutePath,{maxDepth:5,ignoreDirNames:wn});for(let l of a){if(r.has(l)||e.onlySkillRoots&&!e.onlySkillRoots.has(ze(Ne.dirname(l))))continue;r.add(l);let c=await Jh({allFiles:e.fileSet,fetchFile:e.fetchFile,skillFilePath:l,discoveryRoute:s.discoveryRoute,allowNormalization:e.allowNormalization,issues:t});c&&Bo(n,c)}}let o=await m6(e.fileSet,e.fetchFile,t,e.allowNormalization);for(let s of o)Bo(n,s);for(let s of Wa(e.fileSet,".",{maxDepth:6,ignoreDirNames:wn})){if(r.has(s)||e.onlySkillRoots&&!e.onlySkillRoots.has(ze(Ne.dirname(s))))continue;r.add(s);let a=await Jh({allFiles:e.fileSet,fetchFile:e.fetchFile,skillFilePath:s,discoveryRoute:"recursive",allowNormalization:e.allowNormalization,issues:t});a&&Bo(n,a)}return[...n.values()]}async function d6(e,t,n){let r=Cr(t),i=new Map,o=new Set,s=p6(e,t);for(let c of s){if(!await Ya(c.absolutePath))continue;let u=c.discoveryRoute==="root"?[r.join(c.absolutePath,"SKILL.md")]:await Yh(c.absolutePath,t,{maxDepth:5,ignoreDirNames:wn});for(let d of u){let p=r.normalize(d);if(o.has(p)||!await Ya(p))continue;o.add(p);let m=await Wh({rootPath:e,skillFilePath:p,platform:t,discoveryRoute:c.discoveryRoute,issues:n});m&&Bo(i,m)}}let a=await g6(e,t,n);for(let c of a)Bo(i,c);let l=await Yh(e,t,{maxDepth:6,ignoreDirNames:wn});for(let c of l){let u=r.normalize(c);if(o.has(u))continue;o.add(u);let d=await Wh({rootPath:e,skillFilePath:u,platform:t,discoveryRoute:"recursive",issues:n});d&&Bo(i,d)}return[...i.values()]}var wn=new Set([".git",".skills-layer","node_modules","dist","coverage"]),f6=/(^|\/)SKILL\.md$/;function Qh(){let e=new Map;e.set(".","root"),e.set("skills","skills"),e.set("skills/.curated","curated"),e.set("skills/.experimental","experimental"),e.set("skills/.system","system");for(let t of We({},"linux","/repo")){let n=Mt(Ne.relative("/repo",t.targets.projectSkillsPath));n.length===0||n==="skills"||e.set(n,"agent")}return[...e.entries()].map(([t,n])=>({absolutePath:t,discoveryRoute:n}))}function p6(e,t){let n=Cr(t),r=new Map;r.set(e,"root"),r.set(n.join(e,"skills"),"skills"),r.set(n.join(e,"skills",".curated"),"curated"),r.set(n.join(e,"skills",".experimental"),"experimental"),r.set(n.join(e,"skills",".system"),"system");for(let i of We({},t,e)){let o=Mt(n.relative(e,i.targets.projectSkillsPath));o.length===0||o==="skills"||r.set(i.targets.projectSkillsPath,"agent")}return[...r.entries()].map(([i,o])=>({absolutePath:i,discoveryRoute:o}))}async function m6(e,t,n,r){let i=[".claude-plugin/marketplace.json",".claude-plugin/plugin.json"].filter(s=>e.has(s)),o=[];for(let s of i){let a;try{a=JSON.parse(x6(await t(s),s))}catch{n.push({severity:"warning",code:"plugin-manifest-invalid",message:"Plugin manifest could not be parsed as JSON.",path:s});continue}let l=tR(a,Ne.dirname(s));if(l.length===0){n.push({severity:"warning",code:"plugin-manifest-empty",message:"Plugin manifest did not declare a usable plugin or skills root.",path:s});continue}for(let c of l){let u=ze(c.relativeRootPath),d=Wa(e,u,{maxDepth:5,ignoreDirNames:wn});for(let p of d){let m=await Jh({allFiles:e,fetchFile:t,skillFilePath:p,discoveryRoute:"plugin_manifest",pluginName:c.pluginName,pluginManifestPath:s,allowNormalization:r,issues:n});m&&o.push(m)}}}return o}async function g6(e,t,n){let r=Cr(t),i=[r.join(e,".claude-plugin","marketplace.json"),r.join(e,".claude-plugin","plugin.json")],o=[];for(let s of i){if(!await Ya(s))continue;let a;try{a=JSON.parse(await Zh(s,"utf8"))}catch{n.push({severity:"warning",code:"plugin-manifest-invalid",message:"Plugin manifest could not be parsed as JSON.",path:Mt(r.relative(e,s))});continue}let l=tR(a,r.relative(e,ZI(s)));if(l.length===0){n.push({severity:"warning",code:"plugin-manifest-empty",message:"Plugin manifest did not declare a usable plugin or skills root.",path:Mt(r.relative(e,s))});continue}for(let c of l){let u=r.resolve(e,...c.relativeRootPath.split("/"));if(!aR(e,u,t)){n.push({severity:"warning",code:"plugin-root-escaped",message:"Plugin manifest resolved outside the inspected source root and was ignored.",path:Mt(r.relative(e,s))});continue}if(!await Ya(u))continue;let d=await Yh(u,t,{maxDepth:5,ignoreDirNames:wn});for(let p of d){let m=await Wh({rootPath:e,skillFilePath:p,platform:t,discoveryRoute:"plugin_manifest",pluginName:c.pluginName,pluginManifestPath:Mt(r.relative(e,s)),issues:n});m&&o.push(m)}}}return o}function tR(e,t){if(!Kh(e))return[];let n=t.length===0?".":Mt(t),r=zh(e,["plugin_root","pluginRoot","skills_root","skillsRoot","root","path","directory"]),i=[];if(Array.isArray(e.plugins))for(let o of e.plugins){if(!Kh(o))continue;let s=zh(o,["plugin_root","pluginRoot","skills_root","skillsRoot","root","path","directory"]),a=typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():void 0,l=s??(r&&a?`${r}/${a}`:void 0);l&&i.push({pluginName:a,relativeRootPath:_d(n,l)})}if(Array.isArray(e.skills))for(let o of e.skills){if(typeof o=="string"&&o.trim().length>0){let c=r?`${r}/${o.trim()}`:o.trim();i.push({relativeRootPath:_d(n,c)});continue}if(!Kh(o))continue;let s=zh(o,["root","path","directory"]),a=typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():void 0,l=s??(r&&a?`${r}/${a}`:void 0);l&&i.push({pluginName:a,relativeRootPath:_d(n,l)})}return i.length>0?i:r?[{pluginName:typeof e.name=="string"?e.name.trim():void 0,relativeRootPath:_d(n,r)}]:[{pluginName:typeof e.name=="string"?e.name.trim():void 0,relativeRootPath:n}]}function _d(e,t){let n=ze(t);return e===".claude-plugin"&&!t.startsWith(".")?n:Ja(e,n)}async function Wh(e){let t=Cr(e.platform),n=ZI(e.skillFilePath);if(!aR(e.rootPath,n,e.platform))return null;let r;try{r=await h6(n,e.platform)}catch(l){if(!(l instanceof No))throw l;let c=l.message;return e.issues.push({severity:"warning",code:"skill-too-large",message:c,path:Mt(t.relative(e.rootPath,e.skillFilePath))}),null}let i=Ie(r),o=Za(i,null);if(!o||!i.parsedSkill)return jo(e.issues,i,Mt(t.relative(e.rootPath,e.skillFilePath))),null;let s=ze(t.relative(e.rootPath,n)),a=oR(e.discoveryRoute,s);return{skillSlug:o,description:i.parsedSkill.frontmatter.description,relativeSkillRoot:s,relativeSkillFile:Mt(t.relative(e.rootPath,e.skillFilePath)),discoveryRoute:a,...e.pluginName?{pluginName:e.pluginName}:{},...e.pluginManifestPath?{pluginManifestPath:e.pluginManifestPath}:{},files:r,originalFiles:r,validation:i}}async function Jh(e){let t=ze(Ne.dirname(e.skillFilePath)),n;try{n=await y6(t,e.allFiles,e.fetchFile)}catch(c){if(!(c instanceof No))throw c;let u=c.message;return e.issues.push({severity:"warning",code:"skill-too-large",message:u,path:e.skillFilePath}),null}let r=t!=="."?fi(Ne.basename(t))??void 0:void 0,i=bd({files:n,fallbackSkillSlug:r,allowNormalization:e.allowNormalization??!0}),o=i.validation,s=i.skillSlug??Za(o,null);if(!s||!o.parsedSkill)return jo(e.issues,o,e.skillFilePath),null;let a=ze(t),l=oR(e.discoveryRoute,a);return{skillSlug:s,description:i.description??o.parsedSkill.frontmatter.description,...i.originalSkillName?{originalSkillName:i.originalSkillName}:{},relativeSkillRoot:a,relativeSkillFile:e.skillFilePath,discoveryRoute:l,...e.pluginName?{pluginName:e.pluginName}:{},...e.pluginManifestPath?{pluginManifestPath:e.pluginManifestPath}:{},...i.normalizationIssues.length>0?{normalizationIssues:i.normalizationIssues}:{},...i.normalizationProvenance?{normalizationProvenance:i.normalizationProvenance}:{},files:i.files,originalFiles:n,validation:o}}async function h6(e,t){let n=[],r=Cr(t);async function i(o){let s=await YI(o,{withFileTypes:!0});for(let a of s){let l=r.join(o,a.name),c=Mt(r.relative(e,l));if(a.isDirectory()){if(wn.has(a.name)||l!==e&&await Ya(r.join(l,"SKILL.md")))continue;await i(l);continue}if(!ey(c)){if(n.length>=Cd)throw new No(`Skill root contains too many files. The maximum allowed is ${Cd}.`);n.push({path:c,...(await Xh(l)).mode&73?{executable:!0}:{},...Je(new Uint8Array(await Zh(l)))})}}}return await i(e),n.sort((o,s)=>o.path.localeCompare(s.path))}async function y6(e,t,n){let r=new Set([...t].filter(o=>o==="SKILL.md"||o.endsWith("/SKILL.md")).map(o=>ze(Ne.dirname(o)))),i=[...t].filter(o=>kr(o,e)!==null).filter(o=>!sR(e,o,r)).filter(o=>{let s=kr(o,e);return s!==null&&!ey(s)}).sort((o,s)=>o.localeCompare(s));if(i.length>Cd)throw new No(`Skill root contains too many files (${i.length}). The maximum allowed is ${Cd}.`);return Promise.all(i.map(async o=>{let s;try{s=await n(o)}catch(a){throw new Oo(a)}return{path:kr(o,e)??o,...typeof s=="string"?{content:s}:s}}))}async function Yh(e,t,n){let r=Cr(t),i=[];async function o(s,a){if(a>n.maxDepth)return;let l=await YI(s,{withFileTypes:!0});for(let c of l){if(c.isDirectory()){if(n.ignoreDirNames.has(c.name))continue;await o(r.join(s,c.name),a+1);continue}c.name==="SKILL.md"&&i.push(r.join(s,c.name))}}return await o(e,0),i.sort()}function Wa(e,t,n){let r=[];for(let i of e){if(Ne.basename(i)!=="SKILL.md")continue;let o=kr(i,t);if(o===null)continue;let s=o.split("/").filter(a=>a.length>0);s.length!==0&&(s.slice(0,-1).some(a=>n.ignoreDirNames.has(a))||s.length-1>n.maxDepth||r.push(i))}return r.sort((i,o)=>i.localeCompare(o))}function w6(e){return e.kind==="url"?e.url:e.kind==="well-known"?e.sourceUrl:e.rawUrl}function nR(e,t){return e.kind==="github"?`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${t}`:`https://${e.host}/${e.namespace}/${e.repo}/-/raw/${e.ref}/${t}`}function ey(e){let t=ze(e);if(t==="."||t.length===0)return!1;let n=t.split("/").filter(o=>o.length>0);if(n.some(o=>wn.has(o)))return!0;let r=n[n.length-1]??"",i=Buffer.from([46,68,83,95,83,116,111,114,101]).toString("ascii");return r===i||r==="Thumbs.db"}var v6=new WeakMap;async function b6(e,t){let n=v6.get(t);if(e.kind!=="github"||!/^([a-f0-9]{40})$/iu.test(e.ref)||!n)return(await zI(e,t)).entries;let r=`${e.owner}/${e.repo}@${e.ref}`,i=ny(e.subpath),o=async u=>{let d=zI(e,t);return n.size<32&&(n.set(u,d),d.catch(()=>n.delete(u))),await d},s=u=>u.entries.map(d=>({...d})),a=n.get(r);if(!a)return s(await o(r));let l=await a;if(l.root===null||l.root===i)return s(l);let c=n.get(`${r}#${i}`);return s(c?await c:await o(`${r}#${i}`))}async function kd(e,t,n,r){let i=await t(`https://api.github.com/repos/${e.owner}/${e.repo}/git/trees/${encodeURIComponent(n)}${r?"?recursive=1":""}`,{headers:{"user-agent":"skills-layer-source-inspector"}});if(!i.ok)throw new mi(i.status,await Sr(i));return await i.json()}function Sd(e,t){return(e.tree??[]).filter(n=>n.type==="blob"&&typeof n.path=="string"&&!rR(n.mode)).map(n=>({path:`${t}${n.path}`,...n.mode==="100755"?{executable:!0}:{},providerBlobSha:Fo(n.sha),sizeBytes:Number.isSafeInteger(n.size)&&(n.size??-1)>=0?n.size:null}))}function GI(e,t){for(let n of e.tree??[]){let r=Fo(n.sha);if(n.type==="tree"&&typeof n.path=="string"&&r&&t(n.path))return{path:n.path,sha:r}}return null}function _6(e){return e instanceof Error&&/^Safe remote fetch response exceeds \d+ bytes\.$/u.test(e.message)}async function k6(e,t,n){let r=new Map,i=c=>{for(let u of c)r.set(u.path,u)},o=c=>{if(c.truncated===!0)throw new Error("github_repository_context_incomplete");return c},s=()=>[...r.values()].sort((c,u)=>c.path.localeCompare(u.path)),a=e.ref,l="";for(let c of n.split("/")){let u=o(await kd(e,t,a,!1));i(Sd(u,l));let d=GI(u,m=>m.toUpperCase()==="LICENSES");d&&i(Sd(o(await kd(e,t,d.sha,!1)),`${l}${d.path}/`));let p=GI(u,m=>m===c);if(!p)return s();a=p.sha,l=`${l}${c}/`}return i(Sd(o(await kd(e,t,a,!0)),l)),s()}async function zI(e,t){if(e.kind==="github"){let o=ny(e.subpath),s=null;try{s=await kd(e,t,e.ref,!0)}catch(a){if(o==="."||!_6(a))throw a}if(s&&s.truncated!==!0)return{entries:Sd(s,"").sort((a,l)=>a.path.localeCompare(l.path)),root:null};if(o===".")throw new Error("github_repository_context_incomplete");return{entries:await k6(e,t,o),root:o}}let n=encodeURIComponent(`${e.namespace}/${e.repo}`),r=[],i=1;for(;;){let o=new URLSearchParams({recursive:"true",ref:e.ref,per_page:"100",page:String(i)}),s=await t(`https://${e.host}/api/v4/projects/${n}/repository/tree?${o.toString()}`);if(!s.ok)throw new mi(s.status,await Sr(s));let a=await s.json();r.push(...a.filter(c=>c.type==="blob"&&typeof c.path=="string"&&!rR(c.mode)).map(c=>({path:c.path,...c.mode==="100755"?{executable:!0}:{},providerBlobSha:Fo(c.id),sizeBytes:null})));let l=s.headers.get("x-next-page");if(!l||l.trim().length===0||(i=Number.parseInt(l,10),Number.isNaN(i)||i<1))break}return{entries:r.sort((o,s)=>o.path.localeCompare(s.path)),root:null}}function rR(e){return e==="120000"}async function S6(e,t,n){if(/^[a-f0-9]{40}$/iu.test(e.ref))return{commitSha:e.ref.toLowerCase(),treeSha:null};if(e.kind==="github")try{let i=await t(`https://api.github.com/repos/${e.owner}/${e.repo}/commits/${encodeURIComponent(e.ref)}`,{headers:{"user-agent":"skills-layer-source-inspector"}});if(!i.ok)throw new mi(i.status,await Sr(i));let o=await i.json(),s=Fo(o.sha);if(!s)throw new Error("GitHub source revision did not resolve to an immutable commit.");return{commitSha:s,treeSha:Fo(o.commit?.tree?.sha)}}catch{return{commitSha:n,treeSha:null}}let r=encodeURIComponent(`${e.namespace}/${e.repo}`);try{let i=await t(`https://${e.host}/api/v4/projects/${r}/repository/commits/${encodeURIComponent(e.ref)}`);if(!i.ok)throw new mi(i.status,await Sr(i));let o=await i.json(),s=Fo(o.id);if(!s)throw new Error("GitLab source revision did not resolve to an immutable commit.");return{commitSha:s,treeSha:null}}catch{return{commitSha:n,treeSha:null}}}function C6(e){let t=Ad("sha256");for(let n of[...e].sort((r,i)=>r.relativeSkillRoot.localeCompare(i.relativeSkillRoot))){t.update(n.relativeSkillRoot),t.update("\0");for(let r of[...n.originalFiles].sort((i,o)=>i.path.localeCompare(o.path)))t.update(r.path),t.update("\0"),t.update(re(r)),t.update("\0")}return`content-sha256:${t.digest("hex")}`}function Fo(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function A6(e){return`sha256:${Ad("sha256").update(e).digest("hex")}`}function x6(e,t){if(typeof e=="string")return e;if(typeof e.content!="string")throw new Error(`${t} must be valid bounded UTF-8 text.`);return e.content}async function I6(e,t){let n=new URL(e),r=n.pathname.replace(/\/+$/u,""),i=r.match(/^(.*\/\.well-known\/skills)(?:\/.*)?$/iu),o=[`${n.protocol}//${n.host}${r}/.well-known/skills/index.json`];i&&o.push(`${n.protocol}//${n.host}${i[1]}/index.json`),r.length>0&&!r.includes("/.well-known/skills")&&o.push(`${n.protocol}//${n.host}/.well-known/skills/index.json`),r.endsWith("/.well-known/skills")&&o.unshift(`${n.protocol}//${n.host}${r}/index.json`),r.endsWith("/.well-known/skills/index.json")&&o.unshift(`${n.protocol}//${n.host}${r}`);for(let s of[...new Set(o)])try{let a=await t(s);if(!a.ok||!(a.headers.get("content-type")??"").includes("json"))continue;return{indexUrl:s,index:jI(await a.json())}}catch{continue}return null}async function R6(e,t){try{let n=await t(e);return!n.ok||!(n.headers.get("content-type")??"").includes("json")?null:NI(await n.json())}catch{return null}}async function KI(e,t){try{let n=await t(e);return!n.ok||!(n.headers.get("content-type")??"").includes("json")?null:MI(await n.json())}catch{return null}}function HI(e){let t={};for(let n of e.manifest.skill.files)t[n.path]=n.url;return{kind:"well-known",input:e.skillFilter?`${e.inputSource.input}#${e.skillFilter}`:e.inputSource.input,indexUrl:e.detectedIndex.indexUrl,providerName:e.manifest.provider.name||e.detectedIndex.index.provider.name,providerUrl:e.manifest.provider.baseUrl||e.detectedIndex.index.provider.baseUrl,skillSlug:e.manifest.skill.slug,skillManifestUrl:e.manifestUrl,sourceUrl:e.manifest.skill.sourceUrl,files:e.manifest.skill.files.map(n=>n.path),fileUrls:t,canonicalSource:`${e.detectedIndex.indexUrl}#${e.manifest.skill.slug}`,...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function WI(e,t){let n=e;for(let[r,i]of Object.entries(t))n=n.replaceAll(`{${r}}`,encodeURIComponent(i));return n}function P6(e){try{return new URL(e).searchParams.get("q")?.trim()??""}catch{return""}}function iR(e){let t=e.toLowerCase();return t.endsWith(".md")||t.endsWith(".txt")}function E6(e){try{let r=new URL(e).pathname.match(/\/\.well-known\/skills\/([^/]+)(?:\/.*)?$/iu)?.[1];return r&&r!=="index.json"&&r!=="search.json"?r:void 0}catch{return}}function Za(e,t){return e.parsedSkill?.frontmatter.name??(t?.kind==="well-known"?t.skillSlug:void 0)}function Mo(e,t){return!e||e===t}function ty(e,t){return JI(e.discoveryRoute)-JI(t.discoveryRoute)||e.relativeSkillRoot.localeCompare(t.relativeSkillRoot)}function Bo(e,t){let n=`${t.skillSlug}:${t.relativeSkillRoot}`,r=e.get(n);if(!r){e.set(n,t);return}let i=ty(t,r)<0?t:r,o=i===t?r:t;e.set(n,{...i,pluginName:i.pluginName??o.pluginName,pluginManifestPath:i.pluginManifestPath??o.pluginManifestPath})}function JI(e){switch(e){case"remote_file":return 0;case"root":return 1;case"curated":return 2;case"skills":return 3;case"system":return 4;case"experimental":return 5;case"plugin_manifest":return 6;case"agent":return 7;case"recursive":return 8}}function ze(e){let t=Mt(e);return t.length===0?".":t}function ny(e){let t=ze(e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""));return t==="SKILL.md"?".":t.endsWith("/SKILL.md")?ze(Ne.dirname(t)):t}function D6(e){let t=(e??[]).map(r=>r.replaceAll("\\","/").replace(/^\/+/u,"").trim()).filter(r=>r.length>0),n=[...new Set(t)];return n.includes("SKILL.md")?n:["SKILL.md",...n]}function T6(e,t){let n=new URL(e),r=n.toString().endsWith("/SKILL.md")?n.toString().slice(0,-8):`${n.toString().replace(/\/+$/u,"")}/`;return new URL(t.replace(/^\/+/u,""),r).toString()}function oR(e,t){return e==="skills"&&t.startsWith("skills/.curated/")?"curated":e==="skills"&&t.startsWith("skills/.system/")?"system":e==="skills"&&t.startsWith("skills/.experimental/")?"experimental":e}function Cr(e){return e==="win32"?JV:Ne}function Mt(e){return e.replaceAll("\\","/")}function zh(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}function Kh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ja(e,t){let n=e==="."?"":e.replace(/\/+$/u,""),r=t.replace(/^\.\/+/u,"");return[n,r].filter(i=>i.length>0).join("/")||"."}function kr(e,t){let n=ze(e),r=ze(t);return r==="."?n:n===r?".":n.startsWith(`${r}/`)?n.slice(r.length+1):null}function sR(e,t,n){let r=ze(Ne.dirname(t));for(;r!=="."&&r!==e;){if(n.has(r))return!0;r=ze(Ne.dirname(r))}return!1}function $6(e,t){let n=[];return jo(n,e,t),n}function jo(e,t,n){if(!t.valid)for(let r of t.issues)r.severity==="error"&&L6(e,{severity:"warning",code:r.code,message:r.message,path:n})}function L6(e,t){e.some(n=>n.code===t.code&&n.message===t.message&&n.path===t.path)||e.push(t)}function aR(e,t,n){let r=Cr(n),i=r.resolve(e),o=r.resolve(t),s=r.relative(i,o);return s.length===0||!s.startsWith("..")&&!r.isAbsolute(s)}async function Ya(e){try{return await Xh(e),!0}catch{return!1}}var mi=class extends Error{constructor(n,r){super(r.message);this.status=n;this.name="ApiErrorLike"}status};async function Sr(e){let t=e.headers.get("content-type")??"",n=e.clone();if(t.includes("application/json"))try{let r=await e.json(),i=typeof r.error=="string"?r.error:typeof r.message=="string"?r.message:"";if(i.trim().length>0)return new Error(i.trim())}catch{}return new Error(await n.text()||`Remote source request failed with ${e.status}.`)}var O6=18;function F6(e,t){let n=e.map(c=>kr(c,t)).filter(c=>c!==null),r=new Set(n),i=new Set,o=[],s=Qh();for(let c of s){let u=c.discoveryRoute==="root"?r.has("SKILL.md")?["SKILL.md"]:[]:Wa(r,c.absolutePath,{maxDepth:5,ignoreDirNames:wn});for(let d of u)i.has(d)||(i.add(d),o.push(d))}for(let c of Wa(r,".",{maxDepth:6,ignoreDirNames:wn}))i.has(c)||(i.add(c),o.push(c));let a=new Set(o.map(c=>ze(Ne.dirname(c)))),l=[];for(let c of o){let u=ze(Ne.dirname(c)),d=[...r].filter(p=>kr(p,u)!==null).filter(p=>!sR(u,p,a)).filter(p=>{let m=kr(p,u);return m!==null&&!ey(m)}).sort((p,m)=>p.localeCompare(m));l.push({skillFilePath:c,skillRoot:u,bundleFilePaths:d,bundleFileCount:d.length,estimatedCost:d.length+O6})}return l.sort((c,u)=>c.skillFilePath.localeCompare(u.skillFilePath))}import{constants as lR}from"node:fs";import{lstat as Rd,open as B6,opendir as N6,realpath as dR}from"node:fs/promises";import{dirname as fR,isAbsolute as iy,parse as pR,relative as Xa,resolve as Qa,sep as mR}from"node:path";var te=class extends Error{code;issueCodes;issues;preview;constructor(t,n=[],r){super(`Local bundle rejected (${t}).`),this.name="LocalBundleIntakeError",this.code=t,this.issueCodes=[...new Set(n)].sort((i,o)=>i.localeCompare(o)),this.issues=r?.issues??[],this.preview=r?.preview}},M6=32*1024,j6=64*1024;async function Uo(e){let t=V6(e.limits),n=G6(e.maxTraversalEntries,t.maxFiles),r=Qa(e.cwd),i=Qa(r,e.sourcePath);await z6(r,e.sourcePath,i);let o=await vR(i);oy(o);let s=await uR(i),a=o.isDirectory()?s:await uR(fR(i));sy(a,s);let l={rootRealPath:a,limits:t,maxTraversalEntries:n,traversalEntries:0,fileCount:0,declaredTotalBytes:0,skillsIgnore:"",excludePath:Gf(),files:[],excluded:[],hooks:e.hooks};if(o.isFile()){let d=eG(i),p=l.excludePath(d);p?l.excluded.push({path:d,reason:p}):await yR(i,d,o,l)}else await W6(i,o,l);let c;try{c=Jn({files:l.files,skillsIgnore:l.skillsIgnore,limits:t})}catch{let d=ln({files:l.files,skillsIgnore:l.skillsIgnore,limits:t});throw new te("canonical_bundle_rejected",d.issues.map(p=>p.code),U6(d))}if(c.files.length===0)throw new te("local_bundle_empty");let u=new Map;for(let d of[...l.excluded,...c.excluded])u.set(d.path,d);return{...c,excluded:[...u.values()].sort((d,p)=>d.path.localeCompare(p.path))}}function U6(e){return{issues:e.issues.map(t=>{let n=q6(t.code),r=cR(t.path,t.code);return{code:t.code,...r?{path:r}:{},message:t.message,...n}}),preview:{fileCount:e.preview.fileCount,totalBytes:e.preview.totalBytes,bundleSha256:e.preview.bundleSha256,files:e.preview.files.filter(t=>cR(t.path,"preview")).map(t=>({...t}))}}}function cR(e,t){if(!(!e||t==="pii_path"||e.startsWith("/")||/^[A-Za-z]:/u.test(e)||e.includes("\\")||e.split("/").some(n=>!n||n==="."||n==="..")||/[^\s@]+@[^\s@]+\.[^\s@]+/u.test(e)))return e}function q6(e){return e==="pii_email"||e==="pii_phone"||e==="pii_path"?{remediationId:"remove_personal_data",remediation:"Remove personal contact data from distributable skill files and validate again."}:e.startsWith("secret_")?{remediationId:"remove_secret",remediation:"Remove the secret and reference a runtime-provided credential instead."}:e.includes("path")||e==="reserved_path"||e==="binary_content"?{remediationId:"fix_bundle_entry",remediation:"Rename, remove, or convert the listed bundle entry to portable UTF-8 text."}:e.includes("exceeded")||e==="file_too_large"?{remediationId:"reduce_bundle_size",remediation:"Reduce the listed file or bundle size to the documented canonical limits."}:{remediationId:"fix_canonical_bundle",remediation:"Correct the listed canonical intake issue and run validation again."}}function V6(e){let t={...we,...e};return ln({files:[],limits:t,runDlp:!1}),t}function G6(e,t){let n=e??Math.max(256,t*8);if(!Number.isInteger(n)||n<=0)throw new te("local_traversal_budget_exceeded");return n}async function z6(e,t,n){let r=H6(e,t,n);for(let i=0;i<r.length;i+=1){let o=await vR(r[i]);if(o.isSymbolicLink()){if(K6(r[i],o,t,e,n,i))continue;throw new te("local_entry_symlink")}if(i<r.length-1&&!o.isDirectory())throw new te("local_entry_non_regular")}}function K6(e,t,n,r,i,o,s=process.platform){if(s==="win32"||!iy(n)||ay(Xa(r,i))||o!==0||t.uid!==0n)return!1;let a=pR(e).root;return fR(e)===a}function H6(e,t,n){if(!iy(t))return ry(e,Xa(e,n));let r=Xa(e,n);if(ay(r))return ry(e,r);let i=pR(n).root;return ry(i,Xa(i,n))}function ry(e,t){let n=[],r=e;for(let i of t.split(mR))!i||i==="."||(r=Qa(r,i),n.at(-1)!==r&&n.push(r));return n}async function W6(e,t,n){let r=await hR(e,t,n);if(r.includes(".skillsignore")){let i=Qa(e,".skillsignore"),o=await bR(i);if(oy(o),!o.isFile())throw new te("local_entry_non_regular");n.skillsIgnore=await Y6(i,".skillsignore",o,M6,n);try{n.excludePath=Gf(n.skillsIgnore)}catch{throw new te("canonical_bundle_rejected",["skillsignore_invalid"])}n.files.push({path:".skillsignore",content:n.skillsIgnore})}await gR(e,t,r,"",n)}async function J6(e,t,n,r){let i=await hR(e,n,r);await gR(e,n,i,t,r)}async function gR(e,t,n,r,i){for(let o of n){let s=r?`${r}/${o}`:o;if(!r&&s===".skillsignore")continue;let a=i.excludePath(s);if(a){i.excluded.push({path:s.normalize("NFC"),reason:a});continue}Q6(s,i.limits);let l=Qa(e,o);await i.hooks?.beforeEntryInspection?.({relativePath:s});let c=await bR(l);oy(c),await i.hooks?.afterEntryInspection?.({relativePath:s,kind:c.isDirectory()?"directory":"file"}),await xd(l,c);let u={relativePath:s,kind:c.isDirectory()?"directory":"file"};await i.hooks?.afterEntryValidation?.(u);let d=await _R(l);sy(i.rootRealPath,d),c.isDirectory()?await J6(l,s,c,i):await yR(l,s,c,i)}await xd(e,t)}async function hR(e,t,n){let r;try{r=await N6(e)}catch{throw new te("local_entry_unreadable")}let i=[];try{for(;;){let o=await r.read();if(!o)break;if(n.traversalEntries+=1,n.traversalEntries>n.maxTraversalEntries)throw new te("local_traversal_budget_exceeded");i.push(o.name)}}catch(o){throw o instanceof te?o:new te("local_entry_unreadable")}finally{await r.close().catch(()=>{})}return await xd(e,t),i.sort((o,s)=>o.localeCompare(s))}async function yR(e,t,n,r){if(r.fileCount+=1,r.fileCount>r.limits.maxFiles)throw new te("local_file_count_exceeded");let i=zf(t,r.limits);if(n.size>BigInt(i))throw new te("local_file_bytes_exceeded");let o=r.declaredTotalBytes+Number(n.size);if(!Number.isSafeInteger(o)||o>r.limits.maxTotalBytes)throw new te("local_total_bytes_exceeded",["local_total_bytes_exceeded"],{issues:[{code:"local_total_bytes_exceeded",path:t,message:`Bundle exceeds the ${r.limits.maxTotalBytes}-byte upload limit.`,remediationId:"reduce_bundle_size",remediation:"Remove unnecessary files or reduce their size, then validate again."}]});let s=await wR(e,t,n,i,r),a=Je(s,Wn(t,s));if(typeof a.contentBase64=="string"&&Sb(t))throw new te("local_entry_invalid_utf8");r.declaredTotalBytes=o,r.files.push({path:t,...a,...(n.mode&0o111n)!==0n?{executable:!0}:{}})}async function Y6(e,t,n,r,i){let o=await wR(e,t,n,r,i);try{return new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new te("local_entry_invalid_utf8")}}async function wR(e,t,n,r,i){await xd(e,n);let o=await _R(e);sy(i.rootRealPath,o);let s={relativePath:t,kind:"file"};await i.hooks?.beforeFileOpen?.(s);let a;try{a=await B6(e,lR.O_RDONLY|lR.O_NOFOLLOW)}catch(l){throw new te(tG(l)?"local_entry_raced":"local_entry_unreadable")}try{let l=await a.stat({bigint:!0});if(!l.isFile())throw new te("local_entry_non_regular");if(!Id(n,l))throw new te("local_entry_raced");await i.hooks?.afterFileOpen?.(s);let c=await Z6(a,r),u=await a.stat({bigint:!0});if(!Id(l,u)||BigInt(c.byteLength)!==u.size)throw new te("local_entry_raced");return await i.hooks?.afterFileMetadataValidation?.(s),await X6(e,u),c}catch(l){throw l instanceof te?l:new te("local_entry_unreadable")}finally{await a.close().catch(()=>{})}}async function Z6(e,t){let n=[],r=0;for(;;){let i=t+1-r,o=Buffer.allocUnsafe(Math.min(j6,i)),{bytesRead:s}=await e.read(o,0,o.byteLength,r);if(s===0)break;if(r+=s,r>t)throw new te("local_file_bytes_exceeded");n.push(o.subarray(0,s))}return Buffer.concat(n,r)}async function vR(e){try{return await Rd(e,{bigint:!0})}catch{throw new te("local_entry_unreadable")}}async function bR(e){try{return await Rd(e,{bigint:!0})}catch{throw new te("local_entry_unreadable")}}function oy(e){if(e.isSymbolicLink())throw new te("local_entry_symlink");if(!e.isDirectory()&&!e.isFile())throw new te("local_entry_non_regular")}async function xd(e,t){let n;try{n=await Rd(e,{bigint:!0})}catch{throw new te("local_entry_raced")}if(!Id(t,n))throw new te("local_entry_raced")}async function X6(e,t){let n;try{n=await Rd(e,{bigint:!0})}catch{throw new te("local_entry_raced")}if(!Id(t,n))throw new te("local_entry_raced")}function Id(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.ctimeNs===t.ctimeNs}async function uR(e){try{return await dR(e)}catch{throw new te("local_entry_unreadable")}}async function _R(e){try{return await dR(e)}catch{throw new te("local_entry_raced")}}function sy(e,t){if(!ay(Xa(e,t)))throw new te("local_entry_outside_root")}function ay(e){return e===""||!e.startsWith(`..${mR}`)&&e!==".."&&!iy(e)}function Q6(e,t){if(e.split("/").length>t.maxDepth)throw new te("local_path_depth_exceeded");if(Buffer.byteLength(e,"utf8")>t.maxPathBytes)throw new te("local_path_length_exceeded")}function eG(e){let t=e.replaceAll("\\","/").split("/");return t[t.length-1]}function tG(e){return["ELOOP","ENOENT","ENOTDIR"].includes(String(e.code))}import{lstat as nG,readdir as rG,readFile as iG}from"node:fs/promises";import{join as oG,relative as sG}from"node:path";var aG=Object.freeze({maxEntries:1e4,maxFiles:1e3,maxFileBytes:20*1024*1024,maxTotalBytes:64*1024*1024}),gi=class extends Error{reasonCode="local_eval_input_too_large";constructor(t){super(`local_eval_input_too_large: ${t}`),this.name="LocalEvalInputTooLargeError"}};async function kR(e,t){let n={...aG,...t.limits},r={entries:0,totalBytes:0},i=[],o=async s=>{for(let a of await rG(s,{withFileTypes:!0})){if(++r.entries>n.maxEntries)throw new gi(`more than ${n.maxEntries} entries`);if(t.skipEntry(a.name))continue;let l=oG(s,a.name);if(a.isDirectory()){await o(l);continue}if(!a.isFile()||t.skipFile(a.name))continue;let c;try{let u=await nG(l);if(u.size>n.maxFileBytes)throw new gi(`a file is larger than ${n.maxFileBytes} bytes`);if(r.totalBytes+u.size>n.maxTotalBytes)throw new gi(`files exceed ${n.maxTotalBytes} bytes`);if(i.length+1>n.maxFiles)throw new gi(`more than ${n.maxFiles} files`);c={path:sG(e,l).split("\\").join("/"),content:await iG(l,"utf8"),...u.mode&73?{executable:!0}:{}},r.totalBytes+=u.size}catch(u){if(u instanceof gi)throw u;continue}i.push(c)}};return await o(e),i.sort((s,a)=>s.path.localeCompare(a.path))}var lG=Tt(ei(),1);import{createHash as cG}from"node:crypto";var SR="skills-layer.commercial-rights-declaration.v1",uG="I declare that I own this skill bundle or am authorised by its rightsholder to distribute it commercially, and that charging for it does not infringe the rights of any other person.",Tte=`sha256:${cG("sha256").update(uG).digest("hex")}`;import{createHash as dG}from"node:crypto";var fG=6,pG=1e3,mG=3e4,gG=5e3,hG=1e3,yG=12e4;function Ed(e){return e.reduce((t,n)=>t+Ki(n),0)>we.maxTotalBytes}async function cy(e){let t=e.apiKey?"/api/v1/me/source-hydrations":"/api/v1/source-hydrations",n=e.baseUrl.replace(/\/+$/u,""),r=e.apiKey?{authorization:`Bearer ${e.apiKey}`}:{},i=e.sleep??bG,o=e.files.map(u=>{let d=re(u);return{file:u,bytes:d,mediaType:u.mediaType?.trim()||Wn(u.path,d),sha256:`sha256:${dG("sha256").update(d).digest("hex")}`}}),s=await ly(()=>e.fetchFn(`${n}${t}`,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify({...e.apiKey?{}:{visibility:"public"},files:o.map(({file:u,bytes:d,mediaType:p,sha256:m})=>({path:u.path,...u.executable?{executable:!0}:{},sizeBytes:d.byteLength,sha256:m,mediaType:p}))})}),{sleep:i,retryBusy:!1}),a=Pd(s,"manifestId"),l=new Map((Array.isArray(s.files)?s.files:[]).filter(u=>!!u&&typeof u=="object"&&!Array.isArray(u)).map(u=>[Pd(u,"path"),Pd(u,"uploadPath")]));for(let{file:u,bytes:d,mediaType:p}of o){let m=l.get(u.path);if(!m)throw new Error(`Source hydration upload path is missing for ${u.path}.`);await ly(()=>e.fetchFn(`${n}${m}`,{method:"PUT",headers:{"content-type":p,...r},body:Buffer.from(d)}),{sleep:i,retryBusy:!0})}let c=await ly(()=>e.fetchFn(`${n}${t}/${encodeURIComponent(a)}`,{headers:r}),{sleep:i,retryBusy:!1});if(c.status!=="validated")throw new Error("Source hydration upload did not reach validated state.");return{manifestId:a,candidateId:Pd(c,"candidateId")}}async function ly(e,t){for(let n=1;;n+=1){let r=await e(),i=await r.text(),o=_G(i),s=n<fG?wG(r,o,n,t.retryBusy):null;if(s===null)return kG(r,i,o);await t.sleep(s)}}function wG(e,t,n,r){return e.status===429?qo(t)&&t.reasonCode==="anonymous_upload_quota_exceeded"?null:CR(e.headers.get("retry-after"))??gG:r&&e.status===409&&vG(t)?CR(e.headers.get("retry-after"))??Math.min(mG,pG*2**(n-1)):null}function vG(e){return qo(e)?e.status==="unavailable"||qo(e.data)&&e.data.status==="unavailable":!1}function CR(e){let t=e?.trim()??"";if(!t)return null;let n=/^\d+$/u.test(t)?Number(t)*1e3:Date.parse(t)-Date.now();return Number.isFinite(n)?Math.min(yG,Math.max(hG,n)):null}function bG(e){return new Promise(t=>setTimeout(t,e))}function _G(e){try{return e?JSON.parse(e):null}catch{return null}}function kG(e,t,n){if(!e.ok){let r=qo(n)&&typeof n.error=="string"?n.error:t||e.statusText||"Source hydration request failed.";throw new Error(r)}if(!qo(n))throw new Error("Source hydration returned an invalid response.");return n.schemaVersion!=="skills-layer.creator.operation.v1"&&qo(n.data)?n.data:n}function qo(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Pd(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`Source hydration response is missing ${t}.`);return n}var Hte=256*1024;var nne=26*1024*1024;var SG=1024*1024;var hi=Object.freeze({...we,maxTotalBytes:20*SG});var dne=Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r+=1)n=(n&1)!==0?3988292384^n>>>1:n>>>1;return n>>>0});import{createHash as CG,randomUUID as RR,timingSafeEqual as AG}from"node:crypto";import{constants as Ar}from"node:fs";import{chmod as xG,lstat as Rr,mkdir as hy,mkdtemp as IG,open as Ld,realpath as fy,readdir as RG,rename as Pr,rm as PR}from"node:fs/promises";import{basename as wi,dirname as Nn,join as jt,parse as Od,posix as uy,resolve as Fd,sep as el}from"node:path";var PG=3e4,AR=5*6e4,tl=/^sha256:[a-f0-9]{64}$/u,ER=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,DR=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,EG=new TextEncoder().encode("SKILLS-LAYER-MANIFEST-V1\0"),Bd=typeof Ar.O_NOFOLLOW=="number"?Ar.O_NOFOLLOW:0;async function TR(e){return LR(e,!0)}async function $R(e){return LR(e,!1)}async function LR(e,t){let n=DG(e.preActivationTimeoutMs),{envelope:r,files:i,manifestV2:o}=TG(e.archiveBytes,e.envelope);if(t&&$G(e.approval,r),o){let y=new Set(o.files.filter(w=>w.byteClass==="approved_binary_asset").map(w=>w.path));Td(i.filter(w=>!y.has(w.path)))}else Td(i);let s=Fd(e.targetDir),a=await Go(s);if(a===Od(a).root)throw new Error("Atomic install target cannot be a filesystem root.");if(wi(a)!==ti(i))throw new Error("Atomic install target basename must equal the verified skill frontmatter name.");let l=Nn(a);await rl(l),await hy(l,{recursive:!0,mode:448}),await rl(l);let c=await tn(l,"Atomic install parent"),u=await wy(a),d=await IG(jt(l,`.${wi(a)}.skills-layer-stage-`)),p=await tn(d,"Atomic install stage"),m=null,g=!1,h=!1;try{await yi(e.checkpoint,"after_stage_created");for(let _ of i)await LG(d,_),await yi(e.checkpoint,"after_file_written");await Vo(d,r.manifest.files,p);let y=await BG({callback:e.preActivate,stageDir:d,files:r.manifest.files,timeoutMs:n});if(y.status!=="passed")throw new Error(`Static pre-activation Eval failed: ${y.reasonCode}`);await Vo(d,r.manifest.files,p),await xR(d,r.manifest.files),await yi(e.checkpoint,"after_static_eval"),await Vo(d,r.manifest.files,p),await xR(d,r.manifest.files),await xr(l,c,"Atomic install parent changed during staging."),await UR(a,u),await bt(l),e.expectedPreviousReceipt&&await nl(a,e.expectedPreviousReceipt),u.exists&&(m=jt(l,`.${wi(a)}.skills-layer-backup-${RR()}`),await Pr(a,m),g=!0,await bt(l),await yi(e.checkpoint,"after_target_backed_up"),e.expectedPreviousReceipt&&await nl(m,e.expectedPreviousReceipt)),await Pr(d,a),h=!0,await bt(l),await yi(e.checkpoint,"after_stage_activated");let w=JG({targetDir:s,generation:r.generation,archiveSha256:r.archive.sha256,manifestSha256:r.manifest.sha256,files:r.manifest.files,...o?{manifestV2:o}:{}}),b=await MG(m,l);return m=b.backupStillExists?m:null,{status:u.exists?"replaced":"created",receipt:w,staticEvaluation:y,cleanupPending:b.backupStillExists,...b.backupStillExists&&m?{cleanupPath:m}:{}}}catch(y){throw await NG({targetDir:a,stageDir:d,parentDir:l,backupDir:m,backupMoved:g,stageActivated:h,originalError:y}),y}}function Td(e){if(e.some(t=>typeof t.path=="string"&&t.path!==t.path.normalize("NFC")))throw new Error("Portable install paths must use NFC Unicode normalization.");try{let t=Jn({files:e,runDlp:!1,limits:{maxTotalBytes:qe.maxTotalFileBytes}});if(t.excluded.length>0||t.files.length!==e.length)throw new Error("install-control or excluded paths are not deliverable files");for(let n=0;n<t.files.length;n+=1){let r=t.files[n],i=e.find(o=>o.path===r.path);if(!i||i.content!==r.content)throw new Error("portable normalization changed the approved file set")}}catch(t){throw new Error(`Portable install paths rejected: ${VR(t)}`,{cause:t})}}async function OR(e){if(!ER.test(e.reasonCode))throw new Error("Quarantine reason code is invalid.");yy(e.receipt);let t=await Go(e.receipt.targetDir),n=Nn(t);await rl(t);let r=await tn(n,"Atomic quarantine parent"),i=await nl(t,e.receipt),o=await jR(e.discoveryRoots),s=await Go(e.quarantineRoot);py({targetDir:t,quarantineRoot:s,discoveryRoots:o});let a=await BR({callback:e.authorizeQuarantine,context:{receipt:e.receipt,targetDir:t,quarantineRoot:s,discoveryRoots:o,reasonCode:e.reasonCode},receipt:e.receipt,allowedPurposes:["quarantine_blocked","quarantine_revoked"]});await hy(s,{recursive:!0,mode:448}),await rl(s),await xG(s,448);let l=await my(s,"External quarantine root");py({targetDir:t,quarantineRoot:l,discoveryRoots:o});let c=await tn(l,"External quarantine root");if(c.dev!==r.dev)throw new Error("External quarantine root must be on the same filesystem for an atomic fail-closed move.");let u=jt(l,`${wi(t)}.skills-layer-quarantine-${RR()}`);await xr(n,r,"Atomic quarantine parent changed."),await xr(l,c,"External quarantine root changed."),await xr(t,i,"Installed generation changed before quarantine."),await Pr(t,u);try{await bt(n),await bt(l),await Vo(u,e.receipt.files,i),await yi(e.checkpoint,"after_quarantine_rename")}catch(d){throw await Pr(u,t),await bt(n),await bt(l),d}return Object.freeze({status:"quarantined",reasonCode:e.reasonCode,targetDir:e.receipt.targetDir,quarantineRoot:l,quarantineDir:u,discoveryRoots:Object.freeze([...o]),quarantineAuthorization:a,receipt:e.receipt})}async function FR(e){jG(e.quarantine);let t=await Go(e.quarantine.receipt.targetDir),n=await jR(e.quarantine.discoveryRoots),r=await my(e.quarantine.quarantineRoot,"External quarantine root"),i=await my(e.quarantine.quarantineDir,"Quarantine tree"),o=Nn(t);if(py({targetDir:t,quarantineRoot:r,discoveryRoots:n}),Nn(i)!==r||!wi(i).startsWith(`${wi(t)}.skills-layer-quarantine-`))throw new Error("Quarantine generation is outside its validated external quarantine root.");let s=await tn(o,"Atomic restore parent"),a=await tn(r,"External quarantine root"),l=await nl(i,e.quarantine.receipt),c=await wy(t);if(c.exists)throw new Error("Cannot restore quarantine because the install target already exists.");let u={receipt:e.quarantine.receipt,targetDir:t,quarantineRoot:r,quarantineDir:i,discoveryRoots:n,reasonCode:e.quarantine.reasonCode,quarantineAuthorization:e.quarantine.quarantineAuthorization},d=await BR({callback:e.authorizeRestore,context:u,receipt:e.quarantine.receipt,allowedPurposes:["restore_fresh_approval"],forbiddenAuthorizationId:e.quarantine.quarantineAuthorization.authorizationId});await xr(o,s,"Atomic restore parent changed."),await xr(r,a,"External quarantine root changed."),await xr(i,l,"Quarantine generation changed before restore."),await UR(t,c),await Pr(i,t);try{await bt(o),await bt(r),await Vo(t,e.quarantine.receipt.files,l),await yi(e.checkpoint,"after_restore_rename"),await UG(e.finalizeRestore,{...u,restoreAuthorization:d})}catch(p){throw await Pr(t,i),await bt(o),await bt(r),p}return e.quarantine.receipt}function DG(e){let t=e??PG;if(!Number.isInteger(t)||t<=0||t>AR)throw new Error(`Static pre-activation timeout must be an integer from 1 to ${AR} ms.`);return t}function TG(e,t){let n=pc({archiveBytes:e,envelope:t});if(n.format==="v2"){let r=fc(n.envelope);return{envelope:{generation:n.envelope.generation,archive:n.envelope.archive,manifest:{sha256:r.manifestSha256,files:r.files}},files:n.files(),manifestV2:r.manifestV2}}return{envelope:n.envelope,files:n.files()}}function $G(e,t){let n=e?.generation;if(e?.status!=="approved"||!n||n.skillSlug!==t.generation.skillSlug||n.semanticVersion!==t.generation.semanticVersion||n.generationId!==t.generation.generationId||!Ir(e.archiveSha256,t.archive.sha256)||!Ir(e.manifestSha256,t.manifest.sha256))throw new Error("Install denied: approved artifact identity does not match the verified deliverable.")}async function LG(e,t){let n=jt(e,...t.path.split("/"));await OG(e,Nn(n));let r=await Ld(n,Ar.O_WRONLY|Ar.O_CREAT|Ar.O_EXCL|Bd,384);try{await r.writeFile(re(t)),t.executable&&await r.chmod(448),await r.sync()}finally{await r.close()}}async function OG(e,t){let n=t.slice(e.length).split(el).filter(Boolean),r=e;for(let i of n){r=jt(r,i);try{await hy(r,{mode:448})}catch(s){if(!ZG(s))throw s}let o=await Rr(r);if(o.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link in the staged tree: ${r}`);if(!o.isDirectory())throw new Error(`Atomic install staged path is not a directory: ${r}`)}}async function Vo(e,t,n){let r=await tn(e,"Install generation root");if(n&&!$d(r,n))throw new Error("Install generation root changed during staging.");let i=new Map(t.map(c=>[c.path,c])),o=new Set;for(let c of t){let u=uy.dirname(c.path);for(;u!==".";)o.add(u),u=uy.dirname(u)}let s=new Set,a=new Set,l=async(c,u)=>{let d=await tn(c,"Install generation directory"),p=(await RG(c,{withFileTypes:!0})).sort((g,h)=>YG(g.name,h.name));for(let g of p){let h=jt(c,g.name),y=u?uy.join(u,g.name):g.name,w=await Rr(h);if(w.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link in the generation tree: ${y}`);if(w.isDirectory()){if(!o.has(y))throw new Error(`Installed generation manifest has an unexpected directory: ${y}`);a.add(y),await l(h,y);continue}if(!w.isFile())throw new Error(`Atomic install refuses a non-regular generation entry: ${y}`);let b=i.get(y);if(!b)throw new Error(`Installed generation manifest has an unexpected file: ${y}`);if(process.platform!=="win32"&&(w.mode&73)!==0!=(b.executable===!0))throw new Error(`Installed generation executable mode mismatch for ${y}.`);let _=await FG(h,b.sizeBytes);if(_.sizeBytes!==b.sizeBytes||!Ir(_.sha256,b.sha256))throw new Error(`Installed generation manifest mismatch for ${y}.`);s.add(y)}let m=await tn(c,"Install generation directory");if(!$d(d,m))throw new Error(`Install generation directory changed while verified: ${u||"."}`)};if(await l(e,""),s.size!==t.length||a.size!==o.size)throw new Error("Installed generation manifest is incomplete.");return await xr(e,r,"Install generation root changed while verified."),r}async function FG(e,t){let n=await Ld(e,Ar.O_RDONLY|Bd);try{let r=await n.stat();if(!r.isFile())throw new Error(`Expected a regular installed generation file: ${e}`);if(r.size>t)throw new Error(`Installed generation file exceeds its approved size: ${e}`);let i=new Uint8Array(await n.readFile());return{sizeBytes:i.byteLength,sha256:qR(i)}}finally{await n.close()}}async function BG(e){let t=new AbortController,n,r=new Promise((i,o)=>{n=setTimeout(()=>{t.abort(),o(new Error(`Static pre-activation Eval timed out after ${e.timeoutMs} ms.`))},e.timeoutMs)});try{let i=await Promise.race([Promise.resolve().then(()=>e.callback({stageDir:e.stageDir,files:e.files,signal:t.signal})),r]);if(!i||i.status!=="passed"&&i.status!=="failed"||i.status==="passed"&&(typeof i.evidenceId!="string"||i.evidenceId.length===0)||i.status==="failed"&&(typeof i.reasonCode!="string"||i.reasonCode.length===0))throw new Error("Static pre-activation Eval returned an invalid result.");return i}finally{clearTimeout(n)}}async function xR(e,t){for(let r of t){let i=await Ld(jt(e,...r.path.split("/")),Ar.O_RDONLY|Bd);try{await i.sync()}finally{await i.close()}}let n=new Set([e]);for(let r of t){let i=Nn(jt(e,...r.path.split("/")));for(;i.startsWith(e)&&i!==Nn(e)&&(n.add(i),i!==e);)i=Nn(i)}for(let r of[...n].sort((i,o)=>o.length-i.length))await bt(r)}async function NG(e){try{e.stageActivated&&await Pr(e.targetDir,e.stageDir),e.backupMoved&&e.backupDir&&await Pr(e.backupDir,e.targetDir),await zG(e.stageDir),await bt(e.parentDir)}catch(t){let n=e.backupDir?` from ${e.backupDir}`:"";throw new Error(`Atomic install rollback requires manual recovery${n}.`,{cause:new AggregateError([e.originalError,t])})}}async function MG(e,t){if(!e)return{backupStillExists:!1};try{return await PR(e,{recursive:!0,force:!1}),await bt(t),{backupStillExists:!1}}catch(n){return vi(n)?{backupStillExists:!1}:{backupStillExists:!0}}}async function nl(e,t){yy(t);try{return await Vo(e,t.files)}catch(n){throw new Error(`Installed generation manifest verification failed: ${VR(n)}`,{cause:n})}}async function Mn(e){try{return await nl(e.targetDir,e),Object.freeze({status:"verified",generation:e.generation,manifestSha256:e.manifestSha256})}catch{return Object.freeze({status:"changed",reasonCode:"installed_tree_manifest_mismatch",generation:e.generation,manifestSha256:e.manifestSha256})}}function yy(e){if(!e||typeof e.targetDir!="string"||!tl.test(e.archiveSha256)||!tl.test(e.manifestSha256)||!Array.isArray(e.files)||e.files.length===0)throw new Error("Installed generation receipt manifest is invalid.");let t=KG(e.files);if(e.manifestV2){let n=e.manifestV2,r=new Set(n.files.filter(s=>s.byteClass==="approved_binary_asset").map(s=>s.path));Td(e.files.filter(s=>!r.has(s.path)).map(s=>({path:s.path,content:""})));for(let s of r){let a=ks(s);if(!a.ok||a.path!==s)throw new Error("Portable install paths rejected: binary asset path is not portable.")}let i=n.files.map(s=>`${s.path}\0${s.runtimeSizeBytes}\0${s.runtimeSha256}`),o=e.files.map(s=>`${s.path}\0${s.sizeBytes}\0${s.sha256}`);if(!Ir(rp(n),n.manifestDigest)||!Ir(n.manifestDigest,e.manifestSha256)||i.join(`
|
|
937
|
+
`)!==o.join(`
|
|
938
|
+
`))throw new Error("Installed generation receipt manifest digest is invalid.");return}if(Td(e.files.map(n=>({path:n.path,content:""}))),!Ir(qR(t),e.manifestSha256))throw new Error("Installed generation receipt manifest digest is invalid.")}function jG(e){if(!e||e.status!=="quarantined"||!ER.test(e.reasonCode)||typeof e.targetDir!="string"||typeof e.quarantineRoot!="string"||typeof e.quarantineDir!="string"||!Array.isArray(e.discoveryRoots)||e.discoveryRoots.length===0||!e.receipt||!NR(e.quarantineAuthorization)||e.quarantineAuthorization.purpose!=="quarantine_blocked"&&e.quarantineAuthorization.purpose!=="quarantine_revoked"||!MR(e.quarantineAuthorization,e.receipt)||e.targetDir!==e.receipt?.targetDir)throw new Error("Quarantine record is invalid.");yy(e.receipt)}async function BR(e){if(typeof e.callback!="function")throw new Error("Exact-generation authorization callback is required.");let t=await e.callback(e.context);if(t?.status==="denied")throw new Error(`Exact-generation authorization denied: ${t.reasonCode||"unspecified"}.`);if(!NR(t)||!e.allowedPurposes.includes(t.purpose)||!MR(t,e.receipt)||t.authorizationId===e.forbiddenAuthorizationId)throw new Error("Exact-generation authorization is invalid, stale, reused, or bound to different bytes.");return qG(t)}async function UG(e,t){if(typeof e!="function")throw new Error("Restore release callback is required.");let n=await e(t);if(n?.status!=="released"||!DR.test(n.releaseId)){let r=n?.status==="denied"?n.reasonCode:"invalid_release_decision";throw new Error(`Restore release denied: ${r}.`)}}function NR(e){return typeof e=="object"&&e!==null&&"status"in e&&e.status==="authorized"&&"authorizationId"in e&&typeof e.authorizationId=="string"&&DR.test(e.authorizationId)&&"purpose"in e&&(e.purpose==="quarantine_blocked"||e.purpose==="quarantine_revoked"||e.purpose==="restore_fresh_approval"||e.purpose==="purge_quarantined")&&"generation"in e&&typeof e.generation=="object"&&e.generation!==null&&"archiveSha256"in e&&typeof e.archiveSha256=="string"&&"manifestSha256"in e&&typeof e.manifestSha256=="string"}function MR(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&Ir(e.archiveSha256,t.archiveSha256)&&Ir(e.manifestSha256,t.manifestSha256)}function qG(e){return Object.freeze({...e,generation:Object.freeze({...e.generation})})}async function jR(e){if(!Array.isArray(e)||e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error("External quarantine requires the complete non-empty discovery root set.");let t=[],n=new Set;for(let r of e){let i=await Go(r),o=Dd(i);n.has(o)||(t.push(i),n.add(o))}return Object.freeze(t)}function py(e){let t=Dd(e.targetDir),n=Dd(e.quarantineRoot),r=e.discoveryRoots.map(Dd);if(!r.some(i=>t!==i&&dy(t,i)))throw new Error("Install target is not inside the authoritative discovery root set.");for(let i of r)if(dy(n,i)||dy(i,n))throw new Error("Quarantine root must be physically outside and non-overlapping with every discovery root.")}function Dd(e){let t=Fd(e).normalize("NFC"),n=Od(t).root,r=t===n?t:t.replace(/[\\/]+$/u,"");return process.platform==="linux"?r:r.toLocaleLowerCase("en-US")}function dy(e,t){return e===t||e.startsWith(t.endsWith(el)?t:`${t}${el}`)}async function wy(e){try{let t=await Rr(e,{bigint:!0});if(t.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link target: ${e}`);if(!t.isDirectory())throw new Error(`Atomic install target must be a directory: ${e}`);return{exists:!0,identity:{dev:t.dev,ino:t.ino}}}catch(t){if(vi(t))return{exists:!1,identity:null};throw t}}async function UR(e,t){let n=await wy(e);if(n.exists!==t.exists||t.identity!==null&&(n.identity===null||!$d(t.identity,n.identity)))throw new Error("Atomic install target changed while the approved generation was staged.")}async function tn(e,t){let n=await Rr(e,{bigint:!0});if(n.isSymbolicLink())throw new Error(`${t} refuses a symbolic link: ${e}`);if(!n.isDirectory())throw new Error(`${t} must be a directory: ${e}`);return{dev:n.dev,ino:n.ino}}async function xr(e,t,n){let r=await tn(e,"Atomic install identity check");if(!$d(r,t))throw new Error(n)}function $d(e,t){return e.dev===t.dev&&e.ino===t.ino}async function Go(e){let t=await VG(Fd(e));await rl(t);try{if((await Rr(t)).isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link: ${t}`);return await fy(t)}catch(i){if(!vi(i))throw i}let n=[],r=t;for(;;)try{await Rr(r);break}catch(i){if(!vi(i))throw i;let o=Nn(r);if(o===r)throw new Error(`Unable to resolve atomic install target parent: ${t}`);n.unshift(wi(r)),r=o}return jt(await fy(r),...n)}async function my(e,t){let n=await Go(e);return await tn(n,t),n}async function VG(e){let t=Od(e).root,n=e.slice(t.length).split(el).filter(Boolean);if(n.length===0)return e;let r=jt(t,n[0]),i;try{i=await Rr(r)}catch(o){if(vi(o))return e;throw o}return i.isSymbolicLink()?jt(await fy(r),...n.slice(1)):e}async function rl(e){let t=Fd(e),n=Od(t).root,r=t.slice(n.length).split(el).filter(Boolean),i=n;for(let o of r){i=jt(i,o);try{if((await Rr(i)).isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link: ${i}`)}catch(s){if(vi(s))return;throw s}}}async function bt(e){let t;try{t=await Ld(e,Ar.O_RDONLY|Bd),await t.sync()}catch(n){if(!GG(n))throw n}finally{await t?.close()}}function GG(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EINVAL"||t==="ENOTSUP"||t==="EOPNOTSUPP"||process.platform==="win32"&&(t==="EPERM"||t==="EISDIR"||t==="EBADF")}async function zG(e){try{await PR(e,{recursive:!0,force:!1})}catch(t){if(!vi(t))throw t}}async function yi(e,t){await e?.(t)}function KG(e){let t=[EG,IR(e.length)];for(let n of e){if(typeof n.path!="string"||!Number.isSafeInteger(n.sizeBytes)||n.sizeBytes<0||!tl.test(n.sha256)||n.executable!==void 0&&typeof n.executable!="boolean")throw new Error("Installed generation receipt manifest entry is invalid.");let r=new TextEncoder().encode(n.path);t.push(IR(r.byteLength),r,HG(n.sizeBytes),gy(n.sha256))}return e.some(n=>n.executable)&&t.push(new TextEncoder().encode("\0executable-v1\0"),Uint8Array.from(e.map(n=>n.executable?1:0))),WG(t)}function IR(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function HG(e){let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function WG(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 JG(e){let t=Object.freeze({...e.generation}),n=Object.freeze(e.files.map(r=>Object.freeze({...r})));return Object.freeze({...e,generation:t,files:n})}function qR(e){return`sha256:${CG("sha256").update(e).digest("hex")}`}function Ir(e,t){return typeof e=="string"&&tl.test(e)&&tl.test(t)&&AG(gy(e),gy(t))}function gy(e){return Buffer.from(e.slice(7),"hex")}function YG(e,t){return Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}function VR(e){return e instanceof Error?e.message:String(e)}function vi(e){return GR(e)==="ENOENT"}function ZG(e){return GR(e)==="EEXIST"}function GR(e){return typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function zR(e){if(e.pathState==="absent"){if(e.receiptState==="verified")throw new Error("An absent target cannot have a verified receipt observation.");return il("externally_removed","exact_target_absent")}if(e.pathState==="unreadable"){if(e.receiptState==="verified")throw new Error("An unreadable target cannot have a verified receipt observation.");return il("unreadable","exact_target_unreadable")}if(e.pathState==="replaced_type"){if(e.receiptState==="verified")throw new Error("A replaced target cannot have a verified receipt observation.");return il("drifted","exact_target_replaced")}if(e.receiptState==="unchecked")throw new Error("A present exact target receipt must be checked before reconciliation.");return e.receiptState==="changed"?il("drifted","exact_tree_changed"):e.hostState==="detached"?il("host_detached","host_registration_detached"):Object.freeze({state:"active",reasonCode:"exact_target_verified",runnable:!0,recoverable:!0})}function il(e,t){return Object.freeze({state:e,reasonCode:t,runnable:!1,recoverable:!0})}import{createHash as XG}from"node:crypto";var QG="skills-layer-signatures-v1";var ez="security/signature-packs",xne=`${ez}/source/current.json`;var KR=nz(tz({version:QG,generatedAt:"2026-06-14T00:00:00.000Z",issuer:"skills-layer-local",signatures:[{id:"SL-SIG-COMMODITY-WEBHOOK-EXFIL",ruleId:"SL-SIG-002",title:"Commodity webhook exfiltration",severity:"critical",confidence:.92,tags:["exfiltration","webhook","secret-harvest"],regexes:[`https://(?:discord(?:app)?\\.com/api/webhooks|hooks\\.slack\\.com/services|webhook\\.site)/[^\\s"']+`],explanation:"Content references a commodity webhook endpoint often used for data exfiltration."},{id:"SL-SIG-REMOTE-BOOTSTRAP",ruleId:"SL-SIG-001",title:"Remote bootstrap execution",severity:"high",confidence:.88,tags:["remote-bootstrap","shell"],regexes:["(?:curl|wget)\\s+[^\\n|]+\\|\\s*(?:sudo\\s+(?:-\\S+\\s+)*)?(?:env\\s+(?:\\S+=\\S+\\s+)*)?(?:bash|sh|zsh|python|node)"],explanation:"Content downloads remote code and pipes it directly into an interpreter."},{id:"SL-SIG-DESTRUCTIVE-AUTONOMY",ruleId:"SL-SIG-004",title:"Destructive autonomous action",severity:"high",confidence:.84,tags:["destructive","autonomous"],regexes:["\\b(?:rm\\s+-rf|Remove-Item\\s+-Recurse|format\\s+[A-Z]:|git\\s+push\\s+--force)\\b"],explanation:"Content includes destructive commands that can cause irreversible changes."}]}));function tz(e){return{boundary:"skills_layer_signature_pack",version:e.version,generatedAt:e.generatedAt,issuer:e.issuer??"skills-layer-cloud",...e.managedAuthorityDigest?{managedAuthorityDigest:e.managedAuthorityDigest}:{},signatures:e.signatures.map(oz).sort((t,n)=>t.id.localeCompare(n.id))}}function nz(e){let t=`sha256:${ol(zo(e))}`;return{...e,digest:t,signature:ol(zo({boundary:e.boundary,digest:t,issuer:e.issuer,version:e.version}))}}function rz(e){let{digest:t,signature:n,...r}=e;return t===`sha256:${ol(zo(r))}`&&n===ol(zo({boundary:r.boundary,digest:t,issuer:r.issuer,version:r.version}))}function HR(e,t){if(!rz(t))return[];let n=[],r=new Set;for(let i of e){let o=i.content??"";for(let s of t.signatures){if(s.filePattern&&!new RegExp(s.filePattern,"iu").test(i.path))continue;let a=iz(o,s);if(!a)continue;let l=`${s.id}:${i.path}:${a.lineNumber}:${a.tag}`;r.has(l)||(r.add(l),n.push({signatureId:s.id,ruleId:s.ruleId,title:s.title,severity:s.severity,confidence:s.confidence,filePath:i.path,lineNumber:a.lineNumber,matchedTag:a.tag,evidenceHash:`sha256:${ol(`${i.path}
|
|
939
|
+
${a.line}`)}`,explanation:s.explanation}))}}return n}function iz(e,t){let n=e.split(/\r?\n/u);for(let r=0;r<n.length;r+=1){let i=n[r];for(let o of t.strings??[])if(i.toLowerCase().includes(o.toLowerCase()))return{line:i,lineNumber:r+1,tag:o};for(let o of t.regexes??[])if(new RegExp(o,"iu").test(i))return{line:i,lineNumber:r+1,tag:o}}return null}function oz(e){return{id:e.id.trim(),ruleId:e.ruleId.trim(),title:e.title.trim(),severity:e.severity,confidence:Math.max(0,Math.min(1,e.confidence)),tags:[...new Set(e.tags.map(t=>t.trim()).filter(Boolean))].sort(),...e.filePattern?{filePattern:e.filePattern}:{},...e.strings?{strings:e.strings.map(t=>t.trim()).filter(Boolean)}:{},...e.regexes?{regexes:e.regexes.map(t=>t.trim()).filter(Boolean)}:{},explanation:e.explanation.trim()}}function zo(e){return Array.isArray(e)?`[${e.map(zo).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${zo(n)}`).join(",")}}`:JSON.stringify(e)}function ol(e){return XG("sha256").update(e).digest("hex")}import{spawn as Az}from"node:child_process";import{createHash as _y}from"node:crypto";import{constants as tP}from"node:fs";import{chmod as ky,copyFile as nP,lstat as Sy,mkdir as by,mkdtemp as xz,open as Cy,realpath as al,rm as Iz,stat as rP}from"node:fs/promises";import{constants as Rz,tmpdir as Pz}from"node:os";import{extname as iP,isAbsolute as Ez,join as Ho,resolve as ZR}from"node:path";import{createHash as sz,randomBytes as Pne}from"node:crypto";import{posix as az,win32 as lz}from"node:path";var cz=new Set(["shell_execution","filesystem_read","filesystem_write","network_access","browser_access","device_control","api_access","generated_code_execution"]),uz=new Set(["darwin","linux","win32"]),dz=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/u,fz=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,pz=/^[0-9A-Za-z][0-9A-Za-z.+-]{0,127}$/u,vy=/^sha256:[a-f0-9]{64}$/u,mz=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u,gz=/^[^\u0000-\u001f\u007f]{1,4096}$/u;var hz=256,WR=64,yz=64,wz=64,vz=256*1024*1024;function bz(e){_z(e);let t=e.platform==="win32"?lz:az,n={planVersion:1,actionFamily:e.actionFamily,platform:e.platform,executableRealPath:Nd(e.executableRealPath,t),executableSha256:e.executableSha256,argv:Object.freeze([...e.argv]),cwdRealPath:Nd(e.cwdRealPath,t),fileTargets:Object.freeze(e.fileTargets.map(r=>Nd(r,t))),networkTargets:Object.freeze(e.networkTargets.map(Sz)),environmentKeys:Object.freeze([...new Set(e.environmentKeys)].sort()),immutableInputs:Object.freeze([...e.immutableInputs??[]].map(r=>Object.freeze({path:Nd(r.path,t),sha256:r.sha256,size:r.size,argumentIndexes:Object.freeze([...r.argumentIndexes].sort((i,o)=>i-o))})).sort((r,i)=>r.path.localeCompare(i.path))),skill:Object.freeze({slug:e.skillSlug,version:e.version,generationId:e.generationId}),subject:Object.freeze({actorId:e.actorId,...e.deviceId===void 0?{}:{deviceId:e.deviceId},tenantId:e.tenantId,...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId}}),host:Object.freeze({agentId:e.agentId,hostVersion:e.hostVersion,sessionId:e.sessionId}),policy:Object.freeze({revision:e.policyRevision,digest:e.policyDigest})};return Object.freeze(n)}function YR(e){return kz(e),Cz(sl(e))}function _z(e){(!uz.has(e.platform)||!cz.has(e.actionFamily)||!vy.test(e.executableSha256))&&Ut(),(!Array.isArray(e.argv)||e.argv.length>hz||e.argv.some(t=>!Md(t)))&&Ut(),(!Array.isArray(e.fileTargets)||e.fileTargets.length>WR||!Array.isArray(e.networkTargets)||e.networkTargets.length>WR||!Array.isArray(e.environmentKeys)||e.environmentKeys.length>yz||e.environmentKeys.some(t=>!mz.test(t)))&&Ut(),e.immutableInputs!==void 0&&(!Array.isArray(e.immutableInputs)||e.immutableInputs.length>wz||e.immutableInputs.some(t=>!t||typeof t!="object"||!vy.test(t.sha256)||!Number.isSafeInteger(t.size)||t.size<=0||t.size>vz||!Array.isArray(t.argumentIndexes)||t.argumentIndexes.length===0||t.argumentIndexes.some(n=>!Number.isSafeInteger(n)||n<0||n>=e.argv.length)))&&Ut(),(!fz.test(e.skillSlug)||!pz.test(e.version)||!Ko(e.generationId)||!Ko(e.actorId)||!JR(e.deviceId)||!Ko(e.tenantId)||!JR(e.workspaceId)||!Ko(e.agentId)||!Md(e.hostVersion)||!Ko(e.sessionId)||!Number.isSafeInteger(e.policyRevision)||e.policyRevision<=0||!vy.test(e.policyDigest))&&Ut()}function kz(e){(typeof e!="object"||e===null||e.planVersion!==1)&&Ut();let t=bz({platform:e.platform,actionFamily:e.actionFamily,executableRealPath:e.executableRealPath,executableSha256:e.executableSha256,argv:[...e.argv],cwdRealPath:e.cwdRealPath,fileTargets:[...e.fileTargets],networkTargets:[...e.networkTargets],environmentKeys:[...e.environmentKeys],immutableInputs:e.immutableInputs.map(n=>({...n,argumentIndexes:[...n.argumentIndexes]})),skillSlug:e.skill.slug,version:e.skill.version,generationId:e.skill.generationId,actorId:e.subject.actorId,...e.subject.deviceId===void 0?{}:{deviceId:e.subject.deviceId},tenantId:e.subject.tenantId,...e.subject.workspaceId===void 0?{}:{workspaceId:e.subject.workspaceId},agentId:e.host.agentId,hostVersion:e.host.hostVersion,sessionId:e.host.sessionId,policyRevision:e.policy.revision,policyDigest:e.policy.digest});sl(t)!==sl(e)&&Ut()}function Nd(e,t){(!Md(e)||!t.isAbsolute(e))&&Ut();let n=t.normalize(e);return n!==e&&Ut(),n}function Sz(e){Md(e)||Ut();let t;try{t=new URL(e)}catch{Ut()}return(t.protocol!=="https:"||t.username||t.password||t.hash||t.port&&t.port!=="443")&&Ut(),t.toString()}function Ut(){throw new Error("Guardian execution plan input is invalid or unresolved.")}function Md(e){return typeof e=="string"&&gz.test(e)}function Ko(e){return typeof e=="string"&&dz.test(e)}function JR(e){return e===void 0||Ko(e)}function sl(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(sl).join(",")}]`:`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n<r?-1:1).map(([n,r])=>`${JSON.stringify(n)}:${sl(r)}`).join(",")}}`}function Cz(e){return`sha256:${sz("sha256").update(e,"utf8").digest("hex")}`}function Dz(e){return e==="darwin"?"verified_real_path":"snapshot"}var Tz=3e4,$z=50,Lz=3e5,Oz=64*1024,Fz=256,Bz=1024*1024,Nz=256*1024*1024,oP=64*1024,Mz=250,jz=1e3,Uz="/usr/local/bin:/usr/bin:/bin",sP=new Set(["LANG","LC_ALL","LC_CTYPE","TZ","TERM","COLORTERM","NO_COLOR"]),qz=new Set(["HOME","TMPDIR","TMP","TEMP","USERPROFILE","PATH","SystemRoot"]),Vz=new Set(["darwin","linux","win32"]),Gz=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u,ce=class extends Error{constructor(n){super(`Guardian process refused execution: ${n}.`);this.reasonCode=n;this.name="GuardianProcessError"}reasonCode};async function aP(e,t={}){let n=eP(e.timeoutMs??Tz,$z,Lz,"timeout"),r=eP(e.outputLimitBytes??Oz,Fz,Bz,"output limit"),i=n5(process.platform);if(e.plan.platform!==i)throw new ce("platform_mismatch");let o=YR(e.plan),s=await Jz(e.plan);await Xz(e.plan.cwdRealPath);let a=Qz(e.approvedSecrets??{},e.plan.environmentKeys),l=e.temporaryParent??Pz(),c=await xz(Ho(l,"skills-layer-guardian-"));await ky(c,448);let u=Ho(c,"home"),d=Ho(c,"tmp");await Promise.all([by(u,{mode:448}),by(d,{mode:448})]);let p=t.executableLaunch??Dz(i);try{let m=p==="snapshot"?await Yz(s,e.plan.executableSha256,c):null,g=await zz(e.plan,c),h=e5({platform:i,plannedKeys:e.plan.environmentKeys,ambient:e.ambientEnvironment??process.env,approvedSecrets:a,isolatedHome:u,isolatedTemp:d});if(e.signal?.aborted)return cP("aborted",o);Wz(i,e.treeTerminator),await t.beforeLaunchCheck?.();let y=m??await Zz(s,e.plan.executableSha256);return await t5({executable:y,argv:g,cwd:e.plan.cwdRealPath,environment:h,approvedSecrets:Object.values(a),timeoutMs:n,outputLimitBytes:r,signal:e.signal,platform:i,planHash:o,treeTerminator:e.treeTerminator,spawnProcess:t.spawn??Az})}finally{await Iz(c,{recursive:!0,force:!0})}}async function zz(e,t){let n=[...e.argv];if(e.immutableInputs.length===0)return n;let r=Ho(t,"inputs");await by(r,{mode:448});for(let[i,o]of e.immutableInputs.entries()){let s=await al(o.path).catch(()=>"");if(s!==o.path)throw new ce("immutable_input_changed");let a=await Sy(s);if(!a.isFile()||a.size!==o.size)throw new ce("immutable_input_changed");let l=Ho(r,`${i}${iP(o.path)}`);await nP(s,l,tP.COPYFILE_EXCL),await ky(l,256);let c=await Kz(l),u=`sha256:${_y("sha256").update(c).digest("hex")}`;if(c.byteLength!==o.size||u!==o.sha256)throw new ce("immutable_input_changed");for(let d of o.argumentIndexes)n[d]=await Hz(n[d],o.path,e.cwdRealPath,l)}return n}async function Kz(e){let t=await Cy(e,"r");try{let n=await t.readFile();return await t.sync(),n}finally{await t.close()}}async function Hz(e,t,n,r){let i=e.indexOf("="),o=i>0?e.slice(0,i+1):"",s=i>0?e.slice(i+1):e,a=Ez(s)?ZR(s):ZR(n,s);if(await al(a).catch(()=>"")!==t)throw new ce("immutable_input_argument_mismatch");return`${o}${r}`}function XR(e,t=[]){let n=e;for(let r of[...new Set(t)].sort((i,o)=>o.length-i.length))r.length>0&&(n=n.split(r).join("[SECRET_REDACTED]"));return n.replace(/-----BEGIN [^-\r\n]{1,64} PRIVATE KEY-----[\s\S]*?-----END [^-\r\n]{1,64} PRIVATE KEY-----/gu,"[PRIVATE_KEY_REDACTED]").replace(/\b(?:mktplace_|slg_exec_|github_pat_|gh[opusr]_|sk-)[A-Za-z0-9_-]{8,}\b/gu,"[TOKEN_REDACTED]").replace(/\bAuthorization\s*:\s*(?:Bearer|Basic)\s+[^\s,;]+/giu,"Authorization: [REDACTED]").replace(/\b(password|passwd|secret|token|api[_-]?key)\s*[=:]\s*[^\s,;]+/giu,"$1=[REDACTED]").replace(/[^\t\n\r\u0020-\u007e\u00a0-\uffff]/gu,"\uFFFD")}function Wz(e,t){if(e==="win32"&&!t)throw new ce("windows_process_tree_isolation_unavailable")}async function Jz(e){let t=await al(e.executableRealPath).catch(()=>"");if(t!==e.executableRealPath)throw new ce("executable_path_changed");let[n,r]=await Promise.all([Sy(t),rP(t)]);if(!n.isFile())throw new ce("executable_not_regular_file");if(r.size<=0||r.size>Nz)throw new ce("executable_size_invalid");if(e.platform!=="win32"&&(r.mode&73)===0)throw new ce("executable_not_executable");return t}async function Yz(e,t,n){let r=Ho(n,`executable${iP(e)}`);await nP(e,r,tP.COPYFILE_EXCL),await ky(r,320);let i=await Cy(r,"r");try{let o=await i.readFile();if(await i.sync(),`sha256:${_y("sha256").update(o).digest("hex")}`!==t)throw new ce("executable_digest_changed")}finally{await i.close()}return r}async function Zz(e,t){let n=await al(e).catch(()=>"");if(n!==e||!(await Sy(n)).isFile())throw new ce("executable_path_changed");let r=await Cy(n,"r");try{if(`sha256:${_y("sha256").update(await r.readFile()).digest("hex")}`!==t)throw new ce("executable_digest_changed")}finally{await r.close()}return n}async function Xz(e){let t=await al(e).catch(()=>"");if(t!==e)throw new ce("working_directory_changed");if(!(await rP(t)).isDirectory())throw new ce("working_directory_not_directory")}function Qz(e,t){let n=new Set(t),r={};for(let[i,o]of Object.entries(e)){if(!Gz.test(i)||!n.has(i)||qz.has(i)||sP.has(i))throw new ce("secret_not_exactly_approved");if(typeof o!="string"||o.length===0||o.includes("\0")||Buffer.byteLength(o,"utf8")>oP)throw new ce("secret_value_invalid");r[i]=o}return r}function e5(e){let t=e.platform==="win32"?{PATH:"C:\\Windows\\System32",SystemRoot:"C:\\Windows",USERPROFILE:e.isolatedHome,TEMP:e.isolatedTemp,TMP:e.isolatedTemp}:{PATH:Uz,HOME:e.isolatedHome,TMPDIR:e.isolatedTemp},n=new Set(Object.keys(t));for(let r of e.plannedKeys){if(n.has(r))continue;if(Object.hasOwn(e.approvedSecrets,r)){t[r]=e.approvedSecrets[r],n.add(r);continue}if(!sP.has(r))throw new ce("unapproved_environment_key");let i=e.ambient[r];if(typeof i!="string"||i.includes("\0")||Buffer.byteLength(i,"utf8")>oP)throw new ce("ambient_environment_value_invalid");t[r]=i,n.add(r)}if(n.size!==e.plannedKeys.length)throw new ce("environment_plan_mismatch");return t}async function t5(e){let t,n=Date.now();try{t=e.spawnProcess(e.executable,e.argv,{cwd:e.cwd,env:e.environment,shell:!1,windowsHide:!0,detached:e.platform!=="win32",stdio:["ignore","pipe","pipe"]})}catch{return cP("spawn_failed",e.planHash)}return await new Promise(r=>{let i=[],o=[],s=0,a="exited",l=!1,c=!1,u,d=y=>{a==="exited"&&(a=y,QR(t,!1,e.treeTerminator),u=setTimeout(()=>QR(t,!0,e.treeTerminator),Mz),u.unref?.())},p=(y,w)=>{if(l)return;let b=w,_=e.outputLimitBytes-s;if(b.byteLength<=_){y.push(b),s+=b.byteLength;return}y.push(b.subarray(0,Math.max(_,0))),s=e.outputLimitBytes,l=!0,d("output_limit")},m=(y,w)=>{if(c)return;c=!0,clearTimeout(h),u&&clearTimeout(u),e.signal?.removeEventListener("abort",g),a==="exited"&&w==="SIGKILL"&&Date.now()-n<jz&&(a="killed_at_launch");let b=l?`
|
|
940
|
+
[output truncated; process terminated]`:"";r({reason:a,exitCode:y,signal:w,stdout:XR(Buffer.concat(i).toString("utf8")+b,e.approvedSecrets),stderr:XR(Buffer.concat(o).toString("utf8"),e.approvedSecrets),outputTruncated:l,planHash:e.planHash})},g=()=>d("aborted"),h=setTimeout(()=>d("timed_out"),e.timeoutMs);h.unref?.(),e.signal?.addEventListener("abort",g,{once:!0}),t.stdout.on("data",y=>p(i,y)),t.stderr.on("data",y=>p(o,y)),t.once("error",()=>{a="spawn_failed",m(null,null)}),t.once("close",m)})}function QR(e,t,n){if(n){n.terminate(e,t);return}let r=t?"SIGKILL":"SIGTERM";try{if(typeof e.pid!="number"){e.kill(r);return}process.kill(-e.pid,r)}catch{e.kill(r)}}function lP(e){let t=e.signal?Rz.signals[e.signal]??0:0,n=e.exitCode??(e.signal?128+t:1);if(e.reason==="exited"&&n===0)return{exitCode:n,status:"executed",reasonCode:null,headline:"OK Guardian guarded execution complete.",nextStep:null};let r=(i,o,s)=>({exitCode:n,status:"command_failed",reasonCode:i,headline:o,nextStep:s});switch(e.reason){case"killed_at_launch":return r("command_killed_at_launch",`Guardian approved the command, but the operating system stopped it as it started (${e.signal}).`,"The OS refused to start this program, usually a code signing or launch-constraint rule. Run the same command outside Guardian to confirm; on macOS, check that the program is the original signed binary.");case"timed_out":return r("command_timed_out","Guardian stopped the command: it ran past its time limit.",null);case"output_limit":return r("command_output_limit","Guardian stopped the command: its output passed the capture limit.",null);case"aborted":return r("command_aborted","The command was cancelled before it finished.",null);case"spawn_failed":return r("command_spawn_failed","Guardian could not start the command.",null);default:return e.signal?r("command_signalled",`Guardian ran the command; it was stopped by ${e.signal}.`,null):r("command_failed",`Guardian ran the command; it exited with code ${n}.`,null)}}function n5(e){if(!Vz.has(e))throw new ce("unsupported_platform");return e}function eP(e,t,n,r){if(!Number.isSafeInteger(e)||e<t||e>n)throw new ce(`${r.replaceAll(" ","_")}_invalid`);return e}function cP(e,t){return{reason:e,exitCode:null,signal:null,stdout:"",stderr:"",outputTruncated:!1,planHash:t}}function uP(e=gc){async function t(n,r,i,o){let s="secret-tool unavailable or Secret Service operation failed";try{let a=await e("secret-tool",[n,...n==="store"?["--label=Skills Layer CLI"]:[],"service",r,"account",i],o);if((n==="lookup"||n==="clear")&&a.code===1){let l=null;try{l=await e("gdbus",["call","--session","--dest","org.freedesktop.secrets","--object-path","/org/freedesktop/secrets/aliases/default","--method","org.freedesktop.DBus.Properties.Get","org.freedesktop.Secret.Collection","Locked"]),s="Secret Service default collection unavailable or locked"}catch{s="gdbus unavailable; secret-tool fallback could not confirm absence"}if(l?.code===0){if(l.stdout.trim()!=="(<false>,)")throw new Error}else{let c=await e("secret-tool",["search","--unlock","service",r,"account",i]);if(c.code!==0||c.stdout.trim()!=="")throw new Error}return null}if(a.code!==0)throw new Error;return a.stdout||null}catch{throw new Error(`mcp_secure_storage_required: ${s}. Install libsecret secret-tool and gdbus (libglib2.0-bin), then start or unlock a Secret Service keyring in your desktop D-Bus session. No file fallback is available.`)}}return{kind:"linux_secret_service",set:async(n,r,i)=>{await t("store",n,r,i)},get:(n,r)=>t("lookup",n,r),delete:async(n,r)=>{await t("clear",n,r)}}}import{execFile as r5}from"node:child_process";import{existsSync as i5}from"node:fs";var Er="keychain_unavailable",jd="No macOS keychain is available for this HOME.",ll="No macOS keychain is available for this HOME. Sign in from your normal macOS user session, where the login Keychain exists, and run skills-layer mcp setup --client <host-id> there. Cloud MCP has no file fallback; SKILLS_LAYER_CREDENTIAL_STORE=local-file keeps only the login API key in a locked local file.",Ay=class extends Error{reasonCode=Er;constructor(){super(`${Er}: ${jd} Nothing was written to the Keychain.`),this.name="KeychainUnavailableError"}};function o5(e,t){return new Promise((n,r)=>{let i=()=>r(new Error("Keychain command failed.")),o=r5("/usr/bin/security",e,{encoding:"utf8",timeout:3e4,maxBuffer:65536},(s,a)=>{s?r(Object.assign(new Error("Keychain command failed."),{code:s.code})):n(a)});o.stdin.on("error",i),t!==void 0&&o.stdin.end(t)})}function dP(e){if(/[\r\n\0]/u.test(e))throw new Error("Invalid Keychain input.");return`"${e.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"')}"`}async function s5(e,t){try{let n=(await e(["default-keychain","-d","user"])).trim().replace(/^"(.*)"$/su,"$1");return n.startsWith("/")&&(t(n)||t(`${n}-db`))}catch{return!1}}var fP=new WeakMap;function pP(e={}){let t=e.run??o5,n=e.fileExists??i5,r=()=>{let i=fP.get(t);return i||(i=s5(t,n),fP.set(t,i)),i};return{kind:"macos_keychain",async unavailableReason(){return await r()?null:Er},async set(i,o,s){if(/[^\x00-\x7f]/u.test(s))throw new Error("Keychain secrets must contain ASCII characters only.");let a=`add-generic-password -a ${dP(o)} -s ${dP(i)} -X ${Buffer.from(s,"utf8").toString("hex")} -U
|
|
941
|
+
`;if(!s||Buffer.byteLength(a)>=4096)throw new Error("Invalid Keychain input.");if(!await r())throw new Ay;await t(["-i"],a)},async get(i,o){try{return(await t(["find-generic-password","-a",o,"-s",i,"-w"])).replace(/\n$/u,"")||null}catch{return null}},async delete(i,o){try{await t(["delete-generic-password","-a",o,"-s",i])}catch(s){if(s.code!==44)throw s}}}}import{createHash as a5}from"node:crypto";var cl="apiKey",Wo="apiKeyRef",ge="Skills Layer CLI";function xy(e=process.platform,t=process.env){let n=t.SKILLS_LAYER_CREDENTIAL_STORE?.trim().toLowerCase();return n==="local-file"||n==="local_file"||n==="disabled"||process.env.VITEST==="true"&&!Yn(n?.replaceAll("-","_"))?null:e==="linux"?uP():e==="win32"?KC():e==="darwin"?pP():null}async function mP(e,t){if(!(typeof e[cl]=="string"&&e[cl].length>0))return e;let r=Iy(t);if(!r)return e;try{let i={...e,credentialStorage:r.kind},o=l5(e,t.profile);return await r.set(Ry(t),o,e[cl]),i[Wo]=o,delete i[cl],i}catch{return c5(e)}}async function gP(e,t){if(!Yn(e.credentialStorage)||e[cl]||!e[Wo])return e;let n=Iy(t);if(!n)return e;let r=await n.get(Ry(t),e[Wo]);return r?{...e,apiKey:r}:e}async function hP(e,t){if(!e||!Yn(e.credentialStorage)||!e[Wo])return;let n=Iy(t);if(!n)throw new Error("OS credential storage is unavailable; retry logout on this profile\u2019s original machine.");await n.delete(Ry(t),e[Wo])}function l5(e,t){let n=[e.baseUrl??"unknown-base-url",e.userId??e.email??e.role??"unknown-user","apiKey",...t?[`profile:${t}`]:[]].join(`
|
|
942
|
+
`);return`skills-layer-cli:api-key:${a5("sha256").update(n).digest("base64url").slice(0,32)}`}function Iy(e){return e.store!==void 0?e.store:xy(e.platform,e.env??process.env)}function Ry(e){return e.service??ge}function c5(e){let t={...e,credentialStorage:"local_file_locked"};return delete t[Wo],t}var yP=Object.freeze(["mcp:use","catalog:read","identity:read","identity:write","library:read","library:write","creator:read","creator:submit","eval:write","source:read","source:write","billing:read","workspace:read","workspace:write","workspace:approve","guardian:check","guardian:incident"]);function Py(e){let t=e.skillSlug??"<skill-slug>";return{localWork:{purpose:e.purpose,command:e.command,jsonCommand:e.jsonCommand},guardian:{checkCommand:`skills-layer guardian check --skill ${t} --json`,execCommand:`skills-layer guardian exec ${t} --json -- <command>`,mcpTools:["guardian.check","guardian.enforce","guardian.status","guardian.incident"],guidance:"Before risky shell, network, file, secret, browser, API, generated-code, or model-context actions, call MCP guardian.check/guardian.enforce or run skills-layer guardian check. Route shell actions through skills-layer guardian exec when strict local blocking is needed."},setup:{setupCommand:"skills-layer setup",hookStatusCommand:"skills-layer guardian hook status",hookInstallProjectCommand:`skills-layer guardian hook install${e.agent?` --agent ${e.agent}`:""} --scope project`,hookInstallGlobalCommand:`skills-layer guardian hook install${e.agent?` --agent ${e.agent}`:""} --scope global`}}}var u5=Object.freeze(["--ascii","--api-key","--base-url","--color","--detail","--help","--json","--motion","--no-color","--no-interactive","--no-motion","--output-format","--screen-reader","--ui"]),d5=Object.freeze({"auth mfa recovery-codes":Object.freeze(["--code","--mfa-code"])}),f5=Object.freeze(Xl.map(e=>{let t=e.split(" "),n=Gr(t[0],t.slice(1));if(!n)throw new Error(`Public command manifest could not resolve focused help for ${e}.`);let r=y5(e,n.usage),o=!Xl.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(g5(e)),usage:r.join(`
|
|
943
|
+
`)||n.usage,positionals:Object.freeze(h5(r.join(`
|
|
944
|
+
`)||n.usage)),options:Object.freeze([...new Set([...o==="command"?w5(r.join(`
|
|
945
|
+
`)):n.options,...d5[e]??[],"--json"])]),inheritedOptions:u5,outputModes:Object.freeze(["human","json","stream-json"]),mutability:v5(n.sideEffects),humanInLoop:b5(n),fixturePrerequisites:Object.freeze([...n.requiresLogin?["authenticated_account"]:[],...n.requiresNetwork?["reachable_backend"]:[]]),examples:Object.freeze(n.examples),availability:"public"})})),p5=new Map(f5.map(e=>[e.path,e]));function wP(e){let t=e.map(n=>n.trim().toLowerCase()).filter(Boolean);for(let n=t.length;n>=1;n-=1){let r=p5.get(t.slice(0,n).join(" "));if(r)return r}return null}function m5(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 vP=m5;function g5(e){return e==="find"?["search"]:e==="workspaces"?["workspace"]:[]}function h5(e){return[...new Set([...e.matchAll(/<([^>]+)>/gu)].map(t=>t[1]))]}function y5(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 w5(e){return[...new Set([...e.matchAll(/--[a-z][a-z0-9-]*/gu)].map(t=>t[0]))]}function v5(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 b5(e){return e.sideEffects.includes("payment_mutation")?"financial":e.mayOpenBrowser?"browser":e.mayPrompt?"prompt":"none"}import{posix as _5,win32 as k5}from"node:path";function bP(e,t){let n=t==="win32"?k5:_5;if(t==="win32"){let o=Ey(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=Ey(e.XDG_CONFIG_HOME);if(r)return n.join(r,"skills-layer");let i=Ey(e.HOME);if(!i)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(i,".skills-layer")}function Ey(...e){return e.map(t=>t?.trim()).find(t=>!!t)}var S5=/^[\u00a0\u2007\u202f\ufeff]+|[\u00a0\u2007\u202f\ufeff]+$/gu,C5=/^\[(https?:\/\/[^\]\r\n]+)\]\((https?:\/\/[^)\r\n]+)\)$/u;function _P(e){let t=e.indexOf("--");return e.map((n,r)=>{if(t!==-1&&r>t)return n;let i=n.replace(S5,""),o=C5.exec(i);return o&&o[1]===o[2]?o[1]:i})}var kP={creator_example_readiness_required:A("invalid_input","action_required",!1,!0,"Add a concrete sample input, expected output and success criteria, then validate again.",[4]),invalid_issue_comment:A("invalid_input","invalid",!1,!0,"Provide a reply between 1 and 2,000 characters.",[4]),reopen_note_required:A("invalid_input","invalid",!1,!0,"Provide a reopening note between 1 and 2,000 characters.",[4]),invalid_notification_preference:A("invalid_input","invalid",!1,!0,"Choose a feedback event and a boolean enabled preference.",[4]),guardian_admin_mfa_code_required:A("invalid_input","invalid",!1,!0,"Pass --mfa-code <code> or pipe the code with --totp-stdin.",[4]),github_dependency_wait:A("backend_unreachable","unavailable",!0,!0,"GitHub processing is unavailable right now; retry after the wait.",[5]),github_quota_wait:A("rate_limited","rate_limited",!0,!0,"The GitHub request allowance is used up for now; retry after the wait.",[4]),recovery_hold_active:A("policy_blocked","blocked",!0,!0,"This account is on a recovery hold, so this sensitive action is paused until the hold ends.",[4]),source_not_public:A("invalid_input","invalid",!1,!0,"GitHub did not confirm this repository is public. If it is public, import it again; if it is private, import it through a private source connection.",[4]),source_snapshot_consumed:A("conflict","conflict",!1,!0,"This connection's private copy was already used; start a new source connection.",[4]),github_credential_rejected:A("backend_unreachable","unavailable",!0,!0,"Skills Layer's GitHub access was rejected; retry the import later.",[5]),database_busy:A("backend_unreachable","unavailable",!0,!0,"The database did not answer in time; nothing was confirmed saved. Retry shortly.",[5]),feedback_storage_unavailable:A("backend_unreachable","unavailable",!0,!1,"Feedback storage is temporarily unavailable; retry later.",[5]),rescan_held:A("processing_action_required","action_required",!1,!0,"Rescan is held pending processing recovery.",[4,5]),dependency_lockfile_required:A("precondition_required","action_required",!1,!0,"A dependency manifest needs a lockfile before its dependencies can be checked.",[4,5]),exact_artifact_generation_mismatch:A("processing_action_required","action_required",!1,!0,"The stored artifact no longer matches the exact version being rescanned.",[4,5]),platform_eval_authority_unavailable:A("processing_action_required","action_required",!1,!0,"Platform evaluation authority is unavailable for this version.",[4,5]),platform_eval_scheduler_unavailable:A("processing_action_required","action_required",!1,!0,"Platform evaluation scheduling is unavailable for this version.",[4,5]),platform_eval_schedule_failed:A("processing_action_required","action_required",!1,!0,"Platform evaluation could not be scheduled for this version.",[4,5]),semantic_security_schedule_failed:A("processing_action_required","action_required",!1,!0,"The security rescan could not be scheduled for this version.",[4,5]),admin_moderation_required:A("policy_blocked","blocked",!1,!1,"Only platform administrators may change review visibility.",[4]),creator_self_review:A("policy_blocked","blocked",!1,!1,"Skill creators, owners and maintainers cannot review their own skill.",[4]),creator_self_issue:A("policy_blocked","blocked",!1,!1,"Skill creators, owners and maintainers cannot file customer issues on their own skill.",[4]),creator_self_purchase_limit:A("policy_blocked","blocked",!1,!1,"Creators may acquire their own skill once for life, including after a refund.",[4]),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]),keychain_unavailable:A("human_action_required","security_unavailable",!1,!0,"No macOS keychain is available for this HOME. Sign in from your normal macOS user session; Cloud MCP has no file fallback.",[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_role_required:A("permission_denied","access_required",!1,!1,"An administrator account is required for this route.",[4]),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]),api_key_expired:A("login_required","login_required",!1,!0,"The saved sign-in key has expired. Sign in again: skills-layer login",[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]),withdrawal_confirmation_mismatch:A("unchanged","cancelled",!0,!0,"No withdrawal was requested because the confirmation phrase did not match.",[4]),social_auth_timed_out:A("human_action_required","error",!1,!0,"The browser sign-in expired before it was finished.",[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]),command_required:A("invalid_input","error",!1,!0,"Name a command, for example skills-layer search <query>.",[4]),optimize_tokens_text_too_large:A("invalid_input","invalid",!1,!0,"Shorten the text to at most 100,000 characters.",[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]),installed_bundle_root_skill_missing:A("invalid_input","error",!1,!0,"The published bundle has no root SKILL.md, so it cannot be installed.",[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_socket_directory_unsafe:A("human_action_required","mcp_setup_blocked",!1,!0,"Use a user-owned, non-symlink MCP runtime directory with mode 0700.",[4]),mcp_socket_path_unsafe:A("human_action_required","mcp_setup_blocked",!1,!0,"Remove the untrusted socket entry after checking its ownership, then retry MCP setup.",[4]),mcp_runtime_missing:A("human_action_required","mcp_needs_repair",!1,!0,"Install Node.js and run skills-layer mcp repair for the affected client.",[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]),guardian_warning_only:A("unchanged","warning_only",!1,!1,"Guardian is in warnings-only mode for this skill.",[2]),guardian_disabled:A("unchanged","disabled",!1,!1,"Guardian is off for this skill.",[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 A5(e){let t=kP[e];return t?{reasonCode:e,...t}:null}function Ud(e,t={}){if(!e)return t.httpStatus===404?Jo("resource_not_found"):t.httpStatus===401?Jo("login_required"):t.httpStatus===403?Jo("permission_denied"):t.httpStatus===409?Me("conflict","conflict"):t.httpStatus===429?Jo("rate_limited"):(t.httpStatus&&t.httpStatus>=500,Jo("command_failed"));let n=A5(e);return n||(e.startsWith("platform_eval_fixture_preparation_failed_")?Me(e,"processing_action_required","action_required"):e.includes("not_found")||e==="missing_record"?Me(e,"not_found","not_found"):e.includes("rate_limit")?Me(e,"rate_limited","rate_limited",!0):e.includes("quota")||e.includes("_limit_reached")||e.includes("_limit_exhausted")?Me(e,"quota_exceeded","conflict"):e.includes("human")||e.includes("mfa")||e.includes("browser_confirmation")?Me(e,"human_action_required","human_action_required"):e.includes("already_canceled")||e.includes("unchanged")||e.includes("already_complete")?Me(e,"unchanged","unchanged"):e.includes("dependency")||e.includes("precondition")||e.includes("required")?Me(e,"precondition_required","error"):e.includes("processing")||e.includes("pending")||e.includes("already_processing")?Me(e,"processing_action_required","already_processing",!0):e.includes("conflict")||e.includes("already_final")||e.includes("completed")?Me(e,"conflict","conflict"):e.includes("payment")||e.includes("checkout")||e.includes("purchase")?Me(e,"payment_required","human_action_required"):e.includes("source")?Me(e,"source_required","error"):e.includes("backend")||e.includes("unreachable")||e.includes("network")?Me(e,"backend_unreachable","error",!0):e.includes("agent")||e.includes("client")||e.includes("unsupported")?Me(e,"unsupported_client","error"):e.includes("blocked")||e.includes("policy")||e.includes("guardian")?Me(e,"policy_blocked","blocked"):e.includes("forbidden")||e.includes("permission_denied")?Me(e,"permission_denied","error"):e.includes("not_allowed")||e.includes("invalid_transition")?Me(e,"operation_not_allowed","error"):Me(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 Jo(e){return{reasonCode:e,...kP[e]}}function Me(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]}}function SP(e){if(!e.valid)return{publishReadiness:"needs_changes",publishReadinessSummary:"Validation failed. Fix the listed issues before submission.",publishReadinessFinding:null};let t=e.securityReport?.recommendation??null,n=e.securityReport?.findings??[];if(t==="blocked"){let r=n.find(i=>i.blocking)??n.find(i=>i.severity==="error")??n[0];return{publishReadiness:"blocked",publishReadinessSummary:`Structure valid; security review: blocked. This skill will not be published${r?` (${r.ruleId??r.code}: ${r.message})`:""}.`,publishReadinessFinding:r?{ruleId:r.ruleId??null,code:r.code,message:r.message}:null}}if(t==="manual_review"){let r=n.find(i=>i.severity==="error")??n[0];return{publishReadiness:"needs_admin_review",publishReadinessSummary:"Structure valid; security review: manual review. A platform administrator must review it after submission before it can publish.",publishReadinessFinding:r?{ruleId:r.ruleId??null,code:r.code,message:r.message}:null}}return{publishReadiness:"ready",publishReadinessSummary:"Bundle validation complete.",publishReadinessFinding:null}}function Dy(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
946
|
+
`)}
|
|
947
|
+
`}var ul=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",qd=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var Ty=e=>e.name==="backspace";var $y=e=>"1234567890".includes(e.name),Ly=e=>e.name==="enter"||e.name==="return";var Vd=class extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(t){super(),this.cause=t?.cause}},Gd=class extends Error{name="CancelPromptError";message="Prompt was canceled"},dl=class extends Error{name="ExitPromptError"},zd=class extends Error{name="HookError"},Yo=class extends Error{name="ValidationError"};import{AsyncResource as P5}from"node:async_hooks";import{AsyncLocalStorage as x5,AsyncResource as I5}from"node:async_hooks";var CP=new x5;function R5(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function AP(e,t){let n=R5(e);return CP.run(n,()=>{function r(i){n.handleChange=()=>{n.index=0,i()},n.handleChange()}return t(r)})}function bi(){let e=CP.getStore();if(!e)throw new zd("[Inquirer] Hook functions can only be called from within a prompt");return e}function Oy(){return bi().rl}function Fy(e){let t=(...n)=>{let r=bi(),i=!1,o=r.handleChange;r.handleChange=()=>{i=!0};let s=e(...n);return i&&o(),r.handleChange=o,s};return I5.bind(t)}function Zo(e){let t=bi(),{index:n}=t,r={get(){return t.hooks[n]},set(o){t.hooks[n]=o},initialized:n in t.hooks},i=e(r);return t.index++,i}function xP(){bi().handleChange()}var _i={queue(e){let t=bi(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(Oy());if(r!=null&&typeof r!="function")throw new Yo("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[n]=r})},run(){let e=bi();Fy(()=>{e.hooksEffect.forEach(t=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=bi();e.hooksCleanup.forEach(t=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function jn(e){return Zo(t=>{let n=P5.bind(function(o){t.get()!==o&&(t.set(o),xP())});if(t.initialized)return[t.get(),n];let r=typeof e=="function"?e():e;return t.set(r),[r,n]})}function ki(e,t){Zo(n=>{let r=n.get();(!Array.isArray(r)||t.some((o,s)=>!Object.is(o,r[s])))&&_i.queue(e),n.set(t)})}var qt=Tt(Kd(),1);import vn from"node:process";function T5(){return vn.platform!=="win32"?vn.env.TERM!=="linux":!!vn.env.WT_SESSION||!!vn.env.TERMINUS_SUBLIME||vn.env.ConEmuTask==="{cmd::Cmder}"||vn.env.TERM_PROGRAM==="Terminus-Sublime"||vn.env.TERM_PROGRAM==="vscode"||vn.env.TERM==="xterm-256color"||vn.env.TERM==="alacritty"||vn.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var RP={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},PP={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},$5={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},L5={...RP,...PP},O5={...RP,...$5},F5=T5(),B5=F5?L5:O5,Xo=B5,vre=Object.entries(PP);var EP={prefix:{idle:qt.default.blue("?"),done:qt.default.green(Xo.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(e=>qt.default.yellow(e))},style:{answer:qt.default.cyan,message:qt.default.bold,error:e=>qt.default.red(`> ${e}`),defaultAnswer:e=>qt.default.dim(`(${e})`),help:qt.default.dim,highlight:qt.default.cyan,key:e=>qt.default.cyan(qt.default.bold(`<${e}>`))}};function DP(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function TP(...e){let t={};for(let n of e)for(let[r,i]of Object.entries(n)){let o=t[r];t[r]=DP(o)&&DP(i)?TP(o,i):i}return t}function fl(...e){let t=[EP,...e.filter(n=>n!=null)];return TP(...t)}function By({status:e="idle",theme:t}){let[n,r]=jn(!1),[i,o]=jn(0),{prefix:s,spinner:a}=fl(t);return ki(()=>{if(e==="loading"){let c,u=-1,d=setTimeout(()=>{r(!0),c=setInterval(()=>{u=u+1,o(u%a.frames.length)},a.interval)},300);return()=>{clearTimeout(d),clearInterval(c)}}else r(!1)},[e]),n?a.frames[i]:typeof s=="string"?s:s[e==="loading"?"idle":e]??s.idle}function pl(e,t){return Zo(n=>{let r=n.get();if(!r||r.dependencies.length!==t.length||r.dependencies.some((i,o)=>i!==t[o])){let i=e();return n.set({value:i,dependencies:t}),i}return r.value})}function Si(e){return jn({current:e})[0]}function Ny(e){let t=Si(e);t.current=e,ki(n=>{let r=!1,i=Fy((o,s)=>{r||t.current(s,n)});return n.input.on("keypress",i),()=>{r=!0,n.input.removeListener("keypress",i)}},[])}var aE=Tt(LP(),1),lE=Tt(sE(),1);function hl(e,t){return e.split(`
|
|
948
|
+
`).flatMap(n=>(0,lE.default)(n,t,{trim:!1,hard:!0}).split(`
|
|
949
|
+
`).map(r=>r.trimEnd())).join(`
|
|
950
|
+
`)}function Jd(){return(0,aE.default)({defaultWidth:80,output:Oy().output})}function sK({active:e,renderedItems:t,pageSize:n,loop:r}){let i=Si({lastPointer:e,lastActive:void 0}),{lastPointer:o,lastActive:s}=i.current,a=Math.floor(n/2),l=t.reduce((d,p)=>d+p.length,0),c=t.slice(0,e).reduce((d,p)=>d+p.length,0),u=c;if(l>n)if(r)u=o,s!=null&&s<e&&e-s<n&&(u=Math.min(a,Math.abs(e-s)===1?Math.min(o+(t[s]?.length??0),Math.max(c,o)):o+e-s));else{let d=t.slice(e).reduce((p,m)=>p+m.length,0);u=d<n-a?n-d:Math.min(c,a)}return i.current.lastPointer=u,i.current.lastActive=e,u}function Hy({items:e,active:t,renderItem:n,pageSize:r,loop:i=!0}){let o=Jd(),s=w=>(w%e.length+e.length)%e.length,a=e.map((w,b)=>w==null?[]:hl(n({item:w,index:b,isActive:b===t}),o).split(`
|
|
951
|
+
`)),l=a.reduce((w,b)=>w+b.length,0),c=w=>a[w]??[],u=sK({active:t,renderedItems:a,pageSize:r,loop:i}),d=c(t).slice(0,r),p=u+d.length<=r?u:r-d.length,m=Array.from({length:r});m.splice(p,d.length,...d);let g=new Set([t]),h=p+d.length,y=s(t+1);for(;h<r&&!g.has(y)&&(i&&l>r?y!==t:y>t);){let b=c(y).slice(0,r-h);m.splice(h,b.length,...b),g.add(y),h+=b.length,y=s(y+1)}for(h=p-1,y=s(t-1);h>=0&&!g.has(y)&&(i&&l>r?y!==t:y<t);){let w=c(y),b=w.slice(Math.max(0,w.length-h-1));m.splice(h-b.length+1,b.length,...b),g.add(y),h-=b.length,y=s(y-1)}return m.filter(w=>typeof w=="string").join(`
|
|
952
|
+
`)}var hE=Tt(uE(),1);import*as gE from"node:readline";import{AsyncResource as uK}from"node:async_hooks";import{stripVTControlCharacters as lK}from"node:util";var fE="\x1B[?25l",pE="\x1B[?25h",Jy=(e=1)=>e>0?`\x1B[${e}A`:"",Yy=(e=1)=>e>0?`\x1B[${e}B`:"",Zy=(e,t)=>typeof t=="number"&&!Number.isNaN(t)?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`,dE="\x1B[2K",Xy=e=>e>0?(dE+Jy(1)).repeat(e-1)+dE+"\x1B[G":"";var mE=e=>e.split(`
|
|
953
|
+
`).length,cK=e=>e.split(`
|
|
954
|
+
`).pop()??"",yl=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=cK(t),i=lK(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=Jd();t=hl(t,s),n=hl(n,s),i.length%s===0&&(t+=`
|
|
955
|
+
`);let a=t+(n?`
|
|
956
|
+
`+n:""),c=Math.floor(i.length/s)-this.cursorPos.rows+(n?mE(n):0);c>0&&(a+=Jy(c)),a+=Zy(this.cursorPos.cols),this.write(Yy(this.extraLinesUnderPrompt)+Xy(this.height)+a),this.extraLinesUnderPrompt=c,this.height=mE(a)}checkCursorPos(){let t=this.rl.getCursorPos();t.cols!==this.cursorPos.cols&&(this.write(Zy(t.cols)),this.cursorPos=t)}done({clearContent:t}){this.rl.setPrompt("");let n=Yy(this.extraLinesUnderPrompt);n+=t?Xy(this.height):`
|
|
957
|
+
`,n+=pE,this.write(n),this.rl.close()}};var Yd=class extends Promise{static withResolver(){let t,n;return{promise:new Promise((i,o)=>{t=i,n=o}),resolve:t,reject:n}}};function dK(){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 Qy(e){let t=dK();return(r,i={})=>{let{input:o=process.stdin,signal:s}=i,a=new Set,l=new hE.default;l.pipe(i.output??process.stdout);let c=gE.createInterface({terminal:!0,input:o,output:l}),u=new yl(c),{promise:d,resolve:p,reject:m}=Yd.withResolver(),g=()=>m(new Gd);if(s){let w=()=>m(new Vd({cause:s.reason}));if(s.aborted)return w(),Object.assign(d,{cancel:g});s.addEventListener("abort",w),a.add(()=>s.removeEventListener("abort",w))}a.add(ab((w,b)=>{m(new dl(`User force closed the prompt with ${w} ${b}`))}));let h=()=>m(new dl("User force closed the prompt with SIGINT"));c.on("SIGINT",h),a.add(()=>c.removeListener("SIGINT",h));let y=()=>u.checkCursorPos();return c.input.on("keypress",y),a.add(()=>c.input.removeListener("keypress",y)),AP(c,w=>{let b=uK.bind(()=>_i.clearAll());return c.on("close",b),a.add(()=>c.removeListener("close",b)),w(()=>{try{let _=e(r,C=>{setImmediate(()=>p(C))});if(_===void 0){let C=t[1]?.getFileName();throw new Error(`Prompt functions must return a string.
|
|
958
|
+
at ${C}`)}let[I,x]=typeof _=="string"?[_]:_;u.render(I,x),_i.run()}catch(_){m(_)}}),Object.assign(d.then(_=>(_i.clearAll(),_),_=>{throw _i.clearAll(),_}).finally(()=>{a.forEach(_=>_()),u.done({clearContent:!!i.clearPromptOnDone}),l.end()}).then(()=>d),{cancel:g})})}}var yE=Tt(Kd(),1);var bn=class{separator=yE.default.dim(Array.from({length:15}).join(Xo.line));type="separator";constructor(t){t&&(this.separator=t)}static isSeparator(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="separator")}};var rs=Tt(Kd(),1);var fK={icon:{cursor:Xo.pointer},style:{disabled:e=>rs.default.dim(`- ${e}`),description:e=>rs.default.cyan(e),keysHelpTip:e=>e.map(([t,n])=>`${rs.default.bold(t)} ${rs.default.dim(n)}`).join(rs.default.dim(" \u2022 "))},helpMode:"always",indexMode:"hidden",keybindings:[]};function ns(e){return!bn.isSeparator(e)&&!e.disabled}function pK(e){return e.map(t=>{if(bn.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 wE=Qy((e,t)=>{let{loop:n=!0,pageSize:r=7}=e,i=fl(fK,e.theme),{keybindings:o}=i,[s,a]=jn("idle"),l=By({status:s,theme:i}),c=Si(),u=!o.includes("vim"),d=pl(()=>pK(e.choices),[e.choices]),p=pl(()=>{let D=d.findIndex(ns),T=d.findLastIndex(ns);if(D===-1)throw new Yo("[select prompt] No selectable choices. All choices are disabled.");return{first:D,last:T}},[d]),m=pl(()=>"default"in e?d.findIndex(D=>ns(D)&&D.value===e.default):-1,[e.default,d]),[g,h]=jn(m===-1?p.first:m),y=d[g];Ny((D,T)=>{if(clearTimeout(c.current),Ly(D))a("done"),t(y.value);else if(ul(D,o)||qd(D,o)){if(T.clearLine(0),n||ul(D,o)&&g!==p.first||qd(D,o)&&g!==p.last){let j=ul(D,o)?-1:1,M=g;do M=(M+j+d.length)%d.length;while(!ns(d[M]));h(M)}}else if($y(D)&&!Number.isNaN(Number(T.line))){let j=Number(T.line)-1,M=-1,$=d.findIndex(q=>bn.isSeparator(q)?!1:(M++,M===j)),B=d[$];B!=null&&ns(B)&&h($),c.current=setTimeout(()=>{T.clearLine(0)},700)}else if(Ty(D))T.clearLine(0);else if(u){let j=T.line.toLowerCase(),M=d.findIndex($=>bn.isSeparator($)||!ns($)?!1:$.name.toLowerCase().startsWith(j));M!==-1&&h(M),c.current=setTimeout(()=>{T.clearLine(0)},700)}}),ki(()=>()=>{clearTimeout(c.current)},[]);let w=i.style.message(e.message,s),b;if(i.helpMode!=="never")if(e.instructions){let{pager:D,navigation:T}=e.instructions;b=i.style.help(d.length>r?D:T)}else b=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]);let _=0,I=Hy({items:d,active:g,renderItem({item:D,isActive:T,index:j}){if(bn.isSeparator(D))return _++,` ${D.separator}`;let M=i.indexMode==="number"?`${j+1-_}. `:"";if(D.disabled){let q=typeof D.disabled=="string"?D.disabled:"(disabled)";return i.style.disabled(`${M}${D.name} ${q}`)}let $=T?i.style.highlight:q=>q,B=T?i.icon.cursor:" ";return $(`${B} ${M}${D.name}`)},pageSize:r,loop:n});if(s==="done")return[l,w,i.style.answer(y.short)].filter(Boolean).join(" ");let{description:x}=y;return`${[[l,w].filter(Boolean).join(" "),I," ",x?i.style.description(x):"",b].filter(Boolean).join(`
|
|
959
|
+
`).trimEnd()}${fE}`});function Zd(e,t){return async(...n)=>{t.start?.();try{return await e(...n)}finally{t.end?.()}}}async function vE(e,t,n={},r=wE){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 is=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},ot=(e,t="Unavailable")=>typeof e=="string"&&e.trim()?$t(e.trim()):t,ew=e=>{let t=ot(e).replaceAll("_"," ");return t.charAt(0).toUpperCase()+t.slice(1)},bE=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=100?`${e}/100`:"Unavailable";function _E(e,t,n=88){let r=is(e.sourceDisclosure),i=is(e.platformScore),o=is(i.dimensions),s=is(e.securityPosture),a=is(e.price),l=i.availability==="available",c=[["Name",ot(e.name)],["Slug",ot(e.slug)],["Version",ot(e.currentVersion)],["Category",ot(e.category)],["Source",ot(r.sourceRepository)],["Licence",ot(r.identifier,ot(r.label))],["Price",ot(a.display)]];typeof e.catalogPublishedAt=="string"&&e.catalogPublishedAt.trim()?c.push(["Catalog published",ot(e.catalogPublishedAt)]):typeof e.platformPublishedAt=="string"&&e.platformPublishedAt.trim()&&c.push(["Platform published",ot(e.platformPublishedAt)]),t.detail==="full"&&c.push(["Source commit",ot(r.sourceCommitSha)]);let u=[["Platform score",l?bE(i.score):"Unavailable"],["Assessment",ew(l?i.decision:i.availability)]];if(l)for(let[y,w]of[["security_safety","Security and safety"],["runtime_access_control","Runtime access control"],["effectiveness_outcomes","Effectiveness and outcomes"],["trust_integrity","Trust and integrity"]])u.push([w,bE(o[y])]);let d=[["Runtime risk",ew(s.runtimeRisk)],["Security recommendation",ew(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"?ot(e.fullDescription,ot(e.shortDescription,"No description available.")):ot(e.shortDescription,"No description available."),g=[Gi("Description",m),Gi("Skill",Kl(c,n)),Gi("Assessment",Kl(u,n)),Gi("Security",Kl(d,n)),...eb({effectiveness:{assessmentCoverage:is(e.effectiveness).assessmentCoverage}},Hl(t)),Gi("Next",`Review security: skills-layer trust ${p}
|
|
960
|
+
Preview installation: skills-layer install ${p} --dry-run`)],h=Vi(g.join(`
|
|
961
|
+
|
|
962
|
+
`));return t.screenReader?`Skills Layer \u2014 Skill Details
|
|
963
|
+
|
|
964
|
+
${h}`:Xv("Skills Layer \u2014 Skill Details",h,{width:n,unicode:t.unicode})}function kE(e,t){let n=mK(e);return{status:"link_required",provider:e,reasonCode:"social_identity_link_required",summary:`${n} sign-in was not completed because the provider identity needs secure verification.`,why:`${n} returned the email of an existing account, but its stable provider identity did not match the stored link. Email alone is not enough to merge accounts safely.`,nextAction:t?"auth.connect":"auth.recover",nextStep:t?`Run \`skills-layer auth connect --provider ${e}\` to securely reconnect ${n} to the signed-in account.`:`Run \`skills-layer auth recover --method email\` to restore the existing account, then run \`skills-layer auth connect --provider ${e}\` from the authenticated session.`}}function mK(e){switch(e){case"github":return"GitHub";case"gitlab":return"GitLab";case"google":return"Google";case"microsoft":return"Microsoft"}}var V=class extends Error{status;details;constructor(t,n,r){super(n),this.name="ApiError",this.status=t,this.details=r}},_K=1,Yw=1,sf=2,H0="skills-layer-public-cli-v1",st="skills-layer-security-hook",et="Skills Layer Security Hook",Zw="https://api.skills-layer.com",kK="http://127.0.0.1:8787",CE=new Set(["totp-stdin","all-sharing-agents","include-removed","wait","async","json","dry-run","skip-probe","clear-display-name","clear-company","clear-bio","help","list","all","deep","verbose","show-url","no-open","confirm","confirmed","create-account","yes","with-mcp","no-mcp","allow-unmanaged-once","disclose-source","new-enterprise","leave-enterprise","skip-license","replace-unpublished","accept-unverified-source","local-only","allow-incompatible","replace-unverified-source","quick","apply","attest-rights","confirm-free","forget"]),af=new Set(["accept-capability","approval-request-id","grant-json","paraphrase","secret-env","should-not-trigger","should-trigger"]),bw=new Set(["statement","bio","company","description","display-name","feedback","message","note","reason","search","summary"]),_w=new Set(["country","cursor","publisher","price","minimum-score","minimum-stars","badge","action","action-json","agent","amount-cents","api-key","base-url","capability","category","claim-id","client","cloud-trust-ledger","code","commit-sha","created-after","created-before","decision","decision-evidence-json","dependency-audit-status","dir","email","environment","eval-summary","evidence-json","expires","expires-after","expires-before","external-reference","idempotency-key","continuation-key","processing-receipt-id","wait-polls","fixed-version","format","host-version","install","issue-id","comment-id","issue-type","key-id","kind","license","license-file","license-holder","license-year","limit","listing-status","max-characters","method","mfa-code","mode","name","output","path","payment-method","pack","pin","price-cents","provider","purpose","provider-installation-id","provider-owner-id","provider-project-id","provider-repo-id","provenance-intent","publication-status","rating","reference","recovery-code","requested-role","review-id","role","runtime-risk","scope","security-capability","skill","skill-type","sort","source","source-intake-context","space-pack","state","status","seats","text","telemetry-mode","telemetry-policy","guardian-policy","trust","type","unmanaged-policy","version","version-id","visibility","workspace","workspace-name","enterprise-name","answers","answer-json","question-id","decisions-json","patch-json","expected-revision","plan-digest","report-digest","caller-capabilities-json","challenge-digest","observations-json","supplied-resources-json","additional-evidence-json","tags-json","outcome","session-id","creator-session-id","imported-candidate-id","rights-basis","distribution-scope","source-reference"]),lf=new Set(_b),SK=new Set(["standards","marketplace-status","capabilities","schema-plan","optimize-tokens"]);async function nae(e,t={}){let n;try{n=await v_(e,t.readTotpStdin??(()=>w_(process.stdin)),t.stdinIsTty??!!process.stdin.isTTY)}catch(r){let i=ne(r);return S({status:"error",reasonCode:"login_mfa_input_invalid",nextStep:i},i,e.includes("--json"),"login_mfa_input_invalid")}try{let r=await CK(n.args,t);return n.warning?{...r,stderr:`${n.warning}
|
|
965
|
+
${r.stderr}`}:r}catch(r){return P(ne(r),e.includes("--json"))}}async function CK(e,t){e=_P(e);let n=t.env??process.env,r=AK(e),i;try{i=zi(e,n,{stdinIsTty:t.stdinIsTty??!!(t.selectInput?.isTTY??process.stdin.isTTY),stdoutIsTty:t.stdoutIsTty??!!(t.selectOutput?.isTTY??process.stdout.isTTY),stderrIsTty:t.stderrIsTty??!!process.stderr.isTTY})}catch(_){return xK(e,ne(_),r,t)}let o=[],s=i.mode.kind==="json-final"||i.mode.kind==="json-stream",a=i.options.interactive===!1||i.options.screenReader===!0||i.options.motion==="never"||i.options.ui==="classic",l=RK(n.CI)||n.TERM==="dumb",u=t.stdinIsTty===void 0&&t.stderrIsTty===void 0&&t.stdoutIsTty!==!1&&!!(t.promptText||t.promptSecret||t.promptSelect||t.selectInput||t.openUrl||t.emitInfo),d=t.stdoutIsTty===!0&&t.stdinIsTty===void 0&&t.stderrIsTty===void 0,p=a||l&&!u||s&&!u||!i.mode.interactive&&!u&&!d,m=t.emitInfo,g=Wl(i.args),h=i.mode.kind==="json-stream"?Uf({operationId:t.operationId??`op_${ke(8).toString("hex")}`,command:{name:g},now:t.now},t.emitCliEvent,i.mode.detail):void 0,y={...t,renderMode:i.mode,nonInteractive:i.options.interactive===!1,...p?{stdoutIsTty:!1,openUrl:async()=>!1,promptText:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")},promptSecret:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")},promptSelect:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")}}:{},...s?{emitInfo:h?rb(h,m):nb(i.mode,o,m)}:{}},w=h?ib({session:h,commandName:g}):void 0,b;try{b=await PK(i.args,y)}finally{w?.()}return i.mode.kind!=="json-stream"?b:(h.finish(b),{exitCode:b.exitCode,stdout:t.emitCliEvent?"":Dy(h.events),stderr:""})}function AK(e){let t=e.indexOf("--"),n=t===-1?e:e.slice(0,t),r=n.includes("--json"),i=!1;for(let o=0;o<n.length;o+=1){let s=n[o],a=s.startsWith("--output-format=")?s.slice(16):null,l=a??(s==="--output-format"?n[o+1]:void 0);l==="stream-json"?i=!0:l==="json"&&(r=!0),a===null&&s==="--output-format"&&(o+=1)}return i?"stream-json":r?"json":null}function xK(e,t,n,r){let i=/^--(?<option>[a-z0-9-]+) expects one of: (?<accepted>.+)\.$/iu.exec(t);if(!n||!i?.groups)return P(`${t}
|
|
966
|
+
Next: run skills-layer --help`,n==="json");let o=i.groups.option,s=IK(e,o),a={status:"error",reasonCode:"invalid_global_option",option:o,providedValue:$t((s??"<missing>").slice(0,128)),acceptedValues:i.groups.accepted.split(",").map(d=>d.trim()).filter(Boolean),nextAction:"help",nextStep:"Run `skills-layer --help` and provide one accepted global option value."},l=S(a,`Invalid global option --${o}.`,!0,"invalid_global_option");if(n==="json")return l;let c=Wl(e),u=Uf({operationId:r.operationId??`op_${ke(8).toString("hex")}`,command:{name:c},now:r.now},r.emitCliEvent);return u.finish(l),{exitCode:1,stdout:r.emitCliEvent?"":Dy(u.events),stderr:""}}function IK(e,t){let n=`--${t}`,r=`${n}=`,i=e.indexOf("--"),o=i===-1?e:e.slice(0,i);for(let s=0;s<o.length;s+=1){let a=o[s];if(a.startsWith(r))return a.slice(r.length);if(a===n)return o[s+1]}}function RK(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}async function PK(e,t){let n={invocationArgs:e,env:t.env??process.env,platform:t.platform??process.platform,cwd:t.cwd??process.cwd(),now:t.now??(()=>new Date().toISOString()),fetchFn:t.fetch??globalThis.fetch,openUrl:t.openUrl??uJ(t.platform??process.platform),stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY,helpInteractive:t.stdoutIsTty??!!(t.selectInput?.isTTY&&t.selectOutput?.isTTY),renderMode:t.renderMode??zi([],t.env??process.env,{stdinIsTty:!1,stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY,stderrIsTty:!1}).mode,promptText:Zd(t.promptText??lJ(),{start:t.onPromptStart,end:t.onPromptEnd}),promptSecret:Zd(t.promptSecret??BC(),{start:t.onPromptStart,end:t.onPromptEnd}),promptSelect:Zd(t.promptSelect??cJ(t.selectInput??process.stdin,t.selectOutput??process.stdout),{start:t.onPromptStart,end:t.onPromptEnd}),sleep:t.sleep??(c=>new Promise(u=>setTimeout(u,c))),emitInfo:t.emitInfo??(c=>process.stdout.write(`${c}
|
|
967
|
+
`)),emitNotice:t.emitNotice??(c=>process.stderr.write(`${c}
|
|
968
|
+
`)),runtimeWarnings:[],credentialStore:t.credentialStore!==void 0?t.credentialStore:xy(t.platform??process.platform,t.env??process.env),nonInteractive:t.nonInteractive===!0,pathExists:t.pathExists??Ke};if(e[0]==="--json"){if(e.length===1)return S({status:"error",reasonCode:"command_required",nextAction:"help",nextStep:"Run `skills-layer --help --json` to list supported public commands."},"No command was given.",!0,"command_required");e=[...e.slice(1),"--json"]}let r=e[0];if(!r){let c=tw([]),u=await wl(c.flags,n);try{return await nW(c.flags,u)}catch(d){if(d instanceof Error&&d.name==="ExitPromptError")return C0(c.flags.json);throw d}}if(r==="--help"||r==="-h"){let c=tw(e.slice(1));if(c.flags.json||n.renderMode.kind==="json-final"){let u=await wl(c.flags,n),d=Gr();return R(d,"Help loaded.",!0,u)}return{exitCode:0,stdout:Ai(n.renderMode),stderr:""}}if(r==="--version"||r==="-v")return e.includes("--json")?R({status:"ok",version:In},`skills-layer ${In}`,!0,n):{exitCode:0,stdout:`skills-layer ${In}
|
|
969
|
+
`,stderr:""};let i=tw(e.slice(1));if(i.error)return P(i.error,i.flags.json,e);let{flags:o,positionals:s}=i;if(["login","register","auth","identity"].includes(r)&&(o.method==="microsoft"||o.provider==="microsoft"||r==="identity"&&s[0]==="unlink"&&s[1]==="microsoft"))return S({reasonCode:"social_provider_unavailable"},h_,o.json);if(r==="agents"&&s.length===0&&s.push("list"),r==="admin")return P("The public skills-layer package does not include internal commands.",o.json,e);if(r==="version"){let c=await wl(o,n);return R({status:"ok",name:"skills-layer",version:In},`skills-layer ${In}`,o.json,c)}if(!lf.has(r))return AE(r,o.json);let a=wP([r,...s]),l=a?tW(a,e.slice(1)):null;if(a?.kind==="command"&&l)return S({status:"error",reasonCode:"unknown_flag",command:a.path,flag:l,nextAction:`${a.path.replace(/\s+/gu,".")}.help`,nextStep:`Run \`skills-layer ${a.path} --help\` to see the options owned by this command.`},`Unknown flag --${l} for skills-layer ${a.path}.`,o.json,"unknown_flag");if(o.help){if(o.json){let u=await wl(o,n),d=Gr(r,s);return d?R(d,"Help loaded.",!0,u):lf.has(r)?Iw([r,...s],!0):P(kw(r),!0,e)}let c=Ql(r,s);return c?{exitCode:0,stdout:c,stderr:""}:lf.has(r)?Iw([r,...s],o.json):P(kw(r),o.json,e)}try{let c=await wl(o,n);switch(r){case"agents":return await FK(s,o,c);case"backend":return await BK(s,o,c);case"register":return await W0(o,c);case"login":return await J0(o,c);case"logout":return await Y0(o,c);case"whoami":return await ie("/api/v1/whoami",o,c,"Account loaded.",{authenticated:!0});case"profile":return await qK(s,o,c);case"auth":return await GK(s,o,c);case"identity":return await YK(s,o,c);case"api-key":return await QK(s,o,c);case"mcp":return await oH(s,o,c);case"enterprise":return await aH(s,o,c);case"search":case"find":return await $H(s,o,c);case"featured":case"trending":return await i4(r,o,c);case"categories":return s.length>0?qE("categories",s[0],o):await ie("/api/v1/categories",o,c,"Categories loaded.");case"recommend":return await o4(s,o,c);case"compare":return await s4(s,o,c);case"show":return await a4(s,o,c);case"trust":return await l4(s,o,c);case"delisting":return await YW(s,o,c);case"help":return await d4(s,o,c);case"status":return s.length>0?qE("status",s[0],o):await HW(o,c);case"doctor":return await WW(o,c);case"setup":return await YD(o,c);case"validate":return await f4(s,o,c);case"preview-trigger":return await y4(s,o,c);case"creator":return await w4(s,o,c);case"install":return await gs(s,o,c);case"installed":return await P3(o,c);case"remove":return await E3(s,o,c);case"update":return await $3(s,o,c);case"sync":return await O3(o,c);case"restore":return await G3(s,o,c);case"check":return await K3(s,o,c);case"import":return await H3(s,o,c);case"source":return await Y3(s,o,c);case"approval":return await Q3(s,o,c);case"workspace":case"workspaces":return await e8(s,o,c);case"buy":return await o8(s,o,c);case"purchases":return await s8(s,o,c);case"owned":return await ie("/api/v1/me/library",o,c,"Owned skills loaded.",{authenticated:!0});case"export":return await l8(s,o,c);case"library":return await a8(s,o,c);case"add-review":return await f0("add",s,o,c);case"show-reviews":return await f0("show",s,o,c);case"add-issue":return await p0("add",s,o,c);case"issue":return await c8(s,o,c);case"show-issues":return await p0("show",s,o,c);case"guardian":return await u8(s,o,c);default:return AE(r,o.json)}}catch(c){return r==="setup"&&c instanceof Error&&c.name==="ExitPromptError"?C0(o.json):c instanceof V?Fi(c,o.json):c instanceof te?EK(c,o.json):P(ne(c),o.json,e)}}function EK(e,t){return S({status:"error",reasonCode:e.code,why:e.code==="canonical_bundle_rejected"?"One or more bundle files failed canonical intake.":"The local bundle could not be collected safely.",issues:e.issues,blockingFindings:e.issues.map(n=>({code:n.code,...n.path?{path:n.path}:{}})),...e.preview?{preview:e.preview}:{},nextAction:"bundle.fix",nextStep:"Correct the listed files and run `skills-layer validate <path>`."},e.code==="canonical_bundle_rejected"?"The local bundle failed canonical intake. Correct the listed files and validate again.":e.message,t,e.code)}function kw(e){let t=e.trim().toLowerCase();return t==="purchase"?`Unknown command "${e}".
|
|
970
|
+
|
|
971
|
+
Did you mean:
|
|
972
|
+
skills-layer buy <skill-slug>
|
|
973
|
+
skills-layer purchases list`:t==="validation"?`Unknown command "${e}".
|
|
974
|
+
|
|
975
|
+
Did you mean:
|
|
976
|
+
skills-layer validate <path>`:t==="details"?`Unknown command "${e}".
|
|
977
|
+
|
|
978
|
+
Did you mean:
|
|
979
|
+
skills-layer show <skill-slug>`:t==="security-report"?`Unknown command "${e}".
|
|
980
|
+
|
|
981
|
+
Did you mean:
|
|
982
|
+
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function AE(e,t){let n=DK(e),r=n?`Run \`skills-layer ${n} --help\` to inspect the closest supported public command.`:"Run `skills-layer --help` to list supported public commands.";return S({status:"error",reasonCode:"unknown_command",command:$t(e),...n?{suggestion:n}:{},nextAction:"help",nextStep:r},`${kw(e)}
|
|
983
|
+
|
|
984
|
+
Next: ${r.replace(/^Run /u,"run ")}`,t,"unknown_command")}function DK(e){let t=e.trim().toLowerCase(),n={purchase:"buy",validation:"validate",details:"show","security-report":"trust"};if(n[t])return n[t];let r=[...lf].filter(s=>!s.includes(" ")).map(s=>({candidate:s,distance:TK(t,s)})).sort((s,a)=>s.distance-a.distance||s.candidate.localeCompare(a.candidate)),i=r[0],o=r[1];return i&&i.distance<=2&&i.distance<(o?.distance??Number.POSITIVE_INFINITY)?i.candidate:void 0}function TK(e,t){let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=1;r<=e.length;r+=1){let i=[r];for(let o=1;o<=t.length;o+=1)i[o]=Math.min((i[o-1]??0)+1,(n[o]??0)+1,(n[o-1]??0)+(e[r-1]===t[o-1]?0:1));n.splice(0,n.length,...i)}return n[t.length]??t.length}function Ai(e,t=!1){let n=t?vb:bb;return`${sb(e)}
|
|
985
|
+
|
|
986
|
+
${n}`}function $K(e){let t=e.indexOf("--");return e.flatMap((n,r)=>{let i=n.indexOf("=");if(t!==-1&&r>t||!n.startsWith("--")||i<3)return[n];let o=n.slice(2,i);return _w.has(o)||bw.has(o)||af.has(o)?[`--${o}`,n.slice(i+1)]:[n]})}function tw(e){let t=$K(e),n={json:t.includes("--json"),help:!1,dryRun:!1,list:!1,all:!1,deep:!1,verbose:!1,showUrl:!1,noOpen:!1,confirmed:!1,allowUnmanagedOnce:!1,discloseSource:!1,shouldTrigger:[],shouldNotTrigger:[],paraphrase:[],grantJson:[],findingCode:[],acceptCapability:[],approvalRequestId:[]},r=[];for(let i=0;i<t.length;i+=1){let o=t[i];if(!o)continue;if(o==="--"){r.push(...t.slice(i+1));break}if(o==="-h"){n.help=!0;continue}if(!o.startsWith("--")){r.push(o);continue}let s=o.slice(2);if(s!=="install"&&!CE.has(s)&&!bw.has(s)&&!_w.has(s)&&!af.has(s))return{flags:n,positionals:r,error:`Unknown flag --${s}.`};if(CE.has(s)){let l=nw(s);s==="confirm"||s==="yes"?n.confirmed=!0:n[l]=!0;continue}let a=t[i+1];if(!a||a.startsWith("--")){if(s==="install"){n.install="";continue}return{flags:n,positionals:r,error:`Flag --${s} requires a value.`}}if(bw.has(s)){let l=LK(t,i);if(!l.value)return{flags:n,positionals:r,error:`Flag --${s} requires a value.`};n[nw(s)]=l.value,i=l.nextIndex;continue}if(_w.has(s)||af.has(s)){let l=nw(s);if(s==="scope"){let c=Array.isArray(n.scopeValues)?n.scopeValues:[];c.push(a),n.scopeValues=c,n.scope=a}else if(af.has(s)){let c=Array.isArray(n[l])?n[l]:[];c.push(a),n[l]=c}else n[l]=a;i+=1;continue}return{flags:n,positionals:r,error:`Unknown flag --${s}.`}}return typeof n.agent=="string"&&n.agent!=="all"&&(n.agent=Hn(n.agent)??n.agent),{flags:n,positionals:r}}function LK(e,t){let n=[],r=t;for(let i=t+1;i<e.length;i+=1){let o=e[i];if(!o||o.startsWith("--"))break;n.push(o),r=i}return{value:n.length>0?n.join(" "):null,nextIndex:r}}function nw(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function wl(e,t){let n=OK(t.env,t.platform),[r,i]=await Promise.all([aJ(n.configPath,t),se(n.backendPreferencePath)]),o=kn(v(e.baseUrl)??ue(t.env.SKILLS_LAYER_BASE_URL)??ue(i?.preferredBaseUrl)??ue(r?.baseUrl)??Zw);try{Zn(o)}catch{throw new V(400,"Invalid backend URL. Use HTTPS, or HTTP for loopback development only.",{reasonCode:"invalid_base_url",baseUrl:o.replace(/(\/\/)[^/]*@/u,"$1<redacted>@"),nextAction:"backend",nextStep:"Use an HTTPS backend URL without credentials, query parameters, or fragments."})}let s=v(e.apiKey)??ue(t.env.SKILLS_LAYER_API_KEY),a=ue(r?.apiKey),l=ue(r?.baseUrl),c=!l||Nl(l,o),u=s??(c?a:void 0),d=!s&&a&&l&&!c?`Your saved login belongs to ${kn(l)}, but the selected backend is ${o}. Run \`skills-layer backend --base-url ${kn(l)}\` to use that login, or run \`skills-layer login\` for ${o}.`:void 0;return{...t,paths:n,config:r,baseUrl:o,apiKey:u,authBlockedMessage:d}}function OK(e,t){let n=t==="win32"?je:ct,r=bP(e,t);return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-preference.json"),installTargetPreferencePath:n.join(r,"install-target-preference.json"),installsPath:n.join(r,"installs.json"),importsPath:n.join(r,"imports.json"),mcpConfigPath:n.join(r,"mcp.json"),mcpPreferencePath:n.join(r,"mcp-preference.json"),pendingRevocationsPath:n.join(r,"pending-revocations.json"),devicePath:n.join(r,"device.json"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function FK(e,t,n){if(e[0]!=="list")return P(`Unknown agents command "${e[0]??""}".`,t.json);let r=await Vr({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:Ke}),i=We(n.env,n.platform,n.cwd).map(o=>({id:o.id,displayName:o.displayName,capabilities:o.capabilities,detected:r.some(s=>s.id===o.id),detectionSources:r.find(s=>s.id===o.id)?.detectionSources??[],projectSkillsPath:o.targets.projectSkillsPath,globalSkillsPath:o.targets.globalSkillsPath}));return R({status:"ok",results:i},`Found ${i.length} supported agent targets.`,t.json,n)}async function BK(e,t,n){let r=e[0],i=v(t.baseUrl);if(!r&&i||r==="cloud"||r==="local"){let l=kn(i??(r==="local"?kK:Zw)),c=e4(l,t);if(c)return c;if(!t.skipProbe){let m=await u_(l,n.fetchFn);if(m!=="ok")return S({status:"error",reasonCode:m,unchanged:!0,nextStep:"Check the backend address, or use --skip-probe for offline configuration."},m==="backend_unreachable"?"Backend could not be reached.":"The address did not identify a Skills Layer API.",t.json,m)}let u=at(l),d=n.config?.baseUrl??null,p=!n.config?.baseUrl||Nl(n.config.baseUrl,l);return await _e(n.paths.backendPreferencePath,{version:Yw,preferredBaseUrl:l,savedAt:n.now()}),R({status:"updated",selectedBackend:u,selectedBaseUrl:l,savedLoginBaseUrl:d,loginMatchesSelectedBackend:p,loggedIn:!!n.apiKey&&p,...p?{}:{warning:`Saved login belongs to ${d}; selected backend is ${l}.`}},p?`Backend set to ${u}.`:`Backend set to ${u}. Saved login is for ${d}.`,t.json,n)}if(r&&r!=="status")return P(`Unknown backend command "${r}".`,t.json);let o=at(n.baseUrl),s=!n.config?.baseUrl||Nl(n.config.baseUrl,n.baseUrl),a=!!n.apiKey&&s;return R({status:"ok",selectedBackend:o,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:s,loggedIn:a,email:a?n.config?.email??null:null,role:a?n.config?.role??null:null,identitySource:"cached_at_login"},`Backend: ${n.baseUrl}. Account details are cached from login; run skills-layer whoami to check current access.`,t.json,n)}var Cf=[{value:"google",label:"Google",description:"Open browser sign-in and return here"},{value:"github",label:"GitHub",description:"Open browser sign-in and return here"},{value:"gitlab",label:"GitLab",description:"Open browser sign-in and return here"}];async function Af(e,t){if(t.nonInteractive||!t.stdoutIsTty)return e;try{let n=await E(t,"/api/v1/identity/social/providers");return Array.isArray(n.providers)?e.filter(r=>!ji(r.value)||n.providers.includes(r.value)):e}catch{return e}}var NK=[...Cf,{value:"email",label:"Continue with email",description:"Sign in or create an account with an emailed one-time code"},{value:"api_key",label:"API key (advanced)",description:"Paste an existing Skills Layer login key"}],MK=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...Cf],jK=[{value:"email",label:"Email code",description:"Verify account ownership with an emailed one-time code"}];async function W0(e,t){let n=v(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",await Af(MK,t))}catch{return P("register requires --method when interactive selection is unavailable. Try `skills-layer register --method email --email you@example.com`, `skills-layer register --method google`, `skills-layer register --method github` or `skills-layer register --method gitlab`.",!1)}let r=Sn("register","method",n,UH,e,"invalid_method");if(r)return r;if(n==="email"){let a=v(e.email);if(!a&&!e.json)try{a=await t.promptText("Enter your email address: ")}catch{return P("register --method email requires --email when interactive prompts are unavailable.",!1)}a=F(a,"register requires --email.");let l=await E(t,"/api/v1/register",{method:"POST",headers:U(),body:JSON.stringify({method:n,email:a})});if(e.json){let u=l.status==="already_registered"?Ww(l):dt({...l,nextCommand:`skills-layer auth verify --email ${a} --code <code> --json`,nextAction:"auth.verify"}),d=l.status==="already_registered"?`${a} is already registered.`:`Registration started for ${a}.`;return R(u,d,e.json,t)}if(l.status==="already_registered")return R(Ww(l),`${a} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let c;try{c=await t.promptText(`Enter the verification code sent to ${a} (check spam/junk folder if missing): `)}catch{return R(dt(l),`Registration started for ${a}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${a} --code <code>\`.`,!1,t)}return await Av(a,c,e,t,`Verified ${a}.`)}if(!ji(n))return P("register --method must be email, google, github, or gitlab.",e.json);let i=Mi(),o=await Iv({flags:e,backend:t,provider:n,mode:"register",credentialHandoff:i});if(Z(o))return o;let s=await E(t,"/api/v1/identity/social/start",{method:"POST",headers:U(),body:JSON.stringify({provider:n,mode:"register",createAccount:e.createAccount===!0,handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})});return await Ef(n,s,i,e,t,"register",void 0,o)}async function J0(e,t){if(e.withMcp&&e.noMcp)return P("login cannot combine --with-mcp and --no-mcp.",e.json);let n=v(e.apiKey);if(n){let l=await El(t,n,{notifyLogin:!0}),c=await ff(e,{...t,config:l,apiKey:n});if(Z(c))return c;let u=await Aw(e,{...t,config:l,apiKey:n});if(Z(u))return u;let d=u.data?.status==="mcp_not_configured";return R(dt(xw({status:d?"partial_success":"verified",...l,loggedIn:!0,...c.data?{workingMode:c.data}:{},...u.data?{mcp:u.data}:{},...d?{warnings:[u.data]}:{}},u.data)),[`Logged in as ${l.email}.`,Yi(l),c.message??"",u.message??""].filter(Boolean).join(" "),e.json,t)}let r=v(e.method);if(!r&&!e.json)try{let l=await t.promptSelect("Choose how to sign in:",await Af(NK,t));r=l==="api_key"?void 0:l}catch{return P("login requires --api-key or --method <email|google|github|gitlab> when interactive selection is unavailable.",!1)}let i=Sn("login","method",r,jH,e,"invalid_method");if(i)return i;if(r){if(r==="email"){let d=v(e.email);!d&&!e.json&&(d=(await t.promptText("Enter your email address: ")).trim()),d=F(d,"login --method email requires --email.");let p=await E(t,"/api/v1/register",{method:"POST",headers:U(),body:JSON.stringify({email:d})}),m=dt({...p,nextAction:"auth.verify",nextCommand:`skills-layer auth verify --email ${d} --code <code> --json`});if(f(p,"emailDelivery")==="failed")return S({...m,status:"email_delivery_failed",reasonCode:"email_delivery_failed",nextAction:"login.retry",nextStep:"Retry email sign-in after the delivery service recovers, or choose a connected social provider."},"The email code could not be delivered. Retry later or choose another sign-in method.",e.json,"email_delivery_failed");if(f(p,"status")==="already_registered")return P("The backend did not prepare an email sign-in code. Retry later or choose another sign-in method.",e.json);if(e.json)return R(m,`Email sign-in started for ${d}.`,!0,t);let g="";try{g=(await t.promptText("Enter the email code if you received one, or press Enter to stop: ")).trim()}catch{return R(m,`Email sign-in started for ${d}. Check your email (including spam/junk folder), then run \`skills-layer auth verify --email ${d} --code <code>\` when the code arrives.`,!1,t)}return g?await Av(d,g,e,t,`Verified ${d}.`):R(m,`Email sign-in started for ${d}. No code was entered, so nothing else was changed. Run \`skills-layer auth verify --email ${d} --code <code>\` when ready.`,!1,t)}if(!ji(r))return P("login --method must be email, google, github, or gitlab.",e.json);let l=Mi(),c=await Iv({flags:e,backend:t,provider:r,mode:"login",credentialHandoff:l});if(Z(c))return c;let u=await E(t,"/api/v1/identity/social/start",{method:"POST",headers:U(),body:JSON.stringify({provider:r,mode:"login",handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});return await Ef(r,u,l,e,t,"login",void 0,c)}if(!e.json)try{n=(await t.promptSecret("Enter your Skills Layer API key: ")).trim()}catch{return P("login requires an API key.",e.json)}if(!n)return P("login requires --api-key or --method <email|google|github|gitlab>.",e.json);let o=await El(t,n,{notifyLogin:!0}),s=await ff(e,{...t,config:o,apiKey:n});if(Z(s))return s;let a=await Aw(e,{...t,config:o,apiKey:n});return Z(a)?a:R(dt(xw({status:"verified",...o,...s.data?{workingMode:s.data}:{},...a.data?{mcp:a.data}:{}},a.data)),[`Logged in as ${o.email}.`,Yi(o),s.message??"",a.message??""].filter(Boolean).join(" "),e.json,t)}async function Y0(e,t){let n=!1,r=!1,i=await se(t.paths.mcpConfigPath),o=await se(`${t.paths.stateDir}/mcp-credential-refs.json`),s=g_({baseUrl:t.config?.baseUrl??t.baseUrl,userId:t.config?.userId},t.now(),i,o),a=ue(t.config?.apiKey),l=kn(ue(t.config?.baseUrl)??t.baseUrl);if(a){try{await E({...t,baseUrl:l,apiKey:a},"/api/v1/me/working-mode",{method:"DELETE",headers:H(a)}),n=!0}catch{n=!1}try{await pp(h=>E({...t,baseUrl:l,apiKey:a},"/api/v1/me/session/revoke",{method:"POST",headers:U(a),body:JSON.stringify(h)}),{includeCurrent:!0,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:s}),r=!0}catch{r=!1}}let c=hP(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),u=await Promise.allSettled([c,UK(t),c.then(()=>Ae(t.paths.configPath,{force:!0}))]),d=u.every(h=>h.status==="fulfilled");if(!d)return S({status:"logout_incomplete",reasonCode:"local_cleanup_incomplete",serverCredentialsRevoked:r,localCleanupComplete:!1,nextAction:"logout",nextStep:"Unlock the OS credential store and retry logout. Local references were retained for cleanup."},"Server revocation was attempted, but local cleanup is incomplete.",e.json,"local_cleanup_incomplete");let p=!!a&&!r,m=p&&(t.config?.userId&&(t.config.sessionCredentialId||s.length))?await $v(t,{baseUrl:l,userId:t.config.userId,humanKeyIds:t.config.sessionCredentialId?[t.config.sessionCredentialId]:[],mcpKeyIds:s,revokeAllMcp:!1,revokeAdminMcp:!1,createdAt:t.now()}):!1,g=!a&&!!t.apiKey;return R({status:a?"logged_out":"not_logged_in",...g?{automationKeyRevoked:!1,reasonCode:"automation_key_not_revoked",nextAction:"api-key.revoke",nextStep:"To revoke the automation key intentionally, run `skills-layer api-key list`, then `skills-layer api-key revoke --key-id <id> --yes`."}:{},serverWorkingModeCleared:n,serverCredentialsRevoked:r,revocationPending:p,...p?{pendingRecorded:m}:{},localCleanupComplete:d,warnings:d?[]:["Some local cleanup failed. Retry logout to finish clearing local state."],mcpAuthCleared:u[1].status==="fulfilled"},p?m?"Logged out locally. Server revocation is pending and will retry after the same account authenticates again.":"Logged out locally, but server revocation could not be recorded. Reconnect promptly; credentials remain bounded by expiry.":r?"Logged out. The saved session and this profile\u2019s MCP credential were revoked.":t.apiKey?"Local state cleared. Automation key was not revoked. To revoke it intentionally, run skills-layer api-key list, then skills-layer api-key revoke --key-id <id> --yes.":"No saved login; local state cleared.",e.json,t)}async function UK(e){let t=await se(e.paths.mcpConfigPath);if(!t){await Cw(null,e),await Ae(e.paths.mcpPreferencePath,{force:!0});return}let n=t?f(t,"baseUrl")??e.baseUrl:e.baseUrl,r=t?f(t,"clientId")??"codex":"codex",i=mo({baseUrl:n,mcpUrl:t?f(t,"mcpUrl")??`${n}/mcp`:`${n}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:t?f(t,"environment")??at(n):at(n),now:e.now(),env:e.env,platform:e.platform,cwd:e.cwd,stateDir:e.paths.stateDir,mcpConfigPath:e.paths.mcpConfigPath,nodePath:process.execPath}),o=t&&Array.isArray(t.clientIds)?t.clientIds.filter(a=>typeof a=="string"):t?[r]:[];if((await Promise.allSettled([Cw(t,e),...i.targets.filter(a=>o.includes(a.agentId)).map(a=>a.disconnect?.()),Cg(i.bridgePath),Ag(i.brokerPath,i.brokerSocketPath,i.brokerLockPath),Ae(e.paths.mcpPreferencePath,{force:!0})])).some(a=>a.status==="rejected"))throw new Error("MCP local cleanup is incomplete; retry logout.");await Ae(e.paths.mcpConfigPath,{force:!0})}async function qK(e,t,n){let r=e[0]??"show";if(r==="show")return await ie("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(r==="update"){let i=await VK(t,n);if(Z(i))return i;let o=await E(n,"/api/v1/profile",{method:"PATCH",headers:U(n.apiKey),body:JSON.stringify(i)});return R(o,"Profile updated.",t.json,n)}return P(`Unknown profile command "${r}".`,t.json)}async function VK(e,t){let n=rt(e,["displayName","bio","company"]);for(let r of["displayName","bio","company"])if(e[`clear${r[0].toUpperCase()}${r.slice(1)}`]){let i=r.replace(/[A-Z]/gu,o=>`-${o.toLowerCase()}`);if(n[r]!==void 0)return S({reasonCode:"conflicting_flags",unchanged:!0},`Choose either --${i} or --clear-${i}.`,e.json,"conflicting_flags");n[r]=null}if(Object.keys(n).length>0)return n;if(e.json)return P("profile update requires at least one of --display-name, --bio, or --company.",!0);try{let r=await t.promptText("Display name (leave blank to keep unchanged): "),i=await t.promptText("Bio (leave blank to keep unchanged): "),o=await t.promptText("Company (leave blank to keep unchanged): "),s=W({displayName:r||void 0,bio:i||void 0,company:o||void 0});return Object.keys(s).length===0?P("No profile changes entered.",!1):s}catch{return P("profile update requires at least one of --display-name, --bio, or --company.",!1)}}async function GK(e,t,n){let r=e[0];if(r==="register")return await W0({...t,method:"email"},n);if(r==="verify"){let i=F(t.email,"auth verify requires --email."),o=F(t.code,"auth verify requires --code.");return await Av(i,o,t,n,`Verified ${i}.`)}return r==="recover"?await HK(e.slice(1),t,n):r==="connect"?await WK(t,n):r==="mfa"?await JK(e.slice(1),t,n):r==="login"?await J0(t,n):r==="logout"?await Y0(t,n):r==="status"?zK(t,n):r==="repair"?await KK(t,n):P(`Unknown auth command "${r??""}".`,t.json)}function zK(e,t){let n=t.config?.baseUrl?kn(t.config.baseUrl):null,r=!!(t.apiKey&&n&&Nl(n,t.baseUrl)),i=r?op(t.config?.sessionExpiresAt,t.now()):null,o=r&&t.config?.email?`Logged in as ${t.config.email}. ${Yi(t.config)}`.trim():t.config?.baseUrl?`Saved login targets ${n}; selected backend is ${t.baseUrl}. Run \`skills-layer auth repair\` or \`skills-layer login\`.`:"Not logged in. Run `skills-layer login`.";return R({status:"auth_status",selectedBackend:at(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:r,requiresLogin:!r||i?.reasonCode==="api_key_expired",...i?{warnings:[i]}:{},...t.config?.email?{savedLogin:{baseUrl:n,email:t.config.email,role:t.config.role??null,roles:t.config.roles??[],savedAt:t.config.savedAt??null,...t.config.credentialStorage?{credentialStorage:t.config.credentialStorage}:{},...t.config.sessionExpiresAt?{sessionExpiresAt:t.config.sessionExpiresAt}:{},matchesSelectedBackend:r}}:{}},i?`${o}
|
|
987
|
+
${i.message}`:o,e.json,t)}async function KK(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return S({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login` to create a saved session, then use `skills-layer auth repair` only if backend/session metadata drifts."},"No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json,"login_required");let n=kn(t.config.baseUrl);return await _e(t.paths.backendPreferencePath,{version:Yw,preferredBaseUrl:n,savedAt:t.now()}),await Vl(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),R({status:"auth_repaired",baseUrl:n,loggedIn:!0,email:t.config.email,role:t.config.role,credentialStorage:t.config.credentialStorage??"local_file_locked"},`Auth repaired for ${t.config.email}. Backend preference now matches ${n}.`,e.json,t)}async function HK(e,t,n){let r=e[0]??v(t.method);if(!r&&!t.json)try{r=await n.promptSelect("Choose how to recover access:",jK)}catch{return P("auth recover requires --method email when interactive selection is unavailable.",!1)}if(r??="email",ji(r))return S({status:"unsupported_auth_journey",reasonCode:"unsupported_auth_journey",provider:r,nextAction:"account.connect.start",nextStep:`Run \`skills-layer auth connect --provider ${r}\` after signing in.`},`Social identities are connected, not used for account recovery. Sign in, then run \`skills-layer auth connect --provider ${r}\`.`,t.json,"unsupported_auth_journey");if(r!=="complete"&&r!=="email")return P("auth recover --method must be email.",t.json);let i=v(t.email);if(r==="complete"){if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return P("auth recover complete requires --email when interactive prompts are unavailable.",!1)}i=F(i,"auth recover complete requires --email.");let l=v(t.code);if(!l&&!t.json)try{l=await n.promptText("Enter the recovery code: ")}catch{return P("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return l=F(l,"auth recover complete requires --code."),await xE(i,l,t,n)}if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return P("auth recover --method email requires --email when interactive prompts are unavailable.",!1)}i=F(i,"auth recover --method email requires --email.");let o=await E(n,"/api/v1/identity/recover/start",{method:"POST",headers:U(),body:JSON.stringify({email:i,method:r})}),s=Ww(o);if(t.json)return R({...s,nextCommand:`skills-layer auth recover complete --email ${i} --code <code>`,nextAction:"auth.recover.complete",nextStep:"Check your email and complete recovery with the emailed code."},"Recovery started.",!0,n);let a="";try{a=(await n.promptText("Enter the recovery code if you received one, or press Enter to stop: ")).trim()}catch{return R(s,`If this email can continue, instructions have been sent. Check your inbox and spam folder. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}return a?await xE(i,a,t,n):R(s,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}async function WK(e,t){let n=v(e.provider);if(!n&&!e.json)try{n=await t.promptSelect("Choose an identity to connect:",await Af(Cf,t))}catch{return P("auth connect requires --provider when interactive selection is unavailable.",!1)}if(n=F(n,"auth connect requires --provider."),!ji(n))return P("auth connect --provider must be google, github, or gitlab.",e.json);if(!t.apiKey||t.authBlockedMessage)return S({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the connection."},"Sign in before connecting another login method.",e.json,"login_required");if((await E(t,"/api/v1/identity/mfa/status",{headers:U(t.apiKey,t.authBlockedMessage)})).enabled!==!0){let l=await Z0(e,t);return Z(l)?l:R(l,"MFA setup is required before connecting a sign-in method. Complete setup in the browser, then run this command again.",e.json,t)}let i=v(e.mfaCode);if(!i&&!e.json)try{i=await t.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return P("auth connect requires MFA verification. Retry with an interactive terminal.",!1)}if(!i||!/^\d{6}$/u.test(i))return P("auth connect requires a 6-digit --mfa-code when interactive prompts are unavailable.",e.json);let o=await E(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:U(t.apiKey,t.authBlockedMessage),body:JSON.stringify({purpose:"identity.connect",code:i})}),s=F(f(o,"stepUpGrant"),"MFA verification did not return a step-up grant."),a=await E(t,"/api/v1/identity/connect/start",{method:"POST",headers:U(t.apiKey,t.authBlockedMessage),body:JSON.stringify({provider:n,stepUpGrant:s})});return await Ef(n,a,void 0,e,t,"connect","/api/v1/identity/connect/status")}async function JK(e,t,n){let r=e[0]??"status";if(!n.apiKey||n.authBlockedMessage)return S({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the MFA command."},"Sign in before managing MFA.",t.json,"login_required");if(r==="status"){let i=await E(n,"/api/v1/identity/mfa/status",{headers:H(n.apiKey,n.authBlockedMessage)}),o=i.enabled===!1?{...i,nextAction:"account.mfa.setup",nextStep:"Protect this account by running `skills-layer auth mfa setup`."}:i;return R(o,"MFA status loaded.",t.json,n)}if(r==="setup"){let i=await Z0(t,n);return Z(i)?i:R(i,"MFA setup started. Complete it in your browser; recovery codes are shown there once.",t.json,n)}if(r==="verify"){let i=F(v(t.purpose),"auth mfa verify requires --purpose."),o=v(t.mfaCode)??v(t.code);if(!o&&!t.json)try{o=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return P("auth mfa verify requires an interactive code or --mfa-code.",!1)}if(!o||!/^\d{6}$/u.test(o))return P("auth mfa verify requires a 6-digit --mfa-code.",t.json);let s=await E(n,"/api/v1/identity/mfa/verify",{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({purpose:i,code:o})});return R(s,`MFA verified for ${i}.`,t.json,n)}if(r==="recovery-codes"){if(v(t.mfaCode)||v(t.code))return P("Do not pass an authenticator code on the command line. Recovery-code regeneration now requires protected browser verification.",t.json);if(t.json)return R({status:"human_action_required",reasonCode:"human_handoff_required",nextAction:"mfa.recovery_codes.browser",nextStep:"Run `skills-layer auth mfa recovery-codes` in an interactive human terminal to open the protected browser flow.",delivery:"browser_only"},"Recovery-code regeneration requires a protected human browser session.",!0,n);let i=await E(n,"/api/v1/identity/mfa/recovery-codes/regenerate",{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})}),o=F(f(i,"recoveryCodesUrl"),"Recovery-code regeneration did not return a secure browser handoff."),s=F(f(i,"operationId"),"Recovery-code regeneration did not return a secure operation identifier.");!t.noOpen&&await n.openUrl(o)||n.emitInfo(`Open this secure recovery-code link in your browser:
|
|
988
|
+
${o}`),n.emitInfo("Waiting for recovery-code verification to finish in your browser...");let l=await UW(s,n);return Z(l)?l:R({status:"regenerated",action:"mfa.recovery_codes.completed",completedAt:f(l,"completedAt"),delivery:"browser_only",nextAction:"store_recovery_codes",nextStep:"Confirm the replacement recovery codes are saved in your password manager or secure offline location."},"Recovery codes were replaced in your browser.",!1,n)}if(r==="disable"){let i="identity.mfa.disable",o=v(t.mfaCode)??v(t.code);if(!o&&!t.json)try{o=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return P(`auth mfa ${r} requires an interactive code or --mfa-code.`,!1)}if(!o||!/^\d{6}$/u.test(o))return P(`auth mfa ${r} requires a 6-digit --mfa-code.`,t.json);let s=await E(n,"/api/v1/identity/mfa/verify",{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({purpose:i,code:o})}),a=F(f(s,"stepUpGrant"),"MFA verification did not return a step-up grant."),l=await E(n,"/api/v1/identity/mfa/disable",{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({stepUpGrant:a})});return R(l,"MFA disabled.",t.json,n)}return P(`Unknown auth mfa command "${r}".`,t.json)}async function Z0(e,t){let n=await E(t,"/api/v1/identity/mfa/setup/start",{method:"POST",headers:U(t.apiKey,t.authBlockedMessage)}),r=F(f(n,"setupUrl"),"MFA setup did not return a browser handoff."),i=e.noOpen||e.json?!1:await t.openUrl(r);return!e.json&&!i&&t.emitInfo(`Open this secure MFA setup link in your browser:
|
|
989
|
+
${r}`),{...n,status:"human_action_required",nextAction:"mfa.setup.browser",nextStep:"Complete authenticator setup in the browser, save the one-time recovery codes, then return to the CLI."}}async function xE(e,t,n,r){let i=Mi(),o=async(l,c)=>E(r,"/api/v1/identity/recover/complete",{method:"POST",headers:U(),body:JSON.stringify({email:e,code:t,...l?{mfaCode:l}:{},...c?{recoveryCode:c}:{},handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})}),s;try{s=await o(v(n.mfaCode),v(n.recoveryCode))}catch(l){if(!(l instanceof V)||l.status!==428)throw l;if(n.json)return S({status:"human_action_required",reasonCode:"recovery_mfa_required",nextAction:"account.recover.verify_mfa",nextStep:"Retry with --mfa-code <6-digits> or --recovery-code <one-time-code>."},"Recovery needs your second factor.",!0,"recovery_mfa_required");let c=await r.promptSelect("Choose your recovery second factor:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one saved one-time recovery code"}]),u=(await r.promptSecret(c==="authenticator"?"Enter the 6-digit authenticator code: ":"Enter one unused recovery code: ")).trim();s=c==="authenticator"?await o(u,void 0):await o(void 0,u)}if(f(s,"status")!=="recovered")return P("Email recovery did not prepare a secure credential handoff. Start recovery again.",n.json);let a=await E(r,"/api/v1/identity/credential-handoff/exchange",{method:"POST",headers:U(),body:await Pv(i,r)});if(f(a,"status")!=="exchanged"||!f(a,"email")||!f(a,"role")||!f(a,"apiKey"))return P("Email recovery credential handoff failed closed. Start recovery again.",n.json);if(n.json){let l=f(a,"apiKey");return l?(await El(r,l,{expectedEmail:e,knownEmail:f(a,"email")??e,knownRole:f(a,"role")??"user",knownRoles:rn(a,"roles"),knownUserId:f(a,"userId"),knownSessionCredentialId:f(a,"id")}),R(dt({...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions,loggedIn:!0}),`Recovery complete. Sensitive actions are held until ${String(s.holdUntil)}.`,!0,r)):R(dt({...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions,email:e,loggedIn:!1}),`Recovery complete. Sensitive actions are held until ${String(s.holdUntil)}.`,!0,r)}return await xv(e,{...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions},n,r,`Recovered access for ${e}. Sensitive actions are held until ${String(s.holdUntil)}.`)}async function YK(e,t,n){let r=e[0],i=1;if(r==="providers")return await ie("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(r==="start"){let o=v(t.provider);if(!o&&!t.json)try{o=await n.promptSelect("Choose identity provider:",await Af(Cf,n))}catch{return P("identity start requires --provider when interactive selection is unavailable.",!1)}if(o=F(o,"identity start requires --provider."),!ji(o))return P("identity start --provider must be google, github, or gitlab.",t.json);let s=v(t.mode)??"login";if(s!=="login"&&s!=="register")return S({status:"dedicated_auth_journey_required",reasonCode:"dedicated_auth_journey_required",nextStep:s==="recovery"?"Run `skills-layer auth recover`.":"Run `skills-layer auth connect --provider <provider>`."},"Use the dedicated recover or connect command for this account journey.",t.json,"dedicated_auth_journey_required");let a=Mi(),l=await Iv({flags:t,backend:n,provider:o,mode:s,credentialHandoff:a});if(Z(l))return l;let c=await E(n,"/api/v1/identity/social/start",{method:"POST",headers:U(n.apiKey),body:JSON.stringify({provider:o,mode:s,handoffCodeHash:a.authorizationCodeHash,handoffCodeChallenge:a.codeChallenge})});return await Ef(o,c,a,t,n,s,void 0,l)}if(r==="status"){let o=v(t.state)??e[i];return o?await ie(`/api/v1/identity/social/status/${encodeURIComponent(o)}`,t,n,"Social auth status loaded."):P("identity status requires --state.",t.json)}if(r==="continue"){let o=v(t.reference)??e[i];return await ZK(o,t,n)}if(r==="complete"){let o=F(t.provider,"identity complete requires --provider."),s=F(t.state,"identity complete requires --state."),a=F(t.code,"identity complete requires --code."),l=await E(n,"/api/v1/identity/social/complete",{method:"POST",headers:U(n.apiKey),body:JSON.stringify({provider:o,state:s,code:a})});return R(dt(l),"Social auth complete.",t.json,n)}if(r==="list")return await ie("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(r==="unlink"){let o=F(t.provider??e[i],"identity unlink requires a provider."),s=l=>E(n,`/api/v1/me/linked-identities/${encodeURIComponent(o)}`,{method:"DELETE",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({mfaCode:l})}),a;try{a=await s(v(t.mfaCode))}catch(l){if(!(l instanceof V)||l.details?.reasonCode!=="mfa_step_up_required"||t.json||n.nonInteractive||v(t.mfaCode))throw l;a=await s((await n.promptSecret("Enter a fresh authenticator code to unlink this identity: ")).trim())}return R(a,"Identity unlinked.",t.json,n)}return P(`Unknown identity command "${r??""}".`,t.json)}async function ZK(e,t,n){let r=F(e,"identity continue requires --reference <reference>.");if(!/^social_[A-Za-z0-9_-]{20,80}$/u.test(r)||!n.credentialStore)return Pi(t,n);let i=`skills-layer-social-continuation:${r}`,o;try{o=await n.credentialStore.get(ge,i)}catch{o=null}let s=XK(o,r,n.baseUrl);if(!s)return await n.credentialStore.delete(ge,i).catch(()=>{}),Pi(t,n);if(Date.parse(n.now())>=Date.parse(s.expiresAt))return await n.credentialStore.delete(ge,i).catch(()=>{}),Pi(t,n);let a=await E(n,`/api/v1/identity/social/status/${encodeURIComponent(s.state)}`),l=f(a,"status");if(l==="pending")return R({status:"already_processing",reasonCode:"social_auth_pending",reference:r,expiresAt:s.expiresAt,nextAction:"identity.continue",nextStep:`Complete browser sign-in, then rerun \`skills-layer identity continue --reference ${r}\`.`},"Browser sign-in is still pending.",t.json,n);if(l==="mfa_required"){let c=v(t.mfaCode),u=v(t.recoveryCode);if(!c&&!u&&!t.json&&!n.nonInteractive&&n.stdoutIsTty){let p=await n.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),m=(await n.promptSecret(p==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();p==="recovery_code"?u=m:c=m}if(!c&&!u)return S({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],reference:r,nextAction:"identity.continue",nextStep:`Run \`skills-layer identity continue --reference ${r} --mfa-code <6-digits>\` in a human-controlled terminal.`},"MFA is required to finish the social login.",t.json,"login_mfa_required");let d=await E(n,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:U(),body:JSON.stringify({state:s.state,authorizationCode:s.authorizationCode,codeVerifier:s.codeVerifier,...c?{mfaCode:c}:{},...u?{recoveryCode:u}:{}})});if(f(d,"status")!=="verified"||f(d,"credentialHandoff")!=="ready")return P("MFA verification did not authorize the stored login.",t.json)}else if(l!=="verified"&&l!=="recovered")return await n.credentialStore.delete(ge,i).catch(()=>{}),S({status:l??"failed",reasonCode:"social_continuation_terminal",unchanged:!0,nextAction:"login",nextStep:"Start a fresh social login."},"The social login cannot be continued.",t.json,"social_continuation_terminal");try{return await uf(ET(s.provider),{authorizationCode:s.authorizationCode,codeVerifier:s.codeVerifier,authorizationCodeHash:s.authorizationCodeHash,codeChallenge:s.codeChallenge},t,n,s.mode)}finally{await n.credentialStore.delete(ge,i).catch(()=>{})}}function XK(e,t,n){if(!e)return null;try{let r=JSON.parse(e),i=f(r,"provider"),o=f(r,"mode"),s=f(r,"state"),a=f(r,"expiresAt"),l=f(r,"authorizationCode"),c=f(r,"codeVerifier"),u=f(r,"authorizationCodeHash"),d=f(r,"codeChallenge"),p=f(r,"integrityDigest"),m=f(r,"createdAt")??"";return r.version!==1||f(r,"reference")!==t||f(r,"baseUrl")!==n||!i||!ji(i)||o!=="login"&&o!=="register"||!s||!a||!Number.isFinite(Date.parse(a))||!l?.startsWith("social_handoff_")||!c||!u||!d||!p||me("sha256").update(l).digest("base64url")!==u||me("sha256").update(c).digest("base64url")!==d||Rv({version:1,reference:t,baseUrl:n,provider:i,mode:o,authorizationCode:l,codeVerifier:c,authorizationCodeHash:u,codeChallenge:d,createdAt:m,state:s,expiresAt:a})!==p?null:{version:1,reference:t,baseUrl:n,provider:i,mode:o,authorizationCode:l,codeVerifier:c,authorizationCodeHash:u,codeChallenge:d,integrityDigest:p,createdAt:m,state:s,expiresAt:a}}catch{return null}}async function QK(e,t,n){let r=e[0];if(!r)return P("api-key requires create, list, or revoke.",t.json);if(r==="list"){let i=eH(t);if(i.failure)return i.failure;let o=await E(n,"/api/v1/me/api-keys",{headers:H(n.apiKey,n.authBlockedMessage)}),s=ag((await se(n.paths.devicePath))?.deviceId),a=nH(X0(o),i.filters,Date.parse(n.now())).map(l=>tH(l,s,t.json)).map(l=>t.json||!Array.isArray(l.agentHosts)||l.agentHosts.length===0?l:{...l,device:`${String(l.device??"unknown device")} (serves ${[...l.agentHosts].map(String).sort().join(", ")})`});return R({...o,filters:W({...i.filters}),results:a},"API keys loaded.",t.json,n)}if(r==="create"){let i=v(t.name),o=gJ(Array.isArray(t.scopeValues)&&t.scopeValues.length>1?t.scopeValues:t.scope);if(!i)return P("api-key create requires --name.",t.json);if(o.length===0)return P("api-key create requires at least one --scope.",t.json);let s=o.find(p=>!NE.includes(p));if(s)return Un("api-key.create","scope",s,NE,t,"invalid_scope");let a=n4("api-key.create",t.expires,t);if(a)return a;if(t.dryRun){let p=await E(n,"/api/v1/me/api-keys",{method:"POST",headers:U(n.apiKey),body:JSON.stringify({name:i,scopes:o,expiresIn:v(t.expires),dryRun:!0})});return R(p,"API key create dry run passed.",t.json,n)}if(!t.json&&!n.stdoutIsTty){let p=`skills-layer api-key create --name ${JSON.stringify(i)} --scope ${o.join(",")}${v(t.expires)?` --expires ${v(t.expires)}`:""} --json`;return S({status:"blocked",reasonCode:"one_time_key_terminal_required",nextAction:"api-key.create",nextStep:`Run \`${p}\` to receive the key only in data.apiKey, or run the command in an interactive terminal.`},"One-time key delivery needs an interactive terminal. No key was created.",!1,"one_time_key_terminal_required")}let l=Mi(),c=await E(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...H(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:i,scopes:o,...v(t.expires)?{expiresIn:v(t.expires)}:{},handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});if(f(c,"credentialHandoff")!=="ready")return P("API key creation did not prepare a secure credential handoff.",t.json);let u=await E(n,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:U(n.apiKey),body:JSON.stringify({authorizationCode:l.authorizationCode,codeVerifier:l.codeVerifier})}),d=f(u,"apiKey");return f(u,"status")!=="exchanged"||!d?P("API key credential exchange failed closed; prepare the key again.",t.json):Nv(R({...u,secretReturned:!0,secretDelivery:"one_time_client_bound_exchange"},"Automation API key created. Store the separately displayed one-time key securely. Run `skills-layer api-key list` to manage keys.",t.json,n),d,t.json)}if(r==="rotate")return P(`api-key rotate is not part of normal login.
|
|
990
|
+
|
|
991
|
+
For CLI access:
|
|
992
|
+
skills-layer login
|
|
993
|
+
|
|
994
|
+
For automation:
|
|
995
|
+
skills-layer api-key create --name "<name>" --scope <scope> --expires <duration>
|
|
996
|
+
|
|
997
|
+
To remove an old key:
|
|
998
|
+
skills-layer api-key list
|
|
999
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json);if(r==="revoke"){let i=t.keyId??e[1];if(!i)return S({status:"error",reasonCode:"missing_required_argument",command:"api-key revoke",argument:"key-id",nextAction:"api-key.list",nextStep:"Run `skills-layer api-key list`, then revoke a key with `skills-layer api-key revoke --key-id <key-id>`."},`api-key revoke needs a key id.
|
|
1000
|
+
|
|
1001
|
+
Run:
|
|
1002
|
+
skills-layer api-key list
|
|
1003
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json,"missing_required_argument");let o=String(i);if(t.dryRun){let a=await PE(o,n);return a?R(W({status:"pass",wouldRevoke:!0,keyId:o,keyPrefix:f(a,"keyPrefix"),type:f(a,"type"),name:f(a,"name"),scopes:rn(a,"scopes")??[],revokedAt:a.revokedAt??null,nextAction:"api-key.revoke",nextStep:`Run \`skills-layer api-key revoke --key-id ${o} --yes\` to revoke this key.`}),"API key revoke dry run passed.",t.json,n):EE(o,t)}if(!t.confirmed){let a=await PE(o,n);if(!a)return EE(o,t);let l=W({status:"confirmation_required",reasonCode:"confirmation_required",keyId:o,keyPrefix:f(a,"keyPrefix"),type:f(a,"type"),name:f(a,"name"),nextAction:"api-key.revoke",nextStep:`Re-run with \`skills-layer api-key revoke --key-id ${o} --yes\` after confirming this is the key to revoke.`});if(t.json||!n.stdoutIsTty)return S(l,"API key revoke needs confirmation. Re-run with --yes after checking the key id.",t.json,"confirmation_required");if(await n.promptSelect(`Revoke API key ${o}?`,[{value:"cancel",label:"Cancel",description:"Leave this API key active"},{value:"confirm",label:"Revoke",description:"Permanently revoke this API key"}])!=="confirm")return R({status:"canceled",keyId:o},"API key revoke canceled.",t.json,n)}let s=await E(n,`/api/v1/me/api-keys/${encodeURIComponent(o)}/revoke`,{method:"POST",headers:H(n.apiKey,n.authBlockedMessage)});return R(s,s.status==="already_revoked"?"API key was already revoked.":"API key revoked.",t.json,n)}return P(`Unknown api-key command "${r}".`,t.json)}function eH(e){let t=v(e.type);if(t&&!ME.includes(t))return{failure:Un("api-key.list","type",t,ME,e,"invalid_api_key_filter","type")};let n=v(e.status)??"active";if(!jE.includes(n))return{failure:Un("api-key.list","status",n,jE,e,"invalid_api_key_filter","status")};let r=v(e.sort)??"created-desc";if(!UE.includes(r))return{failure:Un("api-key.list","sort",r,UE,e,"invalid_api_key_filter","sort")};let i=[["createdAfter","created-after",e.createdAfter],["createdBefore","created-before",e.createdBefore],["expiresAfter","expires-after",e.expiresAfter],["expiresBefore","expires-before",e.expiresBefore]],o={status:n,sort:r};for(let[s,a,l]of i){let c=v(l);if(c){if(Number.isNaN(Date.parse(c)))return{failure:S({status:"error",reasonCode:"invalid_api_key_filter",field:a,value:c,nextAction:"api-key.list",nextStep:`Use --${a} with an ISO date or timestamp.`},`Invalid api-key list --${a} "${c}". Use an ISO date or timestamp.`,e.json,"invalid_api_key_filter")};o[s]=c}}return{filters:W({...o,...t?{type:t}:{},...v(e.name)?{name:v(e.name)}:{}})}}function IE(e){return`This device's MCP key serves: ${[...e].sort().join(", ")}.`}function tH(e,t,n){return!(t!==void 0&&f(e,"deviceId")===t)&&e.current!==!0?e:{...e,thisDevice:!0,...n?{}:{device:e.device===void 0?"This device":`${String(e.device)} (this device)`}}}function X0(e){return(he(e,"results")??[]).filter(t=>O(t))}function nH(e,t,n){let r=t.name?.toLowerCase();return e.filter(i=>!t.type||f(i,"type")===t.type).filter(i=>t.status==="all"||rH(i,n)===t.status).filter(i=>!r||(f(i,"name")??f(i,"id")??"").toLowerCase().includes(r)).filter(i=>Xd(i,"createdAt",t.createdAfter,"after")).filter(i=>Xd(i,"createdAt",t.createdBefore,"before")).filter(i=>Xd(i,"expiresAt",t.expiresAfter,"after")).filter(i=>Xd(i,"expiresAt",t.expiresBefore,"before")).sort((i,o)=>iH(i,o,t.sort))}function rH(e,t=Date.now()){if(e.revokedAt!==null&&e.revokedAt!==void 0)return"revoked";let n=f(e,"expiresAt");if(!n)return"active";let r=Date.parse(n);return Number.isNaN(r)||r>t?"active":"expired"}function Xd(e,t,n,r){if(!n)return!0;let i=f(e,t);if(!i)return!1;let o=Date.parse(i),s=Date.parse(n);return Number.isNaN(o)||Number.isNaN(s)?!1:r==="after"?o>=s:o<=s}function iH(e,t,n){if(n==="name-asc"||n==="name-desc")return(n==="name-asc"?1:-1)*(f(e,"name")??f(e,"id")??"").localeCompare(f(t,"name")??f(t,"id")??"");let r=n.endsWith("-asc")?1:-1,i=n.startsWith("expires-")?"expiresAt":n.startsWith("last-used-")?"lastUsedAt":"createdAt";return r*(RE(e,i)-RE(t,i))}function RE(e,t){let n=f(e,t);if(!n)return 0;let r=Date.parse(n);return Number.isNaN(r)?0:r}async function PE(e,t){let n=await E(t,"/api/v1/me/api-keys",{headers:H(t.apiKey,t.authBlockedMessage)});return X0(n).find(r=>f(r,"id")===e)}function EE(e,t){return S({status:"not_found",reasonCode:"api_key_not_found",keyId:e,nextAction:"api-key.list",nextStep:"Run `skills-layer api-key list` to find an active key id, then retry revoke."},`API key ${e} was not found.`,t.json,"api_key_not_found")}async function oH(e,t,n){let r=e[0]??"status";if(r==="migrate")return await sH(t,n);if(r==="setup"||r==="repair"){let i=await se(n.paths.mcpConfigPath);if(i&&f(i,"brokerIntegrityProfile")==="extended_v1"){let a=f(i,"clientId")??"codex";return S({status:"unchanged",reasonCode:"mcp_extended_broker_requires_private_cli",nextAction:"mcp.repair.private",nextStep:`Run \`npm run skills-layer -- mcp repair --client ${a}\` from the private checkout.`},"This MCP broker is managed by the private checkout and was left unchanged.",t.json,"mcp_extended_broker_requires_private_cli")}let o=v(t.client);if(o&&t.all)return S({status:"error",reasonCode:"conflicting_mcp_client_selection",client:o,all:!0,nextAction:`mcp.${r}`,nextStep:"Use either --client <agent-id> for one agent or --all for every detected MCP-capable agent."},`mcp ${r} cannot use --client and --all together.`,t.json,"conflicting_mcp_client_selection");if(o&&!CH(o))return rw(o,t);if(o){let a=await se(n.paths.mcpConfigPath),l=a?f(a,"baseUrl")??n.baseUrl:n.baseUrl,c=await ri({baseUrl:l,mcpUrl:a?f(a,"mcpUrl")??`${l}/mcp`:`${l}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:nt(o),environment:a?f(a,"environment")??at(l):at(l),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a});if(c.target.status==="skills_only"){let u=Qd(c);return R(u,`${c.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}let s=await Xw(t,n);return Z(s)?s:R({...s},`MCP configuration written for ${s.clientIds.join(", ")}. Open a fresh agent session, then verify each host: ${s.clientIds.map(a=>`skills-layer mcp verify --client ${a}`).join("; ")}.`,t.json,n)}if(r==="status"||r==="verify"){let i=v(t.client),o=i?nt(i):null;if(i&&!o)return rw(i,t);let s=await Df(n),a=s.config;if(!a){if(o){let m=await ri({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:o,environment:at(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:null});if(m.target.status==="skills_only"){let g=Qd(m);return R(g,`${m.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}return R(s.publicState,s.summary,t.json,n)}let l=Array.isArray(a.clientIds)?a.clientIds.filter(m=>typeof m=="string"&&nt(m)!==null):f(a,"clientId")?[f(a,"clientId")]:[];if(!o&&l.length>1){let m=f(a,"baseUrl")??n.baseUrl,g=[];for(let b of l){let _=await ri({baseUrl:m,mcpUrl:f(a,"mcpUrl")??`${m}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:b,environment:f(a,"environment")??at(m),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a}),I=r==="verify"&&_.configured?await bg({nodePath:f(a,"nodePath")??process.execPath,bridgePath:_.bridge.path,clientId:b}):_.liveProbe;g.push({..._,liveProbe:I,verified:r==="verify"?I.status==="ok":void 0})}let h=g.every(b=>b.configured),y=r==="verify"?g.every(b=>b.verified===!0):void 0,w={status:r==="verify"&&!y?"mcp_needs_repair":h?"mcp_configured":"mcp_needs_repair",configured:h,verified:y,clientIds:l,agentHosts:[...l].sort(),clients:g,sharedBroker:{path:f(a,"brokerPath"),socketPath:f(a,"brokerSocketPath")},nextAction:r==="verify"?"mcp.repair":"mcp.verify"};return r==="verify"&&!y?S(w,"One or more configured MCP hosts failed verification.",t.json,"mcp_multi_client_verify_failed"):R(w,`MCP ${r} completed for ${l.length} configured hosts. ${IE(l)}`,t.json,n)}if(!o&&l.length===0)return S({status:"mcp_needs_repair",reasonCode:"mcp_client_inventory_missing",configured:!1,nextAction:"mcp.repair",nextStep:"Run `skills-layer mcp repair --client <host-id>` or `skills-layer mcp repair --all`."},"The MCP config has no canonical host inventory and was not assigned to Codex implicitly.",t.json,"mcp_client_inventory_missing");let c=o??f(a,"clientId")??(Array.isArray(a.clientIds)&&typeof a.clientIds[0]=="string"?a.clientIds[0]:"codex"),u=f(a,"baseUrl")??n.baseUrl,d=await ri({baseUrl:u,mcpUrl:f(a,"mcpUrl")??`${u}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:f(a,"environment")??at(u),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a});if(d.target.status==="skills_only"){let m=Qd(d);return R(m,`${d.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}if(d.status==="mcp_extension_verification_required")return r==="verify"?S({...d,nextAction:"mcp.verify.private",nextStep:`Run \`${d.nextCommand}\` from the private checkout.`},`MCP for ${d.clientId} uses a broker managed by the private checkout. Verify it there; the public CLI left it unchanged.`,t.json,"mcp_extended_broker_requires_private_cli"):R({...d,nextAction:"mcp.verify.private",nextStep:`Run \`${d.nextCommand}\` from the private checkout.`},`MCP for ${d.clientId} uses a broker managed by the private checkout. Run \`${d.nextCommand}\` for its authoritative integrity and live check.`,t.json,n);if(r==="verify"&&d.configured){if(Array.isArray(a.clientIds)&&!a.clientIds.includes(c))return S({...d,verified:!1,reasonCode:"mcp_client_not_configured",nextAction:"mcp.setup",nextStep:`Run \`skills-layer mcp setup --client ${c}\` to add ${c} to Skills Layer MCP, then run \`skills-layer mcp verify --client ${c}\`.`},`${c} is not set up for Skills Layer MCP on this device. Run skills-layer mcp setup --client ${c}.`,t.json,"mcp_client_not_configured");let m=await bg({nodePath:f(a,"nodePath")??process.execPath,bridgePath:d.bridge.path,clientId:c}),g={...d,verified:m.status==="ok",liveProbe:m};if(m.status!=="ok")return S({...g,nextAction:"mcp.verify",nextStep:`Run \`skills-layer mcp verify --client ${d.clientId}\` again after checking local broker and network availability.`},`MCP config exists for ${d.clientId}, but live bridge verification failed: ${m.message}`,t.json,m.reasonCode??void 0);let h=[...l].sort();return R({...g,agentHosts:h,nextAction:"agent.restart",nextStep:"Open a fresh agent session or restart the agent so it reloads the verified Skills Layer MCP connection."},`MCP verified for ${d.clientId}. ${m.message} ${IE(h)} Open a fresh agent session or restart the agent if tools are not visible yet.`,t.json,n)}let p=d.configured?{...d,nextAction:"mcp.verify",nextStep:`Run \`skills-layer mcp verify --client ${d.clientId}\` for a live tools/list check.`}:{...d,nextAction:"mcp.repair",nextStep:`Run \`${d.nextCommand}\`, then verify again.`};return R(p,d.configured?`MCP configuration is present for ${d.clientId}. Open a fresh agent session if tools are not visible, or run \`skills-layer mcp verify --client ${d.clientId}\` for a live check.`:`MCP needs repair for ${d.clientId}. Run \`${d.nextCommand}\`.`,t.json,n)}if(r==="disconnect"||r==="logout"){let i=await se(n.paths.mcpConfigPath),o=v(t.client),s=o?nt(o):null;if(o&&!s)return rw(o,t);let a=i&&Array.isArray(i.clientIds)?i.clientIds.filter(I=>typeof I=="string"):i&&f(i,"clientId")?[f(i,"clientId")]:[];if(!s&&a.length===0)return R({status:"mcp_not_configured",configured:!1,clientIds:[]},"MCP is not configured on this machine.",t.json,n);if(!s&&!t.all&&a.length>1)return S({status:"needs_mcp_client_scope",reasonCode:"mcp_client_scope_required",configuredClientIds:a,nextAction:`mcp.${r}`,nextStep:`Run \`skills-layer mcp ${r} --client <host-id>\` or add \`--all\`.`},`MCP ${r} requires --client or --all because multiple hosts are configured.`,t.json,"mcp_client_scope_required");let l=t.all?a:[s??a[0]],c=l[0],u=i?f(i,"baseUrl")??n.baseUrl:n.baseUrl,d=await ri({baseUrl:u,mcpUrl:i?f(i,"mcpUrl")??`${u}/mcp`:`${u}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:i?f(i,"environment")??at(u):at(u),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:i});if(d.target.status==="skills_only"){let I=Qd(d);return R(I,`${d.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}let p=mo({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:at(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath}),m=p.targets.filter(I=>l.includes(I.agentId)),g=a.filter(I=>!l.includes(I)),h=g.length>0,y=!1,w=i?f(i,"keyId"):void 0;if(!h&&n.apiKey&&(!i||w))try{await E(n,"/api/v1/me/session/revoke",{method:"POST",headers:U(n.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:w?[w]:[]})}),y=!0}catch{y=!1}for(let I of m)await I.disconnect?.();h&&i?await _e(n.paths.mcpConfigPath,{...i,clientId:g[0],clientIds:g,savedAt:n.now()}):(await Cw(i,n),await Cg(p.bridgePath),await Ag(p.brokerPath,p.brokerSocketPath,p.brokerLockPath),await Ae(n.paths.mcpConfigPath,{force:!0}),await Ae(n.paths.mcpPreferencePath,{force:!0}));let b=!h&&!!(n.apiKey&&i)&&!y,_=b&&(n.config?.userId&&w)?await $v(n,{baseUrl:u,userId:n.config.userId,humanKeyIds:[],mcpKeyIds:[w],revokeAllMcp:!1,revokeAdminMcp:!0,createdAt:n.now()}):!1;return R({status:b?"mcp_revocation_pending":"mcp_disconnected",configured:h,clientId:c,clientIds:l,remainingClientIds:g,serverCredentialsRevoked:y,revocationPending:b,pendingRecorded:_},b?_?"MCP disconnected locally. Server revocation is pending and will retry after this account authenticates again.":"MCP disconnected locally, but server revocation could not be recorded. Reconnect promptly; the machine credential remains bounded by expiry.":"MCP disconnected and its server credential was revoked.",t.json,n)}return P(`Unknown mcp command "${r}". Use setup, status, verify, repair, migrate, or disconnect.`,t.json)}async function sH(e,t){if(e.dryRun&&e.apply)return S({status:"error",reasonCode:"conflicting_mcp_migration_mode",nextAction:"mcp.migrate",nextStep:"Use --dry-run to preview or --apply to remove verified owned entries, but not both."},"Legacy MCP migration cannot use --dry-run and --apply together.",e.json,"conflicting_mcp_migration_mode");let n=v(e.path);if(!n)return S({status:"error",reasonCode:"mcp_legacy_project_path_required",nextAction:"mcp.migrate",nextStep:"Run `skills-layer mcp migrate --path <project-root> --dry-run --json`."},"Legacy MCP migration requires an explicit project root.",e.json,"mcp_legacy_project_path_required");let r=Gn(t.cwd,n),i=await cA({projectRoot:r,stateDir:t.paths.stateDir,nodePath:process.execPath}),o=await se(t.paths.mcpConfigPath),s=o&&Array.isArray(o.clientIds)?o.clientIds.filter(c=>typeof c=="string"&&nt(c)!==null):o&&f(o,"clientId")&&nt(f(o,"clientId"))?[f(o,"clientId")]:[],a=[];for(let c of s){let u=nt(c);if(!u||!o)continue;let d=f(o,"baseUrl")??t.baseUrl;(await ri({baseUrl:d,mcpUrl:f(o,"mcpUrl")??`${d}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:u,environment:f(o,"environment")??at(d),now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:o})).configured&&a.push(u)}let l=await uA({discovery:i,verifiedGlobalHostIds:a,apply:!!e.apply});return l.plannedPaths.length===0?R({status:"mcp_legacy_migration_not_required",projectRoot:r,discovery:i,...l,nextAction:"none",nextStep:"No legacy project MCP registration requires migration."},"No legacy project MCP registration requires migration.",e.json,t):R({status:e.apply?"mcp_legacy_migration_applied":"mcp_legacy_migration_dry_run",projectRoot:r,discovery:i,...l,nextAction:e.apply?"mcp.status":"mcp.migrate",nextStep:e.apply?"Run `skills-layer mcp status --json` and restart affected hosts.":"Verify the replacement global registration, then rerun with `--apply`."},e.apply?`Removed ${l.cleanedPaths.length} verified legacy project registration(s).`:`Legacy MCP migration dry-run found ${l.plannedPaths.length} removable registration(s).`,e.json,t)}async function aH(e,t,n){let r=e[0];if(!r)return S({status:"error",reasonCode:"missing_required_argument",command:"enterprise",argument:"command",nextAction:"enterprise.help",nextStep:"Run `skills-layer enterprise --help` to see available commands."},"enterprise requires a command. Run `skills-layer enterprise --help` to see available commands.",t.json,"missing_required_argument");if(r==="list"){let i;try{i=await E(n,"/api/v1/me/enterprises",{headers:H(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof V&&o.status===404)return S({status:"not_supported",reasonCode:"enterprise_list_not_supported",nextAction:"operator.deploy",nextStep:"Ask an operator to deploy the current Enterprise API, then retry skills-layer enterprise list."},"This backend does not support Enterprise membership listing.",t.json,"enterprise_list_not_supported");throw o}return Rt(i,uH(i,n),"Enterprise memberships loaded.",t.json,n)}if(r==="checkout"){let i=VE(t.seats,"--seats","seats","enterprise checkout",t,{minimum:2});if(Z(i))return i;let o=F(t.enterpriseName??t.name,"enterprise checkout requires --enterprise-name <name>."),s=F(t.workspaceName??t.workspace,"enterprise checkout requires --workspace-name <name>."),a=wH(),l=await E(n,"/api/v1/enterprise/checkout",{method:"POST",headers:{...U(n.apiKey,n.authBlockedMessage),"idempotency-key":a},body:JSON.stringify({seatCount:i,enterpriseName:o,firstWorkspaceName:s,creationIntentId:a,createNewEnterprise:t.newEnterprise===!0})});return f(l,"status")==="enterprise_exists"?Rt(l,cH(l,n),"Existing Enterprise found.",t.json,n):await Sw(l,t,n,"Enterprise checkout prepared.","Opening Enterprise checkout. Complete payment in your browser, then come back here.",{kind:"enterprise",statusPathForCheckoutId:c=>`/api/v1/enterprise/checkout/${encodeURIComponent(c)}`,waitingMessage:"Waiting for Enterprise checkout completion...",completedMessage:"Enterprise checkout completed."})}if(r==="rename"){let i=F(e[1],"enterprise rename requires <enterprise-id>."),o=F(t.enterpriseName??t.name??e[2],"enterprise rename requires --name <enterprise-name>.");return await Ei(`/api/v1/enterprises/${encodeURIComponent(i)}`,{name:o},t,n,"Enterprise updated.")}if(r==="primary-admin"){let i=F(e[1],"enterprise primary-admin requires transfer, status, accept, or cancel.");if(i==="transfer"){let a=F(e[2],"enterprise primary-admin transfer requires <enterprise-id>."),l=F(e[3],"enterprise primary-admin transfer requires <target-user-id>.");return await pe(`/api/v1/enterprises/${encodeURIComponent(a)}/primary-admin-transfers`,{targetUserId:l,outgoingAction:t.leaveEnterprise===!0?"leave_enterprise":"remain_admin"},t,n,"Primary Admin transfer started.")}let o=F(e[2],`enterprise primary-admin ${i} requires <transfer-id>.`),s=`/api/v1/enterprise/primary-admin-transfers/${encodeURIComponent(o)}`;return i==="status"?await ie(s,t,n,"Primary Admin transfer loaded.",{authenticated:!0}):i==="accept"?await pe(`${s}/accept`,{},t,n,"Primary Admin responsibility transferred."):i==="cancel"?await pe(`${s}/cancel`,{},t,n,"Primary Admin transfer cancelled."):P(`Unknown enterprise primary-admin command "${i}". Use transfer, status, accept, or cancel.`,t.json)}if(r==="seats"){if(e[1]&&e[1]!=="add")return P(`Unknown enterprise seats command "${e[1]}".`,t.json);if(e[1]==="add"){let o=F(e[2],"enterprise seats add requires <enterprise-id>."),s=VE(t.seats,"--seats","seats","enterprise seats add",t,{minimum:1});if(Z(s))return s;let a=await E(n,"/api/v1/enterprise/seats/add",{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({enterpriseId:o,additionalSeats:s})});return await Sw(a,t,n,"Enterprise seat checkout prepared.",`Opening checkout for ${s} additional Enterprise seat${s===1?"":"s"}. Complete payment in your browser, then come back here.`,{kind:"enterprise_seats",statusPathForCheckoutId:l=>`/api/v1/enterprise/seats/checkout/${encodeURIComponent(l)}`,waitingMessage:"Waiting for Enterprise seat checkout completion...",completedMessage:"Enterprise seats added."})}let i=await E(n,"/api/v1/enterprise/seats",{headers:H(n.apiKey,n.authBlockedMessage)});return Rt(i,hH(i,n),"Enterprise seats loaded.",t.json,n)}if(r==="members"){let i=F(e[1],"enterprise members requires <enterprise-id>."),o=await E(n,`/api/v1/enterprises/${encodeURIComponent(i)}/members`,{headers:H(n.apiKey,n.authBlockedMessage)});return Rt(o,dH(o,n),"Enterprise members loaded.",t.json,n)}if(r==="invites"){let i=F(e[1],"enterprise invites requires <enterprise-id>."),o=await E(n,`/api/v1/enterprises/${encodeURIComponent(i)}/invites`,{headers:H(n.apiKey,n.authBlockedMessage)});return Rt(o,fH(o,n),"Enterprise invites loaded.",t.json,n)}if(r==="invite"){let i=F(e[1],"enterprise invite requires <enterprise-id>."),o=F(t.email??e[2],"enterprise invite requires --email <email>."),s=F(v(t.workspace),"enterprise invite requires --workspace <workspace-id|all|none>.");return await pe(`/api/v1/enterprises/${encodeURIComponent(i)}/invites`,{email:o,role:v(t.role)??v(t.requestedRole)??"workspace_user",workspaceIds:TH(s)},t,n,"Enterprise invite created.")}if(r==="accept-invite"){let i=F(e[1],"enterprise accept-invite requires <invite-id>."),o=await E(n,`/api/v1/enterprise-invites/${encodeURIComponent(i)}/accept`,{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})});return await Nr(n,o),R(o,"Enterprise invite accepted.",t.json,n)}if(r==="revoke-invite"||r==="resend-invite"){let i=F(e[1],`enterprise ${r} requires <enterprise-id> and <invite-id>.`),o=F(e[2],`enterprise ${r} requires <enterprise-id> and <invite-id>.`),s=r==="revoke-invite"?"revoke":"resend";return await pe(`/api/v1/enterprises/${encodeURIComponent(i)}/invites/${encodeURIComponent(o)}/${s}`,{},t,n,r==="revoke-invite"?"Enterprise invite revoked.":"Enterprise invite resent.")}if(r==="member"){let i=e[1];if(i!=="role"&&i!=="remove")return P(`Unknown enterprise member command "${i??""}".`,t.json);let o=F(e[2],"enterprise member <role|remove> requires <enterprise-id> and <user-id>."),s=F(e[3],"enterprise member <role|remove> requires <enterprise-id> and <user-id>.");if(i==="role"){let a=F(t.role??t.requestedRole,"enterprise member role requires --role <enterprise_admin|workspace_manager|workspace_user>.");return await Ei(`/api/v1/enterprises/${encodeURIComponent(o)}/members/${encodeURIComponent(s)}`,{role:a},t,n,"Enterprise member role updated.")}if(i==="remove")return await Dl(`/api/v1/enterprises/${encodeURIComponent(o)}/members/${encodeURIComponent(s)}`,{method:"DELETE",headers:H(n.apiKey,n.authBlockedMessage)},t,n,"Enterprise member removed.")}if(r==="workspaces"){let i=F(e[1],"enterprise workspaces requires <enterprise-id>."),o=await E(n,`/api/v1/enterprises/${encodeURIComponent(i)}/workspaces`,{headers:H(n.apiKey,n.authBlockedMessage)});return Rt(o,pH(o,n),"Enterprise workspaces loaded.",t.json,n)}if(r==="workspace"){let i=e[1],o=F(e[2],"enterprise workspace <create|rename|archive> requires <enterprise-id>.");if(i==="create"){let a=F(t.workspaceName??t.name??e[3],"enterprise workspace create requires --name <workspace-name>.");return await pe(`/api/v1/enterprises/${encodeURIComponent(o)}/workspaces`,{name:a},t,n,"Enterprise workspace created.")}let s=F(e[3],"enterprise workspace <rename|archive> requires <workspace-id>.");if(i==="rename"||i==="update"){let a=v(t.workspaceName)??v(t.name)??e[4],l=v(t.telemetryPolicy),c=v(t.guardianPolicy);return c&&c!=="standard"&&c!=="strict"?P("--guardian-policy must be standard or strict.",t.json):i==="rename"&&!a?P("enterprise workspace rename requires --name <workspace-name>.",t.json):!a&&!l&&!c?P("enterprise workspace update requires --name <workspace-name>, --telemetry-policy <best_effort|required> or --guardian-policy <standard|strict>.",t.json):l&&l!=="best_effort"&&l!=="required"?P("--telemetry-policy must be best_effort or required.",t.json):await Ei(`/api/v1/workspaces/${encodeURIComponent(s)}`,{enterpriseId:o,...a?{name:a}:{},...l?{telemetryPolicy:l}:{},...c?{guardianPolicy:c}:{}},t,n,"Enterprise workspace updated.")}return i==="archive"?await pe(`/api/v1/workspaces/${encodeURIComponent(s)}/archive`,{enterpriseId:o},t,n,"Enterprise workspace archived."):P(`Unknown enterprise workspace command "${i??""}".`,t.json)}if(r==="workspace-member"){let i=e[1];if(i!=="list"&&i!=="add"&&i!=="remove")return P(`Unknown enterprise workspace-member command "${i??""}".`,t.json);let o=F(e[2],"enterprise workspace-member <list|add|remove> requires <enterprise-id> <workspace-id>."),s=F(e[3],"enterprise workspace-member <list|add|remove> requires <enterprise-id> <workspace-id>.");if(i==="list"){let l=await E(n,`/api/v1/workspaces/${encodeURIComponent(s)}/members?enterpriseId=${encodeURIComponent(o)}`,{headers:H(n.apiKey,n.authBlockedMessage)});return Rt(l,gH(l,n),"Workspace members loaded.",t.json,n)}let a=F(e[4],`enterprise workspace-member ${i} requires <user-id>.`);if(i==="add")return await pe(`/api/v1/workspaces/${encodeURIComponent(s)}/members`,{enterpriseId:o,userId:a,role:v(t.role)??v(t.requestedRole)??"workspace_user"},t,n,"Workspace member added.");if(i==="remove")return await Dl(`/api/v1/workspaces/${encodeURIComponent(s)}/members/${encodeURIComponent(a)}`,{method:"DELETE",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({enterpriseId:o})},t,n,"Workspace member removed.")}if(r==="skill")return await lH(e.slice(1),t,n);if(r==="install-authorize"){let i=F(e[1],"enterprise install-authorize requires <skill-slug>.");return await pe(`/api/v1/skills/${encodeURIComponent(i)}/install-authorize`,{},t,n,"Install authorization evaluated.")}return P(`Unknown enterprise command "${r}".`,t.json)}async function lH(e,t,n){let r=e[0];if(r==="quote"||r==="buy"){let i=F(e[1],`enterprise skill ${r} requires <enterprise-id> and <skill-slug>.`),o=F(e[2],`enterprise skill ${r} requires <enterprise-id> and <skill-slug>.`),s=await E(n,`/api/v1/enterprises/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r==="quote"?"quote":"checkout"}`,{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})});return r==="quote"?Rt(s,yH(s,i,o,n),"Enterprise skill quote loaded.",t.json,n):await Sw(s,t,n,"Enterprise skill checkout prepared.",`Opening Enterprise skill checkout for ${o}. Complete payment in your browser, then come back here.`,{kind:"enterprise_skill",statusPathForCheckoutId:a=>`/api/v1/enterprises/_/skills/_/checkout/${encodeURIComponent(a)}`,waitingMessage:"Waiting for Enterprise skill checkout completion...",completedMessage:"Enterprise skill checkout completed."})}if(r==="entitlements"){let i=F(e[1],"enterprise skill entitlements requires <enterprise-id>."),o=await E(n,`/api/v1/enterprises/${encodeURIComponent(i)}/skill-entitlements`,{headers:H(n.apiKey,n.authBlockedMessage)});return Rt(o,mH(o,n),"Enterprise skill entitlements loaded.",t.json,n)}return P(`Unknown enterprise skill command "${r??""}".`,t.json)}async function Sw(e,t,n,r,i,o){let s=f(e,"checkoutUrl"),a=f(e,"checkoutId"),l=f(e,"status");if(!t.json&&!t.noOpen&&(l==="checkout_required"&&s&&(n.emitInfo(i),await n.openUrl(s)||n.emitInfo(`Open this checkout URL manually to continue: ${s}`)),o&&a&&(l==="checkout_required"||l==="finalizing"))){n.emitInfo(o.waitingMessage);let c=o.statusPathForCheckoutId(a),u=await VW(c,a,n);if(Z(u))return u;let d=f(u,"status");return d==="completion_pending"?Rt(u,SH(u,o.kind,n),"Enterprise checkout completion is still pending.",t.json,n):d!=="completed"&&d!=="already_completed"?P(kH(d,o.kind),t.json):(n.emitInfo(o.completedMessage),Rt(u,o.kind==="enterprise"?vH(u,n):o.kind==="enterprise_seats"?_H(u,n):bH(u,n),o.completedMessage,t.json,n))}return R(e,r,t.json,n)}function cH(e,t){let n=de(t),r=L(e,"enterprise"),i=L(e,"membership"),o=Array.isArray(e.workspaces)?e.workspaces.filter(O):[],s=[`${n.ok("OK")} Existing Enterprise found. No payment was started.`,"",n.section("Enterprise")];if(s.push(` ${n.label("Name")}: ${r?f(r,"name")??"unknown":"unknown"}`),s.push(` ${n.label("ID")}: ${r?f(r,"enterpriseId")??"unknown":"unknown"}`),s.push(` ${n.label("Your role")}: ${ut(i?f(i,"role")??"unknown":"unknown")}`),o.length>0){s.push("",n.section("Workspaces"));for(let l of o)s.push(` ${n.arrow} ${f(l,"name")??"Unnamed"} (${f(l,"workspaceId")??"unknown"})`)}let a=f(e,"nextStep");return a&&s.push("",n.section("Next"),` ${n.arrow} ${a}`),s.join(`
|
|
1004
|
+
`)}function uH(e,t){let n=de(t),r=Array.isArray(e.results)?e.results.filter(O):[],i=[`${n.ok("OK")} Enterprise memberships loaded.`,"",n.section(`Enterprise memberships (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No active Enterprise memberships.")}`),i.join(`
|
|
1005
|
+
`)):(r.forEach((o,s)=>{i.push(`${s+1}. ${f(o,"name")??"Unnamed Enterprise"}`),i.push(` ${n.label("ID")}: ${f(o,"enterpriseId")??"unknown"}`),i.push(` ${n.label("Role")}: ${ut(f(o,"role")??"unknown")}`);let a=K(o,"seatCapacity"),l=K(o,"usedSeats"),c=K(o,"availableSeats");a!==void 0&&l!==void 0&&c!==void 0&&i.push(` ${n.label("Seats")}: ${l} used, ${c} available of ${a}`)}),i.join(`
|
|
1006
|
+
`))}function dH(e,t){let n=de(t),r=Array.isArray(e.results)?e.results.filter(O):[],i=[`${n.ok("OK")} Enterprise members loaded.`,"",n.section(`Enterprise members (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No active Enterprise members.")}`),i.join(`
|
|
1007
|
+
`)):(r.forEach((o,s)=>{let a=Array.isArray(o.workspaceIds)?o.workspaceIds.filter(l=>typeof l=="string"):[];i.push(`${s+1}. ${f(o,"userId")??"Unknown user"}`),i.push(` ${n.label("User ID")}: ${f(o,"userId")??"unknown"}`),i.push(` ${n.label("Role")}: ${ut(f(o,"role")??"unknown")}`),i.push(` ${n.label("Workspaces")}: ${a.length>0?a.join(", "):"None assigned"}`),i.push(` ${n.label("Status")}: ${ut(f(o,"status")??"unknown")}`)}),i.join(`
|
|
1008
|
+
`))}function fH(e,t){let n=de(t),r=Array.isArray(e.results)?e.results.filter(O):[],i=[`${n.ok("OK")} Enterprise invites loaded.`,"",n.section(`Enterprise invites (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No Enterprise invitations.")}`),i.join(`
|
|
1009
|
+
`)):(r.forEach((o,s)=>{let a=Array.isArray(o.workspaceIds)?o.workspaceIds.filter(c=>typeof c=="string"):[];i.push(`${s+1}. ${f(o,"email")??"Unknown recipient"}`),i.push(` ${n.label("Invite ID")}: ${f(o,"inviteId")??"unknown"}`),i.push(` ${n.label("Role")}: ${ut(f(o,"role")??"unknown")}`),i.push(` ${n.label("Workspaces")}: ${a.length>0?a.join(", "):"No workspace access"}`),i.push(` ${n.label("Status")}: ${ut(f(o,"status")??"unknown")}`);let l=f(o,"expiresAt");l&&i.push(` ${n.label("Expires")}: ${l}`)}),i.join(`
|
|
1010
|
+
`))}function pH(e,t){let n=de(t),r=Array.isArray(e.results)?e.results.filter(O):[],i=[`${n.ok("OK")} Enterprise workspaces loaded.`,"",n.section(`Enterprise workspaces (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No active Enterprise workspaces.")}`),i.join(`
|
|
1011
|
+
`)):(r.forEach((o,s)=>{i.push(`${s+1}. ${f(o,"name")??"Unnamed workspace"}`),i.push(` ${n.label("ID")}: ${f(o,"workspaceId")??"unknown"}`),i.push(` ${n.label("Policy")}: ${ut(f(o,"policy")??"unknown")}`),i.push(` ${n.label("Telemetry")}: ${ut(f(o,"telemetryPolicy")??"unknown")}`),i.push(` ${n.label("Status")}: ${ut(f(o,"status")??"unknown")}`)}),i.join(`
|
|
1012
|
+
`))}function mH(e,t){let n=de(t),r=Array.isArray(e.results)?e.results.filter(O):[],i=[`${n.ok("OK")} Enterprise skill entitlements loaded.`,"",n.section(`Enterprise skill entitlements (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No active Enterprise skill entitlements.")}`),i.join(`
|
|
1013
|
+
`)):(r.forEach((o,s)=>{let a=f(o,"skillSlug")??"unknown",l=f(o,"version")??"unknown",c=K(o,"priceCents"),u=K(o,"amountCents"),d=K(o,"multiplier");i.push(`${s+1}. ${f(o,"skillName")??a} (${a}@${l})`),i.push(` ${n.label("Entitlement ID")}: ${f(o,"entitlementId")??"unknown"}`),i.push(` ${n.label("Purchase")}: ${DE(u)} total (${DE(c)} unit \xD7 ${d??"unknown"})`),i.push(` ${n.label("Seats at purchase")}: ${K(o,"seatCountAtPurchase")??"unknown"}`),i.push(` ${n.label("Purchased")}: ${f(o,"purchasedAt")??"unknown"}`),i.push(` ${n.label("Status")}: ${ut(f(o,"status")??"unknown")}`)}),i.join(`
|
|
1014
|
+
`))}function DE(e){return e===void 0?"unknown":`$${(e/100).toFixed(2)}`}function gH(e,t){let n=de(t),r=Array.isArray(e.results)?e.results.filter(O):[],i=[`${n.ok("OK")} Workspace members loaded.`,"",n.section(`Workspace members (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No active workspace members.")}`),i.join(`
|
|
1015
|
+
`)):(r.forEach((o,s)=>{i.push(`${s+1}. ${f(o,"userId")??"Unknown user"}`),i.push(` ${n.label("User ID")}: ${f(o,"userId")??"unknown"}`),i.push(` ${n.label("Role")}: ${ut(f(o,"role")??"unknown")}`),i.push(` ${n.label("Status")}: ${ut(f(o,"status")??"unknown")}`)}),i.join(`
|
|
1016
|
+
`))}function hH(e,t){let n=de(t),r=Array.isArray(e.results)?e.results.filter(O):[],i=[`${n.ok("OK")} Enterprise seats loaded.`,"",n.section(`Enterprise seats (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No active Enterprise seat pools.")}`),i.join(`
|
|
1017
|
+
`)):(r.forEach((o,s)=>{i.push(`${s+1}. ${f(o,"name")??"Unnamed Enterprise"}`),i.push(` ${n.label("ID")}: ${f(o,"enterpriseId")??"unknown"}`);let a=[["Capacity",K(o,"seatCapacity")],["Used",K(o,"usedSeats")],["Reserved",K(o,"reservedSeats")],["Available",K(o,"availableSeats")]];for(let[l,c]of a)c!==void 0&&i.push(` ${n.label(l)}: ${c}`);a.every(([,l])=>l===void 0)&&(i.push(` ${n.label("Seat information")}: unavailable from this backend`),i.push(` ${n.arrow} Ask an operator to deploy the current Enterprise API, then retry this command.`))}),i.join(`
|
|
1018
|
+
`))}function yH(e,t,n,r){let i=de(r),o=K(e,"priceCents"),s=K(e,"amountCents"),a=[`${i.ok("OK")} Enterprise skill quote loaded.`,"",i.section("Quote")];a.push(` ${i.label("Skill")}: ${f(e,"skillName")??n}`),a.push(` ${i.label("Version")}: ${f(e,"version")??"unknown"}`),o!==void 0&&a.push(` ${i.label("Unit price")}: ${TE(o)}`),s!==void 0&&a.push(` ${i.label("Enterprise total")}: ${TE(s)}`);let l=K(e,"multiplier");return l!==void 0&&a.push(` ${i.label("Purchase multiplier")}: ${l}`),a.push("",i.section("Next")),a.push(` ${i.arrow} skills-layer enterprise skill buy ${t} ${n}`),a.join(`
|
|
1019
|
+
`)}function TE(e){return`$${(e/100).toFixed(2)}`}function wH(){return`enterprise_creation_${globalThis.crypto.randomUUID().replaceAll("-","").toLowerCase()}`}function vH(e,t){let n=de(t),r=L(e,"enterprise"),i=L(e,"firstWorkspace"),o=L(e,"membership"),s=r?f(r,"enterpriseId"):void 0,a=i?f(i,"workspaceId"):void 0,l=r?K(r,"seatCapacity"):void 0,c=r?K(r,"usedSeats"):void 0,u=r?K(r,"availableSeats"):void 0,d=[`${n.ok("OK")} Enterprise is ready.`,"",n.section("Enterprise")];return d.push(` ${n.label("Name")}: ${r?f(r,"name")??"unknown":"unknown"}`),d.push(` ${n.label("ID")}: ${s??"unknown"}`),l!==void 0&&c!==void 0&&u!==void 0&&d.push(` ${n.label("Seats")}: ${c} used, ${u} available of ${l}`),d.push("",n.section("First workspace")),d.push(` ${n.label("Name")}: ${i?f(i,"name")??"unknown":"unknown"}`),d.push(` ${n.label("ID")}: ${a??"unknown"}`),i&&d.push(` ${n.label("Policy")}: ${ut(f(i,"policy")??"unknown")}`),d.push("",n.section("Your access")),d.push(` ${n.label("Role")}: ${ut(o?f(o,"role")??"unknown":"unknown")}`),s&&a&&(d.push("",n.section("Next")),d.push(` ${n.arrow} skills-layer enterprise invite ${s} --email <email>`),d.push(` ${n.arrow} skills-layer workspace current`),d.push(` ${n.arrow} skills-layer workspace approve ${a} <skill-slug>`)),d.join(`
|
|
1020
|
+
`)}function bH(e,t){let n=de(t),r=L(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(`
|
|
1021
|
+
`)}function _H(e,t){let n=de(t),r=L(e,"enterprise"),i=K(e,"addedSeats"),o=r?K(r,"seatCapacity"):void 0,s=r?K(r,"usedSeats"):void 0,a=r?K(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(`
|
|
1022
|
+
`)}function kH(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 SH(e,t,n){let r=de(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(`
|
|
1023
|
+
`)}function ut(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 Rt(e,t,n,r,i){return r?R(e,n,!0,i):{exitCode:0,stdout:t,stderr:""}}function nt(e){let t=Yl(e);return t.status==="unknown"?null:t.hostId}function CH(e){return nt(e)!==null}function Q0(e){return Kn.includes(e)}function rw(e,t){return S({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 Qd(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 Xw(e,t){let n=v(e.environment)??at(t.baseUrl),r=[...yP],i=`${t.baseUrl}/mcp`,o=mo({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 AH(e,t,o);if(s.clientIds.length===0)return S({status:"needs_mcp_client_choice",reasonCode:"needs_mcp_client_choice",configured:!1,detectedClientIds:s.detectedClientIds,supportedClientIds:o.targets.filter($=>$.status==="automatic").map($=>$.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=mo({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 $=l.targets.filter(B=>B.status==="automatic"&&s.clientIds.includes(nt(B.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:$.map(B=>({clientId:B.agentId,scope:"user_global",configPath:B.configPath})),skippedClients:l.targets.filter(B=>B.status!=="automatic").map(B=>({clientId:B.agentId,reason:B.reason})),bridgePath:l.bridgePath,brokerPath:l.brokerPath,nextAction:"mcp.setup"}}let c=l.targets.filter($=>$.status==="automatic"&&s.clientIds.includes(nt($.agentId)));try{for(let $ of c)await $.preflight?.()}catch($){let B=$ instanceof Error&&$.message.startsWith("mcp_socket_")?$.message.split(":")[0]:$ instanceof Error&&$.message.startsWith("mcp_config_symlink_rejected")?"mcp_config_symlink_rejected":"mcp_registration_ownership_ambiguous";return S({status:"mcp_setup_blocked",configured:!1,unchanged:!0,reasonCode:B,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."},$ instanceof Error?$.message:"MCP host configuration preflight failed.",e.json,B)}if(As(t.baseUrl)&&!t.credentialStore)return S({status:"security_unavailable",reasonCode:"mcp_secure_storage_required",configured:!1,unchanged:!0,nextAction:"mcp.setup",nextStep:ap(t.platform)},"Skills Layer Cloud MCP setup requires supported OS-secure credential storage. No MCP credential was created.",e.json,"mcp_secure_storage_required");let u=As(t.baseUrl)?await t.credentialStore.unavailableReason?.():null;if(u)return S({status:"security_unavailable",reasonCode:u,configured:!1,unchanged:!0,nextAction:"mcp.setup",nextStep:ll},`${jd} No MCP credential was created.`,e.json,u);if(!t.apiKey)return S({status:"login_required",reasonCode:"login_required",configured:!1,unchanged:!0,nextAction:"login",nextStep:"Run `skills-layer login`, then retry `skills-layer mcp setup`."},"Sign in before setting up MCP. No MCP credential was created.",e.json,"login_required");let d=await se(t.paths.mcpConfigPath),p=Array.isArray(d?.clientIds)?d.clientIds.flatMap($=>{let B=typeof $=="string"?nt($):null;return B?[B]:[]}):[],m=[...new Set([...p,...s.clientIds])],g=Mi(),{deviceId:h}=await dT(t),y=await E(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:U(t.apiKey),body:JSON.stringify({clientId:vg,deviceId:h,linkedClientIds:m,environment:n,scopes:r,handoffCodeHash:g.authorizationCodeHash,handoffCodeChallenge:g.codeChallenge})});if(f(y,"credentialHandoff")!=="ready")return P("MCP setup did not prepare a secure credential handoff.",e.json);let w=await E(t,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:U(t.apiKey),body:JSON.stringify({authorizationCode:g.authorizationCode,codeVerifier:g.codeVerifier})}),b=f(w,"apiKey");if(!b)return P("MCP token credential exchange failed closed.",e.json);let _;try{_=await xH(t,{token:b,clientId:vg,environment:n})}catch($){if(!($ instanceof Zi))throw $;let B=f(w,"id"),q=!1;if(B)try{await E(t,"/api/v1/me/session/revoke",{method:"POST",headers:U(t.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:[B]})}),q=!0}catch{t.config?.userId&&await $v(t,{baseUrl:t.baseUrl,userId:t.config.userId,humanKeyIds:[],mcpKeyIds:[B],revokeAllMcp:!1,revokeAdminMcp:!1,createdAt:t.now()})}return S({reasonCode:"mcp_secure_storage_required",configured:!1,nextStep:ap(t.platform)},q?"OS-secure credential storage failed; the new MCP credential was revoked.":"OS-secure credential storage failed; revocation requires retry.",e.json,"mcp_secure_storage_required")}let I={..._,shared:!0,keyId:f(w,"id")??null,tokenPrefix:f(w,"keyPrefix")??null,scopes:Array.isArray(w.scopes)?w.scopes:[]},x=await se(t.paths.mcpConfigPath),C=`${t.paths.stateDir}/mcp-credential-refs.json`,D=await se(C),T=fp({baseUrl:t.baseUrl,userId:t.config?.userId},t.now(),D,x,I),j=[...ss(D??{},ge),...ss(x??{},ge),...ss(I,ge)];if(await _e(C,{revocationRefs:T,tokens:Object.fromEntries(j.map($=>[$.tokenRef,{tokenRef:$.tokenRef,credentialService:$.service,credentialStorage:t.credentialStore.kind}]))}),await _e(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:i,clientId:a,clientIds:m,environment:n,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,...I,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,brokerLockPath:l.brokerLockPath,nodePath:l.nodePath,bridgePath:l.bridgePath,brokerIntegrityProfile:"standard_v1",brokerChecksum:l.brokerChecksum,savedAt:t.now()}),t.credentialStore){let $=new Set(ss(I,ge).map(B=>`${B.service}:${B.tokenRef}`));for(let B of j)$.has(`${B.service}:${B.tokenRef}`)||await t.credentialStore.delete(B.service,B.tokenRef);await _e(C,{revocationRefs:T,tokens:Object.fromEntries(j.filter(B=>$.has(`${B.service}:${B.tokenRef}`)).map(B=>[B.tokenRef,{tokenRef:B.tokenRef,credentialService:B.service,credentialStorage:t.credentialStore.kind}]))})}let M=c;for(let $ of M)await $.apply?.();return await Ae(t.paths.mcpPreferencePath,{force:!0}),{...dt(w),status:"mcp_configured",evidenceStale:l.evidenceStale,warnings:l.warnings,clientId:a,clientIds:s.clientIds,linkedClientIds:m,agentHosts:[...m].sort(),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:M.length,appliedClients:M.map($=>$.agentId),targets:l.targets.map($=>({agentId:$.agentId,displayName:$.displayName,tier:$.tier,status:$.status,transport:$.transport,configPath:$.configPath,bridgePath:$.bridgePath,restartRequired:$.restartRequired,reason:$.reason,instructions:$.instructions}))}}}async function AH(e,t,n){let r=v(e.client),i=n.targets.filter(l=>l.status==="automatic").flatMap(l=>{let c=nt(l.agentId);return c?[c]:[]});if(r){let l=nt(r);return{clientIds:l?[l]:[],detectedClientIds:[],selectionSource:"explicit"}}if(e.all)return{clientIds:i,detectedClientIds:i,selectionSource:"all"};let o=await hb({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=nt(l);if(c)return{clientIds:[c],detectedClientIds:[],selectionSource:"explicit"}}catch{}return{clientIds:[],detectedClientIds:[],selectionSource:"choice_required"}}async function xH(e,t){if(!e.credentialStore){if(As(e.baseUrl))throw new Zi;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}let n=IH({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(ge,n,t.token),{tokenRef:n,credentialStorage:e.credentialStore.kind,credentialService:ge,tokenStorage:e.credentialStore.kind}}catch{if(As(e.baseUrl))throw new Zi;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function Cw(e,t){let n=`${t.paths.stateDir}/mcp-credential-refs.json`,r=await se(n),i=[...ss(e??{},ge),...ss(r??{},ge)];if(!t.credentialStore){if(i.length)throw new Error("OS credential storage is unavailable; retry cleanup on this profile's original machine.");await Ae(n,{force:!0});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 Ae(n,{force:!0})}function ss(e,t){let n=new Map;$E(e,t,n);let r=e.tokens;if(O(r))for(let i of Object.values(r))O(i)&&$E(i,t,n);return[...n.values()]}function $E(e,t,n){let r=f(e,"tokenRef");if(!r||!Yn(f(e,"credentialStorage")))return;let i=f(e,"credentialService")??t;n.set(`${i}:${r}`,{service:i,tokenRef:r})}function IH(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
1024
|
+
`);return`skills-layer-cli:mcp-token:${me("sha256").update(t).digest("base64url").slice(0,32)}`}async function Aw(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 se(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 Ae(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 Xw(e,t);if(Z(s)){let a=RH(s);return{data:a,message:a.reasonCode===Er?`Login completed, but MCP was not configured. ${ll}`:"Login completed, but MCP was not configured. Choose a verified host with `skills-layer mcp setup --client <host-id>` or use `--all`."}}return{data:s,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}function RH(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":e.stderr.includes(jd)&&(t=Er)}return{status:"mcp_not_configured",configured:!1,reasonCode:t,nextAction:"mcp.setup",nextCommand:"skills-layer mcp setup --client <host-id>",nextStep:t===Er?ll:"Run `skills-layer mcp setup --client <host-id>` after resolving the reported MCP prerequisite, or use `--all`."}}function xw(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:t.reasonCode===Er?ll:"Run `skills-layer mcp setup` when you want Skills Layer available to your AI tools."}:e:e}async function ff(e,t){if(t.config&&!t.config.edition){let u=await E(t,"/api/v1/capabilities"),d=gp(u.edition);d&&(t.config.edition=d,await Vl(t.paths.configPath,t.config,t))}if(t.config?.edition==="community")return{};let n;try{n=await E(t,"/api/v1/me/working-modes",{headers:H(t.apiKey,t.authBlockedMessage)})}catch{return{}}await Nr(t,n);let r=Array.isArray(n.modes)?n.modes.filter(O):[],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=PH(r,i);if(s.length===0)return{};if(e.json)return S({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 S({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 E(t,"/api/v1/me/working-mode",{method:"PUT",headers:U(t.apiKey,t.authBlockedMessage),body:JSON.stringify({modeId:a})});await Nr(t,l);let c=s.find(u=>u.value===a)?.label??a;return{data:l,message:`Selected workspace: ${c}.`}}function PH(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(g=>f(g,"enterpriseId")).filter(Boolean)),d=u.size>1?f(o,"enterpriseId"):f(o,"workspaceId"),p=u.size>1?"Enterprise":"Workspace",m=EH(d??s);return{value:s,label:`${l} (${p} ${m})`,...s===t?{description:"Currently selected"}:{}}})}function EH(e){return e.replace(/^(?:enterprise|workspace)_/u,"").slice(0,8)}function DH(e){if(!e)return null;let t=e.mode??e.workingMode,n=O(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 Nr(e,t){let n=DH(t);if(!n||!e.config)return e.config;let r={...e.config,...n,workingModeSavedAt:e.now()};return await Vl(e.paths.configPath,r,e),e.config=r,r}async function LE(e,t,n){let r=[...new Set(t.map(i=>i.trim()).filter(Boolean))];for(let i of r){let o=await Qw(e,i,n);if(o)return o}return null}async function Qw(e,t,n){if(!e.apiKey)return null;let r=e.config?.workingModeType;if(r!=="personal"&&r!=="enterprise_workspace"){let i;try{i=await E(e,"/api/v1/me/install-policy",{headers:H(e.apiKey,e.authBlockedMessage)})}catch(o){if(o instanceof V&&(o.status===403||o.status===409))return iw(o.details??{error:o.message},t,n.json);throw o}if(await Nr(e,i),i.requiresWorkingModeSelection===!0)return S({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 E(e,`/api/v1/skills/${encodeURIComponent(t)}/install-authorize`,{method:"POST",headers:U(e.apiKey,e.authBlockedMessage),body:JSON.stringify({agent:v(n.agent),version:v(n.version),allowIncompatible:n.allowIncompatible===!0})});return await Nr(e,i),f(i,"status")==="authorized"?null:iw(i,t,n.json)}catch(i){if(i instanceof V&&(i.status===403||i.status===409))return iw(i.details??{error:i.message},t,n.json);throw i}}function iw(e,t,n){let r=O(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 S({...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 TH(e){let t=v(e);if(t)return t.split(",").map(n=>n.trim()).filter(Boolean)}async function $H(e,t,n){let r=e.join(" ").trim()||v(t.search)||"",i=new URLSearchParams;r&&i.set("query",r);let o=v(t.runtimeRisk);if(o&&!OE.includes(o))return sw("runtime-risk",o,OE,t);let s=v(t.agent);if(s&&!Q0(s))return S({status:"error",reasonCode:"unknown_agent",filter:"agent",value:s,acceptedValues:Kn,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=v(t.trust);if(a&&!FE.includes(a))return sw("trust",a,FE,t);let l=v(t.securityCapability),c=WH(l);if(l&&!c)return sw("security-capability",l,eD,t);let u=DT(i,t);if(typeof u=="string")return S({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");be(i,"agent",t.agent),be(i,"capability",t.capability),be(i,"trust",a),be(i,"runtime-risk",o),be(i,"security-capability",c);let d=await E(n,`/api/v1/search${Re(i)}`);if(t.install!==void 0){let m=v(t.install);if(!m){if(t.json)return P("search --install requires an explicit skill slug in the public CLI package.",!0);let h=_n(d);if(h.length===0)return P("Search results do not include any installable skills. Run search again with a broader query.",!1);if(h.length===1)m=h[0].value;else try{m=await n.promptSelect("Select a search result to install:",h)}catch{return P("No search result was selected for install.",!1)}}let g=dJ(d);return g.includes(m)?await gs([m],t,n,{origin:"search_result",fallbackPolicy:"eligible_public"}):P(g.length===0?`Search results do not include "${m}". Run search again with a matching query first.`:`Search results do not include "${m}". Run search again with a matching query or choose one of: ${g.join(", ")}.`,t.json)}let p=jf(d,"effectiveQuery");return R({...d,...u.length?{warnings:[...Array.isArray(d.warnings)?d.warnings:[],...u]}:{}},p?`Search complete. ${p}`:"Search complete.",t.json,n)}var OE=ub,FE=cb,eD=["filesystem_read","filesystem_write","network_access","api_access","browser_access","device_control","generated_code_execution","secret_handling","model_context","shell_access"],LH={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"},ow=["local","project","global","workspace"],bl=["private","public","unlisted"],ls=["private","public","unlisted"],BE=["github","gitlab","local","generic_git","domain"],OH=["owner","maintainer"],FH=["open","acknowledged","fixed","closed","rejected","abusive","reopened","resolved"],BH=["visible","flagged","hidden"],NH=["bug","quality","safety","other"],MH=["approved","denied"],jH=["email","google","github","gitlab"],UH=["email","google","github","gitlab"],NE=["catalog:read","library:read","creator:read","creator:submit","source:read","source:write","guardian:check","guardian:incident","workspace:read","workspace:write","workspace:approve","mcp:use"],ME=["automation","mcp","agent"],jE=["active","expired","revoked","all"],UE=["created-desc","created-asc","expires-desc","expires-asc","name-asc","name-desc","last-used-desc","last-used-asc"];var qH=["json","llm","report","passport","sarif","markdown","pdf"],VH=["json","sarif","report","passport","markdown"],ef=[...db,"score"],GH=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u,zH=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,KH=/^[a-f0-9]{6,64}$/iu;function HH(e,t,n,r){let i=v(t);if(!i)return{};if(!/^\d+$/u.test(i))return{failure:S({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:S({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 sw(e,t,n,r){return S({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 WH(e){if(e)return eD.includes(e)?e:LH[e]}function Un(e,t,n,r,i,o,s=t){return S({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 Sn(e,t,n,r,i,o,s=t){let a=v(n);if(!(!a||r.includes(a)))return Un(e,t,a,r,i,o,s)}function Fr(e,t){let n=v(t.version);return n&&!xf(n)?ev(e,n,t):void 0}function JH(e,t,n){return S({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 tD(e,t,n){return t&&!zH.test(t)?JH(e,t,n):void 0}function YH(e,t,n,r){return S({status:"error",reasonCode:"invalid_format",format:t,acceptedValues:r,nextAction:e,nextStep:`Use --format ${r.join(", ")}.`},`Invalid ${e} --format "${t}". Use ${r.join(", ")}.`,n.json,"invalid_format")}function nD(e,t){let n=v(t.format),r=e==="trust"?qH:VH;return n&&!r.includes(n.toLowerCase())?YH(e,n,t,r):void 0}function ZH(e,t,n){return S({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 XH(e,t){let n=v(t.commitSha);return n&&!KH.test(n)?ZH(e,n,t):void 0}function QH(e,t){return S({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 e4(e,t){try{Zn(e);return}catch{return QH(e,t)}}function qE(e,t,n){return S({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 jl(e,t){let n=v(t.scope);if(n&&!ow.includes(n))return{failure:S({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:ow,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${ow.join(", ")}.`,t.json,"invalid_install_filter")};let r=v(t.agent);return r&&!(e==="install"&&r==="all")&&!Q0(r)?{failure:S({status:"error",reasonCode:"unknown_agent",filter:"agent",value:r,acceptedValues:Kn,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 rD(e,t){let n=jl(e,t);if(n.failure)return n.failure;let r=v(t.version);if(e==="install"&&r&&!xf(r))return ev("install",r,t)}function ev(e,t,n){return S({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 t4(e,t,n){return S({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 n4(e,t,n){let r=v(t);if(r&&$C(r)===null)return t4(e,r,n)}function Mr(e,t,n,r,i,o){let s=v(e);if(!s)return{};if(!/^\d+$/u.test(s))return{failure:S({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:S({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 VE(e,t,n,r,i,o){let s=Mr(e,t,n,`invalid_${n.replace(/[A-Z]/gu,a=>`_${a.toLowerCase()}`)}`,i,o);return s.failure?s.failure:s.value===void 0?P(`${r} requires ${t} <count>.`,i.json):s.value}function r4(e){let t=v(e.paymentMethod)??"card";return GH.test(t)?{value:t}:{failure:S({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 i4(e,t,n){let r=new URLSearchParams,i=DT(r,t);if(typeof i=="string")return S({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=v(t.sort);if(o&&!ef.includes(o))return S({status:"error",reasonCode:"invalid_sort",sort:o,acceptedValues:ef,nextAction:e,nextStep:`Use --sort with one of: ${ef.join(", ")}.`},`${e} --sort must be one of: ${ef.join(", ")}.`,t.json,"invalid_sort");be(r,"search",t.search),be(r,"sort",o);let s=await E(n,`/api/v1/${e}${Re(r)}`);return e==="trending"&&!t.json?{exitCode:0,stdout:Yv({...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"?Wv(s.basis):`${$f(e)} skills loaded.`,t.json,n)}async function o4(e,t,n){let r=e.join(" ").trim();if(!r)return P("recommend requires a task.",t.json);let i=HH("recommend",t.limit,20,t);if(i.failure)return i.failure;let o=new URLSearchParams({task:r});be(o,"limit",i.value);let s=await E(n,`/api/v1/recommend?${o.toString()}`,{headers:An(n.apiKey)}),a=jf(s,"effectiveTask"),l=f(s,"summary")??"Recommendations loaded.";return R(s,a?`${l} ${a}`:l,t.json,n)}async function s4(e,t,n){if(e.length<2)return P("compare requires two or more skill slugs.",t.json);if(e.length>5)return S({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 E(n,`/api/v1/skills/compare?${r.toString()}`),o=Array.isArray(i.missing)?i.missing.filter(s=>typeof s=="string"):[];return o.length>0?S({...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:k9(i,"Comparison loaded.",de(n),t.verbose),stderr:""}}async function a4(e,t,n){let r=F(e[0],"show requires a skill slug."),i=await E(n,`/api/v1/skills/${encodeURIComponent(r)}`);return R(lg(i),"Skill loaded.",t.json,n)}async function Lr(e,t,n,r){e.apiKey&&await oI({event:rI({osFamily:nI(e.platform),nodeMajor:Number(process.versions.node.split(".")[0]),operation:t,outcome:n,operationId:r,occurredAt:e.now()}),publish:async i=>{await E(e,"/api/v1/creator/platform-telemetry",{method:"POST",headers:U(e.apiKey),body:JSON.stringify(i)})}})}async function l4(e,t,n){let r=F(e[0],"trust requires a skill slug."),i=nD("trust",t);if(i)return i;let o=v(t.format)?.toLowerCase(),s=v(t.output);if(o==="pdf"&&!s)return S({status:"error",reasonCode:"trust_pdf_output_required",nextAction:"trust",nextStep:`Run skills-layer trust ${r} --format pdf --output <file.pdf>.`},"trust --format pdf needs --output <file> because a PDF cannot be printed to the terminal.",t.json,"trust_pdf_output_required");let a=new URLSearchParams;be(a,"format",t.format),be(a,"version",t.version),be(a,"versionId",t.versionId);let l=`/api/v1/skills/${encodeURIComponent(r)}/platform-score${Re(a)}`;if(o==="sarif"||o==="markdown"||o==="pdf"){let u=await u4(n,l);if(s){let p=tt(n.cwd,s);return await Tf(p,u),R({status:"ok",skillSlug:r,format:o,outputPath:p,bytes:u.byteLength},`Platform Score ${o} written to ${p}.`,t.json,n)}let d=new TextDecoder().decode(u);return t.json?R(o==="sarif"?JSON.parse(d):{format:o,content:d},"Platform Score loaded.",!0,n):ob(o==="sarif"?`${JSON.stringify(JSON.parse(d),null,2)}
|
|
1025
|
+
`:d)}let c=await E(n,l);return!t.json&&o==="passport"?{exitCode:0,stdout:$t(await c4(c,n)),stderr:""}:!t.json&&hd(c)?{exitCode:0,stdout:$t(jh(c)),stderr:""}:R(c,"Platform Score loaded.",t.json,n)}async function c4(e,t){let n=$o.safeParse(e);if(!n.success)return"Skill Passport loaded, but it is not a valid signed Skill Passport V1.";let r=n.data,i="could not be verified (the issuer's public key is not published)";try{let s=await E(t,"/.well-known/skills-layer/passport-keys.json"),l=(Array.isArray(s.keys)?s.keys:[]).find(c=>c.keyId===r.issuer.keyId)?.publicKeyPem;if(typeof l=="string"){let c=Uh({passport:r,publicKeys:{[r.issuer.keyId]:z0(l)},now:t.now(),expectedSubject:r.subject,expectedReport:r.report,currentPassportId:r.passportId});i=c.valid?`valid (key ${r.issuer.keyId})`:`INVALID (${c.reasonCode})`}}catch{}let o=r.platformScore;return[`Skill Passport \u2014 ${r.subject.slug} ${r.subject.version}`,`Platform Score: ${o.score===null?"Withheld":`${o.score}/100 (${o.band}, ${za(o.band)})`} \u2014 ${o.decision??o.availability}`,`Report: ${r.report.reportId} revision ${r.report.revision}`,`Issued: ${r.issuedAt} \xB7 Expires: ${r.expiresAt}`,`Signature: ${i}`,`Verify: ${r.verificationUrl}`].join(`
|
|
1026
|
+
`)}async function u4(e,t){Zn(e.baseUrl);let n=await e.fetchFn(`${e.baseUrl}${t}`,{redirect:"error"}).catch(r=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ne(r)}`)});if(!n.ok)throw await Ev(n);return new Uint8Array(await n.arrayBuffer())}async function d4(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(kb(),"Help loaded.",!0,n);let a=e.length===1?Jl(r,bs):null;if(a)return R({status:"ok",kind:"goal_help",goal:a},"Help loaded.",!0,n);let l=r==="topic"?Gr(e[1]):Gr(r,e.slice(1));if(l)return R(l,"Help loaded.",!0,n);if(r!=="topic"&&!SK.has(r??""))return Iw(e,!0)}if(!r){if(n.renderMode.kind==="json-stream"||!n.helpInteractive)return{exitCode:0,stdout:Ai(n.renderMode),stderr:""};let a;try{a=await n.promptSelect("What do you want to do?",fb(bs))}catch{a=void 0}if(!a)return{exitCode:0,stdout:Ai(n.renderMode),stderr:""};if(a==="full")return os(Ai(n.renderMode,!0),"full",t,n);let l=Jl(a,bs);return l?os(qf(l),l.id,t,n):{exitCode:0,stdout:Ai(n.renderMode),stderr:""}}if(r==="full")return os(Ai(n.renderMode,!0),"full",t,n);let o=e.length===1?Jl(r,bs):null;if(o)return os(qf(o),o.id,t,n);let s=Ql(e[0],e.slice(1));if(s)return os(s,e.filter(Boolean).join(" "),t,n);if(r==="topic"){let a=Ql(e[1]);if(a)return os(a,e[1]??"overview",t,n);let l=new URLSearchParams;return e[1]&&l.set("topic",e[1]),await ie(`/api/v1/help${Re(l)}`,t,n,"Help topic loaded.")}if(r==="standards")return await ie("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let a=await E(n,"/api/v1/marketplace/status");return t.json?R(a,"Marketplace status loaded.",!0,n):R(I9(a),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let a=await E(n,"/api/v1/capabilities");return R(P9(a),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return P("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let a=F(t.text,"help optimize-tokens requires --text."),l=E9(t.maxCharacters,t.json);if(Z(l))return l;let c=await E(n,"/api/v1/optimize-tokens",{method:"POST",headers:U(n.apiKey),body:JSON.stringify({text:a,...l?{maxCharacters:l}:{}})});return R(c,"Token optimization complete.",t.json,n)}return P(`Unknown help command "${r}".`,t.json)}function os(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 Iw(e,t){let n=e.filter(Boolean).join(" ").trim()||"help";return S({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 f4(e,t,n){let r=F(e[0]??t.path,"validate requires a file or directory."),i=tt(n.cwd,r);if(!await Ke(i))return LD("validate",r,t,n);let o=(await Uo({cwd:n.cwd,sourcePath:r,limits:hi})).files;o=await p4({files:o,resolvedTarget:i,flags:t,backend:n});let s=Ie(o,{profile:oh}),a={files:o,sourceIntakeContext:v(t.sourceIntakeContext),publicationStatus:v(t.publicationStatus),dependencyAuditStatus:v(t.dependencyAuditStatus),category:v(t.category),discloseSource:!!t.discloseSource},l,c=()=>E(n,"/api/v1/validation/preview",{method:"POST",headers:U(n.apiKey),body:JSON.stringify(W(a))});try{l=await c().catch(async _=>{if(_ instanceof V&&_.status<500)throw _;return await n.sleep(1e3),c()})}catch(_){if(_ instanceof V&&_.status===422&&_.details)l=mJ(_.details);else throw _}let u=s.issues.filter(_=>_.code.startsWith("license_")),d=L(l,"validation")??l,p=[...u,...ms(d,l,"warnings"),...ms(d,l,"issues").filter(_=>O(_)&&_.severity==="warning"),...ms(l,d,"warnings")],m=new Set,g=m4({...l,license:s.license,licenseIssues:u,warnings:p.filter(_=>{let I=O(_)?`${_.code}:${_.message}`:String(_);return m.has(I)?!1:(m.add(I),!0)})},o),h=g.valid===!1||L(g,"validation")?.valid===!1,y=typeof g.publishReadiness=="string"?g:SP({valid:!h,securityReport:L(g,"securityReport")}),w={...g,publishReadiness:y.publishReadiness,publishReadinessSummary:y.publishReadinessSummary,publishReadinessFinding:y.publishReadinessFinding??null},b=!h&&y.publishReadiness==="blocked";return t.json?h?S({...Gw(g,n.renderMode.detail,"validate"),nextAction:"validate",nextStep:"Fix the listed issues, then run validate again."},"Validation failed.",!0,"bundle_invalid"):b?S({...Gw(w,n.renderMode.detail,"validate"),nextAction:"validate",nextStep:"Remove the behaviour the security review blocked, then run validate again."},y.publishReadinessSummary,!0,"validation_security_blocked"):R(w,y.publishReadiness==="needs_admin_review"?y.publishReadinessSummary:"Validation complete.",!0,n,"validate"):{exitCode:h||b?1:0,stdout:D9(w,r,n),stderr:""}}async function p4(e){if(Ie(e.files).license?.status==="verified"||e.flags.json||!e.backend.stdoutIsTty)return e.files;let n=await nd({cwd:e.backend.cwd,files:e.files,skip:!1,interactive:!0,prompt:iD(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 Bi(e.resolvedTarget)).isDirectory()?e.resolvedTarget:ye(e.resolvedTarget),s=`creator_patch_${me("sha256").update(o).update("\0").update(e.backend.now()).digest("hex").slice(0,24)}`;try{await td({targetDir:o,files:yh(e.files,n.selection),confirmed:!0})}catch(a){throw await Lr(e.backend,"patch","failed",s),a}return await Lr(e.backend,"patch","succeeded",s),(await Uo({cwd:e.backend.cwd,sourcePath:o})).files}function m4(e,t){return{...e,evalReadiness:Sh(t),excludedFromRuntime:Wi(t)}}function g4(e,t){let n=h4(e);return Eo({status:n?"not_run":"generated_only",skillSlug:t.skillSlug,version:t.version,artifactDigest:Fe(e),...n?{evalPackDigest:n}:{},generatedAt:t.generatedAt,runnerVersion:In,counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})}function h4(e){let t=e.find(n=>{let r=zt(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 Po(JSON.parse(t.content))}catch{return}}async function y4(e,t,n){let r=F(e[0]??t.path,"preview-trigger requires a file or directory."),i=tt(n.cwd,r);if(!await Ke(i))return LD("preview-trigger",r,t,n);let o=(await Uo({cwd:n.cwd,sourcePath:r,limits:hi})).files,s=await E(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:U(n.apiKey),body:JSON.stringify({files:o,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?R(s,"Trigger preview complete (keyword-overlap lint; no agent was run, so these are not trigger rates).",!0,n):{exitCode:0,stdout:T9(s,r,n),stderr:""}}async function w4(e,t,n){let r=e[0];if(["create","sessions","resume","cancel","inspect","answer","resources","resource-decide","tool-contract","draft","validate","eval","improve","revise","materialize","finalize"].includes(r??""))return await v4(r,e.slice(1),t,n);if(r==="init")return await _4(e.slice(1),t,n);if(r==="rules")return await ie("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(r==="submissions")return await ie("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(r==="status"){let i=F(e[1],"creator status requires a skill slug.");try{let o=await E(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/status`,{headers:H(n.apiKey,n.authBlockedMessage)}),s=L(o,"processing");!f(o,"nextStep")&&s&&["queued","running"].includes(String(s.status))&&(o.nextAction="creator.status",o.nextStep=`Check creator status in 30 seconds; ${s.stage==="semantic_security"?"the security review":"evaluation"} is still in progress.`);let a=L(L(o,"submission")??{},"latestFailure"),l=L(o,"evaluation"),c=[...Array.isArray(o.warnings)?o.warnings:[],...s&&s.history!==!0?[`Processing stage: ${f(s,"stage")}; status: ${f(s,"status")}.`]:[],...l?[`Eval outcome: ${f(l,"summary")}`]:[],...a?[`Latest attempt ${f(a,"version")}: ${f(a,"reasonCode")}.`]:[]];return R(y_({...o,...c.length?{warnings:c}:{}}),f(o,"summary")??"Submission status loaded.",t.json,n)}catch(o){if(o instanceof V&&o.status===404)return T4(i,t);throw o}}if(r==="charge-status"){let i=F(e[1],"creator charge-status requires a charge id.");return await ie(`/api/v1/me/private-skill-charges/${encodeURIComponent(i)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(r==="spaces")return await x4(e.slice(1),t,n);if(r==="submit")return await Pw(e.slice(1),t,n,!1);if(r==="submit-version")return await Pw(e.slice(1),t,n,!0);if(r==="check-slug"){let i=F(e[1],"creator check-slug requires a slug.");return await E4(i,t,n)}if(r==="rename"){let i=F(e[1],"creator rename requires the current slug."),o=F(e[2],"creator rename requires the new slug."),s=tD("creator.rename",o,t);return s||await Ei(`/api/v1/me/submissions/${encodeURIComponent(i)}/slug`,{nextSkillSlug:o},t,n,"Skill renamed.")}if(r==="pricing")return await L4(e,t,n);if(r==="update-listing"){let i=F(e[1],"creator update-listing requires a skill slug.");return await O4(i,t,n)}if(r==="visibility"){let i=F(e[1],"creator visibility requires a skill slug."),o=Fr("creator.visibility",t);if(o)return o;let s=v(t.visibility)??e[2],a=na(s);if(!a||!bl.includes(a))return S({status:"error",reasonCode:"invalid_visibility",skillSlug:i,visibility:s??null,acceptedValues:bl,nextAction:"creator.visibility.update",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${bl.join(", ")}.`,t.json,"invalid_visibility");let l=await E(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/visibility`,{method:"PATCH",headers:U(n.apiKey),body:JSON.stringify(W({visibility:a,dryRun:t.dryRun}))});return q3(l)?S(l,V3(l,i),t.json,f(l,"reasonCode")??f(l,"status")):R(l,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(r==="trust"){let i=F(e[1],"creator trust requires a skill slug."),o=new URLSearchParams;be(o,"version",t.version),be(o,"versionId",t.versionId);let s=await E(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/platform-score${Re(o)}`,{headers:H(n.apiKey,n.authBlockedMessage)});return!t.json&&hd(s)?{exitCode:0,stdout:$t(jh(s)),stderr:""}:R(s,"Platform Score loaded.",t.json,n)}if(r==="security-report"){let i=F(e[1],"creator security-report requires a skill slug."),o=nD("creator.security-report",t);if(o)return o;let s=Fr("creator.security-report",t);if(s)return s;let a=new URLSearchParams;be(a,"format",t.format),be(a,"version",t.version),be(a,"versionId",t.versionId);let l=await E(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security-report${Re(a)}`,{headers:H(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?R(l,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:W9(l,i,n),stderr:""}}if(r==="rescan-security"){let i=F(e[1],"creator rescan-security requires a skill slug."),o=Fr("creator.rescan-security",t);if(o)return o;let s=await E(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security/rescan`,{method:"POST",headers:U(n.apiKey),body:JSON.stringify(W(rt(t,["version","versionId"])))});return t.json?R(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:J9(s,i,n),stderr:""}}if(r==="provenance"){let i=F(e[1],"creator provenance requires a skill slug.");return await ie(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership`,t,n,"Provenance loaded.",{authenticated:!0})}if(r==="claim"||r==="verify"||r==="dispute")return await B4(r,e,t,n);if(r==="issues"||r==="reviews"||r==="update-issue"||r==="moderate-review")return await V4(r,e,t,n);if(r==="analytics"){let i=F(e[1],"creator analytics requires a skill slug.");return await N4(i,t,n)}if(r==="delist"||r==="relist"){let i=F(e[1],`creator ${r} requires a skill slug.`),o=v(t.reason)??(r==="relist"?"Creator relisted skill":"");return o.trim().length<3?P("creator delist requires --reason (at least 3 characters).",t.json,n.invocationArgs):await Ei(`/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 ie("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(r==="payout-profile")return v(t.country)?await YE(t,n):await M4(t,n);if(r==="payout-link")return await YE(t,n);if(r==="payouts")return await ie("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(r==="withdraw"){if(!v(t.amountCents))return P("creator withdraw requires --amount-cents.",t.json,n.invocationArgs);let i=Mr(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});if(i.failure)return i.failure;let o=v(t.idempotencyKey)??ZW(),s=t.json?await E(n,"/api/v1/me/payout-profile",{headers:H(n.apiKey,n.authBlockedMessage)}).then(g=>({payoutCurrency:g.profile.currency,payoutDisclosure:Mv(g.profile.currency)})):{};if(t.json&&!v(t.mfaCode))return S({...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 S({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=aD(t,n),l=W({amountCents:i.value,reason:v(t.reason)}),c={...U(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: ${le(Number(d.amountCents??i.value),String(d.currency??"usd"))}, remaining withdrawable balance ${typeof d.withdrawableAfterCents=="number"?le(d.withdrawableAfterCents,"usd"):"unknown"}.
|
|
1027
|
+
`+(typeof d.payoutDisclosure=="string"?`${d.payoutDisclosure}
|
|
1028
|
+
`:"")+`Type exactly "${u.confirmationPhrase}" to confirm: `)!==u.confirmationPhrase){let g=`skills-layer creator withdraw --amount-cents ${i.value}`;return S({status:"cancelled",reasonCode:"withdrawal_confirmation_mismatch",withdrawalRequested:!1,nextAction:"creator.withdraw",nextStep:`Run \`${g}\` again and type the confirmation phrase exactly as shown.`},"No withdrawal was requested: the confirmation phrase did not match. Your balance is unchanged.",!1,"withdrawal_confirmation_mismatch")}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 K4(e.slice(1),t,n):P(`Unknown creator command "${r??""}".`,t.json,n.invocationArgs)}var GE="\0derived";function Rw(e,t){return`${e}-${me("sha256").update(JSON.stringify(t)).digest("hex").slice(0,32)}`}async function v4(e,t,n,r){let i=v(n.idempotencyKey)??(e==="create"?`creator-${ke(12).toString("hex")}`:GE),o=v(n.sessionId)??t[0],s=v(n.expectedRevision),a=s===void 0?void 0:Number(s);if(s!==void 0&&(!Number.isInteger(a)||Number(a)<1))return P("--expected-revision must be a positive integer.",n.json,r.invocationArgs);let l=m=>{if(!o)throw new Error(`creator ${m} requires a session id.`);if(a===void 0)throw new Error(`creator ${m} requires --expected-revision.`);return{sessionId:o,expectedRevision:a,idempotencyKey:i}},c,u="POST",d;if(e==="create"){let m=v(n.skill)??t[0],g=v(n.outcome)??v(n.description),h=v(n.mode)??"guided";h==="guided"&&!n.json&&r.stdoutIsTty&&(m||(m=(await r.promptText(`Choose a unique kebab-case skill name:
|
|
1029
|
+
> `)).trim()),g||(g=(await r.promptText(`What outcome should this skill reliably produce?
|
|
1030
|
+
> `)).trim())),d=W({idempotencyKey:i,mode:h,outcome:g,skillSlug:m,description:v(n.description),license:v(n.license),importedCandidateId:v(n.importedCandidateId)}),c="/api/v1/creator/sessions"}else if(e==="sessions")c="/api/v1/creator/sessions",u="GET";else if(e==="resume"){if(!o)return P("creator resume requires a skill slug or session id.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/resume/${encodeURIComponent(o)}`,u="GET"}else if(e==="inspect"){if(!o)return P("creator inspect requires a session id.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(o)}`,u="GET"}else if(e==="cancel"){let m=l("cancel");c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/cancel`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,...v(n.reason)?{reason:v(n.reason)}:{}}}else if(e==="answer"){let m=l("answer"),g=v(n.questionId);if(g){let h;if(n.answerJson!==void 0)h=It(n.answerJson,"answer-json");else if(!n.json&&r.stdoutIsTty){let y=await E(r,`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}`,{headers:H(r.apiKey,r.authBlockedMessage)}),w=cs(y);if(!w)throw new Error("Creator response did not include the canonical interview turn");if(!w.currentQuestion||w.currentQuestion.id!==g)return P("The requested question is not the session's current canonical question.",n.json,r.invocationArgs);h=Yu(g,await r.promptText(`${w.currentQuestion.prompt}
|
|
1031
|
+
> `))}else return P("creator answer --question-id requires --answer-json outside an interactive terminal.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/turn-answers`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,questionId:g,answer:h}}else if(n.answers!==void 0){let h=It(n.answers,"answers");if(!h||typeof h!="object"||Array.isArray(h))return P("creator answer requires --answers with a JSON object.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/answers`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,...v(n.skill)?{skillSlug:v(n.skill)}:{},answers:h}}else{if(n.json||!r.stdoutIsTty)return P("creator answer requires --question-id and --answer-json outside an interactive terminal.",n.json,r.invocationArgs);let h=await E(r,`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}`,{headers:H(r.apiKey,r.authBlockedMessage)}),y;!Gx(h)&&!v(n.skill)&&(y=(await r.promptText(`Choose a unique kebab-case skill name:
|
|
1032
|
+
> `)).trim());let w=cs(h,!1);if(w?.currentQuestion){let b=Yu(w.currentQuestion.id,await r.promptText(`${w.currentQuestion.prompt}
|
|
1033
|
+
> `));c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/turn-answers`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,questionId:w.currentQuestion.id,answer:b,...v(n.skill)??y?{skillSlug:v(n.skill)??y}:{}}}else{let b=await qx({suggestedDomain:Vx(h),promptText:r.promptText});c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/answers`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,answers:b,...v(n.skill)??y?{skillSlug:v(n.skill)??y}:{}}}}}else if(e==="resources"){let m=l("resources"),g=n.suppliedResourcesJson===void 0?void 0:It(n.suppliedResourcesJson,"supplied-resources-json");if(g!==void 0&&!Array.isArray(g))return P("creator resources --supplied-resources-json must be a JSON array.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/resource-plan`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,...g?{suppliedResources:g}:{}}}else if(e==="resource-decide"){let m=l("resource-decide"),g=It(n.decisionsJson,"decisions-json");if(!Array.isArray(g))return P("creator resource-decide requires --decisions-json with a JSON array.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/resource-decisions`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,decisions:g}}else if(e==="tool-contract"){let m=l("tool-contract"),g=It(n.patchJson,"patch-json");if(!g||typeof g!="object"||Array.isArray(g))return P("creator tool-contract requires --patch-json with a JSON object.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/tool-contract`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,patch:g}}else if(e==="draft"){let m=l("draft"),g=!!n.apply;if(!n.dryRun&&!g)return P("creator draft requires --dry-run or --apply.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/${g?"draft-apply":"draft-plan"}`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,...g?{planDigest:F(v(n.planDigest),"creator draft --apply requires --plan-digest.")}:{}}}else if(e==="validate"){let m=l("validate");c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/validate`;let g=n.license!==void 0||n.licenseFile!==void 0||n.skipLicense||n.licenseHolder!==void 0||n.licenseYear!==void 0?(await nd({cwd:r.cwd,explicitIdentifier:v(n.license),explicitLicenseFile:v(n.licenseFile),explicitCopyrightHolder:v(n.licenseHolder),explicitYear:v(n.licenseYear),skip:!!n.skipLicense,interactive:!1})).selection:void 0;g&&"filePath"in g&&delete g.filePath,d={expectedRevision:m.expectedRevision,idempotencyKey:i,...g===void 0?{}:{licenseSelection:g},...v(n.category)===void 0?{}:{category:v(n.category)}}}else if(e==="eval"){let m=l("eval"),g=n.callerCapabilitiesJson===void 0?void 0:It(n.callerCapabilitiesJson,"caller-capabilities-json");if(g!==void 0&&(!g||typeof g!="object"||Array.isArray(g)))return P("creator eval --caller-capabilities-json must be a JSON object.",n.json,r.invocationArgs);let h=n.observationsJson===void 0?void 0:It(n.observationsJson,"observations-json");if(h!==void 0&&!Array.isArray(h))return P("creator eval --observations-json must be a JSON array.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/evals`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,...g?{callerCapabilities:g}:{},...v(n.challengeDigest)?{challengeDigest:v(n.challengeDigest)}:{},...h?{observations:h}:{}}}else if(e==="improve"){let m=l("improve"),g=!!n.apply;if(g&&!v(n.planDigest))return P("creator improve --apply requires --plan-digest.",n.json,r.invocationArgs);let h=n.additionalEvidenceJson===void 0||g?void 0:It(n.additionalEvidenceJson,"additional-evidence-json");if(h!==void 0&&!Array.isArray(h))return P("creator improve --additional-evidence-json must be a JSON array.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/improvements${g?"/apply":""}`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,...g?{planDigest:v(n.planDigest)}:{},...h?{additionalEvidence:h}:{}}}else if(e==="revise"){let m=l("revise"),g=It(n.patchJson,"patch-json");if(!g||typeof g!="object"||Array.isArray(g)||!Array.isArray(g.files)||g.files.length===0)return P("creator revise --patch-json must contain a non-empty files array.",n.json,r.invocationArgs);let h=g,y=n.dryRun===!0;if(!y&&!v(n.planDigest))return P("creator revise apply requires --plan-digest from creator revise --dry-run.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/revisions${y?"/preview":""}`,d={expectedRevision:m.expectedRevision,...y?{}:{idempotencyKey:i,planDigest:v(n.planDigest)},files:h.files,...typeof h.skillSlug=="string"?{skillSlug:h.skillSlug}:{}}}else if(e==="materialize"){if(!o)return P("creator materialize requires a session id.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(o)}/materialize`}else{let m=l("finalize"),g=Mr(n.priceCents,"--price-cents","priceCents","invalid_price_cents",n,{minimum:0});if(g.failure)return g.failure;let h=n.tagsJson===void 0?void 0:It(n.tagsJson,"tags-json");if(h!==void 0&&(!Array.isArray(h)||!h.every(y=>typeof y=="string"&&y.trim().length>0)))return P("creator finalize --tags-json must be a JSON array of non-empty strings.",n.json,r.invocationArgs);c=`/api/v1/creator/sessions/${encodeURIComponent(m.sessionId)}/finalize`,d={expectedRevision:m.expectedRevision,idempotencyKey:i,version:F(v(n.version),"creator finalize requires --version."),...v(n.visibility)?{visibility:v(n.visibility)}:{},...g.value!==void 0?{priceCents:g.value}:{},...v(n.category)?{category:v(n.category)}:{},...h?{tags:h}:{},...n.attestRights?{attestRights:!0,rightsBasis:v(n.rightsBasis),distributionScope:v(n.distributionScope),sourceReference:v(n.sourceReference)}:{}}}d?.idempotencyKey===GE&&(d.idempotencyKey=Rw("creator",{subcommand:e,endpoint:c,body:{...d,idempotencyKey:null}}));let p=await E(r,c,{method:u,headers:u==="GET"?H(r.apiKey,r.authBlockedMessage):U(r.apiKey),...d?{body:JSON.stringify(d)}:{}});if((e==="create"||e==="resume")&&!n.json&&r.stdoutIsTty&&cs(p,!1)&&(p=await b4(p,r)),e==="materialize"){let m;try{m=zx(p.data)}catch(w){let b=w;return await Lr(r,"materialize","failed",`creator_materialize_failed_${me("sha256").update(c).update("\0").update("unknown").digest("hex").slice(0,24)}`),S(p,b.message,n.json,b.reasonCode)}let g=v(n.dir)?tt(r.cwd,v(n.dir)):z(r.cwd,m.skillSlug);if(!n.confirmed){let w=await Yx({targetDir:g,files:m.files});return await Lr(r,"plan","succeeded",`creator_plan_${me("sha256").update(g).update("\0").update(m.skillSlug).update("\0").update(r.now()).digest("hex").slice(0,24)}`),R({...p,materialization:{status:"preview",plan:w},nextAction:"creator.materialize",nextStep:`Review the file plan, then run skills-layer creator materialize ${o} --dir ${JSON.stringify(g)} --confirm.`},"Materialization preview; no files written.",n.json,r)}let h=`creator_materialize_${me("sha256").update(g).update("\0").update(m.skillSlug).digest("hex").slice(0,24)}`,y;try{y=await td({targetDir:g,files:m.files,confirmed:!0})}catch(w){return await Lr(r,"materialize","failed",`${h}:failed`),P(ne(w),n.json,r.invocationArgs)}return await Lr(r,"materialize","succeeded",h),R({...p,materialization:y},`Creator workspace materialized at ${g}.`,n.json,r)}if(e==="revise"){n.dryRun&&!f(p,"nextStep")&&(p.nextAction="creator.revise",p.nextStep="Review the replacement digest, then apply it with this exact plan digest and session revision.");let m=L(p,"data")??p,g=Array.isArray(m.removedPaths)?m.removedPaths.filter(h=>typeof h=="string"):[];g.length&&(p.warnings=[`Files removed: ${g.join(", ")}`,...g.includes(".skills-layer/skill.yaml")?["The required root control manifest is removed; validation will fail until it is restored."]:[]])}return R(p,typeof p.summary=="string"?p.summary:`Creator ${e} completed.`,n.json,r)}async function b4(e,t){let n=e,r=null;for(;;){await zE(n,t,!1);let i=cs(n);if(!i)throw new Error("Creator response did not include the canonical interview turn");if(!i.currentQuestion)try{let u=await E(t,`/api/v1/creator/sessions/${encodeURIComponent(String(n.sessionId))}/resource-plan`,{method:"POST",headers:U(t.apiKey),body:JSON.stringify({expectedRevision:n.revision,idempotencyKey:Rw("creator-resource",{sessionId:n.sessionId,revision:n.revision})})});return await zE({...n,revision:u.revision},t,!0),u}catch(u){throw aw(u,n)}let o=i.confirmationSummary?`Review the normalized interview:
|
|
1034
|
+
${JSON.stringify(i.confirmationSummary,null,2)}
|
|
1035
|
+
`:"",s=i.currentQuestion.suggestedAnswer?`
|
|
1036
|
+
Suggested answer: ${i.currentQuestion.suggestedAnswer}`:"",a=r?`Previous answer was not accepted: ${r}
|
|
1037
|
+
`:"",l;try{l=await t.promptText(`${o}${a}[${i.progress.questionNumber}/${i.progress.maximumQuestions}] ${i.currentQuestion.prompt}${s}
|
|
1038
|
+
Why: ${i.currentQuestion.whyAsked}
|
|
1039
|
+
> `)}catch(u){throw aw(u,n)}let c;try{c=Yu(i.currentQuestion.id,l)}catch(u){r=ne(u);continue}try{n=await E(t,`/api/v1/creator/sessions/${encodeURIComponent(String(n.sessionId))}/turn-answers`,{method:"POST",headers:U(t.apiKey),body:JSON.stringify({expectedRevision:n.revision,idempotencyKey:Rw("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 V&&u.status===422){r=ne(u);continue}throw aw(u,n)}}}async function zE(e,t,n){await _e(z(t.paths.stateDir,"creator-resume.json"),{version:1,baseUrl:t.baseUrl,sessionId:String(e.sessionId),skillSlug:cs(e,!1)?.skillSlug??null,revision:e.revision,completed:n,savedAt:t.now()})}function aw(e,t){let n=cs(t,!1)?.skillSlug||String(t.sessionId),r=e instanceof V&&e.status===409?" The server revision is authoritative; reload it before answering again.":"";return new Error(`${ne(e)}${r} Resume with skills-layer creator resume ${n}.`)}function cs(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 _4(e,t,n){let r=v(t.skill)??e[0]??"my-skill",i=tD("creator.init",r,t);if(i)return i;if(t.quick&&!v(t.outcome))return P("creator init --quick requires --outcome.",t.json,n.invocationArgs);let o=v(t.dir)?tt(n.cwd,v(t.dir)):z(n.cwd,r),s;try{s=Mx(v(t.type))}catch(w){return P(ne(w),t.json,n.invocationArgs)}let a=v(t.category),l=await Jx(o),c=await nd({cwd:n.cwd,files:l.files,explicitIdentifier:v(t.license),explicitLicenseFile:v(t.licenseFile),skip:!!t.skipLicense,interactive:!t.json&&n.stdoutIsTty,prompt:iD(n)}),u=jx({skillSlug:r,description:v(t.description)??v(t.outcome)??`Helps with ${r.replaceAll("-"," ")}.`,...t.quick?{quickOutcome:v(t.outcome)}:{},skillType:s,category:a,licenseSelection:c.selection}),d=`creator_init_${me("sha256").update(o).update("\0").update(r).update("\0").update(n.now()).digest("hex").slice(0,24)}`,p;try{p=await td({targetDir:o,files:u,confirmed:t.confirmed})}catch(w){throw await Lr(n,"materialize","failed",d),w}if(await Lr(n,p.status==="confirmation_required"?"plan":"materialize","succeeded",d),p.status==="confirmation_required"){let w={status:"confirmation_required",reasonCode:"scaffold_overwrite_confirmation_required",targetDir:p.plan.targetDir,changes:p.plan.changes,preservedEntryCount:p.plan.preservedEntryCount,nextAction:"creator.init",nextStep:"Review the reported create/replace diff, then rerun with --confirm only if every replacement is intended."};return S(w,k4(p.plan),t.json,"scaffold_overwrite_confirmation_required")}let m=Ie(u),g=Sh(u),h=z(p.plan.targetDir,"SKILL.md"),y=W({status:p.status,path:h,skillSlug:r,skillType:s,category:a,targetDir:p.plan.targetDir,files:u.map(w=>w.path),fileCount:u.length,licenseStatus:m.license?.status??"unspecified",licenseIdentifier:m.license?.identifier??void 0,licenseSource:c.source,evaluationStatus:g.status,evalReadiness:g,warnings:[...m.issues.filter(w=>w.severity==="warning"),...g.status==="attention_needed"?[{severity:"warning",code:"evaluation_readiness_limited",message:"The scaffold is structurally valid, but its evaluation readiness needs attention before submission."}]:[]],validation:m});return t.json?R(y,`Created ${h}.`,!0,n):{exitCode:0,stdout:M9(y,p.plan.targetDir,h,n),stderr:""}}function iD(e){return{select:(t,n)=>e.promptSelect(t,n),text:t=>e.promptText(t)}}function k4(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(`
|
|
1040
|
+
`)}async function Ke(e){try{return await K0(e),!0}catch{return!1}}async function S4(e){try{return(await Bi(e)).isFile()}catch{return!1}}function oD(e){return e.attestRights?{attestRights:!0,rightsBasis:v(e.rightsBasis)??"self_authored",distributionScope:v(e.distributionScope)??"commercial_distribution",rightsDeclarationVersion:SR}:{}}async function Pw(e,t,n,r){let i=v(t.visibility);if(i){let C=na(i);if(!C||!bl.includes(C))return Un(r?"creator.submit-version":"creator.submit","visibility",i,bl,t,"invalid_visibility")}let o=Mr(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let s=v(t.spacePack),a=s===void 0?void 0:_s(s);if(a===null)return Un(r?"creator.submit-version":"creator.submit","spacePack",s,["5","10","20","50"],t,"invalid_private_skill_space_pack","space-pack");let l=v(t.creatorSessionId);if(l){let C=r?F(v(t.skill)??e[0],"creator submit-version with --creator-session-id requires a skill slug."):null,D=r?{creatorSessionId:l,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",...t.dryRun?{dryRun:!0}:{}}:{creatorSessionId:l,...t.dryRun?{dryRun:!0}:{},...a?{privateSkillSpacePack:a}:{}},T=r?`/api/v1/me/submissions/${encodeURIComponent(C)}/versions`:"/api/v1/me/submissions",j=await E(n,T,{method:"POST",headers:KE(n,t.dryRun?null:{path:T,creatorSessionId:l}),body:JSON.stringify(D)});return HE(j,t,n)??R(j,t.dryRun?F0(j):j.status==="submission_incomplete"?`Creator session submission is incomplete. ${f(j,"nextStep")??"Retry this session submission to complete finalization."}`:"Finalized Creator session submitted.",t.json,n)}let c=r?F(v(t.skill)??e[0],"creator submit-version requires a skill slug."):v(t.skill),u=F(v(t.source)??(r?e[1]:e[0])??t.path,`creator ${r?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),d=await $l(u,n.cwd);if(t.list)return await I4(u,d,c,t,n);let p=Fr(r?"creator.submit-version":"creator.submit",t);if(p)return p;if(!d&&!xl(u)&&(PT(u)||/^(?:github|gitlab):/iu.test(u)))return R4(u,t);let m=d?.files??(await Uo({cwd:n.cwd,sourcePath:u,limits:hi})).files;if(t.dryRun&&Ed(m))return C4(m,{slug:c,flags:t,backend:n});if(!r){let C=await P4(m,t,n);if(C)return C}let g=Ed(m)?await cy({baseUrl:n.baseUrl,apiKey:n.apiKey,fetchFn:n.fetchFn,files:m}):null,h=W({...g?{hydrationManifestId:g.manifestId}:{files:m},version:v(t.version),dryRun:t.dryRun,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",evalSummary:g4(m,{skillSlug:c??tv(m)??"unknown",version:v(t.version)??"0.0.0",generatedAt:n.now()}),replaceUnpublished:r&&t.replaceUnpublished===!0?!0:void 0,priceCents:o.value,privateSkillSpacePack:a,...oD(t),...d?{sourceMetadata:d.sourceMetadata}:{},...rt(t,["displayName","skillType","category","visibility","source","skill"])}),y=r&&c?`/api/v1/me/submissions/${encodeURIComponent(c)}/versions`:"/api/v1/me/submissions",w=await E(n,y,{method:"POST",headers:KE(n,t.dryRun?null:{path:y,request:h,files:m}),body:JSON.stringify(h)});if(w.excludedFromRuntime=Wi(m),t.json||t.noOpen||w.status!=="checkout_required"||typeof w.checkoutUrl!="string"||typeof w.chargeId!="string")return HE(w,t,n)??R(w,t.dryRun?F0(w):w.status==="submission_incomplete"?`${r?"Version":"Submission"} saved, but finalisation is incomplete. ${f(w,"nextStep")??"Run creator status for this skill and follow its recovery step."}`:r?"Version submitted.":"Submission uploaded.",t.json,n);let b=L(w,"spacePack"),_=b?_s(b.code):null;n.emitInfo(_?`No private skill space is left. Opening checkout for ${Zl(_).label} (${Zl(_).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(w.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${w.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let x=await GW(w.chargeId,n);return Z(x)?x:x.status!=="submitted"?R({...w,chargeStatus:x.status},`Payment is still ${x.status}. You can rerun \`skills-layer creator charge-status ${w.chargeId}\` to continue tracking it.`,t.json,n):R(x,r?"Version submitted.":"Submission uploaded.",t.json,n)}function KE(e,t){let n=U(e.apiKey);if(!t)return n;let{hydrationManifestId:r,files:i,evalSummary:o,...s}=t.request??{},a=t.files?me("sha256").update(JSON.stringify(t.files.map(c=>[c.path,c.content??null,c.contentBase64??null]))).digest("hex"):null,l=me("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 HE(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 C4(e,t){let n="creator.submit",r=Ie(e,{profile:oh}),i=e.reduce((l,c)=>l+Ki(c),0),o=t.slug??tv(e),s=["skill_name_availability","security_review","moderation","pricing_and_checkout","eval_evidence"],a=W({status:r.valid?"ready":"blocked",reasonCode:r.valid?"local_preview_only":"invalid_bundle",dryRun:!0,previewMode:"local",operation:n,uploaded:!1,skillSlug:o,version:v(t.flags.version),bundle:{fileCount:e.length,totalBytes:i,transport:"source_hydration",artifactDigest:Fe(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 A4="Use `skills-layer creator spaces` or `skills-layer creator spaces buy --pack 5|10|20|50`.";function WE(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\`: ${wb}.`}async function x4(e,t,n){let r=e[0];if(r===void 0||r==="status"){let u=await E(n,"/api/v1/me/private-skill-spaces",{headers:H(n.apiKey,n.authBlockedMessage)});return R(u,WE(u),t.json,n)}if(r!=="buy")return P(`Unknown creator spaces action "${r}". ${A4}`,t.json,n.invocationArgs);let i=v(t.pack)??e[1],o=i===void 0?void 0:_s(i);if(o===null)return Un("creator.spaces.buy","pack",i,["5","10","20","50"],t,"invalid_private_skill_space_pack","pack");let s=await E(n,"/api/v1/me/private-skill-spaces/checkout",{method:"POST",headers:U(n.apiKey),body:JSON.stringify(o?{privateSkillSpacePack:o}:{})});if(s.status!=="checkout_required"||typeof s.checkoutUrl!="string")return R(s,WE(s),t.json,n);let a=Zl(_s(L(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 I4(e,t,n,r,i){if(t)return R(JE(lv(e,t,n)),"Source skills loaded.",r.json,i);let o=await xD(i,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},r);return o.kind==="failure"?o.result:R(JE(o.inspection),"Source skills loaded.",r.json,i)}function JE(e){return{...e,sourceSubmissionSupported:!0}}function R4(e,t){let r=`skills-layer source connection start --provider ${PD(e)} --source ${e} --visibility ${v(t.visibility)??"private"} --provenance-intent private_source_import`;return S({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 P4(e,t,n){let r=v(t.skill)??tv(e);if(!r)return null;let i;try{i=await E(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(r)}`,{headers:H(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof V&&o.status===404)return sD(r,t);throw o}if(i.available===!1||f(i,"reasonCode")==="unavailable"||f(i,"reasonCode")==="reserved"){let o=f(i,"assignedSlug"),s=W({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 S(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 E4(e,t,n){try{let r=await E(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:H(n.apiKey,n.authBlockedMessage)});return R(D4(r),"Slug status loaded.",t.json,n)}catch(r){if(r instanceof V&&r.status===404)return sD(e,t);throw r}}function sD(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 S(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 D4(e){let t=e.available===!0,n=f(e,"assignedSlug");if(t)return W({requestedSlug:f(e,"requestedSlug"),available:!0,reasonCode:f(e,"reasonCode")??"available",assignedSlug:n});let r=L(e,"slugAssignment"),i=Array.isArray(r?.candidateSlugs)?r.candidateSlugs.filter(o=>typeof o=="string").slice(0,3):void 0;return W({...e,...r?{slugAssignment:{...r,...i?{candidateSlugs:i}:{}}}:{},...i?{candidateSlugs:i}:{}})}function T4(e,t){return S({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 tv(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 $4(n??$e(ye(t.path)))}function $4(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function L4(e,t,n){let r=F(e[1],"creator pricing requires a skill slug."),i=Fr("creator.pricing",t);if(i)return i;let o=new URLSearchParams;if(be(o,"version",t.version),!t.priceCents)return await ie(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Re(o)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Mr(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 E(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Re(o)}`,{headers:H(n.apiKey,n.authBlockedMessage)});return d.dryRun!==!0||d.status!=="preview"?P("This backend does not support read-only pricing previews. Upgrade the backend before retrying.",t.json,n.invocationArgs):R(d,"Pricing preview; the live price is unchanged.",t.json,n)}let l=await E(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Re(o)}`,{headers:H(n.apiKey,n.authBlockedMessage)}),c=K(l,"priceCents")??0,u=K(l,"revision");if(!u||!Number.isSafeInteger(u)||u<1)return P("Pricing authority did not return a valid revision.",t.json,n.invocationArgs);if(a>c&&!t.confirmed){let d=W({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 Ei(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing`,{priceCents:a,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:v(t.version),expectedRevision:u,idempotencyKey:v(t.idempotencyKey)?.trim()||`pricing-${ke(12).toString("hex")}`,reason:"Creator changed the version list price through CLI.",...oD(t)},t,n,"Pricing updated.")}async function O4(e,t,n){try{return await Ei(`/api/v1/me/submissions/${encodeURIComponent(e)}`,rt(t,["displayName","summary","description","category","skillType","license"]),t,n,"Listing updated.")}catch(r){if(r instanceof V&&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 S(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}}function F4(e,t){let n=f(e,"verificationToken"),r=f(e,"verificationPath"),i=f(e,"claimId");if(!n||!r||!i)return e;let o=f(e,"proofUrl");return{...e,nextAction:"verify",nextStep:`Commit a file at ${r} containing exactly ${n} to the repository's default branch${o?` (it must be readable at ${o})`:""}, then run skills-layer creator verify ${f(e,"skillSlug")??t} --claim-id ${i}.`}}async function B4(e,t,n,r){let i=F(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let o=Sn("creator.claim","requestedRole",n.requestedRole,OH,n,"invalid_requested_role","requested-role");if(o)return o}try{if(e==="claim"){let o=await E(r,`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/claim`,{method:"POST",headers:U(r.apiKey),body:JSON.stringify(W(rt(n,["requestedRole","message"])))});return R(F4(o,i),"Ownership claim submitted.",n.json,r)}if(e==="verify"){let o=F(n.claimId,"creator verify requires --claim-id."),s=await E(r,`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/verify`,{method:"POST",headers:U(r.apiKey),body:JSON.stringify({claimId:o})});return R(s,f(s,"status")==="manual_review_required"?"Sent for admin review: no linked GitHub or GitLab login with access to the repository proved ownership.":"Ownership claim verified.",n.json,r)}return F(n.message,"creator dispute requires --message."),await pe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/dispute`,rt(n,["message"]),n,r,"Ownership dispute submitted.")}catch(o){if(o instanceof V&&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:v(n.requestedRole),nextAction:e==="claim"?"search":"creator.ownership.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 S(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 N4(e,t,n){try{return await ie(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(r){if(r instanceof V&&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 S(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 M4(e,t){let n=await E(t,"/api/v1/me/payout-profile",{headers:H(t.apiKey,t.authBlockedMessage)});return R(n,"Creator payout profile loaded.",e.json,t)}function aD(e,t){let n={};return(r,i)=>EC({session:n,code:v(e.mfaCode),interactive:!e.json&&!t.nonInteractive&&t.stdoutIsTty,promptSecret:t.promptSecret,verify:async o=>{let s=await E(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:U(t.apiKey),body:JSON.stringify({purpose:"creator_payout",code:o})});return F(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),E(t,r,{...i,headers:s})}})}async function YE(e,t){let n=j4(v(e.mode));if(e.mode&&n===null)return P("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let r;try{r=await aD(e,t)("/api/v1/me/payout-profile/link",{method:"POST",headers:U(t.apiKey),body:JSON.stringify(W({...n?{mode:n}:{},country:v(e.country)}))})}catch(o){if(o instanceof V&&q4(o))return S({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=uT(r);return i&&U4(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 j4(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 U4(e){return!e.json&&!e.noOpen}function q4(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 V4(e,t,n,r){let i=F(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await ie(`/api/v1/me/skills/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await ie(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let l=F(n.issueId,"creator update-issue requires --issue-id."),c=F(n.status,"creator update-issue requires --status."),u=Sn("creator update-issue","status",c,FH,n,"invalid_issue_status");if(u)return u;let d=Fr("creator update-issue",{...n,version:n.fixedVersion});if(d)return d;try{let p=await E(r,`/api/v1/me/skills/${encodeURIComponent(i)}/issues/${encodeURIComponent(l)}`,{method:"PATCH",headers:U(r.apiKey),body:JSON.stringify(W(rt(n,["status","fixedVersion","note"])))});return R(p,p.status==="unchanged"?"Issue unchanged.":"Issue updated.",n.json,r)}catch(p){if(p instanceof V&&p.status===404)return G4(i,l,n);throw p}}let o=F(n.reviewId,"creator moderate-review requires --review-id."),s=n.action==="flag"?"flagged":F(n.status,"creator moderate-review requires --status."),a=Sn("creator moderate-review","status",s,BH,n,"invalid_review_status");if(a)return a;try{return await pe(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews/${encodeURIComponent(o)}/moderate`,rt(n,["action","status","reason"]),n,r,n.action==="flag"?"Review flagged for admin attention. Public visibility is unchanged.":"Review updated.")}catch(l){if(l instanceof V&&l.status===404)return z4(i,o,n);throw l}}function G4(e,t,n){return S({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 z4(e,t,n){return S({status:"not_found",reasonCode:"review_not_found",skillSlug:e,reviewId:t,nextAction:"creator.reviews.summary",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 K4(e,t,n){let r=e[0],i=F(e[1],`creator source ${r??""} requires a source connection id.`),o=v(t.skill)??e[2];if(r==="prepare"){let s=Fr("creator.source.prepare",t);if(s)return s;let a=Sn("creator.source.prepare","visibility",t.visibility,ls,t,"invalid_visibility");if(a)return a;let l=Mr(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=v(t.source)??e[2],u=c?await $l(c,n.cwd):void 0;return await pe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/prepare`,W({...rt(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=Fr("creator.source.publish-request",t);if(s)return s;let a=Sn("creator.source.publish-request","visibility",t.visibility,ls,t,"invalid_visibility");if(a)return a;let l=Mr(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:v(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await pe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/publish-request`,W({skillSlug:o,approvalRequestIds:c,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:v(t.version),...rt(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("skillSlug",o),await ie(`/api/v1/me/source-connections/${encodeURIComponent(i)}/release-status${Re(s)}`,t,n,"Source release status loaded.",{authenticated:!0})}return P(`Unknown creator source command "${r??""}".`,t.json,n.invocationArgs)}function Ew(e){return!e.list&&!e.dryRun}async function ZE(e){if(!Ew(e.flags)||v(e.flags.visibility)==="private"||v(e.flags.scope)==="workspace")return null;if(e.flags.all&&Array.isArray(e.inspection.catalogueDecisions)){let p=[];for(let m of _n(e.inspection)){let g=await gs([],{...e.flags,all:!1,json:!0,source:f(e.inspection,"catalogueSourceInput")??e.source,skill:m.value},e.backend);if(g.exitCode!==0){let h=JSON.parse(g.stderr||g.stdout);return S({status:"source_install_batch_partial",reasonCode:h.reasonCode??"source_install_child_failed",failedSkill:m.value,results:p,failure:h.data},"Source installation stopped; earlier results are retained.",e.flags.json,h.reasonCode??"source_install_child_failed")}p.push(JSON.parse(g.stdout).data)}return R({status:"source_install_batch",results:p},"Source installation results loaded.",e.flags.json,e.backend)}let t=L(e.inspection,"catalogueMatch");if(!t&&e.selectedSkillSlug&&typeof e.inspection.catalogueSourceInput=="string"){let p=await Ow(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=L(p.inspection,"catalogueMatch"),t&&(e.inspection=p.inspection)}if(!t)return null;let n=en(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=>O(p)&&p.skillSlug===e.selectedSkillSlug),c=O(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?S({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"):gs([r],{...e.flags,source:void 0,skill:void 0,version:i},e.backend,{...lD,expectedSourceGeneration:{generationId:o,version:i}})}var lD={origin:"direct",fallbackPolicy:"eligible_public"};function H4(e){return{origin:"update_existing",fallbackPolicy:f(e??{},"acquisitionMode")==="authenticated_account"?"account_required":"eligible_public"}}async function gs(e,t,n,r=lD){let i=await W4(e,t,n,r),o=n.pendingInstallPreferenceUse;return n.pendingInstallPreferenceUse=void 0,i.exitCode===0&&o&&await o(),i}async function W4(e,t,n,r){if(e[0]==="status"&&e[1]){if(t.wait){let h=new AbortController,y=()=>h.abort();process.once("SIGINT",y);try{let w=await PC({read:()=>E(n,`/api/v1/install-receipts/${encodeURIComponent(e[1])}`,{headers:An(n.apiKey),signal:h.signal}),sleep:n.sleep,signal:h.signal,maximumPolls:t.waitPolls===void 0?20:Number(t.waitPolls)});return R(t.json?w:og(w),"Submission progress loaded. Stopping a wait does not cancel server work.",t.json,n)}finally{process.removeListener("SIGINT",y)}}let g=await E(n,`/api/v1/install-receipts/${encodeURIComponent(e[1])}`,{headers:An(n.apiKey)});return R(t.json?g:og(g),i_(e[1]),t.json,n)}if(e[0]==="cancel"&&e[1])return H(n.apiKey,n.authBlockedMessage),pe(`/api/v1/install-receipts/${encodeURIComponent(e[1])}/cancel`,{},t,n,"Cancellation recorded; cleanup may still be pending.");if(e[0]==="select"&&e[1]){let g=v(t.continuationKey),h=v(t.skill);return g||H(n.apiKey,n.authBlockedMessage),h?pe(`/api/v1/install-receipts/${encodeURIComponent(e[1])}/selection${g?"/anonymous":""}`,{selection:h,...g?{continuationKey:g}:{}},t,n,"Selection saved on the existing receipt."):P("Choose one skill with --skill on the existing receipt.",t.json)}let i=rD("install",t);if(i)return i;if(t.localOnly&&(t.visibility!==void 0||v(t.scope)==="workspace"||n.config?.workingModeType==="enterprise_workspace"))return S({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=v(t.source);if(o){if(t.async&&!t.list&&!t.dryRun){let q=en(o),Y=v(t.idempotencyKey),Le=v(t.visibility);if(!["github","gitlab"].includes(q.kind)||!Y||!Le)return P("Asynchronous source submission requires a remote provider source, --visibility and a stable --idempotency-key.",t.json);let Gt=n.apiKey?"/api/v1/me/source-installs":"/api/v1/source-imports";return pe(Gt,{source:o,skillSlug:v(t.skill),all:t.all,visibility:Le,...!n.apiKey&&v(t.continuationKey)?{continuationKey:v(t.continuationKey)}:{}},t,n,"Submission saved. Use install status with its receipt; retry with the same idempotency key.",{"idempotency-key":Y})}let g=v(t.skill),h=n0(o,g,t);if(h)return h;let y=await $l(o,n.cwd);if(y)return await QE(o,y,g,t,n);if(t.localOnly)return S({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let w=r0(o,t);if(w)return w;let b=t.list||t.dryRun||!g&&!t.all,_=await Ow(n,o,{source:o,skillSlug:g,listOnly:b,...t.all?{all:!0}:{},preferCatalogue:Ew(t),visibility:v(t.visibility)},t);if(_.kind==="failure")return _.result;let I=_.inspection;if(t.list)return R(I,"Source skills loaded.",t.json,n);let x=bf(o,I,t);if(x)return x;let C=await _l({source:o,inspection:I,requestedSkillSlug:g,mode:"install",flags:t,backend:n});if(C.kind==="failure")return C.result;if(t.dryRun)return R(Lw(o,I,C.skillSlug,t),"Source install preview ready.",t.json,n);let D=t.all?_n(I).map(q=>q.value):[C.skillSlug??_n(I)[0]?.value??$e(o)],T=await ZE({inspection:I,source:o,selectedSkillSlug:C.skillSlug,flags:t,backend:n});if(T)return T;let j=await LE(n,D,t);if(j)return j;let M=f(I,"catalogueSourceInput")??o,$=await e0({backend:n,flags:t,source:M,skillSlug:C.skillSlug,defaultAcceptUnverifiedSource:Or(o,t,n,_.sourceAccess)==="public"});if(Z($))return $;let B;try{B=await o0({source:M,skillSlug:C.skillSlug,flags:t,backend:n,sourceAccess:_.sourceAccess})}catch(q){if($)return await l0({backend:n,flags:t,source:M,sourceAccess:_.sourceAccess,skillSlug:C.skillSlug??D[0],unverifiedMaterialization:$,error:q});if(q instanceof V)return a0(o,q,t);throw q}return await Al({backend:n,result:B,fallbackSlug:C.skillSlug??f(B,"skillSlug")??o,source:M,sourceAccess:_.sourceAccess,flags:t,requestedVisibility:Or(o,t,n,_.sourceAccess),...$?{unverifiedMaterialization:$}:{}})}let s=F(e[0]??t.install,"install requires a skill slug or --source.");if(PT(s)){let g=n0(s,v(t.skill),t);if(g)return g;let h=await $l(s,n.cwd);if(h)return await QE(s,h,v(t.skill),t,n);if(t.localOnly)return S({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let y=r0(s,t);if(y)return y;let w=v(t.skill),b,_="unknown",I=async q=>{if(b)return null;let Y=await Ow(n,s,{source:s,skillSlug:w,listOnly:q,...t.all?{all:!0}:{},preferCatalogue:Ew(t),visibility:v(t.visibility)},t);return Y.kind==="failure"?Y.result:(b=Y.inspection,_=Y.sourceAccess,null)};if(t.list){let q=await I(!0);return q||R(b,"Source skills loaded.",t.json,n)}if(!w&&!t.all){let q=await I(!0);if(q)return q;let Y=b,Le=bf(s,Y,t);if(Le)return Le;let Gt=await _l({source:s,inspection:Y,requestedSkillSlug:w,mode:"install",flags:t,backend:n});if(Gt.kind==="failure")return Gt.result;w=Gt.skillSlug}if(t.dryRun){let q=await I(!0);if(q)return q;let Y=b,Le=await _l({source:s,inspection:Y,requestedSkillSlug:w,mode:"install",flags:t,backend:n});return Le.kind==="failure"?Le.result:(w=Le.skillSlug,R(Lw(s,Y,w,t),"Source install preview ready.",t.json,n))}let x=await I(!1);if(x)return x;let C=b,D=t.all?_n(C).map(q=>q.value):[w??_n(C)[0]?.value??$e(s)],T=await ZE({inspection:C,source:s,selectedSkillSlug:w,flags:t,backend:n});if(T)return T;let j=await LE(n,D,t);if(j)return j;let M=f(C,"catalogueSourceInput")??s,$=await e0({backend:n,flags:t,source:M,skillSlug:w,defaultAcceptUnverifiedSource:Or(s,t,n,_)==="public"});if(Z($))return $;let B;try{B=await o0({source:M,skillSlug:w,flags:t,backend:n,sourceAccess:_})}catch(q){if($)return await l0({backend:n,flags:t,source:M,sourceAccess:_,skillSlug:w??D[0],unverifiedMaterialization:$,error:q});if(q instanceof V)return a0(s,q,t);throw q}return await Al({backend:n,result:B,fallbackSlug:w??f(B,"skillSlug")??$e(s),source:M,sourceAccess:_,flags:t,requestedVisibility:Or(s,t,n,_),...$?{unverifiedMaterialization:$}:{}})}if(t.localOnly)return S({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");if(v(t.scope)==="workspace"){let g=F(t.workspace,"workspace installs require --workspace <workspace-id>."),h=await cD(n,`/api/v1/workspaces/${encodeURIComponent(g)}/skills/${encodeURIComponent(s)}/approve`,{dryRun:t.dryRun},t);return Z(h)?h:t.dryRun?await DD(h,"Workspace approval preview ready.",t,n):R(h,"Workspace approval requested.",t.json,n)}if(!n.apiKey&&r.fallbackPolicy==="eligible_public")return await lw({target:s,flags:t,backend:n,catalogContext:r});if(!t.dryRun){let g;try{g=await Qw(n,s,t)}catch(h){if(Dw(r,h))return await lw({target:s,flags:t,backend:n,catalogContext:r});throw h}if(g)return g}let a=await dD(s,t,n);if("result"in a)return a.result;let l=a.flags,c=W({skillSlug:s,version:v(l.version),scope:v(l.scope),agent:v(l.agent),allowIncompatible:l.allowIncompatible===!0,dryRun:t.dryRun}),u;try{u=await nv(n,c,t)}catch(g){if(Dw(r,g))return await lw({target:s,flags:t,backend:n,catalogContext:r,effectiveFlags:l});throw g}if(Z(u))return u;let d=u;if(d.status==="purchase_required")return OD(d,s,t,n);if(await Nr(n,d),t.dryRun)return await ED(d,l,n);let p=await rv(n,d,s,l,{expectedSourceGeneration:r.expectedSourceGeneration});if(Z(p))return p;let m=await av(n,{...p,acquisitionMode:"authenticated_account",acquisitionOrigin:r.origin},s,l);return await fs(n,m,s),us(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,Ii(l))}async function lw(e){let t=e.backend.apiKey?{...e.backend,apiKey:void 0,authBlockedMessage:void 0}:e.backend,n=e.effectiveFlags;if(!n){let o=await dD(e.target,e.flags,e.backend);if("result"in o)return o.result;n=o.flags}let r=v(n.version),i={status:"anonymous_public",skillSlug:e.target,...r?{version:r}:{},scope:v(n.scope),agent:v(n.agent),acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin};if(e.flags.dryRun)try{let o=await pf(t,i,e.target,r,{exportMode:"public"});return await ED({...i,...gf(o)},e.flags,t)}catch(o){if(o instanceof V)return Fi(o,e.flags.json);throw o}try{let o=await rv(t,i,e.target,n,{exportMode:"public",expectedSourceGeneration:e.catalogContext.expectedSourceGeneration});if(Z(o))return o;let s=await av(t,{...o,acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin},e.target,n);return await fs(t,s,e.target),us(s,"Public skill installed locally without an account.",e.flags.json,t,Ii(n))}catch(o){if(o instanceof V)return Fi(o,e.flags.json);throw o}}function Dw(e,t){return e.fallbackPolicy==="eligible_public"&&t instanceof V&&t.status===401&&["api_key_invalid_or_expired","api_key_expired"].includes(f(t.details??{},"reasonCode")??"")}async function cD(e,t,n,r){let i=o=>E(e,t,{method:"POST",headers:U(e.apiKey),body:JSON.stringify(o)});try{return await i(n)}catch(o){let s=uD(o);if(!s)throw o;return r.json||!e.stdoutIsTty?S({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"?S({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 nv(e,t,n,r="/api/v1/install"){let i=o=>E(e,r,{method:"POST",headers:U(e.apiKey),body:JSON.stringify(o)});try{return await i(t)}catch(o){let s=uD(o);if(!s)throw o;return n.json||!e.stdoutIsTty?S({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"?S({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 uD(e){if(!(e instanceof V)||e.status!==409||!e.details)return null;let t=O(e.details.data)?e.details.data:e.details,n=O(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 dD(e,t,n){let r=v(t.scope),i=v(t.agent);if(t.dryRun||r==="workspace"||r==="local"||r!==void 0&&i!==void 0)return{flags:t};if(i==="all")return{flags:{...t,scope:r??"project"}};if(t.json||n.nonInteractive||!n.stdoutIsTty){if(i)return{flags:{...t,scope:r??"project"}};let I=(await Vr({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:Ke})).filter(x=>x.detectionSources.includes("project"));return I.length===1?{flags:{...t,agent:I[0].id,scope:r??"project"}}:{result:S({status:"materialization_target_required",reasonCode:"materialization_target_required",skillSlug:e,nextStep:`skills-layer install ${e} --agent <id> --scope project`},"Select an agent and project scope before installing files.",t.json,"materialization_target_required")}}let o=We(n.env,n.platform,n.cwd),s=J4(n),a=await Y4(n.paths.installTargetPreferencePath),l=a?.workingModeId===s,c=l&&a?.agent?o.find(_=>_.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 n.pendingInstallPreferenceUse=()=>_e(n.paths.installTargetPreferencePath,{...a,usesSinceConfirmation:a.usesSinceConfirmation+1,savedAt:n.now()}),{flags:{...t,agent:c.id,scope:a.scope}};let p=await Vr({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:Ke}),m=p.filter(_=>_.detectionSources.includes("project")),g=i??ue(n.env.SKILLS_LAYER_AGENT),h=g?o.find(_=>_.id===g):void 0;if(g&&!h)return{result:P(`Unsupported agent "${g}". Run \`skills-layer agents list\` to choose a supported install target.`,t.json)};if(!h&&m.length===1&&(h=m[0]),!h){let _=ue(n.config?.lastSelectedAgent);h=_?p.find(I=>I.id===_)??o.find(I=>I.id===_):void 0}if(!h&&p.length===1&&(h=p[0]),!h&&p.length>1){let _=await n.promptSelect("Multiple supported agents were detected. Select one to install for:",p.map(I=>({value:I.id,label:`${I.displayName} (${I.detectionSources.join(", ")})`})));h=p.find(I=>I.id===_)}if(!h)return{result:P("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 _=[{value:"project",label:"Project (this folder)"}];h.targets.globalSkillsPath&&_.push({value:"global",label:"Global (all projects)"}),y=_.length===1?_[0].value:await n.promptSelect(`Install ${e} for ${h.displayName} where?`,_)}let w=i!==void 0||r!==void 0,b=a?.policy==="ask_every_time"&&l;if(!w&&!b&&(y==="project"||y==="global")){let _=y==="project"?"Project":"Global",x=await n.promptSelect(`Remember ${h.displayName} / ${_} 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:h.id,scope:y,usesSinceConfirmation:1,workingModeId:s,savedAt:n.now()}:{version:1,policy:"ask_every_time",usesSinceConfirmation:0,workingModeId:s,savedAt:n.now()};await _e(n.paths.installTargetPreferencePath,x)}return{flags:{...t,agent:h.id,scope:y}}}function J4(e){return e.apiKey?ue(e.config?.workingModeId)??"personal":"anonymous"}async function Y4(e){let t=await se(e);return!O(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 rv(e,t,n,r,i={}){if(v(r.agent)==="all")return await Z4(e,t,n,r,i);let o=iv(e,t,n,r);if(o.status==="skip")return S({status:"materialization_target_required",reasonCode:"materialization_target_required",skillSlug:n,nextStep:`skills-layer install ${n} --agent <id> --scope project`},"No local materialization target was selected; no install was recorded.",r.json,"materialization_target_required");if(o.status==="cache_only"){let g=await pf(e,t,o.skillSlug,o.version,i),h=await hf({backend:e,exportResult:g,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(Z(h))return h;let w=(e.platform==="win32"?je:ct).join(e.paths.bundlesDir,o.skillSlug,h.envelope.generation.semanticVersion,encodeURIComponent(h.envelope.generation.generationId),"bundle.zip");return await Tf(w,h.bytes),{...t,...gf(g),version:h.envelope.generation.semanticVersion,scope:"local",allowIncompatible:r.allowIncompatible===!0,installSecurity:h.installSecurity,acceptedCapabilities:h.acceptedCapabilities,archiveSha256:h.archiveSha256,archiveHashFormat:h.archiveHashFormat,manifestSha256:h.envelope.manifest.sha256,generationId:h.envelope.generation.generationId,sourceContentDigest:Fe(h.files),verificationStatus:"verified",cachedArtifact:{state:"verified",bundlePath:w,generation:h.envelope.generation,archiveSha256:h.archiveSha256,manifestSha256:h.envelope.manifest.sha256,savedAt:e.now()}}}if(o.status==="failure")return S({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:o.skillSlug,nextStep:o.nextStep},o.message,r.json,"materialization_target_invalid");let s=await ws({backend:e,skillSlug:o.skillSlug,agentId:o.agent.id,scope:o.scope,flags:r});if(s)return s;let a=await pf(e,t,o.skillSlug,o.version,i),l=await hf({backend:e,exportResult:a,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(Z(l))return l;let c=(await Pe(e)).installs[o.skillSlug],u=sn(c,{scope:o.scope,installedPath:(e.platform==="win32"?je:ct).join(o.skillsPath,ti(l.files)),platform:e.platform})[0]?.record,d=u?f(u,"sourceContentDigest"):void 0,p=Fe(l.files);if(u?.verificationStatus==="unverified"&&!r.replaceUnverifiedSource&&(await Mn({targetDir:(e.platform==="win32"?je:ct).join(o.skillsPath,ti(l.files)),generation:l.envelope.generation,archiveSha256:l.archiveSha256,...ov(l.envelope)})).status!=="verified")return S({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 sv({backend:e,skillSlug:o.skillSlug,scope:o.scope,agent:o.agent,skillsPath:o.skillsPath,allowIncompatible:r.allowIncompatible===!0,installSecurity:l.installSecurity,acceptedCapabilities:l.acceptedCapabilities,bytes:l.bytes,files:l.files,envelope:l.envelope,approval:l.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});return{...t,...gf(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},...Cl(e),...m,...m.guardianActivationReceipt?{warnings:[...he(t,"warnings")??[],...he(m,"warnings")??[]]}:{}}}async function Z4(e,t,n,r,i){let o=L(t,"materializationPlan")??L(t,"installPlan"),s=v(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 S({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=await Vr({env:e.env,platform:e.platform,cwd:e.cwd,pathExists:Ke}),c=new Map;for(let x of l){let C=s==="global"?x.targets.globalSkillsPath:x.targets.projectSkillsPath;if(!C)continue;let D=Br(C,e.platform),T=c.get(D);T?T.agents.push(x):c.set(D,{agent:x,agents:[x],skillsPath:C})}if(c.size===0)return S({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");let u=f(t,"version")??f(t,"currentVersion"),d=await pf(e,t,a,u,i),p=await hf({backend:e,exportResult:d,flags:r,skillSlug:a,expectedSourceGeneration:i.expectedSourceGeneration});if(Z(p))return p;let m=[],g=vu(p.files);for(let[x,C]of c)C.agents=C.agents.filter(D=>{let T=bu({compatibilityMatrix:g,agent:D});return T.allowed||m.push({agent:D.id,reasonCode:T.reasonCode}),T.allowed}),C.agents.length===0?c.delete(x):C.agent=C.agents[0];if(c.size===0)return S({reasonCode:"incompatible_agent",skippedAgents:m,nextStep:"Choose one detected compatible agent with --agent <id> --scope project."},"No detected compatible agents can install this skill.",r.json,"incompatible_agent");for(let x of c.values())for(let C of x.agents){let D=await ws({backend:e,skillSlug:a,agentId:C.id,scope:s,flags:r});if(D)return D}let h=Fe(p.files),y=(await Pe(e)).installs[a],w;if(!r.replaceUnverifiedSource)for(let x of c.values()){let C=(e.platform==="win32"?je:ct).join(x.skillsPath,ti(p.files)),D=sn(y,{scope:s,installedPath:C,platform:e.platform})[0];if(D?.record.verificationStatus==="unverified"&&(await Mn({targetDir:C,generation:p.envelope.generation,archiveSha256:p.archiveSha256,...ov(p.envelope)})).status!=="verified"){w=D;break}}if(w)return S({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:a,materializationId:w.materializationId,installedContentDigest:f(w.record,"sourceContentDigest"),approvedContentDigest:h,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 b=[];for(let x of c.values()){let C=await sv({backend:e,skillSlug:a,scope:s,agent:x.agent,skillsPath:x.skillsPath,allowIncompatible:r.allowIncompatible===!0,installSecurity:p.installSecurity,acceptedCapabilities:p.acceptedCapabilities,bytes:p.bytes,files:p.files,envelope:p.envelope,approval:p.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});b.push({...t,scope:s,agent:x.agent.id,targetAgent:x.agent.id,...Cl(e),...C})}let _=b[0],I=_[yf];return{...t,...gf(d),archiveSha256:p.archiveSha256,archiveHashFormat:p.archiveHashFormat,scope:s,agent:"all",targetAgents:[...c.values()].flatMap(x=>x.agents.map(C=>C.id)),skippedAgents:m,materializationPlan:{scope:s,agent:"all",physicalTargetCount:b.length,agentCount:l.length},materializationResults:b,materializedWrites:b.flatMap(x=>Array.isArray(x.materializedWrites)?x.materializedWrites:[]),materializedSkillRoot:f(_,"materializedSkillRoot"),...Cl(e),...hD(I)?{[yf]:I}:{}}}async function ws(e){let t=e.backend.config?.workingModeType==="enterprise_workspace",n=e.purpose==="enable"?await jr(e.backend,e.skillSlug):void 0,r=e.enforceRequired?"enforce":await jr(e.backend,e.skillSlug);if(!t&&r!=="enforce"&&r!=="enabled")return null;let i=ue(e.backend.config?.workingModeWorkspaceId);if(t&&!i)return S({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 o=await Vt(e.backend,e.scope),s=(he(o,"hooks")??[]).filter(O).find(p=>f(p,"agent")===e.agentId&&f(p,"scope")===e.scope&&p.active===!0),a=fn(e.agentId),l=xa({evaluationContext:"activation_eligibility",requestedMode:"enforce",workspacePolicy:t?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:a?.maximumTier==="strict_candidate",hookInstalled:!!s,strictHookVerified:s?.strictPreActionBlocking===!0&&s.evidenceCapability==="strict",exactActivationVerified:s?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"none",materializationState:"active"}),c=l.activationAllowed&&l.countedAsEnforced,u=t&&e.backend.config.workingModeGuardianPolicy==="standard"&&s!==void 0&&s.configActive!==!1;if(c||u)return 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:c?"strict_verified":"hook_unverified",observedAt:e.backend.now()}),null;let d=n==="enforce"||n==="enabled"?"enforce":n==="disabled"?"disabled":"warning_only";return S({status:"blocked",reasonCode:"guardian_enforcement_unavailable",skillSlug:e.skillSlug,...e.purpose==="enable"?{currentMode:d,currentProtection:l.label}:{},workspaceId:i,agent:e.agentId,scope:e.scope,measuredProtection:{...l,evidenceCapability:s?.evidenceCapability??"unverified",evidenceReasons:s?.evidenceReasons??[a?.reasonCode??"host_has_no_supported_guardian_route"]},nextAction:"guardian.hook.install",nextStep:!s||s.configActive===!1||s.entriesActive===!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>"} ${i??"<workspace-id>"} --guardian-policy standard. Hook installation alone does not prove strict enforcement.`:e.backend.config?.workingModeType==="personal"?"This host has no current strict verification, so Guardian enforce cannot be switched on here. Use a supported agent host, or keep this skill in warnings-only mode.":"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."},e.purpose==="enable"?`Guardian enforce is unavailable on this host (${e.agentId}, ${e.scope}); current protection: ${l.label}. ${e.skillSlug} stays in ${d==="warning_only"?"warnings-only":d} mode.`:t&&e.backend.config.workingModeGuardianPolicy==="standard"&&(!s||s.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 Tw(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 Cl(e){return e.config?.workingModeType!=="enterprise_workspace"?{}:W({workingModeType:"enterprise_workspace",enterpriseId:e.config.workingModeEnterpriseId,workspaceId:e.config.workingModeWorkspaceId,workingModeWorkspaceId:e.config.workingModeWorkspaceId})}function iv(e,t,n,r){let i=L(t,"materializationPlan")??L(t,"installPlan"),o=v(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=v(r.agent)??f(t,"agent")??f(t,"targetAgent")??(i?f(i,"agent")??f(i,"targetAgent"):void 0)??ue(e.config?.lastSelectedAgent)??"codex",l=We(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 pf(e,t,n,r,i={}){if(typeof t.downloadUrl=="string"&&O(t.artifactEnvelope)&&O(t.artifactApproval)&&O(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${Re(o)}`:`/api/v1/me/library/${encodeURIComponent(n)}/export${Re(o)}`,l=await E(e,a,{headers:s?{}:H(e.apiKey,e.authBlockedMessage)});if(!s&&!O(l.platformScoreAuthority))try{let c=await E(e,`/api/v1/skills/${encodeURIComponent(n)}/export${Re(o)}`,{headers:{}});return{...l,platformScoreAuthority:c.platformScoreAuthority}}catch(c){if(!(c instanceof V)||![401,403,404].includes(c.status))throw c}return s?{...l,downloadUrl:X4(n,f(l,"version")??r)}:l}function X4(e,t){let n=new URLSearchParams;return t&&n.set("version",t),`/api/v1/skills/${encodeURIComponent(e)}/download${Re(n)}`}function Q4(e){let t=f(e,"visibility")??f(e,"versionVisibility"),n=f(e,"publicationStatus");return fD(e)&&(t==="public"||n==="clean_publishable"||n==="publishable_with_findings")}function e3(e){return fD(e)}async function Al(e){let t=mf(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(!e3(t)){let c=L(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,g=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"generationId"):void 0,h=c?f(c,"status")??f(t,"status")??"submitted":f(t,"status")??"submitted",y=h==="catalogue_submission_failed"||u==="source_ingestion_candidate_not_claimable",w=f(t,"workflowId"),b=f(t,"processingAttemptId"),_=f(t,"jobId"),I=f(t,"intakeReceiptId"),x=L(t,"progress")??{},C=!y&&t.continuationConfirmed!==!1&&!!(w||b||_)&&["queued","running","catalogue_processing_scheduled","held_for_moderation","source_install_pending_review","reused"].includes(h),D={status:y?"rejected":h==="reused"&&I?"reused":C?h==="reused"?"reused":"accepted":I?"accepted":"unconfirmed",reasonCode:u,continuationConfirmed:C,nextActor:f(x,"nextActor")??(C?"platform":u==="source_ingestion_candidate_not_claimable"?"operator":"requester")},T=W({...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:g,sourceContentDigest:e.unverifiedMaterialization?f(e.unverifiedMaterialization,"sourceContentDigest"):void 0,visibility:r,catalogueVisibilityRequested:r,requestedVisibility:r,catalogueStatus:h,publiclyDiscoverable:!1,intakeAdmission:D,assessmentStatus:f(x,"status")??(C?"pending":"unconfirmed"),publicationStatus:"not_published",distributionStatus:"verified_artifact_required",workflowId:w,processingAttemptId:b,jobId:_,intakeReceiptId:I,progress:t.progress,intakeReceiptIds:t.intakeReceiptIds,candidateIds:t.candidateIds,wakeStatus:t.wakeStatus,uploadIntent:t.uploadIntent,backgroundWorkStatus:C?"catalogue_review_continues_automatically":"retry_or_operator_action_required",publication:c?mf(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:v(e.flags.scope)??"project",agent:v(e.flags.agent)??"codex",activation:d?"unverified_install_request_authorized":"approved_artifact_only"},nextStep:d?`Local installation is complete as Unverified / Unscored. ${C?"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.`:C?`Run skills-layer ${I?`install status ${I}`:`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 fs(e.backend,T,n),us(T,d?`External source installed locally as unverified; ${C?"catalogue review continues":"catalogue continuation is unconfirmed"}.`:C?"Source submitted; installation is pending approval.":"Source installation is held; catalogue continuation is unconfirmed.",e.flags.json,e.backend,Ii(e.flags))}let i=L(L(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 S({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 rv(e.backend,t,n,e.flags,{exportMode:Q4(t)?"public":"auto",...i?{expectedSourceGeneration:{generationId:o,version:s}}:{}})}catch(c){if(!(c instanceof V)||![404,502,503,504].includes(c.status))throw c;let u=W({...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 fs(e.backend,u,n),us(u,"Source installed locally as unverified; the published catalogue artifact is temporarily unavailable.",e.flags.json,e.backend,Ii(e.flags))):S(u,"The published catalogue artifact is temporarily unavailable.",e.flags.json,"catalogue_artifact_unavailable")}if(Z(a))return a;let l=await av(e.backend,a,n,e.flags);return await fs(e.backend,l,n),us(l,_3(e.source,e.flags,e.backend,l,e.sourceAccess),e.flags.json,e.backend,Ii(e.flags))}function mf(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=>O(r)?mf(r):r)]]:O(n)?[[t,mf(n)]]:[[t,n]]))}function fD(e){if(gD(e.artifactApproval).status==="ok"&&e.artifactEnvelope!==void 0&&typeof e.downloadUrl=="string")return!0;let n=L(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 gf(e){return W({version:f(e,"version"),storageKey:f(e,"storageKey"),expiresAt:f(e,"expiresAt")})}async function hf(e){let t=gD(e.exportResult.artifactApproval);if(t.status!=="ok"){let p=t.status==="missing";return Dr(e,p?"artifact_v1_approval_missing":"artifact_v1_approval_invalid",p?`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 Dr(e,"source_catalogue_generation_mismatch","The exported artifact does not match the exact version and generation resolved for this source.");let r=r3({backend:e.backend,exportResult:e.exportResult,approval:n,skillSlug:e.skillSlug});if(r.status!=="ok")return Dr(e,r.reasonCode,r.message);if(e.exportResult.artifactEnvelope===void 0)return Dr(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 S({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(o3(e.backend.baseUrl,i));if(!o.ok){let p=await Ev(o),m=p.details?f(p.details,"reasonCode"):void 0;throw new V(o.status,`Unable to download exported bundle (${o.status}${m?`, ${m}`:""}).`,p.details)}let s;try{s=await s3(o)}catch(p){return Dr(e,"artifact_v1_archive_bounds_failed",`Downloaded ${e.skillSlug} exceeded Artifact Format v1 archive bounds.`,{verificationError:ne(p)})}let a,l;try{let p=pc({archiveBytes:s,envelope:e.exportResult.artifactEnvelope});a=p.format==="v2"?t3(p.envelope):p.envelope,l=p.files()}catch(p){let m=p instanceof Kr&&p.format==="v2";return Dr(e,m?"artifact_v2_verification_failed":"artifact_v1_verification_failed",`Downloaded ${e.skillSlug} failed Artifact Format ${m?"v2":"v1"} verification.`,{verificationError:ne(p)})}if(!i3(n,a))return Dr(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");if(a.generation.skillSlug!==e.skillSlug||c!==void 0&&c!==a.generation.skillSlug||u!==void 0&&u!==a.generation.semanticVersion)return Dr(e,"artifact_v1_target_mismatch",`Downloaded ${e.skillSlug} was approved for a different skill or version.`);let d=mD({...e,files:l,version:a.generation.semanticVersion});return Z(d)?d:{...d,status:"ok",bytes:s,files:l,envelope:a,approval:n,archiveSha256:a.archive.sha256,archiveBytesSha256:a.archive.sha256,archiveHashFormat:pD(a)?"artifact_v2_zip":"artifact_v1_zip"}}function t3(e){let t=fc(e);return{generation:e.generation,archive:e.archive,manifest:{sha256:t.manifestSha256,files:t.files,fileCount:t.files.length,totalFileBytes:t.files.reduce((n,r)=>n+r.sizeBytes,0)},manifestV2:t.manifestV2,artifactV2Envelope:e}}function n3(e){return e.artifactV2Envelope??e}function pD(e){return e.manifestV2}function ov(e){let t=pD(e);return{manifestSha256:e.manifest.sha256,files:e.manifest.files,...t?{manifestV2:t}:{}}}function mD(e){let t=IC(Ie(e.files,{profile:"external_ingest_tolerant"}),e.files),n=L(e.exportResult,"securityReport"),r=n&&L(n,"capabilityProfile"),i=u=>Array.isArray(u)?u.filter(d=>typeof d=="string"):[],o=[...new Set([...t.declaredCapabilities,...i(r?.declaredCapabilities)])],s=[...new Set([...t.detectedCapabilities,...i(r?.detectedCapabilities)])],a=n?.recommendation,l={securityScore:typeof n?.securityScore=="number"?n.securityScore:null,recommendation:a==="blocked"||a==="manual_review"?a:"approved",findings:Array.isArray(n?.findings)?n.findings.map(u=>({blocking:O(u)&&u.blocking===!0})):[],capabilityProfile:{declaredCapabilities:o,detectedCapabilities:s,mismatches:s.filter(u=>!o.includes(u)),runtimeRisk:t.runtimeRisk==="high"||r?.runtimeRisk==="high"?"high":t.runtimeRisk==="elevated"||r?.runtimeRisk==="elevated"?"elevated":"low"}},c=xC({skillSlug:e.skillSlug,version:e.version,securityReport:l,consentedCapabilities:e.flags.acceptCapability});return c.status!=="ready"?S({status:c.status,reasonCode:c.reasonCode,skillSlug:e.skillSlug,installSecurity:c,requiredConsentCapabilities:c.requiredConsentCapabilities,nextStep:c.status==="consent_required"?`Retry the same ${e.consentCommand??"install"} command with ${c.requiredConsentCapabilities.map(u=>`--accept-capability ${u}`).join(" ")} after reviewing this access.`:"Keep this skill inactive until a corrected version passes security review."},c.status==="consent_required"?`Explicit capability consent is required before ${e.consentCommand==="export"?"export":"installation"}.`:"Security review requires quarantine; no skill files were installed.",e.flags.json,c.reasonCode):{installSecurity:c,acceptedCapabilities:[...new Set(e.flags.acceptCapability)].sort()}}function r3(e){let t=L(e.exportResult,"platformScoreAuthority"),n=t?.machineReport,r=t?.passport,i=t?.parityManifest,o=t?f(t,"passportPublicKey"):void 0;if(!t||!hd(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=$o.safeParse(r),a=Oh.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=Uh({passport:s.data,publicKeys:{[s.data.issuer.keyId]:z0(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 gD(e){return e==null?{status:"missing"}:!O(e)||e.status!=="approved"||!O(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 i3(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 Dr(e,t,n,r={}){return S({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 o3(e,t){return/^https?:\/\//iu.test(t)?t:`${kn(e)}${t.startsWith("/")?"":"/"}${t}`}async function s3(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>qe.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>qe.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 sv(e){let t=bu({compatibilityMatrix:vu(e.files),agent:e.agent,allowIncompatible:e.allowIncompatible});if(!t.allowed)throw new V(409,"The creator does not support this agent or its required capabilities are unavailable.",{...t,status:"blocked",nextStep:"Choose a supported agent or retry with --allow-incompatible after reviewing the compatibility requirements."});let n=e.verificationStatus??"verified";if(n==="verified"&&!e.approval)throw new Error("Verified materialization requires platform artifact approval.");let r=e.backend.platform==="win32"?je:ct,i=Fe(e.files),o=r.join(e.backend.paths.bundlesDir,e.skillSlug,e.envelope.generation.semanticVersion,encodeURIComponent(e.envelope.generation.generationId),"bundle.zip"),s=r.join(e.skillsPath,ti(e.files)),a=We(e.backend.env,e.backend.platform,e.backend.cwd).filter($=>{let B=e.scope==="global"?$.targets.globalSkillsPath:$.targets.projectSkillsPath;return B!==null&&Br(B,e.backend.platform)===Br(e.skillsPath,e.backend.platform)}).map($=>$.id).sort(),l=`activation_${ke(16).toString("hex")}`,c={targetDir:s,generation:e.envelope.generation,archiveSha256:e.envelope.archive.sha256,...ov(e.envelope)},u=pT({scope:e.scope,targetDir:s,platform:e.backend.platform}),d=await Pe(e.backend);for(let[$,B]of Object.entries(d.installs)){let q=[B,...Et(B).map(Y=>Y.record)].flatMap(Y=>[_t(Y)?.receipt.targetDir,f(Y,"materializedSkillRoot"),f(Y,"materializedPath")]);if($!==e.skillSlug&&q.some(Y=>Y&&Cv(s,Y,e.backend.platform)))throw new V(409,`Install folder already belongs to another skill (${$}).`,{reasonCode:"local_name_conflict",skillSlug:e.skillSlug,conflictingSkillSlug:$,materializedSkillRoot:s,nextStep:"Choose another scope or remove the conflicting installation before retrying."})}let p=d.installs[e.skillSlug],m=kt(p)[u];if(!m&&await Ke(s))throw new V(409,"The skill name is already occupied by an unmanaged local folder.",{reasonCode:"local_name_conflict",skillSlug:e.skillSlug,materializedSkillRoot:s,nextStep:"Choose another scope or move the existing folder before retrying."});let g=JSON.stringify(m??null),h=Ol({state:"pending_activation",operationId:l,receipt:c,backend:e.backend}),y=Ol({state:"active",operationId:l,receipt:c,backend:e.backend}),w={skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,targetAgents:a.length>0?a:[e.agent.id],materializedPath:s,materializedSkillRoot:s,materializationId:u,bundlePath:o,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:i,verificationStatus:n,installSecurity:e.installSecurity,acceptedCapabilities:e.acceptedCapabilities??[],compatibilityOverride:t.compatibilityOverride,compatibility:t,...Cl(e.backend),...Tw(e.backend,e.agent.id,e.scope),localLifecycle:h,savedAt:e.backend.now()};await Tf(o,e.bytes);let b=e.files.find($=>$e($.path).toLowerCase()==="skill.md"),_=b?await DW({backend:e.backend,skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,skillDocumentPath:r.join(s,...XE(b.path)),skillDocumentContent:b.content??""}):void 0,I,x=!1,C;try{let $={targetDir:s,...n==="verified"&&m?.verificationStatus==="unverified"&&!e.replaceUnverifiedSource?{expectedPreviousReceipt:c}:{},archiveBytes:e.bytes,envelope:n3(e.envelope),preActivate:async({stageDir:B})=>{let q=await l3({backend:e.backend,stageDir:B,envelope:e.envelope});return q.status==="passed"?(I=q.evalRun,{status:"passed",evidenceId:q.evidenceId}):{status:"failed",reasonCode:q.reasonCode}},checkpoint:async B=>{if(B==="after_static_eval"){await Vn(e.backend,q=>{let Y=q.installs[e.skillSlug],Le=kt(Y)[u];if(JSON.stringify(Le??null)!==g)throw new Error(`Local install materialization for ${e.skillSlug} changed during atomic activation.`);q.installs[e.skillSlug]=qn({existing:Y,skillSlug:e.skillSlug,materialization:w,backend:e.backend})}),x=!0;return}B==="after_stage_activated"&&await Vn(e.backend,q=>{let Y=q.installs[e.skillSlug],Le=kt(Y)[u],Gt=Le?_t(Le):null;if(!Gt||Gt.state!=="pending_activation"||Gt.operationId!==l)throw new Error(`Atomic activation receipt reservation for ${e.skillSlug} was lost before commit.`);q.installs[e.skillSlug]=qn({existing:Y,skillSlug:e.skillSlug,materialization:{...w,localLifecycle:y,savedAt:e.backend.now()},backend:e.backend})})}};C=n==="verified"?await TR({...$,approval:e.approval}):await $R($)}catch($){throw x&&await o9({backend:e.backend,skillSlug:e.skillSlug,materializationId:u,operationId:l,baselineMaterialization:m}),$}if(!I)throw new Error("Static pre-activation Eval did not produce generation-bound evidence.");let D=await Pe(e.backend),T=kt(D.installs[e.skillSlug])[u],j=T?_t(T):null;if(!j||j.state!=="active"||j.operationId!==l)throw new Error(`Atomic activation receipt for ${e.skillSlug} was not committed.`);let M=C.receipt.files.map($=>({path:CD(e.backend.cwd,r.join(s,...XE($.path))),bytes:$.sizeBytes}));return{...e.backend.config?.workingModeType==="enterprise_workspace"?{status:"installed"}:{},bundlePath:o,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,...Cl(e.backend),...Tw(e.backend,e.agent.id,e.scope),materializedPath:s,materializedSkillRoot:s,materializationId:u,targetAgents:a.length>0?a:[e.agent.id],archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:i,verificationStatus:n,installSecurity:e.installSecurity,acceptedCapabilities:e.acceptedCapabilities??[],compatibilityOverride:t.compatibilityOverride,compatibility:t,materializedWrites:M,..._?{guardianRuntimeMetadata:_}:{},localLifecycle:y,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}:{}},[yf]:I}}var yf=Symbol("skills-layer.pre-activation-eval"),a3=new Set(["file_exists","json_valid","schema_match","section_exists","regex_match","artifact_valid"]);async function l3(e){let t=await yD(e.stageDir),n=Fe(t),r=vD(t,n),i=l=>bI({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:$w()}),o=i(r.pack);if(o.outcome!=="completed")return{status:"failed",reasonCode:o.reasonCode};let s=i(bD(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=wD({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 av(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")??v(r.version)??"local";try{let a=t[yf],l;if(hD(a))l=a;else{let u=await yD(tt(e.cwd,i));if(u.length===0)return tf(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"installed_files_unreadable"});l=wD({files:u,skillSlug:o,version:s,generatedAt:e.now()})}let c=await y3(e,l.summary);if(c.status==="recorded"){let u=await wI({stateDir:e.paths.stateDir,submitted:!0,now:e.now()});return tf({...t,...c.effectiveness?{effectiveness:c.effectiveness}:{},localEvalEvidence:u},r,{status:c.replayed?"already_recorded":"recorded",source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,evidenceRevision:c.evidenceRevision,evidenceSubmitted:!0})}return tf(t,r,{status:c.status,source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,reasonCode:c.reasonCode,evidenceSubmitted:!1})}catch(a){return tf(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"local_eval_failed",message:ne(a)})}}function hD(e){return O(e)&&(e.source==="submitted"||e.source==="inferred"||e.source==="invalid_submitted")&&O(e.summary)&&e.summary.schemaVersion==="skills-layer.eval.summary.v1"}async function yD(e){return kR(e,{skipEntry:c3,skipFile:d3})}function c3(e){return e===".git"||e==="node_modules"||e==="coverage"||e===u3()||e==="dist"}function u3(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}function d3(e){return e==="bundle.zip"||/^\.skills-layer-.*\.json$/u.test(e)}function wD(e){let t=Fe(e.files),n=vD(e.files,t);if(!ld(n.pack).valid)return{source:"invalid_submitted",summary:Eo({status:"runner_unavailable",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:t,evalPackDigest:Po(n.pack),generatedAt:e.generatedAt,runnerVersion:$w(),counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})};let i=p3(n.pack).map(s=>({id:s.id,assertions:s.assertions.map(a=>m3(a,e.files))})),o=g3(i);return{source:n.source,summary:Eo({status:h3(o),skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:typeof n.pack.artifactDigest=="string"?n.pack.artifactDigest:t,evalPackDigest:Po(n.pack),generatedAt:e.generatedAt,runnerVersion:$w(),counts:{cases:i.length,assertions:o.total,passed:o.passed,failed:o.failed,skipped:o.skipped}})}}function vD(e,t){let n=f3(e);return n?{pack:n,source:"submitted"}:{pack:bD(e,t),source:"inferred"}}function f3(e){for(let t of e){let n=zt(t.path,e);if(!(n.type!=="evidence"||!t.content||!n.relativePath.toLowerCase().endsWith(".eval.json")))try{let r=JSON.parse(t.content);if(O(r))return r}catch{return{schemaVersion:"invalid",artifactDigest:Fe(e),origin:"submitted",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[]}}}}function bD(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 p3(e){return Array.isArray(e.cases)?e.cases.flatMap(t=>!O(t)||typeof t.id!="string"||!Array.isArray(t.assertions)?[]:[{id:t.id,assertions:t.assertions.filter(O)}]):[]}function m3(e,t){return typeof e.type=="string"&&!a3.has(e.type)?{status:"skipped",reasonCode:"runner_unavailable"}:sd(e,{files:t})}function g3(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 h3(e){return e.failed>0?"failed":e.passed>0?"passed":e.skipped>0?"runner_unavailable":"not_run"}function $w(){return`skills-layer-public-cli:${In}:local-install`}async function y3(e,t){if(!e.apiKey)return{status:"local_only",reasonCode:"not_authenticated"};try{let n=await E(e,"/api/v1/me/evals/results",{method:"POST",headers:{"content-type":"application/json",...H(e.apiKey,e.authBlockedMessage)},body:JSON.stringify({evalSummary:t})}),r=L(n,"evalEvidence");return{status:"recorded",effectiveness:L(n,"effectiveness"),evidenceRevision:r?K(r,"revision"):void 0,replayed:r?.replayed===!0}}catch(n){return{status:"submit_failed",reasonCode:n instanceof V?`http_${n.status}`:"request_failed"}}}function tf(e,t,n){return t.json?{...e,localEval:n}:e}function XE(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 QE(e,t,n,r,i){let o=v(r.visibility)??"private";if(o!=="private"&&o!=="public")return S({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=lv(e,t,n);if(r.list)return R(s,"Local source skills loaded.",r.json,i);let a=bf(e,s,r);if(a)return a;let l=await _l({source:e,inspection:s,requestedSkillSlug:n,mode:"install",flags:r,backend:i});if(l.kind==="failure")return l.result;let c=l.skillSlug??_n(s)[0]?.value??SD(e),u=w3(t.files,c),d=ln({files:u,limits:hi}),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({...Lw(e,s,c,r),installKind:"local_source_submission",excludedFromRuntime:Wi(u),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 wf({backend:i,flags:r,source:e,skillSlug:c,files:u,defaultAcceptUnverifiedSource:!0});if(Z(y))return y;let w={...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 fs(i,w,c),us(w,"Local source installed as unverified and unscored. No files were uploaded.",r.json,i,Ii(r))}if(!i.apiKey)return S({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 Qw(i,c,r);if(m)return m;let g;if(_D(r,i)){let y=await wf({backend:i,flags:r,source:e,skillSlug:c,files:u});if(Z(y))return y;g=y}let h;try{let y=Ed(u)?await cy({baseUrl:i.baseUrl,apiKey:i.apiKey,fetchFn:i.fetchFn,files:u}):null;h=await E(i,"/api/v1/me/source-installs",{method:"POST",headers:{"content-type":"application/json",...H(i.apiKey,i.authBlockedMessage)},body:JSON.stringify(W({...y?{hydrationManifestId:y.manifestId}:{files:u},skillSlug:c,version:v(r.version),visibility:o,category:v(r.category),displayName:v(r.displayName),skillType:v(r.skillType),sourceMetadata:t.sourceMetadata}))})}catch(y){return g?await Al({backend:i,flags:r,source:e,fallbackSlug:c,sourceAccess:"authenticated",requestedVisibility:o,unverifiedMaterialization:g,result:{status:"catalogue_submission_failed",skillSlug:c,uploadIntent:p,reasonCode:y instanceof V?"catalogue_submission_failed":"catalogue_submission_unavailable"}}):S({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 V?"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 Al({backend:i,result:{...h,uploadIntent:p},fallbackSlug:f(h,"skillSlug")??c,source:e,sourceAccess:"authenticated",flags:r,requestedVisibility:o,...g?{unverifiedMaterialization:g}:{}})}function w3(e,t){let n=cv(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 e0(e){if(!e.flags.all&&!(!e.defaultAcceptUnverifiedSource&&!_D(e.flags,e.backend)))try{let t=en(e.source),n=await XI({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 wf({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:S({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:S({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 wf(e){let t=ln({files:e.files,limits:hi}),n=Ie(e.files,{profile:"external_ingest_tolerant"}),r=HR(e.files,KR),i=[...t.issues.filter(x=>x.severity==="error").map(x=>({code:x.code,concern:/^(?:secret_|pii_|sensitive_)/u.test(x.code)?"privacy":"integrity",...x.path?{path:x.path}:{}})),...n.issues.filter(x=>x.severity==="error").map(x=>({code:x.code,concern:"package_validity"})),...r.filter(x=>x.severity==="high"||x.severity==="critical").map(x=>({code:x.ruleId,concern:"security",path:x.filePath,...x.lineNumber?{lineNumber:x.lineNumber}:{}}))],o=i.map(x=>x.code);if(o.length>0){let x=i.some(C=>C.concern==="security")?"critical_local_preflight_blocked":"source_package_invalid";return S({status:"unverified_install_blocked",reasonCode:x,skillSlug:e.skillSlug,findingCodes:[...new Set(o)].sort((C,D)=>C.localeCompare(D)),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,x)}let s=mD({...e,version:v(e.flags.version)??"local",exportResult:{}});if(Z(s))return s;if(!(e.flags.acceptUnverifiedSource===!0||e.defaultAcceptUnverifiedSource===!0||await v3(e)))return S({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");if(e.flags.agent==="all"){let x=await Vr({env:e.backend.env,cwd:e.backend.cwd,platform:e.backend.platform,pathExists:Ke}),C=v(e.flags.scope)??"project",D=vu(e.files),T=[],j=new Map;for(let $ of x){let B=bu({compatibilityMatrix:D,agent:$,allowIncompatible:e.flags.allowIncompatible===!0}),q=C==="project"?$.targets.projectSkillsPath:C==="global"?$.targets.globalSkillsPath:null;if(!B.allowed||!q){T.push({agent:$.id,reasonCode:B.allowed?"materialization_target_invalid":B.reasonCode});continue}let Y=Br(q,e.backend.platform);j.set(Y,[...j.get(Y)??[],$])}if(j.size===0)return S({status:"blocked",reasonCode:"materialization_target_required",skippedAgents:T,nextStep:"Choose an installed compatible agent and retry with --agent <agent> --scope project|global."},"No compatible detected agent has an available installation target.",e.flags.json,"materialization_target_required");let M=[];for(let $ of j.values()){let B=await wf({...e,flags:{...e.flags,scope:C,agent:$[0].id,acceptUnverifiedSource:!0}});if(Z(B))return B;M.push(B)}return{...M[0],agent:"all",scope:C,targetAgents:[...j.values()].flatMap($=>$.map(B=>B.id)),skippedAgents:T,materializationResults:M,materializedWrites:M.flatMap($=>Array.isArray($.materializedWrites)?$.materializedWrites:[])}}let l=iv(e.backend,{skillSlug:e.skillSlug,materializationPlan:{scope:v(e.flags.scope)??"project",agent:v(e.flags.agent)??"codex"}},e.skillSlug,e.flags);if(l.status==="failure")return S({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:e.skillSlug,nextStep:l.nextStep},l.message,e.flags.json,"materialization_target_invalid");if(l.status==="skip"||l.status==="cache_only")return S({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 c=await ws({backend:e.backend,skillSlug:e.skillSlug,agentId:l.agent.id,scope:l.scope,flags:e.flags});if(c)return c;let u=Fe(e.files),d=en(e.source),p=d.kind==="github"?d.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,m=e.relativeSkillRoot,g=d.kind==="github"&&/^[a-f0-9]{40}$/u.test(d.ref)?{provider:"github",repository:`${d.owner}/${d.repo}`,commitSha:d.ref,sourceRoot:!m||m==="."?p:p==="."?m:`${p}/${m}`,sourceContentDigest:t.preview.bundleSha256}:void 0,h=u.slice(7,19),y=v(e.flags.version)??`0.0.0-external.${h}`,w=`generation_unverified_${u.slice(7,39)}`,b=e.files.filter(x=>zt(x.path,e.files).type==="runtime").map(x=>x.path),_=Hb({generation:{skillSlug:e.skillSlug,semanticVersion:y,generationId:w},reviewPackageFiles:e.files,runtimeAllowlist:b});return{...await sv({backend:e.backend,skillSlug:e.skillSlug,scope:l.scope,agent:l.agent,skillsPath:l.skillsPath,...s,allowIncompatible:e.flags.allowIncompatible===!0,bytes:_.archiveBytes,files:uc({archiveBytes:_.archiveBytes,envelope:_.envelope}),envelope:_.envelope,verificationStatus:"unverified"}),source:e.source,sourceContentDigest:u,...g?{sourceSnapshot:{...g,runtimeDigest:u,archiveSha256:_.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(x=>x.code),...n.issues.map(x=>x.code),...r.map(x=>x.ruleId)]}}}function _D(e,t){return e.acceptUnverifiedSource===!0||!e.json&&!t.nonInteractive&&t.stdoutIsTty}async function v3(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 lv(e,t,n){let r=cv(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 cv(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=ye(t.path).replaceAll("\\","/"),r=n==="."?".":n,i=kD(t.content??"")??SD(r==="."?t.path:r),o=b3(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 kD(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function b3(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function SD(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}function CD(e,t){let n=df(e,t);return n&&!n.startsWith("..")&&!je.isAbsolute(n)?n.split("\\").join("/"):t}function Or(e,t,n,r="unknown"){let i=v(t.visibility);return i==="public"||i==="private"?i:r==="anonymous"&&vf(e)?"public":r==="authenticated"?"private":!n.apiKey&&vf(e)?"public":"private"}function vf(e){try{let t=en(e).kind;return t==="github"||t==="gitlab"}catch{return/^https:\/\/(?:github|gitlab)\.com\//iu.test(e.trim())}}function uv(e,t,n,r="unknown"){return Or(e,t,n,r)==="private"||v(t.visibility)==="unlisted"||r==="authenticated"?"/api/v1/me/source-installs":"/api/v1/source-imports"}function AD(e,t,n,r="unknown"){return{"content-type":"application/json",...uv(e,t,n,r)==="/api/v1/me/source-installs"?H(n.apiKey,n.authBlockedMessage):{}}}function _3(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,c=r&&f(r,"verificationStatus")==="verified"?"Public source skill installed and verified.":"Public source install planned.";return o==="public"||s==="clean_publishable"||s==="publishable_with_findings"||l==="published"?c:o==="private"||s==="private"||a==="private"||l==="private_source_installed"?"Private source skill installed.":Or(e,t,n,i)==="public"?c:"Private source skill installed."}async function _l(e){let t=_n(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:k3(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:t0(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:t0(e.source,t,e.flags)}}}function t0(e,t,n){let r=t.map(i=>i.value);return S({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 n0(e,t,n){if(n.all&&t)return S({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 r0(e,t){try{if(en(e).kind!=="local")return}catch{return}return S({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:xl(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."},xl(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 k3(e,t,n,r){return S({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 _n(e){let t=[e.results,e.skills,e.discoveredSkills,L(e,"source")?.results,L(e,"inspection")?.results],n=new Set,r=[];for(let i of t)if(Array.isArray(i))for(let o of i){let s=S3(o);!s||n.has(s.value)||(n.add(s.value),r.push(s))}return r}function S3(e){if(!O(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=L(e,"parsedSkill"),o=L(e,"frontmatter")??(i?L(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 i0(e,t,n,r,i,o={}){return W({...t,skillSlug:n,scope:v(r.scope),agent:v(r.agent),workspace:v(r.workspace),version:v(r.version),visibility:o.visibility??v(r.visibility),category:v(r.category),displayName:v(r.displayName),skillType:v(r.skillType),all:r.all,acceptCapability:r.acceptCapability})}async function o0(e){let t=e.sourceAccess??"unknown",n=uv(e.source,e.flags,e.backend,t);try{return await E(e.backend,n,{method:"POST",headers:AD(e.source,e.flags,e.backend,t),body:JSON.stringify(i0(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 V&&r.status===401&&v(e.flags.visibility)!=="private"&&t!=="authenticated"&&vf(e.source))return await E(e.backend,"/api/v1/source-imports",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i0(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{visibility:"public"}))});throw r}}function Lw(e,t,n,r){return W({status:"dry_run",source:e,selectedSkillSlug:n,all:r.all,scope:v(r.scope)??"local",agent:v(r.agent),workspace:v(r.workspace),acceptCapability:r.acceptCapability,candidates:_n(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 xD(e,t,n,r,i={}){try{return{kind:"ok",inspection:await E(e,"/api/v1/source-inspect",{method:"POST",headers:ID(e,i.authMode??"auto"),body:JSON.stringify(W(n))})}}catch(o){if(o instanceof V)return{kind:"failure",result:Fw(t,o,r)};throw o}}function ID(e,t){return t==="anonymous"?{"content-type":"application/json"}:U(e.apiKey)}async function Ow(e,t,n,r){try{let s=await E(e,"/api/v1/source-inspect",{method:"POST",headers:ID(e,"anonymous"),body:JSON.stringify(W(n))}),a=s0(t,s,r);return a?{kind:"failure",result:a}:{kind:"ok",inspection:s,sourceAccess:"anonymous"}}catch(s){if(!(s instanceof V))throw s;let a=s.details??{},l=f(a,"error")??s.message;if(!dv(s.status,l))return{kind:"failure",result:Fw(t,s,r)};if(!e.apiKey)return{kind:"failure",result:Fw(t,s,r)}}let i=await xD(e,t,n,r,{authMode:"authenticated"});if(i.kind==="failure")return i;let o=s0(t,i.inspection,r);return o?{kind:"failure",result:o}:{kind:"ok",inspection:i.inspection,sourceAccess:"authenticated"}}function s0(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=O(i)?i.status:void 0;if(!O(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 S({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=en(e),o=typeof t.catalogueSourceInput=="string"?en(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=O(l)?L(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 S({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 bf(e,t,n){if(_n(t).length>0)return null;let i=C3(t);return S({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."},A3(e,i),n.json)}function C3(e){return(Array.isArray(e.issues)?e.issues:[]).filter(O).map(n=>({...f(n,"code")?{code:f(n,"code")}:{},...f(n,"message")?{message:f(n,"message")}:{},...f(n,"path")?{path:f(n,"path")}:{}}))}function Fw(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(dv(t.status,i))return RD(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Fi(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 S(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 a0(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(dv(t.status,i))return RD(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Fi(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 S(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 l0(e){let t=e.error instanceof V?e.error.details??{}:{},n=e.error instanceof V?f(t,"reasonCode")??"catalogue_submission_failed":"catalogue_submission_unavailable";return await Al({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:Or(e.source,e.flags,e.backend,e.sourceAccess),unverifiedMaterialization:e.unverifiedMaterialization})}function dv(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function RD(e,t,n,r){let i=t.details??{},o=f(i,"error")??t.message,a=`skills-layer source connection start --provider ${PD(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 S(l,`Cloud could not ${r} ${e} directly. If this is a private source, start a private source connection first:
|
|
1041
|
+
${a}`,n.json,"private_source_access_required")}function PD(e){return/gitlab\./iu.test(e)?"gitlab":/github\./iu.test(e)||/^gh:/iu.test(e)?"github":"generic_git"}function A3(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(`
|
|
1042
|
+
`)}async function ED(e,t,n){if(TD(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 S(e,`Install preview is not ready: ${c}`,t.json,l)}let r=v(t.agent)==="all"?We(n.env,n.platform,n.cwd).map(l=>({...t,agent:l.id})):[t];for(let l of r){let c=iv(n,e,"",l);if(c.status!=="ok")continue;let u=await ws({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=>Tw(n,l.agent,l.scope)),o=i.flatMap(l=>Array.isArray(l.warnings)?l.warnings:[]),s=await $D({...e,...i[0],warnings:[...Array.isArray(e.warnings)?e.warnings:[],...o]},n),a=Array.isArray(s.warnings)&&s.warnings.length>0;return x3(s,a?"Install preview ready with warnings.":"Install preview ready.",t,n)}function x3(e,t,n,r){return n.json?R(e,t,!0,r):{exitCode:0,stdout:fv(e,t,r,Ii(n)),stderr:""}}async function DD(e,t,n,r){if(TD(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 S(e,`Workspace approval preview is not ready: ${s}`,n.json,o)}let i=await $D(e,r);return n.json?R(i,t,!0,r):{exitCode:0,stdout:fv(i,t,r),stderr:""}}function TD(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 $D(e,t){let n=o=>({...e,...o,warnings:[...new Set([...he(e,"warnings")??[],...he(o,"warnings")??[]])]}),r=c0(e);if(r)return n(r);let i=f(e,"skillSlug")??f(e,"slug");if(!i)return e;try{let o=await E(t,`/api/v1/skills/${encodeURIComponent(i)}/trust`),s=c0(o);return s?n(s):e}catch{return e}}function c0(e){let t=L(e,"securityReport")??L(e,"report")??e,n=L(e,"trust")??L(t,"trust")??t,r=L(e,"securityPosture")??L(t,"securityPosture"),i=L(e,"capabilityProfile")??L(t,"capabilityProfile"),o=W({securityScore:K(n,"securityScore")??K(n,"score")??K(e,"securityScore")??(r?K(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:he(n,"detectedCapabilities")??he(e,"detectedCapabilities")??(i?he(i,"detectedCapabilities"):void 0),capabilityMismatches:he(n,"capabilityMismatches")??he(e,"capabilityMismatches")??(i?he(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 W({trust:o,effectiveness:L(e,"effectiveness")??L(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:he(e,"warnings")??he(t,"warnings")??he(n,"warnings")})}function Ii(e){return{agent:v(e.agent),scope:v(e.scope)}}async function us(e,t,n,r,i){let s=Array.isArray(e.materializedWrites)&&e.materializedWrites.length>0?{...e,guardianProtection:await I3(r,i)}:e;return n?R(s,t,!0,r):{exitCode:0,stdout:fv(s,t,r,i),stderr:""}}async function I3(e,t){let n=await Vt(e),r=f(n,"enforcementLayer"),i=n.strictPreActionBlocking===!0,o=t.agent&&t.agent!=="all"?t.agent:"<agent>",s=t.scope==="project"||t.scope==="global"?` --scope ${t.scope}`:"",a=`skills-layer guardian hook install --agent ${o}${s}`;return r==="not_installed"?{measuredProtection:"unavailable",label:"Guardian: not active for this host (no Guardian hook installed).",nextStep:`Run ${a} to add Guardian checks before tool calls.`}:i?{measuredProtection:"verified_strict",label:"Guardian: a verified hook checks this host's tool calls."}:{measuredProtection:"candidate_unverified",label:"Guardian: hook installed; it warns but strict blocking is not verified on this host.",nextStep:"Run skills-layer guardian status <skill> to see the mode in use."}}function fv(e,t,n,r={}){let i=de(n),o=[`${i.ok("OK")} ${t}`];for(let M of he(e,"warnings")??[])typeof M=="string"&&o.push(`Warning: ${M}`);o.push(...vI(e.localEvalEvidence));let s=O(e.guardianProtection)?e.guardianProtection:null;if(s&&(o.push(String(s.label)),typeof s.nextStep=="string"&&o.push(` ${s.nextStep}`)),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 M=f(e,"reasonCode");M&&o.push(`Catalogue review reason: ${M}`)}let a=f(e,"skillSlug")??f(e,"slug"),l=f(e,"version")??f(e,"currentVersion"),c=f(e,"catalogueCandidateVersion"),u=f(e,"localProvisionalVersion"),d=f(e,"localGeneration"),p=f(e,"sourceContentDigest");(a||l||c||u||d||p)&&(o.push("",i.section("Skill")),a&&o.push(` ${i.label("Slug")}: ${a}`),c?o.push(` ${i.label("Catalogue Candidate Version")}: ${c}`):l&&o.push(` ${i.label("Version")}: ${l}`),u&&o.push(` ${i.label("Local Provisional Version")}: ${u}`),d&&o.push(` ${i.label("Local Generation")}: ${d}`),p&&o.push(` ${i.label("Source Content Digest")}: ${p}`));let m=f(e,"visibility")??f(e,"versionVisibility"),g=f(e,"catalogueVisibilityRequested")??f(e,"requestedVisibility"),h=f(e,"catalogueStatus"),y=typeof e.publiclyDiscoverable=="boolean"?e.publiclyDiscoverable:void 0,w=f(e,"publicationStatus"),b=f(e,"catalogRecord");(m||g||h||y!==void 0||w||b)&&(o.push("",i.section("Privacy")),g?o.push(` ${i.label("Catalogue Visibility Requested")}: ${g}`):m&&o.push(` ${i.label("Visibility")}: ${m}`),h&&o.push(` ${i.label("Catalogue Status")}: ${h}`),y!==void 0&&o.push(` ${i.label("Publicly Discoverable")}: ${y?"yes":"no"}`),w&&o.push(` ${i.label("Publication")}: ${w}`),b&&o.push(` ${i.label("Catalog record")}: ${b}`));let _=L(e,"materializationPlan")??L(e,"installPlan"),I=f(e,"scope")??(_?f(_,"scope"):void 0),x=f(e,"agent")??f(e,"targetAgent")??(_?f(_,"agent")??f(_,"targetAgent"):void 0),C=Array.isArray(e.materializedWrites)?e.materializedWrites.filter(O):[];if(I||x||C.length>0)if(o.push("",i.section("Local Materialization")),I&&o.push(` ${i.label("Scope")}: ${I}`),x&&o.push(` ${i.label("Agent")}: ${x}`),C.length===0)o.push(` ${i.muted("No local files were written by this command.")}`);else for(let M of C.slice(0,Ue)){let $=f(M,"path");$&&o.push(` ${i.arrow} ${$}`)}let D=G9(e,i).filter(M=>!M.includes("materialized writes:"));D.length>0&&o.push("",...D);let T=(he(e,"requiredConsentCapabilities")??[]).map(M=>` --accept-capability ${String(M)}`).join(""),j=!I&&C.length===0&&a?[`skills-layer install ${a} --scope ${r.scope??"project"} --agent ${x??r.agent??"<agent>"}${T}`]:X9(e);return j.length>0&&o.push("",i.section("Next"),...j.map(M=>` ${i.arrow} ${M}`)),o.join(`
|
|
1043
|
+
`)}function R3(e,t){let n=L(e,"trust"),r=L(e,"securityPosture"),i=L(e,"capabilityProfile"),o=n?.securityScore??n?.score??e.securityScore??r?.securityScore,s=Ce(n,"runtimeRisk")??f(e,"runtimeRisk")??Ce(r,"runtimeRisk")??Ce(i,"runtimeRisk"),a=Ce(n,"recommendation")??f(e,"recommendation")??Ce(r,"recommendation"),l=Ce(n,"label")??Ce(n,"trust")??f(e,"trustStatus")??f(e,"trust")??Ce(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 Ul(e,t,n){let r=[],i=[];if(!t.apiKey)return{warnings:r,revokedSlugs:i};let o=await Pe(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 E(t,`/api/v1/me/entitlements?${c}`,{headers:H(t.apiKey,t.authBlockedMessage)});if(!Array.isArray(u.results))throw new Error("Entitlement status unavailable");a.push(...u.results.filter(O))}}catch{return{warnings:["Could not verify entitlements online; local copies were kept."],revokedSlugs:i}}for(let[l,c]of s){let u=a.find(g=>g.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=Et(c);if(!m.length){r.push(`No managed agent copy found for refunded ${l}. Manually copied folders cannot be removed automatically.`);continue}for(let g of m){let h=typeof g.record.acquisitionBaseUrl=="string"?g.record:m.length===1?c:{},y=typeof h.entitlementId=="string"&&h.entitlementId===u.entitlementId,w=h.acquiredByUserId===t.config?.userId&&typeof h.acquiredByUserId=="string"&&h.acquisitionBaseUrl===t.baseUrl;if(!y&&!w){r.push(`Kept ${l}: this agent copy belongs to an unverified buyer receipt.`);continue}if(i.includes(l)||i.push(l),!(g.lifecycle?.state==="quarantined"||g.lifecycle?.state==="externally_removed")){if(!g.lifecycle||!["active","pending_activation"].includes(g.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 pv({backend:t,skillSlug:l,record:xn(c,g),materializationId:g.materializationId,lifecycle:g.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 P3(e,t){let n=jl("installed",e);if(n.failure)return n.failure;let r=await Ul(e,t),i=e.dryRun?await Pe(t):await Ur(t),o=gT(i).filter(s=>(e.includeRemoved||!["quarantined","removed","externally_removed","host_detached"].includes(f(L(s,"localLifecycle")??{},"state")??f(s,"status")??""))&&(!n.scope||f(s,"scope")===n.scope)&&(!n.agent||Dt(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 E3(e,t,n){let r=F(e[0],"remove requires a skill slug."),i=rD("remove",t);if(i)return i;let s=(t.dryRun?await Pe(n):await Ur(n,r)).installs[r];if(!s)return S({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=v(t.scope),l=v(t.agent),c=sn(s,{scope:a,agent:l});if(c.length>1){let y=t9({backend:n,skillSlug:r,materializations:c,scope:a,agent:l});y.length===1&&(c=y)}if(c.length===0&&Et(s).length>0)return S({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 S({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,availableTargets:c.map(y=>({materializationId:y.materializationId,scope:f(y.record,"scope"),targetAgents:Dt(y.record),materializedSkillRoot:f(y.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?xn(s,u):s,p=u?.lifecycle??null;if(!p){let y=hT(s);if(y){try{await D3({backend:n,skillSlug:r,record:s,cachedArtifact:y})}catch{return S({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 w={status:"removed",skillSlug:r,storageKind:"cached_artifact"};return t.json?R(w,`Removed cached ${r}.`,!0,n):{exitCode:0,stdout:cw(r,n),stderr:""}}return S({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 y={status:"removed",skillSlug:r,removedRecord:d,localLifecycle:p};return t.json?R(y,`${r} is already removed from discovery.`,!0,n):{exitCode:0,stdout:cw(r,n),stderr:""}}if(p.state==="externally_removed"||p.state==="host_detached"){if(t.forget){let y=pr(p.receipt),w=await K8(n,{skillSlug:r,generationId:p.receipt.generation.generationId,receiptSha256:y});return await Vn(n,b=>{let _=b.installs[r];if(!_)return;let I=mT({existing:_,materializationId:u.materializationId,backend:n});I?b.installs[r]=I:delete b.installs[r]}),R({status:"forgotten",skillSlug:r,materializationId:u.materializationId,receiptSha256:y,forgottenAssociationCount:w,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 S({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 S({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,g=Dt(d);if(g.length>1&&!t.allSharingAgents)return S({status:"blocked",reasonCode:"shared_target_confirmation_required",skillSlug:r,affectedAgents:g,materializedSkillRoot:p.receipt.targetDir,nextStep:`Retry skills-layer remove ${r} --scope ${f(d,"scope")} --agent ${l&&g.includes(l)?l:g[0]} --all-sharing-agents to remove the shared copy for every listed agent.`},`Removing ${r} affects ${g.join(", ")}. Confirm with --all-sharing-agents.`,t.json,"shared_target_confirmation_required");try{m=await pv({backend:n,skillSlug:r,record:d,materializationId:u.materializationId,lifecycle:p,reasonCode:"user_removed",purpose:"quarantine_revoked",status:"removed"})}catch(y){return S({status:"blocked",reasonCode:"exact_generation_quarantine_failed",skillSlug:r,error:ne(y),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:cw(r,n),stderr:""}}async function D3(e){let t=e.backend.platform==="win32"?je:ct,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 Ml(n);if(!r.isFile()||r.isSymbolicLink())throw new Error("Cached artifact is not a regular file.");if(`sha256:${me("sha256").update(await on(n)).digest("hex")}`!==e.cachedArtifact.archiveSha256)throw new Error("Cached artifact digest does not match its receipt.");let o=z(ye(n),`.bundle.remove-${ke(12).toString("hex")}`);await Li(n,o);try{let s=await Pe(e.backend),a=s.installs[e.skillSlug],l=a?hT(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 Dv(e.backend,s)}catch(s){throw await Li(o,n).catch(()=>{}),s}await Ae(o,{force:!0})}async function pv(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_${ke(16).toString("hex")}`,n={status:"authorized",authorizationId:`${e.purpose}_${ke(16).toString("hex")}`,purpose:e.purpose,generation:e.lifecycle.receipt.generation,archiveSha256:e.lifecycle.receipt.archiveSha256,manifestSha256:e.lifecycle.receipt.manifestSha256},r=await OR({receipt:e.lifecycle.receipt,reasonCode:e.reasonCode,quarantineRoot:z(e.backend.paths.stateDir,"quarantine"),discoveryRoots:T3(e.backend,e.lifecycle.receipt.targetDir),authorizeQuarantine:async()=>n}),i=Ol({state:"quarantined",operationId:t,receipt:e.lifecycle.receipt,quarantine:r,backend:e.backend}),o;if(await Vn(e.backend,s=>{let a=s.installs[e.skillSlug],l=a?kt(a)[e.materializationId]:void 0,c=l?_t(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]=qn({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 T3(e,t){let n=new Set([ye(t)]);for(let r of We(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 $3(e,t,n){let r=F(e[0],"update requires a skill slug."),i=jl("update",t);if(i.failure)return i.failure;let o=new URLSearchParams,s=v(t.pin);if(s&&!xf(s))return S({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");be(o,"pin",s),t.dryRun&&o.set("dryRun","true");let a=await Ul(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 Pe(n):await Ur(n,r)).installs[r],u=sn(c,i);if(u.length===0&&Et(c).length>0&&(i.scope||i.agent))return S({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 S({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?xn(c,u[0]):c,p=H4(d),m=n,g;try{g=await E(n,`/api/v1/skills/${encodeURIComponent(r)}${Re(o)}`,{headers:An(n.apiKey)})}catch(y){if(Dw(p,y))m={...n,apiKey:void 0,authBlockedMessage:void 0},g=await E(m,`/api/v1/skills/${encodeURIComponent(r)}${Re(o)}`);else{if(y instanceof V&&y.status===404&&d){let w={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 S(w,`${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 V)return Fi(y,t.json);throw y}}if(g.catalogRefreshPending===!0||O(g.skill)&&g.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 h=F3(r,g,d,n);if(s&&!L3(h,s))return S({status:"not_found",reasonCode:"pin_not_resolved",skillSlug:r,requestedPin:s,installedVersion:f(d,"version")??f(d,"currentVersion"),currentVersion:f(h,"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"),w=f(h,"latestAvailableVersion"),b=s??w;if(!!(b&&b!==y)){let I={...t,dryRun:!1,pin:void 0,version:b,scope:v(t.scope)??f(d,"scope")??"project",agent:v(t.agent)??f(d,"agent")??f(d,"targetAgent")??"codex"};return await gs([r],I,m,p)}}return t.json?R(h,"Update check complete.",!0,n):{exitCode:0,stdout:M3(h,n),stderr:""}}function xf(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 L3(e,t){let n=[f(e,"version"),f(e,"currentVersion"),f(e,"latestVersion"),f(e,"targetVersion"),f(e,"availableVersion")].filter(Boolean),r=L(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 O3(e,t){let n=jl("sync",e);if(n.failure)return n.failure;let r=await Ul(e,t),i=e.dryRun?await Pe(t):await Ur(t),o=gT(i).filter(l=>(!n.scope||f(l,"scope")===n.scope)&&(!n.agent||Dt(l).includes(n.agent))),a={status:"synced",results:await Promise.all(o.map(async l=>B3(l,t))),warnings:r.warnings};return e.json?R(a,"Local install records synced.",!0,t):{exitCode:0,stdout:j3(a,t)+r.warnings.map(l=>`
|
|
1044
|
+
${l}`).join(""),stderr:""}}function F3(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 W({...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 B3(e,t){let n=f(e,"skillSlug")??f(e,"slug");if(!n)return{...e,syncStatus:"local_only",backendStatus:"unchecked"};try{let r=await E(t,`/api/v1/skills/${encodeURIComponent(n)}`,{headers:An(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:N3(r)}}catch(r){return r instanceof V&&r.status===404?{...e,syncStatus:"backend_missing",backendStatus:"not_found",selectedBackend:t.baseUrl}:{...e,syncStatus:"unchecked",backendStatus:"error",backendError:ne(r)}}}function N3(e){return W({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 M3(e,t){let n=de(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=L(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(`
|
|
1045
|
+
`)}function j3(e,t){let n=de(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(`
|
|
1046
|
+
`)):(e.results.slice(0,Ue).forEach((i,o)=>{let s=f(i,"skillSlug")??f(i,"slug")??`item-${o+1}`,a=f(i,"syncStatus")??"unchecked",l=f(i,"version")??f(i,"currentVersion");r.push(`${o+1}. ${s}`),r.push(` status: ${a.replaceAll("_"," ")}${l?`; version: ${l}`:""}`),a==="backend_missing"&&r.push(` ${n.muted("Installed locally, but missing from the selected backend catalog.")}`)}),e.results.length>Ue&&r.push(` ${n.muted(`... ${e.results.length-Ue} more`)}`),r.push("",n.section("Next")),r.push(` ${n.arrow} skills-layer installed`),r.push(` ${n.arrow} skills-layer update <skill-slug>`),r.join(`
|
|
1047
|
+
`))}function cw(e,t){let n=de(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(`
|
|
1048
|
+
`)}function U3(e,t,n){let r=de(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(`
|
|
1049
|
+
`)}function q3(e){let t=f(e,"status"),n=f(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function V3(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}`:""}
|
|
1050
|
+
Next step: ${s}`}async function G3(e,t,n){let r=jl("restore",t);if(r.failure)return r.failure;let i=await Pe(n),o=F(e[0],"restore requires a skill slug."),s=i.installs[o];if(!s)return S({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"||Et(s).some(I=>I.record.removedReason==="refunded")){let I=!1;try{let x=await E(n,`/api/v1/me/entitlements?${new URLSearchParams({slugs:o})}`,{headers:H(n.apiKey,n.authBlockedMessage)});I=lt(x.results).some(C=>C.skillSlug===o&&C.status==="active")}catch{}if(!I)return S({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=sn(s,{scope:r.scope,agent:r.agent});if(a.length===0&&Et(s).length>0)return S({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 S({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?xn(s,l):s,u=l?.lifecycle??null;if(!u)return S({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 S({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");if(f(c,"distributionStatus")==="unverified_local"){let I=`skills-layer install ${String(c.source)} --local-only --agent ${String(c.agent)} --scope ${String(c.scope)}`;return S({status:"blocked",reasonCode:"restore_local_only_reinstall_required",skillSlug:o,nextAction:"install",nextStep:`Run \`${I}\` to install it again from the folder.`},`${o} was a local-only install that was never uploaded, so it cannot be restored. Re-install it from the folder.`,t.json,"restore_local_only_reinstall_required")}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 E(n,p?`/api/v1/skills/${encodeURIComponent(o)}/export${Re(d)}`:`/api/v1/me/library/${encodeURIComponent(o)}/export${Re(d)}`,{headers:p?{}:H(n.apiKey,n.authBlockedMessage)})}catch(I){if(I instanceof V)return Fi(I,t.json);throw I}if(m.restoreAuthorization===void 0)return S({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 g=wT(m.restoreAuthorization);if(!g||g.purpose!=="restore_fresh_approval"||!z3(g,u.receipt))return S({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 h=`restore_${ke(16).toString("hex")}`,y=Ol({state:"restore_pending",operationId:h,receipt:u.receipt,quarantine:u.quarantine,backend:n});await Vn(n,I=>{let x=I.installs[o],C=x&&l?kt(x)[l.materializationId]:void 0,D=C?_t(C):null;if(!x||!C||D?.operationId!==u.operationId||D.state!=="quarantined")throw new Error("Local install record changed before its exact restore reservation was created.");I.installs[o]=qn({existing:x,skillSlug:o,materialization:{...C,localLifecycle:y,savedAt:n.now()},backend:n})});let w;try{await FR({quarantine:u.quarantine,authorizeRestore:async()=>g,finalizeRestore:async()=>{let I=!0;return await Vn(n,x=>{let C=x.installs[o],D=C&&l?kt(C)[l.materializationId]:void 0,T=D?_t(D):null;if(!C||!D||!T||T.state!=="restore_pending"||T.operationId!==h){I=!1;return}let j=Ol({state:"active",operationId:h,receipt:u.receipt,backend:n});w={...D,status:"restored",localLifecycle:j,savedAt:n.now()},x.installs[o]=qn({existing:C,skillSlug:o,materialization:w,backend:n})}),I?{status:"released",releaseId:`local_restore_${ke(16).toString("hex")}`}:{status:"denied",reasonCode:"restore_reservation_lost"}}})}catch(I){return await Vn(n,x=>{let C=x.installs[o],D=C&&l?kt(C)[l.materializationId]:void 0,T=D?_t(D):null;!C||!D||T?.operationId!==h||(x.installs[o]=qn({existing:C,skillSlug:o,materialization:{...D,localLifecycle:u,savedAt:n.now()},backend:n}))}).catch(()=>{}),S({status:"blocked",reasonCode:"exact_generation_restore_failed",skillSlug:o,error:ne(I),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(!w)throw new Error(`Atomic restore for ${o} completed without committing its local lifecycle record.`);let b=_t(w),_={status:"restored",skillSlug:o,record:w,localLifecycle:b};return t.json?R(_,`Restored ${o}.`,!0,n):{exitCode:0,stdout:U3(o,w,n),stderr:""}}function z3(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 K3(e,t,n){let r=F(e[0],"check requires a skill slug.");return await ie(`/api/v1/skills/${encodeURIComponent(r)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function H3(e,t,n){let r=F(e[0]??t.source,"import requires a source."),i=Sn("import","visibility",t.visibility,ls,t,"invalid_visibility");if(i)return i;let o=await $l(r,n.cwd);if(o)return await W3(r,o,t,n);let s=J3(r,t);if(s)return s;let a=uv(r,t,n,n.apiKey?"authenticated":"unknown"),l=await E(n,a,{method:"POST",headers:AD(r,t,n,n.apiKey?"authenticated":"unknown"),body:JSON.stringify(W({source:r,skillSlug:v(t.skill),visibility:v(t.visibility)??(n.apiKey&&vf(r)?void 0:Or(r,t,n))}))});return await _e(n.paths.importsPath,{version:1,lastImport:l,savedAt:n.now()}),R(l,"Source import submitted.",t.json,n)}async function W3(e,t,n,r){let i=v(n.skill),o=lv(e,t,i);if(!r.apiKey)return S({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=bf(e,o,n);if(s)return s;let a=await _l({source:e,inspection:o,requestedSkillSlug:i,mode:"import",flags:n,backend:r});if(a.kind==="failure")return a.result;let c=cv(t.files).find(d=>d.skillSlug===a.skillSlug),u=c.relativeSkillRoot==="."?e:`${e.replace(/[\\/]+$/u,"")}/${c.relativeSkillRoot}`;return v(n.version)?await Pw([u],{...n,source:void 0,path:void 0,skill:c.skillSlug},r,!1):S({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 J3(e,t){try{return en(e).kind!=="local"?null:S({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:xl(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."},xl(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 S({status:"error",reasonCode:"invalid_source",source:e,error:ne(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ne(n)}`,t.json,"invalid_source")}}function xl(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function LD(e,t,n,r){let i=tt(r.cwd,t);return S({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 Y3(e,t,n){let r=e[0];if(r==="reference"&&e[1]==="resolve"){let i=F(e[2],"source reference resolve requires a reference."),o=await E(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(i)}`,{headers:An(n.apiKey)}).catch(s=>{if(s instanceof V&&s.status===404&&s.details?.reasonCode==="source_reference_not_found")return{status:"not_found"};throw s});return o.status==="not_found"?S({...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 Z3(e.slice(1),t,n):P(`Unknown source command "${e.join(" ")}".`,t.json)}async function Z3(e,t,n){let r=e[0];if(r==="start"){let o=v(t.provider),s=v(t.source),a=v(t.visibility),l=o?.replace(/-/gu,"_");if(l&&!BE.includes(l))return Un("source.connection.start","provider",o??"",BE,t,"invalid_source_provider");let c=Mr(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=X3(o,s,a,t);if(u)return u;let d=rt(t,["provider","source","mode","visibility","priceCents","license","provenanceIntent","discloseSource","processingReceiptId"]),p=v(t.skill);return p&&(d.requestedSkillSlug=p),await pe("/api/v1/me/source-connections",d,t,n,"Source connection started.")}if(r==="list"){let o=new URLSearchParams,s=v(t.status),a=v(t.limit);s&&o.set("status",s),a&&o.set("limit",a);let l=o.toString();return await ie(`/api/v1/me/source-connections${l?`?${l}`:""}`,t,n,"Source connections listed.",{authenticated:!0})}let i=F(e[1],`source connection ${r??""} requires a connection id.`);if(r==="status")return await ie(`/api/v1/me/source-connections/${encodeURIComponent(i)}`,t,n,"Source connection loaded.",{authenticated:!0});if(r==="complete"){let o=XH("source.connection.complete",t);return o||await pe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/complete`,rt(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return r==="cancel"?await pe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/cancel`,{},t,n,"Source connection cancelled."):r==="revoke"?await pe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/revoke`,{},t,n,"Source connection revoked."):P(`Unknown source connection command "${r??""}".`,t.json)}function X3(e,t,n,r){if(n){let i=na(n);if(!i||!ls.includes(i))return S({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:ls,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${ls.join(", ")}.`,r.json,"invalid_visibility")}if(!e||!t)return null;try{let i=en(t);if((e==="github"||e==="gitlab")&&i.kind!==e)return uw(e,t,r);if(e==="domain"){let o=new URL(t);if(o.protocol!=="https:"||!o.hostname)return uw(e,t,r)}}catch{return uw(e,t,r)}return null}function uw(e,t,n){return S({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 Q3(e,t,n){if(e[0]!=="request")return P(`Unknown approval command "${e[0]??""}".`,t.json);let r=e[1];if(r!=="status"&&r!=="complete")return P("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let i=F(e[2],`approval request ${r??""} requires an approval id.`);if(r==="status")return await ie(`/api/v1/me/approvals/${encodeURIComponent(i)}`,t,n,"Approval status loaded.",{authenticated:!0});let o=F(t.decision,"approval request complete requires --decision."),s=Sn("approval.request.complete","decision",o,MH,t,"invalid_decision");if(s)return s;let a=v(t.mfaCode);if(!a&&!t.json)try{a=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return P("Cancelled: nothing was sent. A decision needs a fresh authenticator code; run the command again, or pass --mfa-code.",!1)}return await pe(`/api/v1/me/approvals/${encodeURIComponent(i)}/complete`,W({decision:o,decisionEvidence:It(t.decisionEvidenceJson,"decision-evidence-json"),mfaCode:a}),t,n,"Approval completed.")}async function e8(e,t,n){let r=e[0]??"list";if(r==="list"){let o=await E(n,"/api/v1/me/workspaces",{headers:H(n.apiKey,n.authBlockedMessage)});return Rt(o,t8(o,n),"Available workspaces loaded.",t.json,n)}if(r==="current"){let o=await E(n,"/api/v1/me/working-mode",{headers:H(n.apiKey,n.authBlockedMessage)});return await Nr(n,o),Rt(o,n8(o,n),"Selected workspace loaded.",t.json,n)}if(r==="select"||r==="use"){let o=F(e[1],"workspace select requires personal or a workspace id."),s=await E(n,"/api/v1/me/working-modes",{headers:H(n.apiKey,n.authBlockedMessage)}),a=(Array.isArray(s.modes)?s.modes:[]).filter(O),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 S({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 S({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 S({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 E(n,"/api/v1/me/working-mode",{method:"PUT",headers:U(n.apiKey,n.authBlockedMessage),body:JSON.stringify({modeId:u})});await Nr(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 P(`Unknown workspace command "${r}".`,t.json);let i=F(e[1],`workspace ${r} requires a workspace id.`);if(r==="request"||r==="approve"||r==="reject"){let o=F(e[2],`workspace ${r} requires a skill slug.`);try{if(r==="request")return await pe(`/api/v1/workspaces/${encodeURIComponent(i)}/skill-requests`,{skillSlug:o,reason:v(t.reason)},t,n,"Workspace skill request captured.");if(r==="approve"){let s=await cD(n,`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/approve`,t.dryRun?{dryRun:!0}:{},t);return Z(s)?s:t.dryRun?await DD(s,"Workspace approval preview ready.",t,n):R(s,"Workspace skill approval evaluated.",t.json,n)}return await pe(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r}`,{reason:v(t.reason)},t,n,"Workspace skill rejected.")}catch(s){if(s instanceof V&&(s.status===403||s.status===404))return r==="reject"&&d0(s)?u0(i,o,t):r==="approve"&&r8(s)?i8(i,o,t,s):dw(i,t);throw s}}if(r==="skills")try{return await ie(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(o){if(o instanceof V&&(o.status===403||o.status===404))return dw(i,t);throw o}if(r==="guide"){let o=F(e[2],"workspace guide requires a skill slug.");try{return await ie(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(s){if(s instanceof V&&s.status===404)return d0(s)?u0(i,o,t):dw(i,t);throw s}}return P(`Unknown workspace command "${r}".`,t.json)}function t8(e,t){let n=de(t),r=Array.isArray(e.results)?e.results.filter(O):[],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")}: ${ut(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(`
|
|
1051
|
+
`)}function n8(e,t){let n=de(t),r=O(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(`
|
|
1052
|
+
`)):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(`
|
|
1053
|
+
`)):(s.push(n.section("Selected workspace"),` ${n.muted("No workspace is currently selected.")}`),s.join(`
|
|
1054
|
+
`))}function dw(e,t){return S({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 u0(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 S(r,`Workspace approval not found for ${t}. Run \`skills-layer workspace approve ${e} ${t}\` first.`,n.json,"workspace_skill_approval_not_found")}function d0(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 r8(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 i8(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 S(o,`Skill ${t} was not found. Run \`skills-layer search ${t}\` before approving it for the workspace.`,n.json,"skill_not_found")}async function o8(e,t,n){let r=F(e[0],"buy requires a skill slug."),i=r4(t);if(i.failure)return i.failure;if(v(t.workspace))return S({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 nv(n,{skillSlug:r,paymentMethod:i.value},t,"/api/v1/buy");if(Z(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 qW(o.purchaseId,n);return Z(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 gs([r],t,n,{origin:"post_purchase",fallbackPolicy:"account_required"}))}async function s8(e,t,n){let r=e[0]??"list";if(r==="list")return await ie("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(r==="spending")return await ie("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let i=F(e[1],`purchases ${r} requires a purchase id.`);if(r==="status")return await ie(`/api/v1/purchases/${encodeURIComponent(i)}`,t,n,"Purchase status loaded.",{authenticated:!0});if(r==="invoice")return await ie(`/api/v1/purchases/${encodeURIComponent(i)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0});if(r==="refund-quote"){let o=await E(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund-quote`,{headers:H(n.apiKey,n.authBlockedMessage)}),s=O(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 E(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund`,{method:"POST",headers:U(n.apiKey),body:JSON.stringify(rt(t,["reason"]))}),s=o.status==="refunded"?await Ul(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 P(`Unknown purchases command "${r}".`,t.json)}function OD(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 a8(e,t,n){let r=e[0];if(r==="search"){let i=new URLSearchParams;return be(i,"query",e.slice(1).join(" ").trim()||v(t.query)),be(i,"limit",v(t.limit)),await ie(`/api/v1/me/search${Re(i)}`,t,n,"Authenticated library search complete.",{authenticated:!0})}if(r==="add"){let i=F(e[1],"library add requires a skill slug."),o=await nv(n,{skillSlug:i},t);return Z(o)?o:o.status==="purchase_required"?OD(o,i,t,n):R(o,"Skill added to library.",t.json,n)}return P(`Unknown library command "${r}".`,t.json)}async function l8(e,t,n){let r=F(e[0],"export requires a skill slug.");if(t.showUrl&&v(t.output))return S({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=v(t.version);if(o&&!xf(o))return ev("export",o,t);be(i,"version",o);let s=await E(n,`/api/v1/me/library/${encodeURIComponent(r)}/export${Re(i)}`,{headers:H(n.apiKey,n.authBlockedMessage)}),a=v(t.output);if(a){let l=await hf({backend:n,exportResult:s,flags:t,skillSlug:r,consentCommand:"export"});if(Z(l))return l;let c=tt(n.cwd,a);await Tf(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 f0(e,t,n,r){if(e==="show"){let l=t[0]?.trim(),c=l?`?skillSlug=${encodeURIComponent(l)}`:"";return await ie(`/api/v1/me/library/reviews${c}`,n,r,"Reviews loaded.",{authenticated:!0})}let i=F(t[0],"add-review requires a skill slug."),o=F(n.rating,"add-review requires --rating.");if(!/^[1-5]$/u.test(o))return S({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=rt(n,["rating","feedback"]);if(typeof n.evalSummary=="string"){let l=await se(Gn(r.cwd,n.evalSummary));if(l===null)return S({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=l}let a=await E(r,`/api/v1/me/library/${encodeURIComponent(i)}/review`,{method:"POST",headers:U(r.apiKey),body:JSON.stringify(s)});return R(a,b_(a),n.json,r)}async function c8(e,t,n){let r=e[0];if(r==="notifications"){if(!t.type&&!t.status)return ie("/api/v1/me/feedback-notifications",t,n,"Feedback email preferences loaded.",{authenticated:!0});if(!t.type||!["enabled","disabled"].includes(String(t.status)))throw new Error("Use issue notifications --type <event> --status enabled|disabled.");let a=await E(n,"/api/v1/me/feedback-notifications",{method:"PATCH",headers:U(n.apiKey),body:JSON.stringify({event:t.type,enabled:t.status==="enabled"})});return R(a,"Feedback email preference saved.",t.json,n)}if(!["reply","replies","reopen","moderate-reply"].includes(r))throw new Error("Use issue reply, replies, reopen, or moderate-reply.");let i=F(e[1],"issue requires a skill slug."),o=F(t.issueId,"issue requires --issue-id."),s=`/api/v1/me/library/${encodeURIComponent(i)}/issues/${encodeURIComponent(o)}`;if(r==="replies")return ie(`${s}/comments`,t,n,"Replies loaded.",{authenticated:!0});if(r==="moderate-reply"){let a=F(t.commentId,"issue moderate-reply requires --comment-id.");if(F(t.reason,"issue moderate-reply requires --reason."),!["hidden","visible"].includes(String(t.status)))throw new Error("Use --status hidden or visible.");let l=await E(n,`/api/v1/me/skills/${encodeURIComponent(i)}/issues/${encodeURIComponent(o)}/comments/${encodeURIComponent(a)}`,{method:"PATCH",headers:U(n.apiKey),body:JSON.stringify({hidden:t.status==="hidden",reason:t.reason})});return R(l,"Reply moderated.",t.json,n)}return F(r==="reply"?t.message:t.note,r==="reply"?"issue reply requires --message.":"issue reopen requires --note."),pe(`${s}/${r==="reply"?"comments":"reopen"}`,rt(t,["message","note"]),t,n,r==="reply"?"Reply added.":"Issue reopened.")}async function p0(e,t,n,r){let i=F(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await ie(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});F(n.message,"add-issue requires --message.");let o=Sn("add-issue","issueType",n.issueType,NH,n,"invalid_issue_type","issue-type");return o||await pe(`/api/v1/me/library/${encodeURIComponent(i)}/report-issue`,rt(n,["issueType","message"]),n,r,"Issue reported.")}async function u8(e,t,n){let r=e[0];if(r==="hook"){let i=e[1];if(i==="install")return await ND(t,n);if(i==="status")return await _8(t,n);if(i==="uninstall")return await b8(t,n);if(i==="run"){let o=await x8(t,n),s=v(t.agent);if(s&&Jt(s)){let a=bo(n.env);await jg({agentId:s,associationState:a?await f8(s,t,n):"unreadable",activationEvent:a?await m8(s,n):!1,delegatedExecution:o[FD]===!0,env:n.env,rawPayloadBase64:ue(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64),result:o})}return o}return P(`Unknown guardian hook command "${i??""}".`,t.json)}if(r==="session"){let i=e[1];return i==="bind"?await C8(e.slice(2),t,n):P(`Unknown guardian session command "${i??""}".`,t.json)}if(r==="enable")return e[1]||t.skill?await pw("enforce",e,t,n):P("guardian enable requires a skill slug.",t.json);if(r==="disable")return await pw("disabled",e,t,n);if(r==="enable-warnings-only")return await pw("warning_only",e,t,n);if(r==="status")return await h8(e,t,n);if(r==="launch")return await A8(e.slice(1),t,n);if(r==="exec")try{let i=await g8(e,t,n);return await m0(i,e,t,n),i}catch(i){throw await m0({exitCode:1,stdout:"",stderr:ne(i)},e,t,n),i}if(r==="check"){let i=F(e[1]??t.skill,"guardian check requires a skill slug.");if((await Ul({...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=O0(t,"check");if(t.grantJson.length>0)return S({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=fJ(t.cloudTrustLedger);if(a.status==="invalid")return P(a.message,t.json);let l=Mw(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(l.status==="invalid")return P(l.message,t.json);let c=await ZD({skillSlug:i,version:v(t.version),action:s,flags:t,backend:n,telemetryMode:l.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=v(t.version)??c.context.version,p=A0(c.context.record),m=W({skillSlug:i,version:d,action:s,path:u,workspaceId:p,guardianPreference:p?void 0:await jr(n,i),unmanagedPolicy:c.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:l.mode,localPreflight:Il(c.context)}),g=await E(n,"/api/v1/guardian/enforce",{method:"POST",headers:U(n.apiKey),body:JSON.stringify(m)});return await ds(n,{skillSlug:i,version:d,action:s,decisionStatus:Uw(g),reasonCode:Pl(g),telemetryMode:l.mode,path:u,authority:g}),R({...g,localPreflight:Il(c.context)},"Guardian check complete.",t.json,n)}if(r==="incident"){let i=F(e[1]??t.skill,"guardian incident requires a skill slug."),o=F(t.version,"guardian incident requires --version."),s=Mw(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return P(s.message,t.json);let a=v(t.path);if(a&&!await Ke(tt(n.cwd,a)))return S({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=await XD({skillSlug:i,flags:t,backend:n}),c=a??l.installedPath,u=A0(l.record),d=O0(t,"incident"),p=It(t.evidenceJson,"evidence-json"),m=s.mode==="cloud_managed"&&!n.apiKey?"local_only":s.mode,g=n.now(),h=W({skillSlug:i,version:o,action:d,evidence:p,path:c,workspaceId:u,telemetryMode:m,incident:!0,reason:v(t.reason),generatedAt:g,...m==="cloud_managed"?{incidentIdempotencyKey:XW()}:{}});if(m==="local_only"){if(!c)return P("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let I=await E0({backend:n,skillSlug:i,version:o,installedPath:c,action:d,reason:v(t.reason)??"Guardian local-only incident"});if(f(I,"status")!=="quarantined"){let D=f(I,"reasonCode")??"guardian_exact_quarantine_failed";return S(I,`Guardian could not physically quarantine the exact installed generation for ${i}.`,t.json,D)}await ds(n,{skillSlug:i,version:o,action:d,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:m,path:c});let x=D0(n,i);await q0(x,JSON.stringify({request:h,response:null,localResponse:I,savedAt:n.now()},null,2));let C=P0(i,I);return R({status:"written",skillSlug:i,version:o,telemetryMode:m,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:I,incidentStatePath:x,incidentPath:I.incidentPath,...C.payload},`${n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence."}${C.sentence}`,t.json,n)}let y=await QW(n,h),w=c?await E0({backend:n,skillSlug:i,version:o,installedPath:c,action:d,reason:v(t.reason)??"Guardian Cloud-managed incident"}):null;if(w&&f(w,"status")!=="quarantined"){let I=f(w,"reasonCode")??"guardian_exact_quarantine_failed";return S({...w,cloudResponse:y},`Guardian recorded the Cloud incident but could not physically quarantine the exact local generation for ${i}.`,t.json,I)}await Ti(n.paths.incidentsDir,{recursive:!0});let b=D0(n,i);await q0(b,JSON.stringify({request:h,response:y,localResponse:w,savedAt:n.now()},null,2)),await ds(n,{skillSlug:i,version:o,action:d,decisionStatus:Uw(y),reasonCode:Pl(y),telemetryMode:s.mode,path:c,authority:y});let _=P0(i,w);return R({...y,telemetryMode:s.mode,localResponse:w,incidentPath:b,..._.payload},`Guardian incident recorded.${_.sentence}`,t.json,n)}return P(`Unknown guardian command "${r??""}".`,t.json)}var FD=Symbol("guardian-delegated-execution");async function m0(e,t,n,r){if(!bo(r.env))return;let i=r.env.SKILLS_LAYER_GUARDIAN_CANARY_AGENT_ID,o=r.env.SKILLS_LAYER_GUARDIAN_CANARY_SCOPE;if(!i||!Jt(i)||o!=="project"&&o!=="global")return;let s=v(n.skill)??t[1];s&&await jg({agentId:i,associationState:await d8(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 d8(e,t,n,r){let i=await ix({agentId:e,scope:t,skillSlug:n,env:r.env});if(!i)return"unreadable";try{let o=await Oi(r,t),s=o.associations[i.associationKey];if(!s||s.agentId!==e||s.scope!==t||s.skillSlug!==n)return"missing";let a=_a(o,{agentId:e,sessionId:s.sessionId,asOf:r.now()});return a.associations.some(c=>Be(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 f8(e,t,n){let r=Ni(v(t.scope));return r.status==="invalid"?"unreadable":await p8(e,r.scope,n)}async function p8(e,t,n){let r=ue(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=Pu(e,i)?.sessionId??qD(e,i);if(!o)return"unreadable";try{let s=await Oi(n,t),a=_a(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 m8(e,t){let n=ue(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!n)return!1;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return Pu(e,r)!==null}catch{return!1}}async function g8(e,t,n){let r=v(t.skill),i=F(r??e[1],"guardian exec requires a skill slug."),o=r?e.slice(1):e.slice(2);if(o.length===0)return P("guardian exec requires a command after --.",t.json);if(t.actionJson!==void 0)return S({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 S({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=Mw(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return P(s.message,t.json);let a=x0(o),l=await ZD({skillSlug:i,version:v(t.version),action:a,flags:t,backend:n,telemetryMode:s.mode});if(l.status!=="ok")return l.result;let c=l.context.installedPath,u=v(t.version)??l.context.version;if(!u)return S({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 uW({commandArgs:o,skillSlug:i,version:u,flags:t,backend:n,localContext:l.context});if(d.status==="blocked")return d.result;let p=x0(o,d.request),m=await jr(n,i),g=await E(n,"/api/v1/guardian/execution/prepare",{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({request:d.request,...m?{guardianPreference:m}:{},...t.dryRun?{dryRun:!0}:{}})}),h=L(g,"warning"),y=L(g,"distributionHold"),w=typeof f(g,"token")=="string"&&L(g,"plan")!==void 0&&L(g,"binding")!==void 0;if(!cW(g)&&!w&&!h){let M=Pl(g);return await ds(n,{skillSlug:i,version:u,action:p,decisionStatus:"blocked",reasonCode:M,telemetryMode:s.mode,path:c,authority:g}),S({...g,status:"blocked",reasonCode:M,skillSlug:i},"Guardian blocked guarded execution.",t.json,M)}if(await ds(n,{skillSlug:i,version:u,action:p,decisionStatus:h?"advisory":"allowed",reasonCode:h?f(h,"reasonCode")??"personal_mode_warning":"within_contract",telemetryMode:s.mode,path:c,authority:g}),t.dryRun)return R({status:h?"allowed_with_warning":"allowed",...h?{warning:h}:{},...y?{distributionHold:y,warnings:[fw]}:{},skillSlug:i,guardian:g0(g),localPreflight:Il(l.context),command:{executable:$e(d.request.executableRealPath),executableSha256:d.request.executableSha256,argvSha256:nT(d.request.argv),cwdRealPath:d.request.cwdRealPath,executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let b=g,_=f(b,"token"),I=L(b,"plan"),x=L(b,"binding");if(!_||!I||!x)return S({status:"blocked",reasonCode:"guardian_grant_response_invalid",skillSlug:i},"Guardian returned an invalid execution grant.",t.json,"guardian_grant_response_invalid");await E(n,"/api/v1/guardian/execution-grants/consume",{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({token:_,plan:I,binding:x,...m?{guardianPreference:m}:{}})});let C;try{C=await aP({plan:I,ambientEnvironment:n.env,approvedSecrets:d.approvedSecrets})}catch(M){let $=M instanceof ce?M.reasonCode:"guardian_process_failed";return S({status:"blocked",reasonCode:$,skillSlug:i,planHash:x.planHash},"Guardian refused the contained process launch.",t.json,$)}let D=lP(C),T={executable:$e(I.executableRealPath),argsCount:I.argv.length,exitCode:D.exitCode,reason:C.reason,signal:C.signal,stdout:C.stdout,stderr:C.stderr,outputTruncated:C.outputTruncated,planHash:C.planHash},j=[...h?[`Guardian warning (${f(h,"reasonCode")??"personal_mode_warning"}): ${f(h,"message")??""}`]:[],...y?[`Guardian notice (guardian_distribution_hold): ${fw}`]:[]];return{exitCode:T.exitCode,stdout:t.json?JSON.stringify({status:D.status,summary:D.headline.replace(/^OK /u,""),why:null,nextAction:null,nextStep:D.nextStep,data:{skillSlug:i,guardian:g0(g),localPreflight:Il(l.context),command:T},warnings:[...h?[f(h,"message")??"Guardian warning."]:[],...y?[fw]:[]],links:[],reasonCode:D.reasonCode,handoff:null},null,2):vW(T,D,j),stderr:t.json?j.map(M=>`${M}
|
|
1055
|
+
`).join("")+T.stderr:""}}function g0(e){let{token:t,...n}=e;return n}var fw="This version is on a distribution hold while Skills Layer reviews it: new installs are paused. Your installed copy keeps running.";async function pw(e,t,n,r){let i=F(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),o=await E(r,"/api/v1/guardian/mode",{method:"POST",headers:U(r.apiKey),body:JSON.stringify({skillSlug:i,requestedPreference:e,source:"public-cli"})});if(o.preferenceAccepted===!0){if(f(o,"effectiveMode")==="enforce"){let s=(await Ur(r,i)).installs[i],a=Et(s).filter(u=>u.lifecycle?.state==="active"||u.lifecycle?.state==="pending_activation"||u.lifecycle?.state==="quarantined");if(a.length===0)return await I0(r,i,o),R({...o,status:"saved",reasonCode:"guardian_preference_saved_not_installed",effectiveMode:"not_installed_here",cloudEffectiveMode:"enforce",activeTargetCount:0,nextAction:"install",nextStep:`Guardian enforce is saved for ${i}, but it is not installed on this device, so nothing is enforced yet. Guardian checks this host when you run \`skills-layer install ${i}\`.`},`Guardian enforce preference saved; ${i} is not installed on this device yet.`,n.json,r);let l=We(r.env,r.platform,r.cwd),c=new Set;for(let u of a){let d=f(u.record,"scope"),p=Dt(u.record);if(d!=="project"&&d!=="global"||p.length===0)return S({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 g=l.find(w=>w.id===m);if(!g)return S({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 h=`${d}:${g.id}`;if(c.has(h))continue;c.add(h);let y=await ws({backend:r,skillSlug:i,agentId:g.id,scope:d,flags:n,enforceRequired:!0,purpose:"enable"});if(y)return y}}}await I0(r,i,o)}return R(o,o.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,r)}async function h8(e,t,n){let r=v(t.skill)??v(e[1]),i={status:"unavailable",skillSlug:r,policySource:"cloud",reasonCode:"login_required",nextAction:"skills-layer login",nextStep:"Sign in with `skills-layer login` so Guardian can load the Cloud policy for your account. Until then the warnings-only default is assumed; local hook and preference posture are still shown below."},o=i;if(n.apiKey)try{o=await BD(n,r)}catch(_){o=_ instanceof V&&_.status===401?{...i,message:ne(_)}:{status:"unavailable",skillSlug:r,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ne(_),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let s=await Vt(n),a=r?await bW(n,r):void 0,l=f(o,"status")==="unavailable",c=f(o,"reasonCode")==="login_required",u=f(s,"enforcementLayer")??"not_installed",d=u!=="not_installed"&&s.strictPreActionBlocking===!0,p=u==="native_hook_candidate",m=l?"The Cloud Guardian policy could not be loaded, so the mode in force is not confirmed here":f(o,"effectiveMode")==="warning_only"?"Guardian checks this skill in warnings-only mode: risky actions run with a recorded warning":f(o,"effectiveMode")==="disabled"?"Guardian is off for this skill":"Cloud Guardian policy is enforced when checked",g=d?{status:"strict_installed",reasonCode:"guardian_hook_strict",enforcementLayer:u,strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:`${m}, and the local host hook can check supported risky actions before execution.`}:p?{status:"candidate_installed",reasonCode:"guardian_hook_candidate",enforcementLayer:u,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:`${m}, but local pre-action checks are not installed for this host. Run \`${await Q8(n,r)}\` or \`skills-layer setup\`.`},h=await y8({backend:n,skillSlug:r,policy:o,hook:s,localPreference:a}),y=!l&&r!==void 0&&(await Pe(n)).installs[r]===void 0,w=f(o,"effectiveMode")==="enforce"&&h.countedAsEnforced!==!0,b=w?`Requested: enforce. Actual: ${String(h.label??"unavailable")} on this device, so Guardian is not enforcing blocking checks here yet. Install and verify a Guardian hook, or use warnings-only.`:f(o,"nextStep");return R(W({status:y?"not_installed":l?"degraded":"ok",...y?{reasonCode:"guardian_skill_not_installed"}:{},skillSlug:f(o,"skillSlug")??r,policy:w?{...o,nextStep:b}:o,localPreference:a,hook:s,cloudPolicy:{status:f(o,"effectiveMode")??f(o,"status")??"unknown",reasonCode:f(o,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:f(o,"nextAction"),nextStep:b},localEnforcement:g,measuredProtection:h,nextAction:c?i.nextAction:y?"install":f(g,"nextAction"),nextStep:c?i.nextStep:y?`Run \`skills-layer install ${r}\` first; Guardian checks a skill on this device once it is installed.`:f(g,"nextStep")}),c?"Guardian status loaded without the Cloud policy. Sign in with `skills-layer login` to load it.":y?`${r} is not installed on this device, so Guardian has nothing to check for it here.`:l?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function y8(e){let t=f(e.policy,"effectiveMode")??(e.localPreference?f(e.localPreference,"effectiveMode")??f(e.localPreference,"requestedPreference"):void 0),n=t==="enforce"?"enforce":t==="disabled"?"disabled":"warning",r="active",i,o,s=[];if(e.skillSlug){o=(await Ur(e.backend,e.skillSlug)).installs[e.skillSlug],s=Et(o);let b=s.map(_=>_.lifecycle?.state??"unreadable");b.some(_=>_==="active"||_==="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 w of["project","global"])try{a.push(...Object.values((await Oi(e.backend,w)).associations).filter(b=>b.state!=="refused"&&(!e.skillSlug||b.skillSlug===e.skillSlug)))}catch{l.add(w)}let c=y0(h0(a,r==="active"),l.size>0),d=(he(e.hook,"hooks")?.filter(O)??[]).filter(w=>w.active===!0),p=s.flatMap(w=>{let b=f(w.record,"scope");if(b!=="project"&&b!=="global")return[];let _=o?xn(o,w):w.record,I=f(_,"workspaceId")??f(_,"workingModeWorkspaceId"),x=f(w.record,"receiptSha256"),C=w.lifecycle?.receipt.generation.generationId,D=w8(w.lifecycle?.state);return Dt(w.record).map(T=>{let j=fn(T),M=d.find(Y=>f(Y,"agent")===T&&f(Y,"scope")===b),$=a.filter(Y=>Y.agentId===T&&Y.scope===b&&(!x||Y.receiptSha256===x)&&(!C||Y.generationId===C)),B=y0(h0($,D==="active"),l.has(b)),q=xa({evaluationContext:"runtime",requestedMode:n,workspacePolicy:I?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:j?.maximumTier==="strict_candidate",hookInstalled:!!M,strictHookVerified:M?.strictPreActionBlocking===!0,exactActivationVerified:M?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:B,materializationState:D});return{materializationId:w.materializationId,agent:T,scope:b,installedPath:w.lifecycle?.receipt.targetDir,receiptSha256:x,generationId:C,materializationState:D,associationState:B,activeAssociationCount:$.filter(Y=>Y.state==="active").length,hookState:M?f(M,"hookState")??"active":"not_installed",evidenceCapability:M?.evidenceCapability??"unverified",exactActivationVerified:M?.exactActivationVerified===!0,activationRoute:M?.activationRoute??null,workspaceRequired:!!I,...q}})}),m=xa({evaluationContext:"runtime",requestedMode:n,workspacePolicy:i?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:d.some(w=>fn(f(w,"agent")??"")?.maximumTier==="strict_candidate"),hookInstalled:d.length>0,strictHookVerified:d.some(w=>w.strictPreActionBlocking===!0),exactActivationVerified:d.some(w=>w.strictPreActionBlocking===!0&&w.exactActivationVerified===!0),completeWrapperVerified:!1,associationState:c,materializationState:r}),g=new Set(p.map(w=>w.label)),h=e.skillSlug&&!o&&n!=="disabled"?{label:"not_installed_here",countedAsEnforced:!1,activationAllowed:!0,runtimeGuardian:!1,reasonCode:"skill_not_installed_here"}:p.length===0?m:{label:g.size===1?p[0].label:"mixed",countedAsEnforced:p.every(w=>w.countedAsEnforced),activationAllowed:p.every(w=>w.activationAllowed),runtimeGuardian:p.every(w=>w.runtimeGuardian),reasonCode:g.size===1?p[0].reasonCode:"mixed_target_protection"},y=s.map(w=>({materializationId:w.materializationId,scope:f(w.record,"scope"),agent:f(w.record,"agent")??f(w.record,"targetAgent"),targetAgents:Dt(w.record),installedPath:w.lifecycle?.receipt.targetDir,receiptSha256:f(w.record,"receiptSha256"),state:w.lifecycle?.state??"unreadable",protectionTargets:p.filter(b=>b.materializationId===w.materializationId)}));return{...h,requestedMode:n,workspaceRequired:!!i,associationState:c,materializationState:r,materializations:y,targets:p,targetCount:p.length,activeAssociationCount:a.filter(w=>w.state==="active").length}}function w8(e){return e==="active"||e==="pending_activation"?"active":e==="externally_removed"||e==="host_detached"||e==="drifted"?e:"unreadable"}function h0(e,t){return t?e.filter(n=>n.state!=="externally_removed"&&n.state!=="host_detached"):e}function y0(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 BD(e,t){let n=t?await jr(e,t):void 0;return await E(e,"/api/v1/guardian/status",{method:"POST",headers:U(e.apiKey),body:JSON.stringify(W({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function v8(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 BD(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ne(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function ND(e,t){let n=v(e.agent)??"codex",r=Ni(e.scope);if(r.status==="invalid")return P(r.message,e.json);let i=We(t.env,t.platform,t.cwd).find(w=>w.id===n);if(!i)return S({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=_W(i,r.scope,t,v(e.hostVersion)??i.installEvidence.hostVersion??"unverified");if(!o)return P(`Guardian ${r.scope} hooks are not available for ${i.displayName}.`,e.json);let s=kv(t,r.scope),a=$0(df(t.cwd,o.hookPath)),l=$0(df(t.cwd,o.configPath)),c=await Sv(s),u=c.hooks.find(w=>f(w,"agent")===i.id&&f(w,"scope")===r.scope),d;try{d=await kW(o,t,u)}catch(w){if(!(w instanceof _f))throw w;let b=`Remove the changed ${i.displayName} hook config file ${o.configPath}, then run skills-layer guardian hook install --agent ${i.id} --scope ${r.scope}.`;return S({status:"blocked",reasonCode:"guardian_hook_ownership_unproven",agent:i.id,scope:r.scope,configPath:o.configPath,nextAction:"guardian.hook.install",nextStep:b},`Skills Layer cannot prove it owns the ${i.displayName} hook config file, so it will not overwrite it. ${b}`,e.json,"guardian_hook_ownership_unproven")}let p=[...c.hooks.filter(w=>f(w,"agent")!==i.id||f(w,"scope")!==r.scope),{hookId:st,hookName:et,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:Wt(o.agent).adapterRevision,evidencePath:SW(t,r.scope,o.agent,o.hostVersion),enabledAt:t.now()}];await _e(s,{version:1,hooks:p});let m=Ug(i.id,o.strictPreActionBlocking),g=m.supportStatus==="warning_only",h=i.id==="claude-code"||i.id==="cursor"?"block":"host_default",y=i.id==="claude-code"?" On Claude Code, a hook that fails or times out blocks the action.":"";return R({status:"enabled",hookId:st,hookName:et,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:o.hookPath,configPath:o.configPath,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,onFailure:h,...m,agentCommandMatrix:Py({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json",agent:i.id}),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:[g?`${i.displayName} hooks can only warn and record (${m.supportReasonCode}), so Guardian cannot block actions on this host and never counts it as enforced.`:"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."]},g?`Guardian hook enabled (warning only: ${i.displayName} cannot block actions).`:`Guardian hook enabled (${i.displayName}: ${m.supportLabel}).${y}`,e.json,t)}async function b8(e,t){let n=v(e.agent);if(!n)return P("guardian hook uninstall requires --agent <agent>.",e.json);let r=Ni(e.scope);if(r.status==="invalid")return P(r.message,e.json);let i=kv(t,r.scope),o=await Sv(i),s=o.hooks.find(y=>f(y,"agent")===n&&f(y,"scope")===r.scope);if(!s)return S({status:"not_installed",reasonCode:"guardian_hook_not_installed",agent:n,scope:r.scope,nextAction:"guardian.hook.status",nextStep:`Run \`skills-layer guardian hook status --scope ${r.scope}\` to see which hooks are installed.`},`No Skills Layer Guardian hook is installed for ${n} in ${r.scope} scope.`,e.json,"guardian_hook_not_installed");let a=[],l=[],c=async(y,w)=>{try{await w()!=="missing"&&a.push(y)}catch(b){l.push(`${y}: ${b instanceof Error?b.message:String(b)}`)}},u=f(s,"configPath"),d=f(s,"hookPath"),p=u?Rl(t,r.scope,u):null,m=[s.configEntryOwnership,s.activationConfigEntryOwnership,...Array.isArray(s.configEntryOwnerships)?s.configEntryOwnerships:[]].filter(O).flatMap(y=>{let w=Jt(n)&&typeof y.eventName=="string"?Ri(y,n,y.eventName):void 0;return w?[w]:[]});if(p&&Jt(n))for(let y of m)await c(`${p} (${y.eventName})`,()=>yx({configPath:p,agentId:n,ownership:y}));let g=hs(s.configFileOwnership);p&&g&&await c(p,()=>Zg({filePath:p,ownership:g}));let h=hs(s.hookFileOwnership);if(d&&h){let y=Rl(t,r.scope,d);await c(y,()=>Zg({filePath:y,ownership:h}))}return await _e(i,{version:1,hooks:o.hooks.filter(y=>y!==s)}),R({status:"removed",agent:n,scope:r.scope,removed:a,leftInPlace:l,nextAction:"guardian.hook.status",nextStep:l.length>0?"Some host entries changed after install, so Skills Layer left them in place. Remove them from the listed files yourself, then restart the agent.":"Restart the agent so it stops loading the Guardian hook.",...l.length>0?{warnings:["Skills Layer only removes hook entries and files whose contents still match what it installed."]}:{}},"Guardian hook removed.",e.json,t)}async function _8(e,t){let n=v(e.scope),r=n?Ni(n):null;if(r?.status==="invalid")return P(r.message,e.json);let i=await Vt(t,r?.status==="valid"?r.scope:void 0),o=lt(i.hooks),s=d=>`${f(d,"agentName")??f(d,"agent")} (${f(d,"scope")})`,a=d=>k8[String(d.hookState)]??f(d,"supportLabel"),l=o.map(d=>`${s(d)}: ${a(d)}`),c=l.length>0?`Guardian status loaded. ${l.join("; ")}.`:"Guardian status loaded.",u=o.map(d=>`${s(d)} ${S8[String(d.onFailure)]}`);return R(i,e.json||u.length===0?c:`${c} If a hook fails or times out: ${u.join("; ")}.`,e.json,t)}var k8={stale_missing_hook:"not running, its hook file is missing",active_missing_config:"not running, its config file is missing",active_missing_entries:"not running, its entries are missing from the config file"},S8={block:"blocks the action",continue:"lets the action go ahead (action_required)",host_default:"uses the host's default",unknown:"is unknown, because its hook entries were not found"};async function C8(e,t,n){let r=Ni(v(t.scope));if(r.status==="invalid")return P(r.message,t.json);let i=F(e[0]??t.skill,"guardian session bind requires a skill slug."),o=F(t.version,"guardian session bind requires --version."),s=v(t.agent);if(!s||!Jt(s))return P("guardian session bind requires an agent with an implemented Guardian pre-tool adapter.",t.json);let a=F(t.hostVersion,"guardian session bind requires --host-version."),l=wv(v(t.guardianPreference)??v(t.mode));if(!l)return P("guardian session bind --mode must be enforce, warning-only, or disabled.",t.json);let c={version:1,scope:r.scope,skillSlug:i,skillVersion:o,...v(t.workspaceId)?{workspaceId:v(t.workspaceId)}:{},agentId:s,hostVersion:a,requestedPreference:l,boundAt:n.now()},u=WD(n,r.scope);return await Ti(ye(u),{recursive:!0,mode:448}),await _e(u,c),await Ae(Nw(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 A8(e,t,n){let r=F(e[0]??t.skill,"guardian launch requires a skill slug."),i=Ni(v(t.scope));if(i.status==="invalid")return P(i.message,t.json);let o=v(t.agent);if(o!=="codex"&&o!=="kiro-cli")return S({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 P("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($e(s).toLowerCase()))return S({status:"blocked",reasonCode:"guardian_launcher_executable_mismatch",agent:o,executable:$e(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 Ur(n,r)).installs[r],c=sn(l,{scope:i.scope,agent:o}).filter(D=>D.lifecycle?.state==="active");if(c.length!==1||!c[0].lifecycle)return S({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 Mn(u.receipt);if(d.status!=="verified")return S({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 ws({backend:n,skillSlug:r,agentId:o,scope:i.scope,flags:t,enforceRequired:!0});if(p)return p;let m=await Vt(n,i.scope),g=(he(m,"hooks")??[]).filter(O).find(D=>f(D,"agent")===o&&f(D,"scope")===i.scope&&D.active===!0&&D.strictPreActionBlocking===!0&&D.exactActivationVerified===!0);if(!g)return S({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 h=v(t.hostVersion)??f(g,"hostVersion")??"unverified",y;try{y=await tT(s,n,Cn(n.platform))}catch(D){return P(ne(D),t.json)}let w=ke(32).toString("base64url"),b=n.now(),_={version:1,launchId:`guardian_launch_${ke(12).toString("hex")}`,tokenSha256:`sha256:${me("sha256").update(w,"utf8").digest("hex")}`,scope:i.scope,agentId:o,hostVersion:h,skillSlug:r,generationId:u.receipt.generation.generationId,receiptSha256:pr(u.receipt),status:"pending",createdAt:b,expiresAt:new Date(Date.parse(b)+15*6e4).toISOString()};await q8(n,i.scope,_);let I=await new Promise((D,T)=>{let j=G0(y,e.slice(2),{cwd:n.cwd,env:{...n.env,SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN:w,SKILLS_LAYER_GUARDIAN_LAUNCH_SCOPE:i.scope},stdio:"inherit"});j.once("error",T),j.once("exit",(M,$)=>D({exitCode:M??1,signal:$}))}).catch(async D=>{throw await k0(n,i.scope,_.launchId).catch(()=>{}),D}),C=(await HD(n,i.scope)).launches[_.launchId]?.status==="associated";return await k0(n,i.scope,_.launchId).catch(()=>{}),R({status:C?"managed_session_completed":"host_exited_before_association",launchId:_.launchId,skillSlug:r,agent:o,scope:i.scope,generationId:_.generationId,hostExitCode:I.exitCode,hostSignal:I.signal,associationObserved:C,nextAction:"guardian.status",nextStep:C?"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."},C?"Managed Guardian host session completed.":"The managed host exited without an observed Guardian session association.",t.json,n)}async function x8(e,t){let n=Ni(v(e.scope)),r=v(e.agent);if(n.status==="invalid"||!r||!Jt(r))return Te(r&&Jt(r)?r:"codex","deny","Guardian hook configuration is invalid.");let i=ue(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!i||i.length>512*1024)return Te(r,"deny","Guardian could not read the bounded host event.");let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return Te(r,"deny","Guardian could not parse the host event.")}return I8(r,o,await R8(r,n,o,e,t))}function I8(e,t,n){let r=O(t)&&typeof t.hook_event_name=="string"?t.hook_event_name:void 0;if(e!=="claude-code"||!r||r==="PreToolUse"||!n.stdout)return n;let i;try{i=JSON.parse(n.stdout)}catch{return n}let o=O(i)&&O(i.hookSpecificOutput)?i.hookSpecificOutput:null;return!o||o.permissionDecision!=="deny"&&o.permissionDecision!=="ask"||typeof o.permissionDecisionReason!="string"?n:Te(e,o.permissionDecision==="deny"?"deny":"warn",o.permissionDecisionReason,r)}async function R8(e,t,n,r,i){let o=Pu(e,n);if(o)return await w0({agentId:e,scope:t.scope,observation:o,rawPayload:n,flags:r,backend:i});let s=qD(e,n);if(!s)return Te(e,"deny","Guardian could not bind this event to the host session.");let a=ue(i.env.SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN);if(a){let m=await V8(i,t.scope,a,e,i.now());if(!m)return Te(e,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token.");let g=m.launch;if(m.disposition==="associated"){let h;try{h=await Oi(i,t.scope)}catch{return Te(e,"deny","Guardian session association evidence is unreadable.")}let y=_a(h,{agentId:e,sessionId:s,asOf:i.now()}),w=y.associations.length===1?y.associations[0]:void 0;return!w||Be(w)!==g.associationKey?Te(e,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token."):await Bw({agentId:e,scope:t.scope,lookup:y,rawPayload:n,backend:i})}return await w0({agentId:e,scope:t.scope,observation:{sessionId:s,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:n,flags:r,backend:i})}let l;try{l=await Oi(i,t.scope)}catch{return Te(e,"deny","Guardian session association evidence is unreadable.")}let c=_a(l,{agentId:e,sessionId:s,asOf:i.now()});if(c.status!=="unrelated")return await Bw({agentId:e,scope:t.scope,lookup:c,rawPayload:n,backend:i});let u=await se(WD(i,t.scope));if(!u||u.version!==1||u.agentId!==e)return await z8(i,t.scope,e)?Te(e,"deny",`Guardian requires \`skills-layer guardian launch <skill> --agent ${e} --scope ${t.scope} -- <host>\` because this host has no trustworthy native skill-activation signal.`):Te(e,"allow","No Skills Layer skill session is bound; unrelated host activity remains outside Guardian.");let d=await se(Nw(i,t.scope));if(!F8(d,u,s,i.now())){let m=If(i);try{let g=await E(i,"/api/v1/guardian/sessions",{method:"POST",headers:U(i.apiKey,i.authBlockedMessage),signal:m,body:JSON.stringify({skillSlug:u.skillSlug,version:u.skillVersion,...u.workspaceId?{workspaceId:u.workspaceId}:{},agentId:e,platform:i.platform,hostVersion:u.hostVersion,sessionId:s,requestedPreference:u.requestedPreference})}),h=L(g,"envelope"),y=JD(g,"publicKeys");if(!h||!y)throw new Error("Guardian session authority returned an invalid envelope.");d={version:1,envelope:h,publicKeys:y,savedAt:i.now()},await _e(Nw(i,t.scope),d)}catch(g){return Te(e,"deny",await mv(g,m.aborted,u,i,"Guardian could not obtain current signed skill-session authority."))}}await B8({binding:u,sessionId:s,cache:d,backend:i}).catch(()=>{});let p=await Eg({agentId:e,platform:i.platform==="darwin"||i.platform==="linux"||i.platform==="win32"?i.platform:"linux",hostVersion:u.hostVersion,rawPayload:n,attributionEnvelope:d.envelope,attributionPublicKeys:d.publicKeys,now:i.now(),evaluate:async(m,g)=>MD(m,u,i,g.effectiveMode)});return{exitCode:p.exitCode,stdout:p.stdout,stderr:p.stderr}}async function w0(e){let t;try{t=await N8(e.observation,e.agentId,e.backend)}catch(u){return await S0(e,"guardian_activation_unresolved"),Ci(e.agentId,e.observation,"deny",ne(u))}let n=pr(t.receipt);if(e.expectedReceiptSha256&&e.expectedReceiptSha256!==n||e.expectedGenerationId&&e.expectedGenerationId!==t.receipt.generation.generationId)return await S0(e,"guardian_managed_launch_mismatch"),Ci(e.agentId,e.observation,"deny","Guardian managed launch no longer matches the exact installed generation.");let r=t.requestedPreference??"warning_only",i=Wt(e.agentId),o=GD(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 hv(e.backend,e.scope,a)}catch{return Ci(e.agentId,e.observation,M8(a),"Guardian could not safely record this exact skill-session association.")}let c=If(e.backend);try{let u=await VD(l,e.backend,c),d=e.backend.now(),p=wa({envelope:u.cache.envelope,publicKeys:u.cache.publicKeys,expectedAgentId:e.agentId,expectedPlatform:Cn(e.backend.platform),now:d});if(p.skillSlug!==l.skillSlug||p.version!==l.skillVersion||p.generationId!==l.generationId||p.sessionId!==l.sessionId||p.workspaceId!==l.workspaceId)throw new Error("Guardian Cloud authority did not match the exact local association.");let m=await Vt(e.backend,e.scope),g=he(m,"hooks")?.filter(O).find(x=>f(x,"agent")===e.agentId&&x.active===!0),h=l.requestedPreference==="warning_only"?"warning":l.requestedPreference,y=p.workspaceRequiredMode===null?null:{requiredMode:p.workspaceRequiredMode,revision:u.policyRevision,updatedBy:"skills-layer-cloud",updatedAt:p.issuedAt},w=P8({enabled:e.qualificationCandidate===!0,managedLaunchId:e.managedLaunchId,agentId:e.agentId,exactHook:g,env:e.backend.env}),b=xa({evaluationContext:"activation_eligibility",requestedMode:h,workspacePolicy:y,hostSupported:fn(e.agentId)?.maximumTier==="strict_candidate",hookInstalled:!!g,strictHookVerified:w||g?.strictPreActionBlocking===!0,exactActivationVerified:w||g?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"pending_authority",materializationState:"active"});if(!b.activationAllowed)return await xi(e.backend,e.scope,Be(l),{state:"stale",reasonCode:b.reasonCode,updatedAt:s}),Ci(e.agentId,e.observation,"deny",`Guardian refused activation because verified enforcement is unavailable (${b.reasonCode}).`);let _=await xi(e.backend,e.scope,Be(l),{state:"active",trustLedgerId:u.trustLedgerId,attributionExpiresAt:p.expiresAt,updatedAt:d}),I=Be(_);return await yv(e.backend,e.scope,I,u.cache),!e.managedLaunchId&&bo(e.backend.env)==="missing_attribution"?(await xi(e.backend,e.scope,I,{state:"stale",reasonCode:"phase149_missing_attribution_canary",updatedAt:d}),await H8(e.backend,e.scope,I),Ci(e.agentId,e.observation,"allow","Guardian qualification removed signed attribution after exact activation.")):(e.managedLaunchId&&await G8(e.backend,e.scope,e.managedLaunchId,I),await nx(e.backend.env),e.managedLaunchId?await Bw({agentId:e.agentId,scope:e.scope,lookup:{status:"active",associations:[_]},rawPayload:e.rawPayload,backend:e.backend}):Ci(e.agentId,e.observation,"allow",b.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(u){return await xi(e.backend,e.scope,Be(l),{state:"pending_authority",reasonCode:"guardian_session_authority_unavailable",updatedAt:s}).catch(()=>{}),Ci(e.agentId,e.observation,"deny",await mv(u,c.aborted,l,e.backend,`Guardian could not establish exact skill-session authority (${ne(u)}).`))}}function P8(e){if(!e.enabled||!e.managedLaunchId?.startsWith("guardian_launch_phase149_")||fn(e.agentId)?.automaticAssociation!=="approved_launcher_required"||e.exactHook?.active!==!0||e.exactHook.configActive!==!0||e.exactHook.evidenceCapability!=="unverified")return!1;let t=he(e.exactHook,"evidenceReasons");return t?.length!==1||t[0]!=="live_canary_evidence_missing"?!1:bo(e.env)!==null}async function Bw(e){if(e.lookup.status==="ambiguous")return Te(e.agentId,"deny","Guardian found multiple active skill associations for this host session.");let t=e.lookup.associations[0];if(!t)return Te(e.agentId,"deny","Guardian expected an exact association but could not load it.");if(e.lookup.status==="terminal")return Te(e.agentId,"deny",t.state==="refused"?"Guardian blocked this session because a skill activation in it was refused.":"Guardian blocked a session whose exact skill was removed or detached.");if(e.lookup.status==="expected_missing_authority")return Te(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 U8(t,e.backend);if(n.status!=="verified")return await xi(e.backend,e.scope,Be(t),{state:n.state,reasonCode:n.reasonCode,updatedAt:e.backend.now()}).catch(()=>{}),Te(e.agentId,"deny","Guardian blocked this session because the exact installed generation is no longer current.");let r=await W8(e.backend,e.scope,Be(t));if(e.lookup.status==="active_authority_stale"||!J8(r,t,e.backend.now())){let a=If(e.backend);try{let l=await VD(t,e.backend,a);r=l.cache;let c=wa({envelope:r.envelope,publicKeys:r.publicKeys,expectedAgentId:e.agentId,expectedPlatform:Cn(e.backend.platform),now:e.backend.now()});await xi(e.backend,e.scope,Be(t),{state:"active",trustLedgerId:l.trustLedgerId,attributionExpiresAt:c.expiresAt,updatedAt:e.backend.now()}),await yv(e.backend,e.scope,Be(t),r)}catch(l){return Te(e.agentId,"deny",await mv(l,a.aborted,t,e.backend,"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 Eg({agentId:e.agentId,platform:Cn(e.backend.platform),hostVersion:t.hostVersion,rawPayload:e.rawPayload,attributionEnvelope:r.envelope,attributionPublicKeys:r.publicKeys,now:e.backend.now(),evaluate:async(a,l)=>{let c=await MD(a,i,e.backend,l.effectiveMode);return o=c.delegatedExecution===!0,c}});return o&&await rx({agentId:e.agentId,scope:e.scope,skillSlug:t.skillSlug,associationKey:Be(t),env:e.backend.env}),{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr,...o?{[FD]:!0}:{}}}async function MD(e,t,n,r){let i=r==="disabled";if(!i&&(e.action.actionFamily==="shell_execution"||e.action.actionFamily==="generated_code_execution")){let c=await Vt(n,t.scope),u=(he(c,"hooks")??[]).filter(O).find(g=>f(g,"agent")===t.agentId&&f(g,"scope")===t.scope&&g.active===!0&&g.configActive===!0&&typeof f(g,"absoluteCliPath")=="string"),d=u?f(u,"absoluteCliPath"):void 0,p=bo(n.env)?ox:void 0;if(d&&e.action.command&&sx({command:e.action.command,cliPath:d,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:Cn(n.platform),...p?{approvedEnvironmentKeys:p}:{}}))return{decision:"allow",reason:"Guardian delegated this exact shell action to the atomic guarded execution wrapper.",delegatedExecution:!0};let m=d?ax({cliPath:d,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:Cn(n.platform),...p?{approvedEnvironmentKeys:p}:{}}):null;return{decision:"deny",reason:m&&m.length<=800?`Use the exact guarded command prefix: ${m} <command>`:"Use the exact Skills Layer Guardian execution wrapper for one-action guarded shell or generated-code execution."}}let o=O8(e),s=o.length>0||!i?o:[L8(e)];if(s.length===0)return{decision:"deny",reason:"Guardian has no exact action mapping for this host event."};let a=s.some(c=>c.type==="file_read")?await $8(n,t.skillSlug):new Set,l=null;for(let c of s){if(c.type==="file_read"&&a.has(Gn(e.action.cwdRealPath,String(c.path))))continue;let u=If(n),d;try{d=await E(n,"/api/v1/guardian/enforce",{method:"POST",headers:U(n.apiKey,n.authBlockedMessage),signal:u,body:JSON.stringify({skillSlug:t.skillSlug,version:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},guardianPreference:t.requestedPreference,telemetryMode:(t.workspaceId,"cloud_managed"),action:c})})}catch(m){return{decision:"deny",reason:await jD(m,u.aborted,t,n)}}let p=L(d,"enforcement");if(p?.canExecute!==!0)return{decision:"deny",reason:`Guardian denied this exact action (${Pl(d)}).`};p.status==="warning_only"&&!l&&(l=Pl(d))}return l?{decision:"warn",reason:`Guardian would block this in enforce mode (${l}); warnings-only mode lets it run.`}:{decision:"allow",reason:"Guardian allowed the exact attributed host action."}}var v0=7500;function E8(e){let t=Number(e.SKILLS_LAYER_GUARDIAN_ENFORCE_TIMEOUT_MS);return Number.isSafeInteger(t)&&t>=50?Math.min(t,v0):v0}var b0=new WeakMap;function If(e){let t=b0.get(e);return t===void 0&&(t=Date.now()+E8(e.env),b0.set(e,t)),AbortSignal.timeout(Math.max(1,t-Date.now()))}async function mv(e,t,n,r,i){return t||e instanceof Tl||!j8(e)?await jD(e,t,n,r):i}var _0="Try again when Guardian Cloud is reachable; `skills-layer doctor --deep` checks the connection.",D8={enforce:"Enforce",warning_only:"Warnings-only",disabled:"Off"};async function jD(e,t,n,r){let i=T8(e,t);if(!t&&UD(e))return i;let o=await jr(r,n.skillSlug),s=(o===void 0?null:wv(o))??n.requestedPreference;return s==="disabled"?`${i} Off mode still checks revocation, the Trust Ledger and drift with Guardian Cloud, so an outage blocks it too.`:`${i} ${D8[s]} mode does not let a Guardian Cloud outage through.`}function UD(e){return e instanceof V&&e.status<500}function T8(e,t){if(t)return`Guardian Cloud did not answer in time, so this action was blocked. ${_0}`;if(e instanceof Tl)return`Guardian sent no request to Guardian Cloud, so this action was blocked. ${e.message}`;let n=UD(e)?"Try again.":_0,r=e instanceof V&&e.details?f(e.details,"reasonCode"):void 0;return r?`Guardian Cloud could not decide (${r.slice(0,96)}), so this action was blocked. ${n}`:`Guardian Cloud could not be reached, so this action was blocked. ${n}`}async function $8(e,t){let n=new Set;for(let r of Et((await Pe(e)).installs[t]))if(r.lifecycle?.state==="active")for(let i of r.lifecycle.receipt.files)n.add(Gn(r.lifecycle.receipt.targetDir,i.path));return n}function L8(e){let t={strictActionSha256:e.actionSha256,toolInputSha256:e.action.toolInputSha256,adapterRevision:e.adapterRevision,host:e.action.host};return e.action.actionFamily==="shell_execution"&&e.action.command?{type:"shell_command",command:e.action.command,metadata:t}:{type:"api_call",target:e.action.toolName,metadata:t}}function O8(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 Te(e,t,n,r){let i=ur(e,{decision:t,reason:n,...r?{eventName:r}:{}});return{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}}function qD(e,t){if(!O(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 F8(e,t,n,r){if(!e||e.version!==1||!O(e.envelope)||!O(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 B8(e){let t=(await Pe(e.backend)).installs[e.binding.skillSlug],n=sn(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 Mn(r.receipt)).status!=="verified")return;let o=wa({envelope:e.cache.envelope,publicKeys:e.cache.publicKeys,expectedAgentId:e.binding.agentId,expectedPlatform:Cn(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 hv(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:pr(r.receipt),...e.binding.workspaceId?{workspaceId:e.binding.workspaceId}:{},requestedPreference:e.binding.requestedPreference,activationSource:"manual_recovery",activationEvidence:`legacy-bind:${e.binding.boundAt}`,adapterRevision:Wt(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 yv(e.backend,e.binding.scope,Be(s),e.cache)}async function N8(e,t,n){let r=await Pe(n),i=Object.entries(r.installs).flatMap(([u,d])=>Et(d).flatMap(p=>{let m=p.lifecycle;if(!m||m.state!=="active")return[];if(!Dt(p.record).includes(t))return[];if(e.referenceKind==="slug"){if(e.skillReference!==u&&e.skillReference!==m.receipt.generation.skillSlug)return[]}else{let g=Gn(m.receipt.targetDir),h=Gn(e.skillReference),y=df(g,h);if(y.startsWith("..")||je.isAbsolute(y)||ct.isAbsolute(y))return[]}return[{skillSlug:u,record:xn(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 Mn(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 jr(n,o.skillSlug),c=l===void 0?a?"enforce":null:wv(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 VD(e,t,n){let r=await E(t,"/api/v1/guardian/sessions",{method:"POST",headers:U(t.apiKey,t.authBlockedMessage),signal:n,body:JSON.stringify({skillSlug:e.skillSlug,version:e.skillVersion,...e.workspaceId?{workspaceId:e.workspaceId}:{},agentId:e.agentId,platform:Cn(t.platform),hostVersion:e.hostVersion,sessionId:e.sessionId,requestedPreference:e.requestedPreference})}),i=L(r,"envelope"),o=JD(r,"publicKeys"),s=L(r,"ledger"),a=s?f(s,"ledgerId"):void 0;if(!i||!o||!a)throw new Error("Guardian session authority returned an invalid exact-generation envelope.");return{cache:{version:1,envelope:i,publicKeys:o,savedAt:t.now()},trustLedgerId:a,policyRevision:i.version===2?i.claims.policyRevision:1}}function M8(e){return e.requestedPreference==="warning_only"&&!e.workspaceId?"allow":"deny"}function j8(e){return e instanceof V?e.status<500:!ne(e).startsWith("Unable to reach ")}function Ci(e,t,n,r){return t.source==="claude_user_prompt_expansion"?n==="deny"?{exitCode:2,stdout:"",stderr:r}:{exitCode:0,stdout:"",stderr:""}:Te(e,n,r)}function GD(e,t,n){let r=v(n.hostVersion);if(r)return r;if(!O(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 Cn(e){return e==="darwin"||e==="win32"?e:"linux"}async function U8(e,t){let n=(await Pe(t)).installs[e.skillSlug],r=sn(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||pr(i.receipt)!==e.receiptSha256)return{status:"invalid",state:"stale",reasonCode:"exact_generation_replaced"};try{await Ml(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 Mn(i.receipt);return o.status==="verified"?{status:"verified"}:{status:"invalid",state:"stale",reasonCode:o.reasonCode}}function zD(e,t){return t==="global"?z(e.paths.stateDir,"guardian-session-associations.json"):z(e.cwd,".skills-layer","guardian-session-associations.json")}function KD(e,t){return t==="global"?z(e.paths.stateDir,"guardian-managed-launches.json"):z(e.cwd,".skills-layer","guardian-managed-launches.json")}async function HD(e,t){let n=await se(KD(e,t));if(!O(n)||n.version!==1||!Number.isSafeInteger(n.revision)||Number(n.revision)<0||!O(n.launches))return{version:1,revision:0,launches:{}};let r=Object.fromEntries(Object.entries(n.launches).flatMap(([i,o])=>{if(!O(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 ql(e,t,n){let r=KD(e,t);await Ui(ye(r));let i=`${r}.lock`,o=null;for(let s=0;s<50&&!o;s+=1)try{o=await $i(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 HD(e,t),a=n(s);return await vs(r,a.store),a.value}finally{await o.close().catch(()=>{}),await Ae(i,{force:!0}).catch(()=>{})}}async function q8(e,t,n){await ql(e,t,r=>({store:{version:1,revision:r.revision+1,launches:{...r.launches,[n.launchId]:n}},value:void 0}))}async function k0(e,t,n){await ql(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 V8(e,t,n,r,i){if(n.length<32||n.length>256||!/^[A-Za-z0-9_-]+$/u.test(n))return null;let o=`sha256:${me("sha256").update(n,"utf8").digest("hex")}`;return await ql(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 G8(e,t,n,r){await ql(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 z8(e,t,n){if(fn(n)?.automaticAssociation!=="approved_launcher_required")return!1;let r=await Pe(e);for(let[i,o]of Object.entries(r.installs)){let s=sn(o,{scope:t,agent:n});for(let a of s){if(a.lifecycle?.state!=="active"&&a.lifecycle?.state!=="pending_activation")continue;let l=xn(o,a);if(f(l,"workspaceId")??f(l,"workingModeWorkspaceId"))return!0;let u=await jr(e,i);if(u==="enforce"||u==="enabled")return!0}}return!1}function Rf(e,t){return t==="global"?z(e.paths.stateDir,"guardian-session-authorities.json"):z(e.cwd,".skills-layer","guardian-session-authorities.json")}async function Oi(e,t){let n=await se(zD(e,t));return n===null?FA():BA(n)}async function gv(e,t,n){let r=zD(e,t);await Ui(ye(r));let i=`${r}.lock`,o=null;try{o=await $i(i,"wx",384);let s=await Oi(e,t),a=n(s);return await vs(r,a.index),a.value}finally{await o?.close().catch(()=>{}),await Ae(i,{force:!0}).catch(()=>{})}}async function S0(e,t){try{await hv(e.backend,e.scope,UA({scope:e.scope,agentId:e.agentId,hostVersion:GD(e.agentId,e.rawPayload,e.flags)??"unverified",observation:e.observation,adapterRevision:Wt(e.agentId).adapterRevision,reasonCode:t,now:e.backend.now()}))}catch{}}async function hv(e,t,n){return await gv(e,t,r=>{let i=NA(r,n,r.revision),o=i.associations[Be(n)];return{index:i,value:o}})}async function xi(e,t,n,r){return await gv(e,t,i=>{let o=MA(i,{key:n,expectedIndexRevision:i.revision,...r});return{index:o,value:o.associations[n]}})}async function K8(e,t){let n=0;for(let r of["project","global"]){let i=await gv(e,r,o=>{let s=jA(o,{...t,expectedIndexRevision:o.revision});return{index:s.index,value:s.removedKeys}});if(n+=i.length,i.length>0){let o=Rf(e,r),s=await Pf(e,r),a=new Set(i);await vs(o,{version:1,revision:s.revision+1,authorities:Object.fromEntries(Object.entries(s.authorities).filter(([l])=>!a.has(l)))})}await ql(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 Pf(e,t){let n=await se(Rf(e,t));return!O(n)||n.version!==1||!Number.isSafeInteger(n.revision)||!O(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 O(i)&&i.version===1&&O(i.envelope)&&O(i.publicKeys)&&typeof i.savedAt=="string"}))}}async function yv(e,t,n,r){let i=Rf(e,t),o=await Pf(e,t);await vs(i,{version:1,revision:o.revision+1,authorities:{...o.authorities,[n]:r}})}async function H8(e,t,n){let r=Rf(e,t),i=await Pf(e,t),o={...i.authorities};delete o[n],await vs(r,{version:1,revision:i.revision+1,authorities:o})}async function W8(e,t,n){return(await Pf(e,t)).authorities[n]??null}function J8(e,t,n){if(!e||e.version!==1||!O(e.envelope)||!O(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 vs(e,t){let n=ye(e);await Ui(n);let r=z(n,`.${$e(e)}.${ke(12).toString("hex")}.tmp`),i=null;try{i=await $i(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
|
|
1056
|
+
`,"utf8"),await i.sync(),await i.close(),i=null,await Li(r,e),await qi(e,384),await Tv(n)}finally{await i?.close().catch(()=>{}),await Ae(r,{force:!0}).catch(()=>{})}}function WD(e,t){return t==="global"?z(e.paths.stateDir,"guardian-session-binding.json"):z(e.cwd,".skills-layer","guardian-session-binding.json")}function Nw(e,t){return t==="global"?z(e.paths.stateDir,"guardian-session.json"):z(e.cwd,".skills-layer","guardian-session.json")}function wv(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 JD(e,t){let n=e[t];if(!O(n))return null;let r=Object.entries(n);return r.every(([,i])=>typeof i=="string")?Object.fromEntries(r):null}async function Vt(e,t){let n=t?[t]:["project","global"],r=[],i=new Set;for(let h of n){let y=kv(e,h);if(i.has(y))continue;i.add(y);let w=await Sv(y);for(let b of w.hooks){let _=f(b,"hookPath"),I=_?Rl(e,h,_):null,x=f(b,"configPath"),C=x?Rl(e,h,x):null,D=I?await Ke(I):!1,T=C?await Ke(C):null,j=T===!0?await Z8(b,C):null,M=f(b,"absoluteCliPath"),$=M?await S4(M)?"current":"stale":"unknown",B=D?T===!1?"active_missing_config":j===!1?"active_missing_entries":$==="stale"?"stale_cli_path":"active":"stale_missing_hook",q=await X8({backend:e,scope:h,hook:b,absoluteHookPath:I,absoluteConfigPath:C,hookActive:D,configActive:T}),Y=j===!1?"unknown":await Y8(b,C,T),Le=hs(b.configFileOwnership)!==void 0;r.push({hookId:f(b,"hookId")??st,hookName:f(b,"hookName")??et,...b,scope:f(b,"scope")??h,hookPath:I??_??null,configPath:C??x??null,active:D&&T!==!1&&j!==!1,configActive:T,entriesActive:j,hookState:B,cliPathState:$,onFailure:Y,strictPreActionBlocking:q.capability==="strict",exactActivationVerified:q.exactActivationVerified,activationRoute:q.activationRoute,evidenceCapability:q.capability,evidenceReasons:q.reasons,...Ug(String(b.agent),q.capability==="strict"),nextStep:j===!1&&Le?`Remove the changed ${f(b,"agentName")??String(b.agent)} hook config file ${C}, then run skills-layer guardian hook install --agent ${String(b.agent)} --scope ${h}.`:!D||T===!1||j===!1||$==="stale"?`Run skills-layer guardian hook install --agent ${String(b.agent)} --scope ${h}.`:Y==="continue"?mw(String(b.agent),h):q.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:q.evidencePath,qualifiedHostExecutablePath:q.qualifiedHostExecutablePath,qualifiedHostExecutableSha256:q.qualifiedHostExecutableSha256})}}let o=r.filter(h=>h.active===!0).length,s=r.filter(h=>h.active===!1).length,a=r.filter(h=>h.hookState==="active_missing_config"),l=r.filter(h=>h.hookState==="active_missing_entries"),c=o>0?a.length+l.length:s,u=r.filter(h=>h.cliPathState==="stale").length,d=r.find(h=>h.cliPathState==="stale"),p=r.find(h=>h.active===!0&&h.onFailure==="continue"),m=a[0],g=l[0];return{status:d||m||g||p?"action_required":"ok",...d?{reasonCode:"guardian_hook_cli_path_stale",nextAction:"guardian.hook.install",nextStep:typeof d.nextStep=="string"?d.nextStep:"Run skills-layer guardian hook install --agent <agent> again to repoint the hook at the current CLI."}:m?{reasonCode:"guardian_hook_config_missing",nextAction:"guardian.hook.install",nextStep:m.nextStep}:g?{reasonCode:"guardian_hook_entries_missing",nextAction:"guardian.hook.install",nextStep:g.nextStep}:p?{reasonCode:"guardian_hook_fails_open",nextAction:"guardian.hook.install",nextStep:mw(String(p.agent),String(p.scope))}:{},enforcementLayer:r.some(h=>h.active===!0&&h.strictPreActionBlocking===!0)?"native_hook":o>0?"native_hook_candidate":"not_installed",strictPreActionBlocking:r.some(h=>h.active===!0&&h.strictPreActionBlocking===!0),exactActivationVerified:r.some(h=>h.active===!0&&h.strictPreActionBlocking===!0&&h.exactActivationVerified===!0),activeHookCount:o,missingHookCount:c,missingConfigCount:a.length,missingEntriesCount:l.length,staleHookCount:s,staleCliPathCount:u,hooks:r,setup:await _v(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."]:[],...u>0?["A Guardian hook points at a Skills Layer CLI path that no longer exists (for example after a Node or CLI upgrade), so it blocks every tool call. Run skills-layer guardian hook install --agent <agent> again to repoint it."]:[],...a.map(h=>`The ${String(h.agentName??h.agent)} Guardian hook config file is missing, so the host does not run the Guardian hook. ${String(h.nextStep)}`),...l.map(h=>`The ${String(h.agentName??h.agent)} Guardian hook entries are missing from its config file, so the host does not run the Guardian hook. ${String(h.nextStep)}`),...p?[`The ${String(p.agentName??p.agent)} Guardian hook was installed by an older CLI and lets the action go ahead if the hook fails or times out. ${mw(String(p.agent),String(p.scope))}`]:[]]}}function mw(e,t){return`Run skills-layer guardian hook install --agent ${e} --scope ${t} again so a Guardian hook that fails or times out blocks the action.`}async function Y8(e,t,n){if(n===!1)return"unknown";let r=String(e.agent),i=Wg({agentId:r,configJson:"{}",ownerships:[]});if(i!=="unknown"||!t||n!==!0)return i;let o=[Ri(e.configEntryOwnership,"claude-code"),Ri(e.activationConfigEntryOwnership,"claude-code","UserPromptExpansion")].filter(a=>a!==void 0),s=await on(t,"utf8").catch(()=>"");return Wg({agentId:r,configJson:s,ownerships:o})}async function Z8(e,t){let n=hs(e.configFileOwnership),r=await on(t).catch(()=>null);if(r===null)return null;if(n)return`sha256:${me("sha256").update(r).digest("hex")}`===n.fileSha256;let o=[e.configEntryOwnership,e.activationConfigEntryOwnership,...Array.isArray(e.configEntryOwnerships)?e.configEntryOwnerships:[]].flatMap(s=>O(s)&&typeof s.agentId=="string"&&typeof s.eventName=="string"?[Ri(s,s.agentId,s.eventName)].filter(a=>a!==void 0):[]);return vx({configJson:r.toString("utf8"),ownerships:o})}async function X8(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?Rl(e.backend,e.scope,o):null;if(!t||!Jt(t))return{capability:"unverified",reasons:["strict_adapter_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(fn(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 se(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 XA({agentId:t,platform:Cn(e.backend.platform),hostVersion:n,adapterRevision:r,hookConfigPath:e.absoluteConfigPath,hookScriptPath:e.absoluteHookPath,absoluteCliPath:i}),c=ZA({evidence:a,currentBinding:l,asOf:e.backend.now()}),u=fn(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 Q8(e,t){let n=t?await QD(t,e):null,r=n&&n.status!=="degraded"?n.record:null,i=r?f(r,"agent")??Dt(r)[0]:void 0;return!r||!i?vv(e,"global"):`skills-layer guardian hook install --agent ${i} --scope ${f(r,"scope")==="global"?"global":"project"}`}var eW={"guardian exec":new Set(["action-json","grant-json"]),"guardian check":new Set(["allow-unmanaged-once","grant-json"])};function tW(e,t){let n=vP(e,t);return n&&eW[e.path]?.has(n)?null:n}async function vv(e,t){let n=c_(ue(e.env.SKILLS_LAYER_AGENT)).agent,r=n?[]:await Vr({env:e.env,platform:e.platform,cwd:e.cwd,pathExists:Ke}),i=n??(r.length===1?r[0].id:void 0);return`skills-layer guardian hook install${i?` --agent ${i}`:""} --scope ${t}`}function C0(e){return{...S({status:"cancelled",reasonCode:"setup_cancelled",nextStep:"Run `skills-layer setup` when ready."},"Setup cancelled.",e,"setup_cancelled"),exitCode:130}}async function YD(e,t){let n=await vv(t,"project"),r=`Setup needs an interactive terminal. Run \`skills-layer setup\`, or use \`skills-layer mcp setup\` and \`${n}\`.`,i={status:"blocked",reasonCode:"setup_needs_terminal",nextStep:r};if(e.json){let p=await se(t.paths.mcpConfigPath),m=p&&Array.isArray(p.clientIds)?p.clientIds.filter(h=>typeof h=="string"):p&&f(p,"clientId")?[f(p,"clientId")]:[],g=await fT(t,m);return S({...i,setup:await _v(t),mcp:{status:p?"mcp_configured":"mcp_not_configured",configured:!!p,clientId:m[0],clientIds:m,hosts:g,mcpUrl:p?f(p,"mcpUrl"):void 0,readiness:p?{status:"configured_needs_agent_reload",verifyCommand:m.length===1?`skills-layer mcp verify --client ${m[0]}`:"skills-layer mcp verify",nextStep:"Open a fresh agent session if Skills Layer tools are not visible yet."}:void 0,nextCommand:p?"skills-layer mcp verify":"skills-layer mcp setup"},guardian:await Vt(t)},r,!0,"setup_needs_terminal")}if(!t.stdoutIsTty)return S({...i,mcp:{nextCommand:"skills-layer mcp setup"},security:{nextCommand:n}},r,!1,"setup_needs_terminal");let o=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(o==="not_now"){let p={version:1,setupChoice:"not_now",mcpChoice:"not_now",mcpPromptedAt:t.now(),guardianHookChoice:"not_now",guardianHookPromptedAt:t.now(),remindAfter:iW(t.now(),7)};return await R0(t,p),R({status:"setup_skipped",mcp:{status:"not_configured",nextCommand:"skills-layer mcp setup"},security:{status:"not_configured",nextCommand:n}},"Skills Layer setup skipped for now. Run `skills-layer setup` when you want MCP and Security hooks on this machine.",!1,t)}if(o!=="both"&&o!=="mcp"&&o!=="security")return P(`Unknown setup option "${o}".`,e.json);let s=o==="both"||o==="mcp",a=o==="both"||o==="security",l={status:"setup_complete",setupChoice:o},c={version:1,setupChoice:o,mcpChoice:s?"configured":"not_requested",mcpPromptedAt:t.now(),guardianHookChoice:a?v(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(s)if(!t.apiKey)l.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},c.mcpChoice="login_required";else{let p=await Xw(e,t);if(Z(p))return p;l.mcp=p}if(a){let p={...e,json:!0,scope:v(e.scope)??"project",agent:v(e.agent)??"codex"},m=await ND(p,t);if(m.exitCode!==0)return m;let g=BW(m.stdout),h=O(g)?g:{status:"enabled",agent:v(p.agent),scope:v(p.scope)};l.security=h,l.agent=f(h,"agent")??v(p.agent),l.scope=f(h,"scope")??v(p.scope),l.enforcementLayer=f(h,"enforcementLayer")??"native_hook_candidate",l.strictPreActionBlocking=h.strictPreActionBlocking===!0,l.hookPath=f(h,"hookPath"),l.configPath=f(h,"configPath"),l.nextAction="guardian.hook.status",l.nextStep=`Run \`skills-layer guardian hook status --scope ${f(h,"scope")??"project"}\` to inspect the candidate binding. Strict pre-action blocking remains unverified until real host allow/deny canaries pass.`}await R0(t,c);let d=(O(l.mcp)?f(l.mcp,"status"):void 0)==="login_required"?"Skills Layer Security setup complete. MCP setup needs login; run `skills-layer login`, then `skills-layer setup`.":o==="security"?"Skills Layer Security Guardian setup complete.":o==="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(l,d,e.json,t)}async function nW(e,t){let n=await Vt(t),r=await _v(t),i=K(n,"activeHookCount")??0;if(t.stdoutIsTty&&i===0&&!r)return await YD(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:`${Ai(t.renderMode)}
|
|
1057
|
+
|
|
1058
|
+
${o}`,stderr:""}}function rW(e,t,n){let r=K(e,"activeHookCount")??0,i=K(e,"missingHookCount")??0,o=f(t,"status")??"unknown",s=f(t,"effectiveMode"),a=f(t,"adminPolicy"),l=f(t,"nextAction"),c=f(t,"nextStep"),u=e.strictPreActionBlocking===!0;return(K(e,"staleCliPathCount")??0)>0?{id:"guardian-local-hook",title:"Guardian local hook",status:"action_required",reasonCode:"guardian_hook_cli_path_stale",summary:"A Guardian hook points at a Skills Layer CLI path that no longer exists, so it blocks every tool call.",enforcementLayer:f(e,"enforcementLayer")??"native_hook_candidate",strictPreActionBlocking:u,measuredProtection:"stale_cli_path",policyStatus:o,adminPolicy:a,effectiveMode:s,nextAction:"guardian.hook.install",nextStep:e.nextStep,recommendedCommand:"skills-layer guardian hook status"}:e.reasonCode==="guardian_hook_entries_missing"?{id:"guardian-local-hook",title:"Guardian local hook",status:"action_required",reasonCode:"guardian_hook_entries_missing",summary:"A Guardian hook's entries are missing from its host config file, so that host does not run the Guardian hook.",enforcementLayer:f(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:u,measuredProtection:"entries_missing",policyStatus:o,adminPolicy:a,effectiveMode:s,nextAction:"guardian.hook.install",nextStep:e.nextStep,recommendedCommand:"skills-layer guardian hook status"}:e.reasonCode==="guardian_hook_config_missing"?{id:"guardian-local-hook",title:"Guardian local hook",status:"action_required",reasonCode:"guardian_hook_config_missing",summary:"A Guardian hook's host config file is missing, so that host does not run the Guardian hook.",enforcementLayer:f(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:u,measuredProtection:"config_missing",policyStatus:o,adminPolicy:a,effectiveMode:s,nextAction:"guardian.hook.install",nextStep:e.nextStep,recommendedCommand:"skills-layer guardian hook status"}:r>0&&i===0&&u?{id:"guardian-local-hook",title:"Guardian local hook",status:"pass",summary:`Guardian native hook active count: ${r}.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:u,measuredProtection:"verified_strict",policyStatus:o,adminPolicy:a,effectiveMode:s,policyNextAction:l,policyNextStep:c,recommendedCommand:"skills-layer guardian hook status"}:r>0&&i===0?{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian candidate hook active count: ${r}; live strict evidence is not current.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook_candidate",strictPreActionBlocking:!1,measuredProtection:"candidate_unverified",policyStatus:o,adminPolicy:a,effectiveMode:s,policyNextAction:l,policyNextStep:c,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: ${r}; missing hooks: ${i}.`,enforcementLayer:f(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:u,measuredProtection:"unavailable",policyStatus:o,adminPolicy:a,effectiveMode:s,policyNextAction:l,policyNextStep:c,recommendedCommand:n,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 iW(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function ZD(e){let t=eT(v(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:P(t.message,e.flags.json)};let n=await XD({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.reasonCode==="unsigned_lockfile_ignored")return Tr({...e,context:n,reasonCode:n.reasonCode,message:"Guardian ignored an unsigned lockfile entry.",why:"A repository lockfile cannot establish installation or execution authority without a matching managed receipt.",nextStep:"Install the exact skill through Skills Layer to create a verified local installation receipt."});if(n.reasonCode==="local_install_target_selection_required")return Tr({...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 Tr({...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 Tr({...e,context:n,reasonCode:"unmanaged_skill_blocked",message:"Guardian blocked unmanaged local skill execution.",why:"The skill path is not backed by a managed install receipt 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?_t(n.record):null;if(r&&r.state!=="active"){let a=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 Tr({...e,context:n,reasonCode:a,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 TW(n.installedPath))return Tr({...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=r?$e(r.receipt.targetDir):e.skillSlug,o=await aW(i,n.installedPath);if(n.identityAssessment=o,o.reattestationRequired===!0)return Tr({...e,context:n,reasonCode:f(o,"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 s=await lW(e.skillSlug,n.installedPath,e.backend,n.record);return n.driftAssessment=s,s.reattestationRequired===!0?Tr({...e,context:n,reasonCode:f(s,"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 Tr(e){return await ds(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:S({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:Il(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)}}function A0(e){return e?f(e,"workspaceId")??f(e,"workingModeWorkspaceId"):void 0}async function XD(e){let t=eT(v(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),r=v(e.flags.path),i=r?tt(e.backend.cwd,r):void 0,o=await QD(e.skillSlug,e.backend,{scope:v(e.flags.scope),agent:v(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:v(e.flags.version)??o?.version,record:o?.record,unmanaged:!!(r&&!o),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function QD(e,t,n={}){let i=(await Ur(t,e)).installs[e];if(i){let o=sn(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=xn(i,o[0]),a=sW(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 oW(t)){let s=await se(o);if(!(!O(s)||!O(s.installs)||!O(s.installs[e])))return{source:"lockfile",status:"degraded",reasonCode:"unsigned_lockfile_ignored",record:{}}}return null}function oW(e){return Array.from(new Set([z(e.cwd,"skills-layer-lock.json"),z(e.paths.stateDir,"skills-layer-lock.json")]))}function sW(e,t){let n=f(e,"materializedSkillRoot");if(n)return{installedPath:nf(tt(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let r=f(e,"canonicalPath");if(r)return{installedPath:nf(tt(t.cwd,r)),installedPathSource:"canonicalPath",status:"ok"};let i=f(e,"path");if(i)return{installedPath:nf(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=$e(c).toLowerCase()==="bundle.zip"||c.toLowerCase().endsWith(".zip");return{installedPath:u?ye(ye(c)):nf(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(O):[]).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?ye(tt(t.cwd,l)):void 0,installedPathSource:l?"materializedWrites":void 0,status:l?"ok":void 0}}function nf(e){return $e(e).toLowerCase()==="skill.md"?ye(e):e}async function aW(e,t){let n=z(t,"SKILL.md");if(!await Ke(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let r=kD(await on(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:ne(r),reattestationRequired:!0}}}async function lW(e,t,n,r){let i=r?_t(r):null;if(i){let p=await Mn(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=z(t,".skills-layer-runtime.json"),s=await se(o),a=s?L(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=z(t,"SKILL.md");if(!await Ke(c))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,reattestationRequired:!0};let u=cT(await on(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 Il(e){return W({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 eT(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 Mw(e,t){let n=v(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 x0(e,t){return{type:"shell_command",command:$e(t?.executableRealPath??e[0]??"command"),...t?{metadata:{executableRealPath:t.executableRealPath,executableSha256:t.executableSha256,argvSha256:nT(t.argv),cwdRealPath:t.cwdRealPath,fileTargets:t.fileTargets,networkTargets:t.networkTargets,environmentKeys:t.environmentKeys,callerActionJsonIgnored:!0,callerGrantJsonIgnored:!0}}:{}}}function cW(e){let t=L(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:Uw(e)!=="blocked"}async function uW(e){let t=dW(e.backend.platform);if(!t)return vl(e,"guardian_platform_unsupported","Guardian guarded execution is unavailable on this platform.");if(t==="win32")return vl(e,"windows_process_tree_isolation_unavailable","Guardian strict execution on Windows requires a verified Job Object process-tree adapter.");if(e.commandArgs.some(wW))return vl(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([tT(e.commandArgs[0],e.backend,t),Sl(e.backend.cwd)]),i=await Bi(n);if(!i.isFile()||i.size<=0||i.size>256*1024*1024)return vl(e,"guardian_executable_invalid","Guardian requires a bounded regular executable file.");let o=`sha256:${me("sha256").update(await on(n)).digest("hex")}`,s=hW(e.flags,e.backend.env),a=await pW(e.commandArgs.slice(1),r,e.backend,t),l=v(e.flags.agent)??(e.localContext.record?f(e.localContext.record,"agent")??f(e.localContext.record,"targetAgent"):void 0)??ue(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:yW(t,Object.keys(s)),skillSlug:e.skillSlug,version:e.version,...v(e.flags.workspaceId)?{workspaceId:v(e.flags.workspaceId)}:{},agentId:l,hostVersion:In,sessionId:`guardian_session_${ke(16).toString("hex")}`}}}catch(n){let r=n instanceof ce?n.reasonCode:"guardian_plan_resolution_failed";return vl(e,r,`Guardian could not resolve the exact execution plan: ${ne(n)}`)}}function vl(e,t,n){return{status:"blocked",result:S({status:"blocked",reasonCode:t,skillSlug:e.skillSlug},n,e.flags.json,t)}}function dW(e){return e==="darwin"||e==="linux"||e==="win32"?e:null}async function tT(e,t,n){if(!e||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Executable name is invalid.");let r=n==="win32"?je:ct,o=r.isAbsolute(e)||e.includes("/")||e.includes("\\")?[r.isAbsolute(e)?e:r.resolve(t.cwd,e)]:fW(e,t,n);for(let s of o.slice(0,128))try{await K0(s,n==="win32"?SE.F_OK:SE.X_OK);let a=await Sl(s);if((await Bi(a)).isFile())return a}catch{}throw new Error(`Executable ${$e(e)} was not found as an accessible regular file.`)}function fW(e,t,n){let r=n==="win32"?je:ct,o=(ue(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"&&!je.extname(e)?(ue(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 pW(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(!mW(c,r))continue;let u=await gW(c,t,n,r);i.add(u);let d=await Bi(u).catch(()=>null);if(d?.isFile()){let p=s.get(u);p?p.argumentIndexes.push(a):s.set(u,{path:u,sha256:`sha256:${me("sha256").update(await on(u)).digest("hex")}`,size:d.size,argumentIndexes:[a]})}}return{fileTargets:[...i].sort(cf),networkTargets:[...o].sort(cf),immutableInputs:[...s.values()].sort((a,l)=>cf(a.path,l.path))}}function mW(e,t){return!e||e.startsWith("-")?!1:(t==="win32"?je:ct).isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.includes("/")||e.includes("\\")}async function gW(e,t,n,r){let i=r==="win32"?je:ct,o=r==="win32"?ue(n.env.USERPROFILE)??ue(n.env.HOME):ue(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 Sl(a)}catch{let l=await Sl(i.dirname(a));return i.join(l,i.basename(a))}}function hW(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 yW(e,t){let n=e==="win32"?["PATH","SystemRoot","TEMP","TMP","USERPROFILE"]:["HOME","PATH","TMPDIR"];return[...new Set([...n,...t])].sort(cf)}function wW(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 nT(e){return`sha256:${me("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function cf(e,t){return e<t?-1:e>t?1:0}function vW(e,t,n){let r=[t.headline,...n.length>0?["",...n]:[],"","Command",` executable: ${e.executable}`,` args count: ${e.argsCount}`,` exit code: ${e.exitCode}`,...e.signal?[` signal: ${e.signal}`]:[]];return t.nextStep&&r.push("","Next",` ${t.nextStep}`),e.stdout&&r.push("","Stdout",e.stdout),e.stderr&&r.push("","Stderr",e.stderr),r.join(`
|
|
1059
|
+
`)}function Ni(e){let t=v(e)??"project";return t==="project"||t==="global"?{status:"valid",scope:t}:{status:"invalid",message:"guardian hooks --scope must be one of: project, global."}}function rT(e){return z(e.paths.stateDir,"guardian-modes.json")}function iT(e){return z(e.paths.stateDir,"setup-state.json")}async function bv(e){let t=await se(rT(e));return{version:1,skills:O(t?.skills)?t.skills:{}}}async function I0(e,t,n){let r=await bv(e);await _e(rT(e),{version:1,skills:{...r.skills,[t]:{requestedPreference:f(n,"requestedPreference")??"warning_only",effectiveMode:f(n,"effectiveMode")??"warning_only",reasonCode:f(n,"reasonCode"),auditId:f(n,"auditId"),updatedAt:e.now()}}})}async function jr(e,t){let r=(await bv(e)).skills[t];return r?f(r,"requestedPreference"):void 0}async function bW(e,t){return(await bv(e)).skills[t]}async function _v(e){let t=await se(iT(e));return O(t)?{version:1,setupChoice:f(t,"setupChoice"),mcpChoice:f(t,"mcpChoice"),mcpPromptedAt:f(t,"mcpPromptedAt"),guardianHookChoice:f(t,"guardianHookChoice"),guardianHookPromptedAt:f(t,"guardianHookPromptedAt"),remindAfter:f(t,"remindAfter")}:null}async function R0(e,t){await _e(iT(e),t)}function _W(e,t,n,r){let i=t==="global"?e.targets.globalRoot:e.targets.projectRoot;if(!i)return null;if(e.id==="codex")return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(i,"hooks.json"),hookPath:z(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="claude-code")return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(i,"settings.json"),hookPath:z(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="cline")return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(i,"guardian-hooks.json"),hookPath:z(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="gemini-cli"){let o=t==="project"?z(n.cwd,".gemini"):i;return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(o,"settings.json"),hookPath:z(o,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}if(e.id==="cursor")return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(i,"hooks.json"),hookPath:z(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="github-copilot"){let o=t==="project"?z(n.cwd,".github","hooks"):z(i,"hooks");return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(o,"skills-layer-guardian.json"),hookPath:z(o,"skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}if(e.id==="opencode")return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(i,"skills-layer-guardian.json"),hookPath:z(i,"plugins","skills-layer-guardian.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="windsurf")return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(i,"hooks.json"),hookPath:z(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="antigravity"||e.id==="antigravity-cli"){let o=t==="project"?z(n.cwd,".agents"):z(ye(i),"config");return{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(o,"hooks.json"),hookPath:z(o,"hooks",`skills-layer-guardian-${e.id}.mjs`),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}return e.id==="kiro-cli"?{agent:e.id,agentName:e.displayName,scope:t,hookId:st,hookName:et,configPath:z(i,"hooks","skills-layer-guardian.json"),hookPath:z(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}:null}var _f=class extends Error{};async function rf(e){try{return await e}catch(t){throw/could not be proven|ownership digest does not match/u.test(ne(t))?new _f(ne(t)):t}}async function kW(e,t,n){await Ti(ye(e.hookPath),{recursive:!0,mode:448}),await Ti(ye(e.configPath),{recursive:!0,mode:448});let r=await Ke(e.configPath)?n:void 0,i=hs(n?.hookFileOwnership),o=await EW(t),s=await Yg({operation:i?"update":"install",filePath:e.hookPath,content:e.agent==="opencode"?RW(e,o,process.execPath):PW(e.agent,e.scope,o,e.hostVersion),...i?{previousOwnership:i}:{}});if(e.agent==="windsurf"){let c=e.agent,u=["pre_read_code","pre_write_code","pre_run_command","pre_mcp_tool_use"],d=Array.isArray(r?.configEntryOwnerships)?r.configEntryOwnerships.flatMap(m=>{for(let g of u){let h=Ri(m,c,g);if(h)return[h]}return[]}):[],p=[];for(let m of u){let g=d.find(y=>y.eventName===m),h=await rf(Nu({configPath:e.configPath,update:{operation:g?"restore":"install",agentId:c,eventName:m,absoluteScriptPath:e.hookPath,...g?{previousOwnership:g}:{}}}));p.push(h.ownership)}return{hookFileOwnership:s.ownership,configEntryOwnerships:p,absoluteCliPath:o}}if(e.agent==="codex"||e.agent==="claude-code"||e.agent==="gemini-cli"||e.agent==="cursor"||e.agent==="antigravity"||e.agent==="antigravity-cli"){let c=e.agent==="gemini-cli"?"BeforeTool":e.agent==="cursor"?"preToolUse":"PreToolUse",u=Ri(r?.configEntryOwnership,e.agent,c),d=bx({agentId:e.agent,scope:e.scope,platform:t.platform,hookPath:e.hookPath}),p=await rf(Nu({configPath:e.configPath,update:{operation:u?"restore":"install",agentId:e.agent,eventName:c,absoluteScriptPath:e.hookPath,...d?{portableCommand:d}:{},...u?{previousOwnership:u}:{}}})),m;if(e.agent==="claude-code"){let g=Ri(r?.activationConfigEntryOwnership,e.agent,"UserPromptExpansion");m=(await rf(Nu({configPath:e.configPath,update:{operation:g?"restore":"install",agentId:e.agent,eventName:"UserPromptExpansion",absoluteScriptPath:e.hookPath,...d?{portableCommand:d}:{},...g?{previousOwnership:g}:{}}}))).ownership}return{hookFileOwnership:s.ownership,configEntryOwnership:p.ownership,...m?{activationConfigEntryOwnership:m}:{},absoluteCliPath:o}}let a=hs(r?.configFileOwnership),l=await rf(Yg({operation:a?"update":"install",filePath:e.configPath,content:`${JSON.stringify(e.agent==="kiro-cli"?AW(e):e.agent==="github-copilot"?xW(e,process.execPath):e.agent==="opencode"?IW(e):CW(e,t),null,2)}
|
|
1060
|
+
`,...a?{previousOwnership:a}:{}}));return{hookFileOwnership:s.ownership,configFileOwnership:l.ownership,absoluteCliPath:o}}function kv(e,t){return t==="global"?z(e.paths.stateDir,"guardian-hooks.json"):z(e.cwd,".skills-layer","guardian-hooks.json")}function SW(e,t,n,r){let i=t==="global"?e.paths.stateDir:z(e.cwd,".skills-layer");return z(i,"guardian-hook-evidence",`${n}-${r}-${Cn(e.platform)}.json`)}async function Sv(e){let t=await se(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter(O):[]}}function Rl(e,t,n){return je.isAbsolute(n)||n.startsWith("/")?n:Gn(t==="global"?e.paths.stateDir:e.cwd,n)}function CW(e,t){return{version:1,hookId:st,hookName:et,agent:e.agent,agentName:e.agentName,scope:e.scope,enforcementLayer:e.enforcementLayer,strictPreActionBlocking:e.strictPreActionBlocking,installedAt:t.now(),hooks:[{name:et,id:st,event:"PreToolUse",command:`node ${sT(e.hookPath)}`,status:"candidate"}]}}function AW(e){return{version:"v1",hooks:[{name:et,description:"Skills Layer Guardian pre-tool authorization",trigger:"PreToolUse",matcher:".*",action:{type:"command",command:`node ${sT(e.hookPath)}`},timeout:0,enabled:!0}]}}function xW(e,t){return{version:1,hooks:{PreToolUse:[{type:"command",matcher:"*",exec:t,args:[e.hookPath],timeoutSec:10}]}}}function IW(e){return{version:1,agent:"opencode",scope:e.scope,hostVersion:e.hostVersion,hookEvent:"tool.execute.before",hookPath:e.hookPath,enabled:!0}}function RW(e,t,n){return`import { spawnSync } from "node:child_process";
|
|
1061
|
+
import { readFileSync } from "node:fs";
|
|
1062
|
+
|
|
1063
|
+
const configPath = ${JSON.stringify(e.configPath)};
|
|
1064
|
+
const expected = Object.freeze({
|
|
1065
|
+
version: 1,
|
|
1066
|
+
agent: "opencode",
|
|
1067
|
+
scope: ${JSON.stringify(e.scope)},
|
|
1068
|
+
hostVersion: ${JSON.stringify(e.hostVersion)},
|
|
1069
|
+
hookEvent: "tool.execute.before",
|
|
1070
|
+
hookPath: ${JSON.stringify(e.hookPath)},
|
|
1071
|
+
enabled: true
|
|
1072
|
+
});
|
|
1073
|
+
|
|
1074
|
+
function verifyConfig() {
|
|
1075
|
+
const observed = JSON.parse(readFileSync(configPath, "utf8"));
|
|
1076
|
+
if (JSON.stringify(observed) !== JSON.stringify(expected)) {
|
|
1077
|
+
throw new Error("Guardian OpenCode plugin configuration changed; refusing tool execution.");
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
export const SkillsLayerGuardian = async ({ directory }) => ({
|
|
1082
|
+
"tool.execute.before": async (input, output) => {
|
|
1083
|
+
verifyConfig();
|
|
1084
|
+
const payload = {
|
|
1085
|
+
hook_event_name: "tool.execute.before",
|
|
1086
|
+
session_id: input.sessionID,
|
|
1087
|
+
call_id: input.callID,
|
|
1088
|
+
cwd: directory,
|
|
1089
|
+
tool_name: input.tool,
|
|
1090
|
+
tool_input: output.args,
|
|
1091
|
+
host_version: ${JSON.stringify(e.hostVersion)}
|
|
1092
|
+
};
|
|
1093
|
+
const result = spawnSync(${JSON.stringify(n)}, [
|
|
1094
|
+
${JSON.stringify(t)},
|
|
1095
|
+
"guardian",
|
|
1096
|
+
"hook",
|
|
1097
|
+
"run",
|
|
1098
|
+
"--agent",
|
|
1099
|
+
"opencode",
|
|
1100
|
+
"--scope",
|
|
1101
|
+
${JSON.stringify(e.scope)},
|
|
1102
|
+
"--host-version",
|
|
1103
|
+
${JSON.stringify(e.hostVersion)}
|
|
1104
|
+
], {
|
|
1105
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1106
|
+
// FNP-G1: a stalled CLI is stopped and the tool call is blocked.
|
|
1107
|
+
timeout: ${oT},
|
|
1108
|
+
killSignal: "SIGKILL",
|
|
1109
|
+
env: {
|
|
1110
|
+
...process.env,
|
|
1111
|
+
SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64: Buffer.from(JSON.stringify(payload), "utf8").toString("base64url")
|
|
1112
|
+
}
|
|
1113
|
+
});
|
|
1114
|
+
if (result.error && result.error.code === "ETIMEDOUT") throw new Error(${JSON.stringify(jw)});
|
|
1115
|
+
if (result.error || result.status !== 0) {
|
|
1116
|
+
const detail = String(result.stderr || "").trim();
|
|
1117
|
+
throw new Error(detail || "Guardian blocked this OpenCode tool call.");
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
});
|
|
1121
|
+
`}var oT=8e3,jw="Skills Layer Guardian did not decide in time, so this action was blocked.";function PW(e,t,n,r="unverified"){let i=ur(e,{decision:"deny",reason:"Skills Layer Guardian could not run, so this action was blocked."}),o={stdout:i.stdout,exitCode:i.exitCode===0&&i.stdout===""?2:i.exitCode},s=ur(e,{decision:"deny",reason:jw});return`#!/usr/bin/env node
|
|
1122
|
+
import { spawnSync } from "node:child_process";
|
|
1123
|
+
import { readFileSync } from "node:fs";
|
|
1124
|
+
|
|
1125
|
+
let raw = "";
|
|
1126
|
+
try {
|
|
1127
|
+
raw = readFileSync(0, "utf8");
|
|
1128
|
+
} catch {
|
|
1129
|
+
raw = "";
|
|
1130
|
+
}
|
|
1131
|
+
${e==="windsurf"?`try {
|
|
1132
|
+
const payload = JSON.parse(raw);
|
|
1133
|
+
payload.cwd = payload.cwd || process.cwd();
|
|
1134
|
+
raw = JSON.stringify(payload);
|
|
1135
|
+
} catch {
|
|
1136
|
+
raw = "";
|
|
1137
|
+
}`:""}
|
|
1138
|
+
|
|
1139
|
+
// FNP-G1: stop the CLI below the host's 10 s hook timeout. The override may only shorten it.
|
|
1140
|
+
const DEFAULT_CHILD_TIMEOUT_MS = ${oT};
|
|
1141
|
+
const requestedChildTimeoutMs = Number(process.env.SKILLS_LAYER_GUARDIAN_HOOK_CHILD_TIMEOUT_MS);
|
|
1142
|
+
const childTimeoutMs = Number.isSafeInteger(requestedChildTimeoutMs) && requestedChildTimeoutMs >= 50
|
|
1143
|
+
? Math.min(requestedChildTimeoutMs, DEFAULT_CHILD_TIMEOUT_MS)
|
|
1144
|
+
: DEFAULT_CHILD_TIMEOUT_MS;
|
|
1145
|
+
|
|
1146
|
+
const result = spawnSync(process.execPath, [
|
|
1147
|
+
${JSON.stringify(n)},
|
|
1148
|
+
"guardian",
|
|
1149
|
+
"hook",
|
|
1150
|
+
"run",
|
|
1151
|
+
"--agent",
|
|
1152
|
+
${JSON.stringify(e)},
|
|
1153
|
+
"--scope",
|
|
1154
|
+
${JSON.stringify(t)},
|
|
1155
|
+
"--host-version",
|
|
1156
|
+
${JSON.stringify(r)},
|
|
1157
|
+
"--json"
|
|
1158
|
+
], {
|
|
1159
|
+
stdio: ["ignore", "pipe", "inherit"],
|
|
1160
|
+
encoding: "utf8",
|
|
1161
|
+
timeout: childTimeoutMs,
|
|
1162
|
+
killSignal: "SIGKILL",
|
|
1163
|
+
env: {
|
|
1164
|
+
...process.env,
|
|
1165
|
+
SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64: Buffer.from(raw, "utf8").toString("base64url")
|
|
1166
|
+
}
|
|
1167
|
+
});
|
|
1168
|
+
|
|
1169
|
+
// GD-R2-02: the deny names the incoming event (for example UserPromptExpansion).
|
|
1170
|
+
function failClosedOutput(fallback = ${JSON.stringify(o.stdout)}) {
|
|
1171
|
+
try {
|
|
1172
|
+
const decision = JSON.parse(fallback);
|
|
1173
|
+
const event = JSON.parse(raw).hook_event_name;
|
|
1174
|
+
// Round 4: Claude Code honours permissionDecision only on PreToolUse; UserPromptExpansion blocks with a top-level decision.
|
|
1175
|
+
if (event === "UserPromptExpansion" && decision.hookSpecificOutput) return JSON.stringify({ decision: "block", reason: decision.hookSpecificOutput.permissionDecisionReason });
|
|
1176
|
+
if (decision.hookSpecificOutput && typeof event === "string" && /^[A-Za-z]{1,64}$/.test(event)) decision.hookSpecificOutput.hookEventName = event;
|
|
1177
|
+
return JSON.stringify(decision);
|
|
1178
|
+
} catch {
|
|
1179
|
+
return fallback;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
function failClosedExit() {
|
|
1183
|
+
process.stderr.write("Skills Layer Guardian hook could not run, so this action was blocked. Run skills-layer doctor to repair the hook.\\n");
|
|
1184
|
+
process.stdout.write(failClosedOutput());
|
|
1185
|
+
process.exit(${o.exitCode});
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
function timedOutExit() {
|
|
1189
|
+
process.stderr.write(${JSON.stringify(`${jw}
|
|
1190
|
+
`)});
|
|
1191
|
+
process.stdout.write(${o.stdout===""?'""':`failClosedOutput(${JSON.stringify(s.stdout)})`});
|
|
1192
|
+
process.exit(${o.exitCode});
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
// FNP-G1: the CLI ran past the limit (for example a Guardian Cloud stall).
|
|
1196
|
+
if (result.error && result.error.code === "ETIMEDOUT") timedOutExit();
|
|
1197
|
+
// G2: a crash, signal, missing CLI or unexpected exit is the host's own deny.
|
|
1198
|
+
if (result.error || result.signal || (result.status !== 0 && result.status !== 2)) failClosedExit();
|
|
1199
|
+
// GD-R2-02: only valid hook JSON (an object) or nothing reaches the host; any other
|
|
1200
|
+
// output would be read as "carry on", so it is a deny.
|
|
1201
|
+
const output = typeof result.stdout === "string" ? result.stdout : "";
|
|
1202
|
+
if (output.trim() !== "") {
|
|
1203
|
+
let parsed;
|
|
1204
|
+
try { parsed = JSON.parse(output); } catch { failClosedExit(); }
|
|
1205
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) failClosedExit();
|
|
1206
|
+
process.stdout.write(output);
|
|
1207
|
+
}
|
|
1208
|
+
process.exit(result.status);
|
|
1209
|
+
`}function P0(e,t){return!t||f(t,"status")!=="quarantined"?{sentence:"",payload:{}}:{sentence:` ${e} was moved to quarantine on this device, so your agents can no longer load it.`,payload:{nextAction:"restore",nextStep:`Review the incident first. If you trust ${e} again, run \`skills-layer restore ${e}\` to bring the quarantined install back.`}}}async function EW(e){let t=ue(e.env.SKILLS_LAYER_CLI_PATH),n=Gn(t??process.argv[1]??""),r=await Ml(n);if(!r.isFile()&&!r.isSymbolicLink())throw new Error("Guardian hook CLI path must resolve to the installed Skills Layer executable.");return await Sl(n)}function hs(e){if(!(!O(e)||e.owner!=="skills-layer"||typeof e.fileSha256!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.fileSha256)))return{owner:"skills-layer",fileSha256:e.fileSha256}}function Ri(e,t,n="PreToolUse"){if(!(!O(e)||e.owner!=="skills-layer"||e.agentId!==t||e.eventName!==n||typeof e.entrySha256!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.entrySha256)))return{owner:"skills-layer",agentId:t,eventName:n,entrySha256:e.entrySha256}}function sT(e){return JSON.stringify(e)}async function DW(e){let t=e.generationId??e.version??"unversioned",n=z(e.backend.paths.stateDir,"runtime",encodeURIComponent(e.skillSlug),`${encodeURIComponent(t)}.json`),r={version:1,generatedAt:e.backend.now(),skillSlug:e.skillSlug,sourceProvider:{id:"skills-layer",name:"Skills Layer",managedBy:"skills-layer-cli"},...e.version?{skillVersion:e.version}:{},...e.generationId?{generationId:e.generationId}:{},guardian:{required:!0,enforcementLayer:"cloud_guardian_with_local_preflight",strictPreActionBlocking:!1,checkCommand:`skills-layer guardian check --skill ${e.skillSlug} --json`,incidentCommand:`skills-layer guardian incident ${e.skillSlug} --path <installed-skill-path> --telemetry-mode local_only --json`,guardedExecutorCommand:`skills-layer guardian exec ${e.skillSlug} --json -- <command>`,mcpCheckTool:"guardian.check",mcpEnforceTool:"guardian.enforce",agentCommandMatrix:Py({purpose:"materialize_skill",command:`skills-layer install ${e.skillSlug}`,jsonCommand:`skills-layer install ${e.skillSlug} --json`,skillSlug:e.skillSlug}),agentGuidance:"MCP-capable agents should call guardian.check or guardian.enforce before risky tool use. Local host hooks should call skills-layer guardian check, and shell actions that need strict wrapping should use skills-layer guardian exec.",sensitiveActionFamilies:["shell_command","network_request","file_read","file_write","secret_read","browser_action","device_action","api_call","generated_code_execution","model_context_promotion"]},materialization:{skillDocumentPath:"SKILL.md",skillDocumentSha256:cT(e.skillDocumentContent)}},i=`${JSON.stringify(r,null,2)}
|
|
1210
|
+
`;return await _e(n,r),{path:CD(e.backend.cwd,n),bytes:new TextEncoder().encode(i).length}}async function TW(e){return await Ke(z(e,".skills-layer-disabled.json"))}async function E0(e){let t=e.backend.now(),r=(await Pe(e.backend)).installs[e.skillSlug],i=sn(r,{installedPath:e.installedPath,platform:e.backend.platform}),o=i.length===1?i[0]:void 0,s=o&&r?xn(r,o):void 0,a=o?.lifecycle??null;if(!s||!a||!o)return{status:"blocked",reasonCode:"guardian_exact_install_receipt_missing",skillSlug:e.skillSlug,generatedAt:t,nextAction:"install",nextStep:"Install the approved skill through Skills Layer before using managed Guardian quarantine."};if(a.state!=="active"&&a.state!=="pending_activation")return{status:"blocked",reasonCode:"guardian_local_lifecycle_not_active",skillSlug:e.skillSlug,generatedAt:t,localLifecycle:a,nextAction:"guardian.incident.review",nextStep:"Review the existing quarantine or incomplete lifecycle before recording another incident."};if(!Cv(e.installedPath,a.receipt.targetDir,e.backend.platform)||e.version!==a.receipt.generation.semanticVersion)return{status:"blocked",reasonCode:"guardian_incident_generation_mismatch",skillSlug:e.skillSlug,generatedAt:t,requestedVersion:e.version,receiptGeneration:a.receipt.generation,nextAction:"guardian.incident.review",nextStep:"Use the indexed exact path and version; Guardian will not quarantine a caller-selected mismatch."};let l;try{l=await pv({backend:e.backend,skillSlug:e.skillSlug,record:s,materializationId:o.materializationId,lifecycle:a,reasonCode:"guardian_incident",purpose:"quarantine_blocked",status:"quarantined"})}catch(g){return{status:"blocked",reasonCode:"guardian_exact_quarantine_failed",skillSlug:e.skillSlug,generatedAt:t,error:ne(g),nextAction:"guardian.incident.review",nextStep:"Keep the skill blocked. Resolve exact-tree drift or filesystem permissions before retrying quarantine."}}let c=t.replace(/[:.]/gu,"-"),u=z(e.backend.paths.incidentsDir,`${e.skillSlug}-${c}.md`),d=z(e.backend.paths.incidentsDir,`${e.skillSlug}-${c}-evidence.json`),p=f(e.action,"type")??"unknown";await _e(d,{version:1,generatedAt:t,skillSlug:e.skillSlug,skillVersion:e.version,actionType:p,reason:qw(e.reason),localLifecycle:l.lifecycle});let m=["# Skills Layer Guardian Incident Report","",`Generated: ${t}`,`Skill: ${e.skillSlug}`,`Version: ${e.version}`,"","## Summary","",qw(e.reason),"","## Evidence","",`- ${t}: ${p} -> blocked and physically quarantined`].join(`
|
|
1211
|
+
`);return await Ui(ye(u)),await Jw(u,`${m}
|
|
1212
|
+
`,{encoding:"utf8",mode:384}),await qi(u,384),{status:"quarantined",generatedAt:t,incidentPath:u,evidencePath:d,quarantineDir:l.quarantine.quarantineDir,localLifecycle:l.lifecycle,writtenFiles:[u,d]}}function Cv(e,t,n){let r=n==="win32"?je:ct,i=r.resolve(e).normalize("NFC"),o=r.resolve(t).normalize("NFC");return n==="linux"?i===o:i.toLocaleLowerCase("en-US")===o.toLocaleLowerCase("en-US")}function D0(e,t){let n=e.now().replace(/[:.]/gu,"-");return z(e.paths.incidentsDir,`${t}-${n}.json`)}async function ds(e,t){let n=z(e.paths.stateDir,"guardian-audit.jsonl");await Ui(ye(n));let r=await $W(n),i=t.authority?L(t.authority,"exactGeneration"):void 0,o=t.authority?L(t.authority,"guardianMode"):void 0,s=W({version:2,generatedAt:e.now(),skillSlug:t.skillSlug,...t.version?{skillVersion:t.version}:{},actionType:f(t.action,"type")??"unknown",actionDigest:`sha256:${me("sha256").update(kf(t.action)).digest("hex")}`,actionTarget:OW(t.action),decisionStatus:t.decisionStatus,reasonCode:t.reasonCode,telemetryMode:t.telemetryMode,telemetryDelivery:t.authority?f(t.authority,"telemetryDelivery")??t.telemetryMode:t.telemetryMode,...i?{generationId:f(i,"generationId"),archiveSha256:f(i,"archiveSha256"),servingRevision:i.servingRevision}:{},...o?{effectiveMode:f(o,"effectiveMode")}:{},...r?{previousEntryHash:r}:{},...t.path?{localPath:lT(t.path)}:{}}),a=`sha256:${me("sha256").update(kf(s)).digest("hex")}`,l=`${JSON.stringify({...s,entryHash:a})}
|
|
1213
|
+
`;await LW(n,Buffer.byteLength(l)),await wK(n,l,{encoding:"utf8",mode:384}),await qi(n,384)}var aT=1048576,T0=3;async function $W(e){let t=await Bi(e).catch(()=>null);if(!t?.isFile()||t.size===0||t.size>aT)return;let r=(await on(e,"utf8")).trimEnd().split(`
|
|
1214
|
+
`).at(-1);if(r)try{let i=JSON.parse(r),o=f(i,"entryHash");return o&&/^sha256:[a-f0-9]{64}$/u.test(o)?o:void 0}catch{return}}async function LW(e,t){let n=await Bi(e).catch(()=>null);if(!(!n?.isFile()||n.size+t<=aT)){await Ae(`${e}.${T0}`,{force:!0});for(let r=T0-1;r>=1;r-=1)await Li(`${e}.${r}`,`${e}.${r+1}`).catch(i=>{if(i.code!=="ENOENT")throw i});await Li(e,`${e}.1`)}}function kf(e){if(Array.isArray(e))return`[${e.map(kf).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${kf(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}function Uw(e){let t=L(e,"decision"),n=L(e,"enforcement"),r=f(t??{},"status")??f(n??{},"status")??f(e,"status");return r==="allowed"||r==="advisory"?r:"blocked"}function Pl(e){let t=L(e,"decision");return f(t??{},"reasonCode")??f(e,"reasonCode")??f(e,"status")??"cloud_guardian_decision"}function OW(e){let t=f(e,"type");if(t==="secret_read")return"redacted_secret";if(t==="shell_command")return"redacted_command";let n=f(e,"url");if(n)try{return new URL(n).origin}catch{return"redacted_url"}let r=f(e,"target");if(r)return qw(r);let i=f(e,"path");return i?lT(i):null}function lT(e){let t=$e(e.trim());return t?`<local-path>/${t}`:"<local-path>"}function qw(e){return e.replace(/sk-[A-Za-z0-9_-]+/gu,"[redacted-secret]").replace(/[A-Z0-9_]*SECRET[A-Z0-9_]*/gu,"[redacted-secret]").replace(/[A-Z0-9_]*TOKEN[A-Z0-9_]*/gu,"[redacted-token]").replace(/[A-Z0-9_]*KEY[A-Z0-9_]*/gu,"[redacted-key]")}function $0(e){return e.split(/[\\/]+/u).join("/")}function cT(e){return me("sha256").update(e).digest("hex")}async function Av(e,t,n,r,i){let o=Mi(),s=v(n.mfaCode),a=v(n.recoveryCode),l=()=>E(r,"/api/v1/verify",{method:"POST",headers:U(),body:JSON.stringify({email:e,code:t,handoffCodeHash:o.authorizationCodeHash,handoffCodeChallenge:o.codeChallenge,...s?{mfaCode:s}:{},...a?{recoveryCode:a}:{}})}),c;try{c=await l()}catch(d){if(!(d instanceof V)||d.details?.reasonCode!=="login_mfa_required"||n.json||r.nonInteractive||!r.stdoutIsTty)throw d;let p=await r.promptSelect("Complete MFA to finish email login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),m=(await r.promptSecret(p==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();p==="recovery_code"?a=m:s=m,c=await l()}if(f(c,"status")!=="verified")return P("Email verification did not prepare a secure credential handoff. Restart verification.",n.json);let u=await E(r,"/api/v1/identity/credential-handoff/exchange",{method:"POST",headers:U(),body:await Pv(o,r)});if(f(u,"status")!=="exchanged"||!f(u,"email")||!f(u,"role")||!f(u,"apiKey"))return P("Email verification credential handoff failed closed. Restart verification.",n.json);if(n.json){let d=f(u,"apiKey");if(d){let p=await El(r,d,{expectedEmail:e,knownEmail:f(u,"email")??e,knownRole:f(u,"role")??"user",knownRoles:rn(u,"roles"),knownUserId:f(u,"userId"),knownSessionCredentialId:f(u,"id")}),m=await ff(n,{...r,config:p,apiKey:d});return Z(m)?m:R(dt({...u,loggedIn:!0,...m.data?{workspaceSelection:m.data}:{}}),["Email verified and login completed.",m.message??""].filter(Boolean).join(" "),!0,r)}return R(dt({...u,email:e,loggedIn:!1,nextCommand:`skills-layer login --method email --email ${e}`,nextAction:"login"}),"Email verified. Login still needs to be completed.",!0,r)}return await xv(e,u,n,r,i)}async function xv(e,t,n,r,i){let o=f(t,"apiKey"),s=f(t,"role")??"user",a=rn(t,"roles"),l=f(t,"userId"),c=o;if(!c&&n.json)return R(dt({...t,email:e,role:s,...a?{roles:a}:{},loggedIn:!1}),`${i} Login still needs to be completed through a human handoff.`,!0,r);if(!c)try{c=(await r.promptSecret(`Enter the API key emailed to ${e} (check spam/junk folder if missing): `)).trim()}catch{return R(dt({...t,email:e,role:s,...a?{roles:a}:{},loggedIn:!1}),`${i} Check your email (including spam/junk folder) for the API key, then run \`skills-layer login\` to finish signing in.`,n.json,r)}if(!c)return P("No API key was entered. Run `skills-layer login` once you have the emailed key.",n.json);let u=await El(r,c,{expectedEmail:e,knownEmail:e,knownRole:s,knownRoles:a,knownUserId:l,knownSessionCredentialId:f(t,"id"),forceProfileValidation:!o}),d=await ff(n,{...r,config:u,apiKey:c});if(Z(d))return d;let p=await Aw(n,{...r,config:u,apiKey:c});if(Z(p))return p;let m=p.data?.status==="mcp_not_configured";return R(dt(xw({...t,status:m?"partial_success":f(t,"status")??"verified",email:u.email,role:u.role,...u.roles?{roles:u.roles}:{},loggedIn:!0,...d.data?{workingMode:d.data}:{},...p.data?{mcp:p.data}:{},...m?{warnings:[p.data]}:{}},p.data)),[`${i} Logged in as ${u.email}.`,Yi(u),d.message??"",p.message??""].filter(Boolean).join(" "),n.json,r)}function Mi(){let e=`social_handoff_${ke(32).toString("base64url")}`,t=ke(48).toString("base64url");return{authorizationCode:e,codeVerifier:t,authorizationCodeHash:me("sha256").update(e).digest("base64url"),codeChallenge:me("sha256").update(t).digest("base64url")}}async function Iv(e){if(!e.backend.nonInteractive)return null;if(!e.backend.credentialStore)return Pi(e.flags,e.backend);let t=`social_${ke(18).toString("base64url")}`,n=`skills-layer-social-continuation:${t}`,r={version:1,reference:t,baseUrl:e.backend.baseUrl,provider:e.provider,mode:e.mode,authorizationCode:e.credentialHandoff.authorizationCode,codeVerifier:e.credentialHandoff.codeVerifier,authorizationCodeHash:e.credentialHandoff.authorizationCodeHash,codeChallenge:e.credentialHandoff.codeChallenge,createdAt:e.backend.now()},i={...r,integrityDigest:Rv(r)};try{let o=JSON.stringify(i);if(await e.backend.credentialStore.set(ge,n,o),await e.backend.credentialStore.get(ge,n)!==o)return await e.backend.credentialStore.delete(ge,n),Pi(e.flags,e.backend)}catch{return await e.backend.credentialStore.delete(ge,n).catch(()=>{}),Pi(e.flags,e.backend)}return{reference:t,account:n,secret:i}}function Pi(e,t){return S({status:"security_unavailable",reasonCode:"social_secure_continuation_unavailable",unchanged:!0,nextAction:"login.interactive",nextStep:"Run the same command in an interactive human terminal with OS-secure credential storage available."},"Secure social continuation is unavailable. No browser login was started.",e.json,"social_secure_continuation_unavailable")}async function FW(e,t,n){if(!n.credentialStore)return!1;let r=f(t,"state"),i=f(t,"expiresAt");if(!r||!i)return await n.credentialStore.delete(ge,e.account).catch(()=>{}),!1;let o={version:e.secret.version,reference:e.secret.reference,baseUrl:e.secret.baseUrl,provider:e.secret.provider,mode:e.secret.mode,authorizationCode:e.secret.authorizationCode,codeVerifier:e.secret.codeVerifier,authorizationCodeHash:e.secret.authorizationCodeHash,codeChallenge:e.secret.codeChallenge,createdAt:e.secret.createdAt,state:r,expiresAt:i},s={...o,integrityDigest:Rv(o)};try{let a=JSON.stringify(s);return await n.credentialStore.set(ge,e.account,a),await n.credentialStore.get(ge,e.account)===a}catch{return await n.credentialStore.delete(ge,e.account).catch(()=>{}),!1}}function Rv(e){return me("sha256").update(JSON.stringify([e.version,e.reference,e.baseUrl,e.provider,e.mode,e.authorizationCode,e.codeVerifier,e.authorizationCodeHash,e.codeChallenge,e.createdAt,e.state??null,e.expiresAt??null])).digest("base64url")}async function Ef(e,t,n,r,i,o,s="/api/v1/identity/social/status",a=null){let l=f(t,"authorizationUrl"),c=F(f(t,"state"),"Social auth did not return a state."),u=ET(e);if(i.nonInteractive)return!a||!await FW(a,t,i)?Pi(r,i):R({status:"human_action_required",reasonCode:"social_auth_browser_handoff",provider:e,mode:o,authorizationUrl:l,reference:a.reference,expiresAt:f(t,"expiresAt"),nextAction:"identity.continue",nextStep:`Complete the browser sign-in, then run \`skills-layer identity continue --reference ${a.reference}\`.`},`${u} browser sign-in is ready. Complete it, then continue with the returned non-secret reference.`,r.json,i);if(l){let p=r.noOpen?!1:await i.openUrl(l);r.json&&!p&&i.emitNotice(`Open this URL in your browser to finish ${u} ${o==="recovery"?"recovery":"sign-in"}:
|
|
1215
|
+
${l}`),r.json||i.emitInfo(o==="recovery"?p?`${u} recovery started. Finish the verification in your browser, then come back here. Waiting for browser recovery to finish...`:`${u} recovery started. Open this URL in your browser, then come back here once it is done:
|
|
1216
|
+
${l}
|
|
1217
|
+
Waiting for browser recovery to finish...`:p?`${u} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`:`${u} sign-in started. Open this URL in your browser, then come back here once it is done:
|
|
1218
|
+
${l}
|
|
1219
|
+
Waiting for browser sign-in to finish...`)}else r.json||i.emitInfo(o==="recovery"?`${u} recovery started. Finish the verification in your browser, then come back here. Waiting for browser recovery to finish...`:`${u} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let d=await jW(c,i,s,{expiresAt:f(t,"expiresAt"),mode:o,provider:e,json:r.json});if(Z(d))return d;if(d.status==="verified"||d.status==="recovered")return await uf(u,n,r,i,o);if(d.status==="mfa_required"){if(!n)return P("Login MFA handoff is unavailable. Start login again.",r.json);let p=v(r.mfaCode),m=v(r.recoveryCode);if(!p&&!m&&!r.json&&i.stdoutIsTty){let h=await i.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),y=(await i.promptSecret(h==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();h==="recovery_code"?m=y:p=y}if(!p&&!m)return S({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],nextAction:"account.login.mfa",nextStep:"Re-run login in a human terminal and complete MFA."},"MFA is required to finish login.",r.json,"login_mfa_required");let g=await E(i,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:U(),body:JSON.stringify({state:c,authorizationCode:n.authorizationCode,codeVerifier:n.codeVerifier,...p?{mfaCode:p}:{},...m?{recoveryCode:m}:{}})});return f(g,"status")!=="verified"||f(g,"credentialHandoff")!=="ready"?P("MFA verification did not authorize the login credential. Start login again.",r.json):await uf(u,n,r,i,o)}if(d.status==="already_registered"||d.status==="link_required"){let p=kE(e,!!i.apiKey&&!i.authBlockedMessage);return S({...p},p.summary,r.json,"social_identity_link_required")}if(d.status==="registration_confirmation_required"){if(!r.json&&i.stdoutIsTty){let m=await i.promptSelect(`Create a new Skills Layer account using your verified ${u} identity?`,[{value:"create",label:"Yes, create my account",description:"Create one account, connect this sign-in, and log in"},{value:"cancel",label:"No",description:"Create nothing and leave Skills Layer unchanged"}])==="create",g=await E(i,"/api/v1/identity/social/registration/confirm",{method:"POST",headers:U(),body:JSON.stringify({state:c,createAccount:m})});return!m||f(g,"status")==="registration_cancelled"?R({status:"registration_cancelled",changed:!1},"Registration cancelled. No Skills Layer account was created.",!1,i):f(g,"status")!=="verified"||f(g,"credentialHandoff")!=="ready"?P("Account creation could not be confirmed safely. Start registration again.",!1):await uf(u,n,r,i,"register")}return S({status:"registration_confirmation_required",reasonCode:"registration_confirmation_required",nextAction:"account.registration.confirm",nextStep:r.createAccount?"Provider verification finished, but account creation still needs confirmation. Start registration again.":"Re-run registration with --create-account after confirming that you want to create this account."},"Account creation needs explicit confirmation.",r.json,"registration_confirmation_required")}return d.status==="linked"?R(d,`${u} sign-in is now connected.`,r.json,i):NW(d)?P(zW(d),r.json):P("Social auth completed with an unexpected response.",r.json)}async function uf(e,t,n,r,i){if(!t)return P("Social credential handoff is unavailable. Start the login flow again.",n.json);let o=await E(r,"/api/v1/identity/social/exchange",{method:"POST",headers:U(),body:await Pv(t,r)});if(f(o,"status")!=="exchanged"||!f(o,"email")||!f(o,"role")||!f(o,"apiKey"))return P("Social credential handoff failed closed. Start the login flow again.",n.json);let s=f(o,"email");return await xv(s,o,n,r,i==="recovery"?`Recovered access for ${s} through ${e}.`:`Verified ${s} through ${e}.`)}function ji(e){return e==="google"||e==="github"||e==="gitlab"||e==="microsoft"}function Z(e){return O(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function BW(e){try{let t=JSON.parse(e);return O(t)?t.data:void 0}catch{return}}function NW(e){return e.status==="registration_required"||e.status==="state_expired"||e.status==="provider_mismatch"||e.status==="identity_conflict"||e.status==="email_required"||e.status==="failed"}var Vw=1500,L0=900*1e3;function MW(e,t){let n=e?Date.parse(e)-Date.parse(t):Number.NaN,r=Number.isFinite(n)&&n>0?Math.min(n,L0):L0;return Math.ceil(r/Vw)+1}async function jW(e,t,n="/api/v1/identity/social/status",r={}){let i=MW(r.expiresAt,t.now());for(let s=0;s<i;s+=1)try{let a=await E(t,`${n}/${encodeURIComponent(e)}`,n.includes("/identity/connect/")?{headers:H(t.apiKey,t.authBlockedMessage)}:void 0),l=f(a,"status")??"failed";if(l==="pending"){await t.sleep(Vw);continue}return(l==="verified"||l==="recovered")&&f(a,"credentialHandoff")==="ready"?{status:l,credentialHandoff:"ready"}:l==="already_registered"||l==="link_required"?{status:l}:l==="linked"?{status:l}:l==="registration_confirmation_required"?{status:l}:l==="mfa_required"?{status:l}:l==="registration_required"||l==="state_expired"||l==="provider_mismatch"||l==="identity_conflict"||l==="email_required"||l==="failed"?{status:l,error:f(a,"error")}:P("Social auth completed with an unexpected response.",!1)}catch(a){if(a instanceof V&&(a.status===404||a.status===429)){await t.sleep(Vw);continue}return P(ne(a),!1)}let o=r.mode==="register"?`skills-layer register --method ${r.provider??"<provider>"}`:`skills-layer login --method ${r.provider??"<provider>"}`;return S({status:"timed_out",reasonCode:"social_auth_timed_out",state:e,...r.expiresAt?{expiresAt:r.expiresAt}:{},nextAction:r.mode==="register"?"register":"login",nextStep:`The browser sign-in was not finished before it expired. Run \`${o}\` to start again.`},`Timed out while waiting for social auth to complete. The browser sign-in expired; run \`${o}\` to start again.`,r.json===!0,"social_auth_timed_out")}async function UW(e,t){let n=`/api/v1/identity/mfa/recovery-codes/operations/${encodeURIComponent(e)}`;for(let r=0;r<210;r+=1)try{let i=await E(t,n,{headers:H(t.apiKey,t.authBlockedMessage)}),o=f(i,"status"),s=L(i,"data");if(o==="pending"||o==="finalizing"){await t.sleep(1500);continue}if(o==="completed")return{...i,completedAt:f(i,"completedAt")??(s?f(s,"completedAt"):void 0)};if(o==="locked"){let a=f(i,"retryAt")??(s?f(s,"retryAt"):void 0);return S({status:"locked",reasonCode:"mfa_challenge_locked",retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1)}return o==="failed"?S({status:"failed",reasonCode:"mfa_recovery_codes_failed",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Recovery codes were not replaced.",!1):o==="expired"?S({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"The recovery-code browser session expired before completion.",!1):P("Recovery-code verification completed with an unexpected response.",!1)}catch(i){if(i instanceof V&&i.status===429){let o=i.details??{},s=f(o,"reasonCode"),a=f(o,"retryAt");if(s==="mfa_challenge_locked")return S({status:"locked",reasonCode:s,retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1);let l=K(o,"retryAfterSeconds"),c=l===void 0?1500:Math.min(6e4,Math.max(1500,l*1e3));await t.sleep(c);continue}return P(ne(i),!1)}return S({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Timed out while waiting for recovery-code verification.",!1)}async function qW(e,t){for(let n=0;n<120;n+=1)try{let r=await E(t,`/api/v1/purchases/${encodeURIComponent(e)}`,{headers:H(t.apiKey,t.authBlockedMessage)});if(!r?.status||r.status==="pending"||r.status==="requires_action"){await t.sleep(1500);continue}return{status:r.status,purchaseId:e}}catch(r){if(r instanceof V&&r.status===429){await t.sleep(1500);continue}return P(ne(r),!1)}return P("Timed out while waiting for purchase confirmation.",!1)}async function VW(e,t,n){let r=null;for(let i=0;i<120;i+=1)try{let o=await E(n,e,{headers:H(n.apiKey,n.authBlockedMessage)});r=o;let s=f(o,"status");if(!s||s==="checkout_required"||s==="pending"||s==="requires_action"||s==="payment_received"||s==="provisioning"||s==="finalizing"){await n.sleep(1500);continue}return o}catch(o){if(o instanceof V&&o.status===429){await n.sleep(1500);continue}return P(ne(o),!1)}try{let i=await E(n,e,{headers:H(n.apiKey,n.authBlockedMessage)}),o=f(i,"status");if(o&&!["checkout_required","pending","requires_action","payment_received","provisioning","finalizing"].includes(o))return i;r=i}catch{}return{...r??{},status:"completion_pending",reasonCode:"enterprise_checkout_completion_pending",checkoutId:t,statusPath:e,retrySafe:!0,nextAction:"check_checkout_status",nextStep:"Check this checkout status again. Do not start a second checkout."}}async function GW(e,t){for(let n=0;n<120;n+=1)try{let r=await E(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:H(t.apiKey,t.authBlockedMessage)}),i=f(r,"status");if(!i||i==="checkout_required"||i==="pending"||i==="requires_action"){await t.sleep(1500);continue}return{...r,status:i}}catch(r){if(r instanceof V&&r.status===429){await t.sleep(1500);continue}return P(ne(r),!1)}return P("Timed out while waiting for payment confirmation.",!1)}function uT(e){let t=L(e,"accountLink");return(t?f(t,"url"):void 0)??f(e,"url")??f(e,"setupUrl")}function zW(e){return e.status==="registration_confirmation_required"?"Account creation requires explicit confirmation.":e.status==="registration_required"?e.error??"No verified account exists for this social identity. Use `skills-layer register` first.":e.status==="state_expired"?"Social auth expired before completion. Start the flow again.":e.status==="provider_mismatch"?"The browser completed a different social provider than the one the CLI started.":e.status==="identity_conflict"?e.error??"This social identity is already linked to another account.":e.status==="email_required"?e.error??"This social profile did not provide an email address.":e.error??"Social auth could not be completed."}async function dT(e){let t=await se(e.paths.devicePath),n=ag(t?.deviceId);return n||(n=LC(ke(16).toString("hex")),await vs(e.paths.devicePath,{version:1,deviceId:n,createdAt:e.now()})),{deviceId:n,deviceName:OC({env:e.env,platform:e.platform,hostname:yK()})}}async function Pv(e,t){return JSON.stringify({authorizationCode:e.authorizationCode,codeVerifier:e.codeVerifier,...await dT(t)})}async function El(e,t,n={}){let r=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole,i=r?await E({...e,apiKey:t},"/api/v1/me",{headers:{...H(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,sessionCredentialId:n.knownSessionCredentialId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},o=f(i,"email")??n.knownEmail??"unknown";if(n.expectedEmail&&o.toLowerCase()!==n.expectedEmail.toLowerCase())throw new Error(`The entered API key belongs to ${o}, not ${n.expectedEmail}. Use the API key emailed to ${n.expectedEmail}.`);let s=await E({...e,apiKey:t},"/api/v1/capabilities",{headers:H(t)}),a={version:_K,baseUrl:e.baseUrl,apiKey:t,edition:gp(s.edition,i.edition),userId:f(i,"userId")??n.knownUserId,sessionCredentialId:f(i,"sessionCredentialId")??n.knownSessionCredentialId,sessionExpiresAt:f(i,"sessionCredentialExpiresAt")??(r?void 0:new Date(Date.parse(e.now())+6048e5).toISOString()),email:o,role:f(i,"role")??n.knownRole??"user",roles:rn(i,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await Vl(e.paths.configPath,a,e),await sJ(e,a),await _e(e.paths.backendPreferencePath,{version:Yw,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function O0(e,t){let n=It(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let r=v(e.action);return t==="incident"?{type:"file_write",path:v(e.path)??".skills-layer/incidents/guardian-incident.json"}:r==="file_read"||r==="file_write"?{type:r,path:v(e.path)??"."}:r==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...r?{target:r}:{}}}async function ie(e,t,n,r,i={}){let o=i.authenticated?H(n.apiKey,n.authBlockedMessage):An(n.apiKey);return await Dl(e,{headers:o},t,n,r)}async function KW(e){let t=e.config;if(!t?.apiKey||e.apiKey!==t.apiKey||t.sessionExpiresAt||t.sessionExpiryCheckedAt)return;let n;try{n=await E(e,"/api/v1/me",{headers:H(e.apiKey)})}catch{return}let r=f(n,"sessionCredentialExpiresAt"),i={...t,...r?{sessionExpiresAt:r}:{sessionExpiryCheckedAt:e.now()}};await Vl(e.paths.configPath,i,e),e.config=i}async function HW(e,t){await KW(t);let[n,r,i]=await Promise.all([E(t,"/api/v1/status",{headers:An(t.apiKey)}),Vt(t),Df(t)]),o={guardian:r,mcp:i.publicState},s=ip(R({...n,localRuntime:o},"Status loaded.",e.json,t),Yi(t.config),e.json),a=t.apiKey?op(t.config?.sessionExpiresAt,t.now()):null;return ip(s,a?.message??"",e.json)}async function fT(e,t){let n=new Set(t);return(await gb({env:e.env,platform:e.platform,cwd:e.cwd,pathExists:e.pathExists})).map(r=>({...r,managedConfigured:n.has(r.hostId)}))}async function Df(e){let t=await se(e.paths.mcpConfigPath),n=t&&Array.isArray(t.clientIds)?t.clientIds.filter(d=>typeof d=="string"&&nt(d)!==null):t&&f(t,"clientId")&&nt(f(t,"clientId"))?[f(t,"clientId")]:[],r=await fT(e,n),i=r.filter(d=>d.installed),o=r.filter(d=>d.configured),s=r.filter(d=>d.managedConfigured),a=!!t,l=!a&&i.length>0,c=a?"mcp_configured":l?"mcp_hosts_detected_unmanaged":"mcp_not_configured",u=a?`Skills Layer MCP is configured for ${n.length} managed host${n.length===1?"":"s"}.`:l?"MCP-capable hosts or host configuration were detected, but the Skills Layer managed bridge is not configured.":"No MCP-capable host or Skills Layer managed bridge was detected on this machine.";return{config:t,configuredClientIds:n,hosts:r,summary:u,publicState:{status:c,configured:a,managedConfigured:a,hostDetected:i.length>0,hostConfigured:o.length>0,clientId:n[0]??null,clientIds:n,detectedHostIds:i.map(d=>d.hostId),hostConfiguredIds:o.map(d=>d.hostId),hosts:r,detectedHostCount:i.length,hostConfiguredCount:o.length,managedConfiguredHostCount:s.length,verifiedHostCount:0,configPath:e.paths.mcpConfigPath,nextCommand:a?"skills-layer mcp verify":"skills-layer mcp setup",verifyCommand:a?n.length===1?`skills-layer mcp verify --client ${n[0]}`:"skills-layer mcp verify":"skills-layer mcp setup",nextAction:a?"mcp.verify":"mcp.setup",nextStep:a?"Verify the Skills Layer managed bridge from a fresh agent session.":l?"Run `skills-layer mcp setup` to connect Skills Layer to a detected MCP-capable host.":"Run `skills-layer mcp setup` to connect Skills Layer to an AI client."}}}async function WW(e,t){if(e.deep)return await JW(e,t);let n=await E(t,"/api/v1/doctor",{headers:An(t.apiKey)}),[r,i,o]=await Promise.all([Vt(t),v8(t),Df(t)]),s=rW(r,i,await vv(t,"project")),a=[...kT(n),s],l=s.reasonCode==="guardian_hook_cli_path_stale"||s.reasonCode==="guardian_hook_config_missing"?{status:"action_required",reasonCode:s.reasonCode,summary:s.summary,nextAction:s.nextAction,nextStep:s.nextStep,recommendedCommand:s.recommendedCommand}:{};return R({...n,...l,guardian:{...r,policy:i},mcp:o.publicState,checks:a},"Doctor checks loaded.",e.json,t)}async function JW(e,t){let n;try{let c=await E(t,"/api/v1/status",{headers:An(t.apiKey)});n=nn("ok","backend_reachable","status","Backend status loaded.",{baseUrl:t.baseUrl,edition:f(c,"edition"),capabilityCount:Array.isArray(c.capabilities)?c.capabilities.length:void 0})}catch(c){n=nn("error","backend_unreachable","backend.status","Selected backend could not be reached.",{baseUrl:t.baseUrl,error:ne(c)})}let r=t.config?.credentialStorage??(t.apiKey?"local_file_locked":"none"),i=await Df(t),o=i.config,s=await Vt(t),a=We(t.env,t.platform,t.cwd).map(c=>({id:c.id,displayName:c.displayName,capabilities:c.capabilities})),l={backend:n,auth:t.apiKey?nn("ok","authenticated","whoami","A local session is available for the selected backend.",{email:t.config?.email,role:t.config?.role,savedLoginMatchesSelectedBackend:!0}):nn("login_required","login_required","login","No usable local session is available for the selected backend.",{savedLoginMatchesSelectedBackend:t.config?.baseUrl?Nl(t.config.baseUrl,t.baseUrl):!0}),credentialStorage:nn(r==="none"?"not_configured":"ok",r==="none"?"credential_storage_not_configured":"credential_storage_ready",r==="none"?"login":"auth.status",r==="none"?"Run `skills-layer login` to create a secure local session.":"Credential storage metadata is present.",{credentialStorage:r,configPath:t.paths.configPath}),mcp:o?nn("configured","mcp_configured","mcp.verify","MCP is configured locally; verify from a fresh agent session if tools are not visible.",{...i.publicState,mcpUrl:f(o,"mcpUrl")}):nn(i.publicState.hostDetected?"detected_unmanaged":"not_configured",i.publicState.status,"mcp.setup",i.summary,{...i.publicState}),guardianHooks:Number(s.staleCliPathCount??0)>0?nn("warn","guardian_hook_cli_path_stale","guardian.hook.install","A Guardian hook points at a Skills Layer CLI path that no longer exists, so it blocks every tool call. Run skills-layer guardian hook install --agent <agent> again.",s):nn(f(s,"enforcementLayer")==="not_installed"?"not_installed":s.strictPreActionBlocking===!0?"ok":"warn",f(s,"enforcementLayer")==="not_installed"?"guardian_hook_not_installed":s.strictPreActionBlocking===!0?"guardian_hook_verified_strict":"guardian_hook_candidate_unverified","guardian.hook.status",f(s,"enforcementLayer")==="not_installed"?"Cloud Guardian checks work when called, but local pre-action hooks are not installed.":s.strictPreActionBlocking===!0?"At least one Skills Layer Security Hook has current matching live-canary evidence.":"A Skills Layer Security Hook is installed, but current live-canary evidence has not verified strict enforcement.",s),localPaths:nn("ok","local_paths_resolved","doctor.deep","Local Skills Layer paths resolved.",{stateDir:t.paths.stateDir,configPath:t.paths.configPath,installsPath:t.paths.installsPath,mcpConfigPath:t.paths.mcpConfigPath}),agentTargets:nn("ok","agent_targets_loaded","agents.list","Supported local agent targets loaded.",{count:a.length,results:a})};return R({status:"ok",deep:!0,sections:l,nextAction:t.apiKey?"status":"login",nextStep:t.apiKey?"Run `skills-layer status --json` for Cloud journey readiness.":"Run `skills-layer login` to sign in, then rerun `skills-layer doctor --deep --json`."},"Deep doctor diagnostics loaded.",e.json,t)}function nn(e,t,n,r,i={}){return W({status:e,reasonCode:t,nextAction:n,nextStep:r,...i})}async function YW(e,t,n){let[r,i,o]=e,s=v(t.email);if(r==="request"&&i){let a=v(t.statement);if(!a)return P("delisting request requires --statement <text> (10 to 4000 characters).",t.json);if(!n.apiKey&&!s)return P("delisting request needs a signed-in account or --email <address> to receive a verification code.",t.json);let l;if(t.evidenceJson!==void 0){let m;try{m=JSON.parse(String(t.evidenceJson))}catch{return P("--evidence-json must be a JSON object.",t.json)}if(!O(m))return P("--evidence-json must be a JSON object.",t.json);l=m}let c=`/api/v1/public/skills/${encodeURIComponent(i)}/delisting-requests`,u=await E(n,c,{method:"POST",headers:U(n.apiKey),body:JSON.stringify(W({statement:a,email:s,evidence:l}))}),d=f(u,"requestId"),p=u.status==="verification_pending"&&d?`Check your email for a 6-digit code (valid 15 minutes), then run: skills-layer delisting verify ${i} ${d} --email <address> --code <code>`:"Delisting request submitted for review.";return R(u,p,t.json,n)}if(r==="verify"&&i&&o){let a=v(t.code);return!s||!a?P("delisting verify requires --email <address> and --code <6-digits>.",t.json):await pe(`/api/v1/public/skills/${encodeURIComponent(i)}/delisting-requests/${encodeURIComponent(o)}/verify`,{email:s,code:a},t,n,"Delisting request submitted for review.")}return P("Use: skills-layer delisting request <skill-slug> --statement <text> [--email <address>] [--evidence-json <json>], or skills-layer delisting verify <skill-slug> <request-id> --email <address> --code <6-digits>.",t.json)}async function pe(e,t,n,r,i,o={}){return await Dl(e,{method:"POST",headers:{...U(r.apiKey),...o},body:JSON.stringify(W(t))},n,r,i)}function ZW(){return`payout_request_${ke(24).toString("base64url")}`}function XW(){return`guardian_incident_${ke(24).toString("base64url")}`}async function QW(e,t){for(let n=0;n<2;n+=1)try{return await E(e,"/api/v1/guardian/enforce",{method:"POST",headers:U(e.apiKey),body:JSON.stringify(t)})}catch(r){if(!(r instanceof V?[500,502,503,504].includes(r.status):r instanceof Error&&r.message.startsWith("Unable to reach "))||n===1)throw r;await e.sleep(250)}throw new Error("Guardian incident retry limit was exhausted.")}async function Ei(e,t,n,r,i){return await Dl(e,{method:"PATCH",headers:U(r.apiKey),body:JSON.stringify(W(t))},n,r,i)}async function Dl(e,t,n,r,i){let o=await E(r,e,t);return R(o,i,n.json,r)}async function E(e,t,n={}){Zn(e.baseUrl);let r=await e.fetchFn(`${e.baseUrl}${t}`,{...n,redirect:"error"}).catch(s=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ne(s)}`)});if(!r.ok)throw await Ev(r);let i=await r.text();if(!i)return{};let o=JSON.parse(i);return o&&typeof o=="object"&&!Array.isArray(o)&&o.schemaVersion!=="skills-layer.creator.operation.v1"&&"data"in o?sa(o.data):sa(o)}async function Ev(e){let t=await e.text();if(t)try{let n=sa(JSON.parse(t));return new V(e.status,f(n,"error")??f(n,"reason")??f(n,"summary")??(e.statusText||"Request failed"),n)}catch{return new V(e.status,t)}return new V(e.status,e.statusText||"Request failed")}var Tl=class extends V{};function H(e,t){if(t)throw new Tl(401,t,{error:t,nextAction:"backend.status",nextStep:t});if(!e)throw new V(401,"Login required.",{error:"Login required.",nextAction:"login",nextStep:"Run `skills-layer login` to sign in, then retry this command."});return{authorization:`Bearer ${e}`}}function An(e){return e?{authorization:`Bearer ${e}`}:{}}function U(e,t){return{"content-type":"application/json",...e||t?H(e,t):{}}}async function $l(e,t){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e)||/^[a-z][a-z0-9+.-]*:(?![\\/])/iu.test(e))return;let n=tt(t,e);try{await Ml(n)}catch{return}let r=await Uo({cwd:t,sourcePath:e,limits:hi});return{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:r.files}}var Ll=class extends Error{constructor(){super("Local Installation Ledger changed concurrently; retry the exact target operation."),this.name="InstallIndexRevisionConflictError"}},Di=/^sha256:[a-f0-9]{64}$/u;function Ol(e){return{version:1,state:e.state,operationId:e.operationId,receipt:e.receipt,...e.quarantine?{quarantine:e.quarantine}:{},updatedAt:e.backend.now()}}function _t(e){let t=L(e,"localLifecycle");if(!t||t.version!==1)return null;let n=f(t,"state"),r=f(t,"operationId"),i=f(t,"updatedAt"),o=yT(t.receipt);if(!n||!["pending_activation","active","quarantined","restore_pending","externally_removed","unreadable","drifted","host_detached"].includes(n)||!r||!i||!o)return null;let s=t.quarantine===void 0?void 0:n9(t.quarantine);return(n==="quarantined"||n==="restore_pending")&&!s?null:{version:1,state:n,operationId:r,receipt:o,...s?{quarantine:s}:{},updatedAt:i}}var e9=new Set(["agent","atomicActivation","guardianRuntimeMetadata","guardianEnforcement","guardianActivationReceipt","harnessUninstalledAt","hostRegistrationState","localLifecycle","materializationId","materializedPath","materializedSkillRoot","materializedWrites","receiptSha256","reconciliation","scope","targetAgent","targetAgents","targetGroup"]);function Fl(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!e9.has(t)))}function Br(e,t){let r=(t==="win32"?je:ct).resolve(e).normalize("NFC");return t==="linux"?r:r.toLocaleLowerCase("en-US")}function pT(e){let t=`${e.scope}\0${Br(e.targetDir,e.platform)}`;return`materialization_${me("sha256").update(t).digest("hex").slice(0,24)}`}function kt(e){let t=e?L(e,"materializations"):void 0;return t?Object.fromEntries(Object.entries(t).flatMap(([n,r])=>O(r)?[[n,r]]:[])):{}}function Et(e){return Object.entries(kt(e)).map(([t,n])=>({materializationId:t,record:n,lifecycle:_t(n)}))}function Dt(e){return Array.from(new Set([...rn(e,"targetAgents")??[],...[f(e,"agent"),f(e,"targetAgent")].filter(t=>!!t)])).sort()}function qn(e){let t=_t(e.materialization),n=f(e.materialization,"scope");if(!t||n!=="project"&&n!=="global")throw new Error("Local Installation Ledger materialization requires an exact lifecycle and project/global scope.");let r=f(e.materialization,"materializationId")??pT({scope:n,targetDir:t.receipt.targetDir,platform:e.backend.platform}),i=kt(e.existing)[r],o=Array.from(new Set([...Dt(i??{}),...Dt(e.materialization)])).sort(),s={...e.materialization,materializationId:r,targetAgents:o,...o.length>1?{targetGroup:`shared:${n}:${o.join(",")}`}:{},receiptSha256:pr(t.receipt),savedAt:e.backend.now()},a={...kt(e.existing),[r]:s},l=Object.keys(a).length===1?s:{};return{...Fl(e.existing??{}),...l,skillSlug:e.skillSlug,materializations:a,materializationCount:Object.keys(a).length,savedAt:e.backend.now()}}function mT(e){let t=kt(e.existing);if(delete t[e.materializationId],Object.keys(t).length===0)return;let n=Object.values(t);return{...Fl(e.existing),...n.length===1?n[0]:{},materializations:t,materializationCount:Object.keys(t).length,savedAt:e.backend.now()}}function sn(e,t={}){return Et(e).filter(n=>{let r=f(n.record,"scope");if(t.scope&&r!==t.scope||t.agent&&!Dt(n.record).includes(t.agent)||t.receiptSha256&&f(n.record,"receiptSha256")!==t.receiptSha256)return!1;if(t.installedPath){let i=n.lifecycle?.receipt.targetDir;if(!i||!Cv(t.installedPath,i,t.platform??process.platform))return!1}return!0})}function t9(e){let t=e.backend.platform==="win32"?je:ct,n=new Set;for(let r of We(e.backend.env,e.backend.platform,e.backend.cwd))if(!(e.agent&&r.id!==e.agent))for(let i of new Set([e.skillSlug,...e.materializations.flatMap(o=>o.lifecycle?[t.basename(o.lifecycle.receipt.targetDir)]:[])]))(!e.scope||e.scope==="project")&&n.add(Br(t.join(r.targets.projectSkillsPath,i),e.backend.platform)),(!e.scope||e.scope==="global")&&r.targets.globalSkillsPath&&n.add(Br(t.join(r.targets.globalSkillsPath,i),e.backend.platform));return e.materializations.filter(r=>{let i=r.lifecycle?.receipt.targetDir;return!!(i&&n.has(Br(i,e.backend.platform)))})}function xn(e,t){return{...Fl(e),...t.record,materializationId:t.materializationId}}function gT(e){return Object.values(e.installs).flatMap(t=>{let n=Et(t);return n.length>0?n.map(r=>xn(t,r)):[t]})}function hT(e){let t=L(e,"cachedArtifact"),n=t?L(t,"generation"):void 0,r=t?f(t,"state"):void 0,i=t?f(t,"bundlePath"):void 0,o=n?f(n,"skillSlug"):void 0,s=n?f(n,"semanticVersion"):void 0,a=n?f(n,"generationId"):void 0,l=t?f(t,"archiveSha256"):void 0,c=t?f(t,"manifestSha256"):void 0,u=t?f(t,"savedAt"):void 0;return r!=="verified"||!i||!o||!s||!a||!l||!Di.test(l)||!c||!Di.test(c)||!u?null:{state:"verified",bundlePath:i,generation:{skillSlug:o,semanticVersion:s,generationId:a},archiveSha256:l,manifestSha256:c,savedAt:u}}function yT(e){if(!O(e))return null;let t=f(e,"targetDir"),n=L(e,"generation"),r=n?f(n,"skillSlug"):void 0,i=n?f(n,"semanticVersion"):void 0,o=n?f(n,"generationId"):void 0,s=f(e,"archiveSha256"),a=f(e,"manifestSha256"),l=he(e,"files");if(!t||!r||!i||!o||!s||!Di.test(s)||!a||!Di.test(a)||!l||l.length===0)return null;let c=l.flatMap(d=>{if(!O(d))return[];let p=f(d,"path"),m=K(d,"sizeBytes"),g=f(d,"sha256");return p&&Number.isSafeInteger(m)&&m>=0&&g&&Di.test(g)&&(d.executable===void 0||typeof d.executable=="boolean")?[{path:p,sizeBytes:m,sha256:g,...d.executable===!0?{executable:!0}:{}}]:[]});if(c.length!==l.length)return null;let u=L(e,"manifestV2");return{targetDir:t,generation:{skillSlug:r,semanticVersion:i,generationId:o},archiveSha256:s,manifestSha256:a,files:c,...u?{manifestV2:u}:{}}}function wT(e){if(!O(e)||e.status!=="authorized")return null;let t=f(e,"authorizationId"),n=f(e,"purpose"),r=L(e,"generation"),i=r?f(r,"skillSlug"):void 0,o=r?f(r,"semanticVersion"):void 0,s=r?f(r,"generationId"):void 0,a=f(e,"archiveSha256"),l=f(e,"manifestSha256");return!t||!n||!["quarantine_blocked","quarantine_revoked","restore_fresh_approval","purge_quarantined"].includes(n)||!i||!o||!s||!a||!Di.test(a)||!l||!Di.test(l)?null:{status:"authorized",authorizationId:t,purpose:n,generation:{skillSlug:i,semanticVersion:o,generationId:s},archiveSha256:a,manifestSha256:l}}function n9(e){if(!O(e)||e.status!=="quarantined")return null;let t=f(e,"reasonCode"),n=f(e,"targetDir"),r=f(e,"quarantineRoot"),i=f(e,"quarantineDir"),o=rn(e,"discoveryRoots"),s=wT(e.quarantineAuthorization),a=yT(e.receipt);return!t||!n||!r||!i||!o||o.length===0||!s||!a?null:{status:"quarantined",reasonCode:t,targetDir:n,quarantineRoot:r,quarantineDir:i,discoveryRoots:o,quarantineAuthorization:s,receipt:a}}async function Pe(e){let t=await se(e.paths.installsPath);return!O(t)||t.version!==sf||!O(t.installs)?{version:sf,revision:0,installs:{}}:{version:sf,revision:Number.isSafeInteger(t.revision)&&Number(t.revision)>=0?Number(t.revision):0,installs:s9(t.installs)}}async function Dv(e,t){let n=e.paths.installsPath,r=ye(n);await Ui(r);let i=`${n}.lock`,o,s=Date.now()+5e3;for(;!o;)try{o=await $i(i,"wx",384)}catch(c){if(c.code!=="EEXIST"||Date.now()>=s)throw c;await new Promise(u=>setTimeout(u,10))}let a=z(r,`.${$e(n)}.${ke(12).toString("hex")}.tmp`),l;try{let c=await se(n),u=O(c)&&c.version===sf&&Number.isSafeInteger(c.revision)&&Number(c.revision)>=0?Number(c.revision):0;if(u!==t.revision)throw new Ll;let d={...t,revision:u+1};l=await $i(a,"wx",384),await l.writeFile(`${JSON.stringify(d,null,2)}
|
|
1220
|
+
`,"utf8"),await l.sync(),await l.close(),l=void 0,await Li(a,n),await qi(n,384),await Tv(r),t.revision=d.revision}catch(c){throw await l?.close().catch(()=>{}),await Ae(a,{force:!0}).catch(()=>{}),c}finally{await o.close().catch(()=>{}),await Ae(i,{force:!0}).catch(()=>{})}}async function Vn(e,t){for(let n=0;n<8;n+=1){let r=await Pe(e);await t(r);try{return await Dv(e,r),r}catch(i){if(!(i instanceof Ll)||n===7)throw i}}throw new Ll}async function Ur(e,t){let n=await Pe(e),r=!1,i=[];for(let[o,s]of Object.entries(n.installs)){if(t&&o!==t)continue;let a=s;for(let l of Et(s)){let c=l.lifecycle;if(!c||c.state!=="active")continue;let u=await r9(l.record,c);if(u.state==="active")continue;let d=u.state;a=qn({existing:a,skillSlug:o,materialization:{...l.record,status:u.state,reconciliation:{version:1,state:u.state,reasonCode:u.reasonCode,observedAt:e.now(),recoverable:u.recoverable},localLifecycle:{...c,state:d,updatedAt:e.now()},savedAt:e.now()},backend:e}),r=!0,i.push({skillSlug:o,generationId:c.receipt.generation.generationId,receiptSha256:pr(c.receipt),state:u.state==="externally_removed"?"externally_removed":u.state==="host_detached"?"host_detached":"stale",reasonCode:u.reasonCode})}n.installs[o]=a}r&&await Dv(e,n);for(let o of i)await i9(e,o).catch(()=>{});return n}async function r9(e,t){let n;try{let o=await Ml(t.receipt.targetDir);n=o.isDirectory()&&!o.isSymbolicLink()?"present_directory":"replaced_type"}catch(o){n=o.code==="ENOENT"?"absent":"unreadable"}let r=n==="present_directory"?(await Mn(t.receipt)).status==="verified"?"verified":"changed":"unchecked",i=e.hostRegistrationState==="detached"||typeof e.harnessUninstalledAt=="string"?"detached":"unknown";return zR({pathState:n,receiptState:r,hostState:i})}async function i9(e,t){for(let n of["project","global"]){let r;try{r=await Oi(e,n)}catch{continue}let i=Object.entries(r.associations).filter(([,o])=>o.skillSlug===t.skillSlug&&o.generationId===t.generationId&&o.receiptSha256===t.receiptSha256&&o.state!=="externally_removed"&&o.state!=="host_detached");for(let[o]of i)await xi(e,n,o,{state:t.state,reasonCode:t.reasonCode,updatedAt:e.now()})}}async function Tv(e){if(process.platform!=="win32")try{let t=await $i(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function o9(e){await Vn(e.backend,t=>{let n=t.installs[e.skillSlug];if(!n)return;let r=kt(n)[e.materializationId],i=r?_t(r):null;if(!i||i.operationId!==e.operationId)return;if(e.baselineMaterialization){t.installs[e.skillSlug]=qn({existing:n,skillSlug:e.skillSlug,materialization:e.baselineMaterialization,backend:e.backend});return}let o=mT({existing:n,materializationId:e.materializationId,backend:e.backend});o?t.installs[e.skillSlug]=o:delete t.installs[e.skillSlug]})}async function fs(e,t,n){let r=f(t,"skillSlug")??f(t,"slug")??n,i=Array.isArray(t.materializationResults)?t.materializationResults.filter(O):_t(t)?[t]:[],o=i.length>0?Fl(t):t;await Vn(e,s=>{let a={...Fl(s.installs[r]??{}),...o,...t.acquisitionMode==="authenticated_account"?{acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId}:{},skillSlug:r,materializations:kt(s.installs[r]),savedAt:e.now()};for(let l of i)a=qn({existing:a,skillSlug:r,materialization:{...l,...t.acquisitionMode==="authenticated_account"?{acquisitionMode:t.acquisitionMode,acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId,entitlementId:t.entitlementId}:{}},backend:e});s.installs[r]=a})}function s9(e){let t={};for(let[n,r]of Object.entries(e))t[n]=O(r)?r:{skillSlug:n,value:r};return t}var Ue=5;function F0(e){return f(e,"summary")??(e.status==="blocked"?`Submission preview blocked: ${f(e,"why")??f(e,"reasonCode")??"requirements not met"}`:"Submission preview ready.")}function vT(e){if(!O(e))return null;let t=f(e,"reasonCode"),n=t==="commercial_rights_declaration_required"||t==="commercial_rights_declaration_invalid";if(!n&&t!=="paid_to_free_confirmation_required")return null;let r=n?"Confirm your rights to distribute this skill.":"Confirm that this paid skill should become free.";return{...e,status:"action_required",error:r,message:r,nextAction:"retry",nextStep:n?"Repeat with --attest-rights --rights-basis self_authored after confirming your rights. For submit or submit-version, also add --distribution-scope commercial_distribution.":"To make this paid skill free, repeat with --price-cents 0 --confirm-free. The generic --yes flag does not confirm this change."}}function R(e,t,n,r,i){O(e)&&Array.isArray(e.results)&&e.results.some(d=>O(d)&&d.status==="failed"&&(d.settlement||d.recovery))&&(t=qv(e.results));let o=vT(e);o&&(e=o,t=String(o.message));let s=e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",a=Sf(e,!n),l=n&&i?Gw(a,r?.renderMode.detail??"standard",i):a,c=O(a)?a:void 0,u={schemaVersion:H0,status:s,statusFamily:u9(s,a),summary:t,why:c?f(c,"why")??null:null,nextAction:c?f(c,"nextAction")??null:null,nextStep:c?f(c,"nextStep")??null:null,data:l,warnings:[...c&&Array.isArray(c.warnings)?c.warnings:[],...r?.runtimeWarnings??[]],links:c&&Array.isArray(c.links)?c.links:[],reasonCode:c?f(c,"reasonCode")??null:null,handoff:c?.handoff??null};return{exitCode:0,stdout:n?JSON.stringify(u,null,2):Vi(p9(a,t,r)),stderr:""}}function Gw(e,t,n){return t==="full"||!O(e)?e:n==="installed"?l9(e,t):c9(e,t)}var bT=["skillSlug","version","scope","agent","targetAgents","materializedSkillRoot","status"],a9=[...bT,"targetAgent","source","sourceKind","installMode","installedAt","savedAt","updatedAt","generationId","installedPathSource","localLifecycle"];function l9(e,t){let n=lt(e.results),r=t==="concise"?bT:a9,i=n.map(o=>as(o,r));return{status:f(e,"status")??"ok",resultCount:n.length,returnedResultCount:i.length,warnings:e.warnings,omittedResultCount:Math.max(0,n.length-i.length),results:i}}function c9(e,t){let n=t==="concise"?3:5,r=L(e,"parsedSkill"),i=r?L(r,"frontmatter"):void 0,o=L(e,"license"),s=[gw("skill.body",r?.body),gw("skill.frontmatter",r?.rawFrontmatter),gw("license.text",o?.text)].filter(d=>d!==void 0),a=B0(e.issues,n),l=B0(e.licenseIssues,n),c=L(e,"evalReadiness"),u=L(e,"aiReview");return W({status:e.status,profile:e.profile,validationProfile:e.validationProfile??e.profile,ingestible:e.ingestible,valid:e.valid,publishReadiness:e.publishReadiness,publishReadinessSummary:e.publishReadinessSummary,publishReadinessFinding:e.publishReadinessFinding,warnings:e.warnings,nextAction:e.nextAction,nextStep:e.nextStep,stats:e.stats,excludedFromRuntime:e.excludedFromRuntime,skill:i?as(i,t==="concise"?["name"]:["name","description","compatibility","license"]):void 0,license:o?as(o,t==="concise"?["status","identifier"]:["status","identifier","detectedIdentifier","declarationSource","filePath","textSha256"]):void 0,issueCount:Array.isArray(e.issues)?e.issues.length:0,returnedIssueCount:a.length,omittedIssueCount:Math.max(0,(Array.isArray(e.issues)?e.issues.length:0)-a.length),issues:a,licenseIssues:l.length>0?l:void 0,evalReadiness:c?as(c,t==="concise"?["status","label","origin","confidence","evidenceFileCount","evaluation","nextAction"]:["schemaVersion","status","label","origin","confidence","creatorReviewed","evidenceFileCount","runtimeFileCount","artifactDigest","evaluation","summaryEnvelope","improvements","recommendedCommands","nextAction"]):void 0,securityReport:e.securityReport,aiReview:u?as(u,["status","reasonCode","message","nextAction","nextStep"]):void 0,rawContent:s})}function B0(e,t){return Array.isArray(e)?e.slice(0,t).map(n=>O(n)?as(n,["severity","code","message","path","nextAction","nextStep"]):n):[]}function gw(e,t){if(typeof t=="string")return{field:e,characterCount:t.length,sha256:`sha256:${me("sha256").update(t).digest("hex")}`}}function as(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function u9(e,t){let n=e.toLowerCase();return n==="submission_incomplete"||n==="partial_success"?"partial_success":n==="blocked"||n==="action_required"?n:n==="pass"||n.includes("dry")?"dry_run_passed":n.includes("created")?"created":n.includes("updated")||n.includes("configured")||n.includes("synced")?"updated":n.includes("revoked")||n.includes("removed")||n.includes("disconnected")?"removed":n.includes("approval")||n.includes("handoff")||O(t)&&t.handoff?"human_handoff":"ok"}var d9="<redacted>";function Sf(e,t=!1){if(typeof e=="string")return zl(t?$t(e):e);if(Array.isArray(e))return e.map(r=>Sf(r,t));if(!O(e))return e;let n={};for(let[r,i]of Object.entries(e))n[r]=f9(r)?d9:Sf(i,t);return n}function f9(e){let t=e.replace(/[^a-z0-9]/giu,"").toLowerCase();return t==="devicecode"||t==="usercode"||t==="verificationcode"||t==="recoverycode"||t==="onetimecode"||t==="password"||t==="clientsecret"||t==="privatekey"||t==="apikey"||t==="rawapikey"||t==="accesstoken"||t==="refreshtoken"||t==="bearertoken"||t==="mcptoken"||t.endsWith("secret")?!0:t.endsWith("token")&&t!=="tokenprefix"&&t!=="verificationtoken"}function p9(e,t,n){let r=n?.renderMode??zi([],{},{stdinIsTty:!1,stdoutIsTty:!1,stderrIsTty:!1}).mode,i=de(n);if(O(e)){if(t.includes("local install records."))return[t,...lt(e.results).map(c=>`${f(c,"skillSlug")} ${f(c,"version")??""} | agents=${Dt(c).join(",")} | scope=${f(c,"scope")??"local"} | path=${f(c,"materializedSkillRoot")??f(c,"bundlePath")??"unavailable"} | ${f(c,"status")??"installed"}`)].join(`
|
|
1221
|
+
`);if(K(e,"pendingPrice")!==void 0)return["Price change pending admin review",`Live price: ${le(K(e,"priceCents")??0,"usd")}`,`Pending price: ${le(K(e,"pendingPrice"),"usd")}`,r_(f(e,"reasonCode")),f(e,"nextStep")].filter(Boolean).join(`
|
|
1222
|
+
`);if(t==="Spending loaded."){let c=f(e,"currency")??"usd",u=[`Total spent: ${le(K(e,"totalSpentCents")??0,c)}`,`Refunded: ${le(K(e,"refundedCents")??0,c)} (${K(e,"refundedCount")??0})`,`Successful purchases: ${K(e,"successfulPurchaseCount")??0}`],d=L(e,"spentByCurrency"),p=Object.entries(d??{}).filter(m=>typeof m[1]=="number"&&m[1]!==0);if(p.length>1){u.push("By currency");for(let[m,g]of p)u.push(`${m.toUpperCase()}: ${le(g,m)}`)}return u.join(`
|
|
1223
|
+
`)}if(["Purchases loaded.","Purchase status loaded.","Invoice loaded."].includes(t))return m9(e,t,i,r.detail==="full");if(t==="Skill loaded.")return _E(e,r);if(t==="Status loaded."&&N0(e))return b9(e,t,i);if(t==="Doctor checks loaded."&&N0(e))return _9(e,t,i);if(t==="Withdrawal requested.")return zv(e);if(t==="Payout setup link created."){let c=uT(e);if(c)return DC(c,L(e,"accountLink")?.expiresAt)}if(t==="Creator payout profile loaded."||O(e.profile)&&"minimumWithdrawalAmountCents"in e.profile)return j9(e,"Creator payout profile loaded.",i);if(t==="Creator earnings loaded."||t==="Earnings loaded."||typeof e.withdrawableBalanceCents=="number"&&!Array.isArray(e.results))return U9(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded."||typeof e.withdrawableBalanceCents=="number"&&Array.isArray(e.results))return q9(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return w9(e,t,i);if(t==="Reviews loaded.")return y9(e,t,i);if(t==="Categories loaded.")return h9(e,t,i)}let o=O(e)?f(e,"status")??"ok":"ok",s=O(e)?L(e,"liveRelease"):null;s&&typeof s.summary=="string"&&(t=`${t} ${s.summary}`);let a=Qv({status:o,summary:t,data:e,next:O(e)?g9(e):[],links:[],warnings:O(e)&&Array.isArray(e.warnings)?e.warnings.filter(c=>typeof c=="string"):[]},r),l=O(e)?L(e,"submission")??L(e,"analytics")??e:null;return l?.listingStatus==="delisted"?`${a}
|
|
1224
|
+
|
|
1225
|
+
Delisted on ${f(l,"delistedAt")??"an unrecorded date"}; existing buyers keep access.`:a}function m9(e,t,n,r){let i=typeof e.purchaseId=="string"?[e]:lt(e.results??e.purchases),o=[t];i.length||o.push("No purchases found.");for(let s of i){let a=f(s,"currency")??"usd",l=y=>`${a==="usd"?"US$":a==="gbp"?"\xA3":`${a.toUpperCase()} `}${(y/100).toFixed(2)}`,u=s.status==="disputed_lost"||s.chargedBack===!0?`Charged back by your bank (net ${l(0)})`:s.status==="disputed"?TC:["pending","expired"].includes(String(s.status))?"No charge":"",d=f(s,"skillSlug")??f(s,"skillName")??f(s,"packCode")??"unknown";if(t==="Purchases loaded."&&!r){o.push(`${f(s,"purchaseId")??"unknown"} | ${d} | ${f(s,"status")??"unknown"} | ${l(K(s,"amountCents")??0)}${u?` | ${u}`:""}`);continue}o.push("",`${n.label("Purchase")}: ${f(s,"purchaseId")??"unknown"}`),!f(s,"skillSlug")&&d!=="unknown"&&o.push(`${n.label("Item")}: ${d}`);for(let[y,w]of[["skillSlug","Skill"],["version","Version"],["status","Status"]]){let b=f(s,y);b&&o.push(`${n.label(w)}: ${b}`)}let p=f(s,"issuedAt");t==="Invoice loaded."&&p&&o.push(`${n.label("Issued")}: ${zn(p)}`);for(let[y,w]of[["amountCents","Amount"],["refundAmountCents",s.status==="refund_requested"?"Requested refund":"Refund"],["netAmountCents","Net amount"]]){let b=K(s,y);b!==void 0&&o.push(`${n.label(w)}: ${l(b)}`)}let m=f(s,"statementDescription");t==="Invoice loaded."&&m&&o.push(m),u&&!(t==="Invoice loaded."&&m?.includes(u))&&o.push(u),s.status==="refund_requested"&&o.push("Refund in progress");let g=f(s,"refundNote");g&&o.push(g);let h=f(s,"refundedAt");if(h){let y=Date.parse(h),w=Number.isFinite(y)?new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC"}).format(y)+" UTC":h;o.push(`${n.label("Refunded on")}: ${w}`)}}return o.join(`
|
|
1226
|
+
`)}function g9(e){let t=tb(e);return t.length>0?t:e.valid===!0?[{id:"creator-submit-dry-run",kind:"command",label:"Preview the submission without publishing",command:{executable:"skills-layer",args:["creator","submit","<path>","--dry-run"]},safeToAutoRun:!0,requiresHuman:!1,safety:"read-only"}]:[]}function h9(e,t,n){let r=lt(e.results??e.categories??e.data),i=[`${n.ok("OK")} ${t}`,"",n.section(`Categories (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No categories returned.")}`),i.join(`
|
|
1227
|
+
`)):(r.slice(0,Ue).forEach((o,s)=>{let a=f(o,"slug")??f(o,"category")??f(o,"name")??`category-${s+1}`,l=f(o,"name")??a,c=o.count;i.push(`${s+1}. ${IT(l)}`);let u=[a?`slug: ${a}`:void 0,c!==void 0?`count: ${Pt("count",c)}`:void 0].filter(d=>!!d);u.length>0&&i.push(` ${u.join("; ")}`)}),r.length>Ue&&i.push(` ${n.muted(`... ${r.length-Ue} more`)}`),i.join(`
|
|
1228
|
+
`))}function y9(e,t,n){let r=lt(e.reviews??e.results),i=[`${n.ok("OK")} ${t}`,"",n.section(`Reviews (${r.length})`)];return r.length===0&&i.push(` ${n.muted("No reviews yet.")}`),r.forEach((o,s)=>{let a=f(o,"reviewId")??f(o,"id"),c=f(o,"skillSlug")??f(o,"slug")??f(o,"skill")??a??`Review ${s+1}`,u=o.rating??o.score,d=f(o,"status"),p=f(o,"updatedAt")??f(o,"createdAt"),m=[a?`review: ${a}`:void 0,u!=null?`rating: ${Pt("rating",u)}`:void 0,d?`status: ${d}`:void 0,p?`updated: ${p}`:void 0].filter(h=>!!h);i.push(`${s+1}. ${c}`),m.length>0&&i.push(` ${m.join("; ")}`);let g=f(o,"feedback")??f(o,"comment")??f(o,"message");g&&i.push(` ${n.label("feedback")}: ${ys(g)}`)}),i.join(`
|
|
1229
|
+
`)}function w9(e,t,n){let r=L(e,"decision"),i=L(e,"enforcement"),o=L(e,"auditEvent"),s=Ce(r,"status")??Ce(i,"status")??"unknown",a=Ce(i,"actionType")??Ce(o,"actionType")??"action",l=Ce(r,"capability")??Ce(i,"capability")??"not specified",c=Ce(r,"reasonCode")??Ce(i,"reasonCode")??"not specified",u=Ce(r,"message")??Ce(i,"message")??"Guardian policy resolved this action.",d=Ce(o,"skillSlug")??"unknown",p=Ce(o,"version")??"unknown",m=kl(i,"canExecute"),g=kl(i,"auditRequired"),h=kl(i,"telemetryRequired"),y=s==="blocked"?"BLOCKED":s==="allowed"?"ALLOWED":"WARNING",w=[`${n.ok("OK")} ${t}`,"",n.section(`${y} ${v9(a)}`),` ${n.label("Skill")}: ${d}`,` ${n.label("Version")}: ${p}`,` ${n.label("Capability")}: ${l}`,` ${n.label("Reason")}: ${u}`,` ${n.label("Reason code")}: ${c}`,` ${n.label("Can execute")}: ${m===!0?"yes":"no"}`,` ${n.label("Audit required")}: ${g===!1?"no":"yes"}`,` ${n.label("Cloud telemetry")}: ${h===!0?"yes":"no"}`,"",n.section("Next")];return s==="blocked"?w.push(` ${n.arrow} Do not run this action.`,` ${n.arrow} Review \`skills-layer trust ${d}\`.`,` ${n.arrow} Run \`skills-layer guardian incident --skill ${d} --version ${p} --path <installed-skill-path> --reason "<reason>"\` if this was unexpected.`):w.push(` ${n.arrow} Continue only with the action Guardian evaluated.`,` ${n.arrow} Re-run guardian check if the action changes.`),w.join(`
|
|
1230
|
+
`)}function kl(e,t){if(O(e))return typeof e[t]=="boolean"?e[t]:void 0}function Ce(e,t){return O(e)?f(e,t):void 0}function v9(e){return e.split(/[_-]+/u).filter(Boolean).map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function N0(e){return!!(L(e,"backend")&&L(e,"auth")&&Array.isArray(e.checks))}function b9(e,t,n){let r=[`${n.ok("OK")} ${t}`,"",n.section("Readiness")],i=f(e,"summary");i&&r.push(` ${i}`);let o=L(e,"backend"),s=o?A9(o):void 0;s&&r.push(` ${n.label("Backend")}: ${s}`);let a=L(e,"auth"),l=a?x9(a):void 0;l&&r.push(` ${n.label("Account")}: ${l}`);let c=a?K(a,"personalModeCount"):void 0,u=a?K(a,"enterpriseWorkspaceCount")??K(a,"workspaceCount"):void 0,d=a?K(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?K(a,"libraryCount"):void 0;p!==void 0&&r.push(` ${n.label("Owned skills")}: ${p}`);let m=L(e,"localRuntime"),g=m?L(m,"guardian"):void 0,h=m?L(m,"mcp"):void 0;(g||h)&&(r.push("",n.section("Local runtime")),g&&r.push(` ${n.label("Guardian")}: ${Ce(g,"enforcementLayer")??"not_installed"}`,` ${n.label("Strict pre-action blocking")}: ${kl(g,"strictPreActionBlocking")===!0?"yes":"no"}`),h&&r.push(` ${n.label("MCP")}: ${kl(h,"configured")===!0?"configured":"not configured"}`));let y=_T(e);return y.length>0&&r.push("",n.section("Next"),...y.map(w=>` ${n.arrow} ${w}`)),r.push(` ${n.arrow} Run \`skills-layer doctor\` for diagnostics.`),r.join(`
|
|
1231
|
+
`)}function _9(e,t,n){let r=f(e,"status"),i=[r==="action_required"?"Action required: Doctor found a problem to fix.":`${n.ok("OK")} ${t}`,"",n.section("Diagnostics")],o=f(e,"summary");o&&i.push(` ${o}`),r&&i.push(` ${n.label("Status")}: ${r}`);let s=d=>{let p=f(d,"status");return M0(p)?0:p==="pass"?2:1},a=kT(e).map((d,p)=>({check:d,order:p})).sort((d,p)=>s(d.check)-s(p.check)||d.order-p.order).map(({check:d})=>d),l=a.filter(d=>M0(f(d,"status"))),c=a.filter(d=>f(d,"status")!=="pass");i.push(l.length===0?" No blocking issues found.":` ${l.length} ${l.length===1?"check needs":"checks need"} attention.`),l.length===0&&c.length>0&&i.push(` Advisory checks needing attention: ${c.length}.`),i.push("",n.section(`Checks (${a.length})`)),a.length===0&&i.push(` ${n.muted("No checks returned by the backend.")}`),a.forEach((d,p)=>{let m=f(d,"status")??"unknown",g=f(d,"title")??f(d,"id")??`Check ${p+1}`;i.push(`${p+1}. ${n.label(`[${m}] ${g}`)}`);let h=f(d,"summary");h&&i.push(` ${h}`);let y=f(d,"why");if(y&&i.push(` ${n.label("Why")}: ${y}`),m!=="pass"){let w=f(d,"nextStep");w&&i.push(` ${n.label("Fix")}: ${w}`);let b=f(d,"recommendedCommand");b&&i.push(` ${n.label("Try")}: ${b}`)}});let u=_T(e);return u.length>0&&i.push("",n.section("Next"),...u.map(d=>` ${n.arrow} ${d}`)),i.join(`
|
|
1232
|
+
`)}function k9(e,t,n,r){let i=[`${n.ok("OK")} ${t}`],o=rn(e,"requestedSlugs");o&&o.length>0&&i.push("",n.section("Requested"),` ${o.join(", ")}`);let s=lt(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=Kw(u)??`Skill ${d+1}`;i.push(`${d+1}. ${p}`),i.push(...Jv(u).map(h=>` ${h}`));let m=S9(u);m&&i.push(` ${m}`);let g=xT(u);g&&i.push(` ${n.label("summary")}: ${r?g.replace(/\s+/gu," ").trim():ys(g)}`)});let a=lt(e.missing);a.length>0&&(i.push("",n.section(`Missing (${a.length})`)),a.forEach((u,d)=>{let p=f(u,"slug")??f(u,"skillSlug")??Kw(u)??`Entry ${d+1}`,m=f(u,"reason")??f(u,"status");i.push(`${d+1}. ${m?`${p} - ${m}`:p}`)}));let l=rn(e,"guidance")??ps(e.guidance);l.length>0&&i.push("",n.section("Guidance"),...l.slice(0,3).map(u=>` ${n.arrow} ${ys(u)}`));let c=C9(s);return c.length>0&&i.push("",n.section("Next"),...c.map(u=>` ${n.arrow} ${u}`)),i.join(`
|
|
1233
|
+
`)}function S9(e){let t=L(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}: ${Pt(String(s),a)}`]).join("; ")}function C9(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 A9(e){let t=f(e,"edition"),n=f(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function x9(e){let t=f(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t==="api_key_expired"?"sign-in key expired":t;let n=f(e,"email"),r=rn(e,"roles");return n&&r&&r.length>0?`${n} (${r.join(", ")})`:n??f(e,"role")}function _T(e){let t=[],n=f(e,"recommendedCommand");n&&t.push(n);let r=f(e,"nextStep");return r&&t.push(r),t}function kT(e){return Array.isArray(e.checks)?e.checks.filter(O):[]}function M0(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function lt(e){return Array.isArray(e)?e.filter(O):[]}function ps(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function I9(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 R9={"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 P9(e){let t=ps(e.capabilities);return{status:"ok",edition:f(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:R9[n]??$f(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function E9(e,t){let n=v(e);if(!n)return;let r=Number(n);return!Number.isInteger(r)||r<=0?P("help optimize-tokens --max-characters must be a positive integer.",t):r<120||r>4e3?P("help optimize-tokens --max-characters must be between 120 and 4000.",t):r}function D9(e,t,n){let r=de(n),i=L(e,"validation")??e,o=L(i,"parsedSkill")??L(e,"parsedSkill"),s=o?L(o,"frontmatter"):void 0,a=f(e,"skillSlug")??(s?f(s,"name"):void 0),l=i.valid===!0||e.valid===!0,c=ms(i,e,"issues").filter(x=>!O(x)||x.severity!=="warning"),u=ms(e,i,"warnings"),d=ms(i,e,"advice"),p=L(i,"stats")??L(e,"stats"),m=f(e,"publishReadiness"),g=L(e,"publishReadinessFinding"),h=g?` (${f(g,"ruleId")??f(g,"code")}: ${f(g,"message")})`:"",y=l&&m==="blocked",w=[l?y?"Structure valid; security review: blocked.":`${r.ok("OK")} Validation complete${u.length?" with warnings":""}.`:"Validation failed."];y?w.push(` ${r.label("Security")}: BLOCKED - this skill will not be published${h}`):l&&m==="needs_admin_review"&&w.push(` ${r.label("Security")}: MANUAL REVIEW - an administrator must approve it after submission${h}`),w.push(` ${r.label("Readiness")}: ${l?y?"blocked":m==="needs_admin_review"?"needs admin review after submission":"ready for dry-run submission":"needs changes before submission"}`),w.push("",...of("Warnings",u,r,"No warnings returned.")),w.push("",r.section("Bundle")),w.push(` ${r.label("Path")}: ${t}`),a&&w.push(` ${r.label("Skill")}: ${a}`),w.push("",r.section("Checks")),w.push(` ${r.arrow} SKILL.md structure and frontmatter`),w.push(` ${r.arrow} Required bundle files and supported directories`),w.push(` ${r.arrow} Secret hygiene, unsafe script signals, and trust-review readiness`),w.push(` ${r.arrow} Trigger quality inputs for should-trigger / should-not-trigger testing`);let b=L(e,"evalReadiness");if(b){let x=L(b,"summaryEnvelope"),C=Array.isArray(x?.statuses)?x.statuses.map(D=>String(D)).join(", "):void 0;w.push("",r.section("Effectiveness Eval")),w.push(` ${r.label("Posture")}: ${f(b,"label")??f(b,"status")??"limited"}`),w.push(` ${r.label("Origin")}: ${f(b,"origin")??"inferred"}`),w.push(` ${r.label("Evaluation")}: not run`),w.push(` ${r.label("Artifact digest")}: ${f(b,"artifactDigest")??"unavailable"}`),b.runtimeFileCount!==void 0&&w.push(` ${r.label("Runtime files")}: ${Pt("runtimeFileCount",b.runtimeFileCount)}`),b.evidenceFileCount!==void 0&&w.push(` ${r.label("Evidence files excluded")}: ${Pt("evidenceFileCount",b.evidenceFileCount)}`),w.push(` ${r.label("Submit envelope")}: mandatory${C?` (${C})`:""}`)}if(p){let x=p.fileCount??p.files??e.fileCount,C=p.bodyWordCount??p.bodyWords??e.bodyWordCount;w.push("",r.section("File Summary")),x!==void 0&&w.push(` ${r.label("File count")}: ${Pt("fileCount",x)}`),C!==void 0&&w.push(` ${r.label("Body words")}: ${Pt("bodyWordCount",C)}`)}let _=L(e,"securityReport");_&&(w.push("",r.section("Security")),w.push(` ${r.label("Recommendation")}: ${f(_,"recommendation")??"unknown"}`),w.push(...of("Findings",Array.isArray(_.findings)?_.findings:[],r,"No security findings returned.")));let I=L(e,"aiReview");if(I){w.push("",r.section("AI Review")),w.push(` ${r.label("Status")}: ${f(I,"status")??"unknown"}`);let x=f(I,"message");x&&w.push(` ${x}`);let C=f(I,"nextStep");C&&w.push(` ${r.arrow} ${C}`)}return w.push("",...of("Issues",c,r,"No blocking issues found.")),w.push("",...of("Advice",d,r,"No extra advice returned.")),w.push("",r.section("Next")),l?(w.push(` ${r.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),w.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`)):w.push(` ${r.arrow} Fix the listed issues, then run skills-layer validate ${t}`),w.join(`
|
|
1234
|
+
`)}function ms(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 of(e,t,n,r){let i=[n.section(`${e} (${t.length})`)];return t.length===0?(i.push(` ${n.muted(r)}`),i):(t.slice(0,Ue).forEach((o,s)=>{i.push(`${s+1}. ${ST(o)}`)}),i)}function ST(e){if(!O(e))return Pt("",e);let t=f(e,"message")??f(e,"title")??f(e,"code")??f(e,"path")??Bl(e);return e.severity==="warning"?`${f(e,"code")??"warning"}: ${t}${e.nextStep?` ${e.nextStep}`:""}`:t||"Details available with --json"}function T9(e,t,n){let r=de(n),i=$9(e),o=L9(e),s=[`${r.ok("OK")} Trigger preview complete (keyword-overlap lint; no agent was run, so these are not trigger rates).`,"",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,Ue).forEach((l,c)=>{s.push(`${c+1}. ${O9(l,c)}`)}),s.push("",r.section(`Guidance (${o.length})`)),o.length===0&&s.push(` ${r.muted("No extra trigger guidance returned.")}`),o.slice(0,Ue).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(`
|
|
1235
|
+
`)}function $9(e){return[...lt(e.promptResults),...lt(e.results),...lt(e.shouldTriggerResults),...lt(e.shouldNotTriggerResults),...lt(e.paraphraseResults)]}function L9(e){let t=ps(e.guidance),n=lt(e.guidance).map(r=>ST(r));return[...t,...n]}function O9(e,t){let n=f(e,"prompt")??f(e,"text")??f(e,"input")??`Prompt ${t+1}`,r=F9(e),i=B9(e),o=N9(e),s=e.keywordOverlap,a=f(e,"reason")??f(e,"explanation")??f(e,"message");return[`"${ys(n)}"`,r?`expected: ${r}`:void 0,i?`actual: ${i}`:void 0,o,s!==void 0?`keyword overlap: ${Pt("keyword overlap",s)}`:void 0,a?`reason: ${ys(a)}`:void 0].filter(l=>!!l).join("; ")}function F9(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 B9(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 N9(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":f(e,"status")}function M9(e,t,n,r){let i=de(r),o=f(e,"skillSlug")??$e(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(`
|
|
1236
|
+
`)}function j9(e,t,n){let r=L(e,"profile")??e,i=yw(r,"requirementsCurrentlyDue"),o=yw(r,"requirementsPastDue"),s=yw(r,"requirementsPendingVerification"),a=["payouts","Enabled"].join(""),l=r.readyForPayouts??r[a],c=l===!0,u=r.coolingActive===!0,d=L(r,"bank"),p=[`${n.ok("OK")} ${t}`,"",n.section("Payout Profile")];return p.push(` ${n.label("Bank")}: ${d?`ending ${f(d,"last4")} (${f(d,"currency")?.toUpperCase()})`:"No stored bank destination yet"}`),d&&p.push(` ${Hv(f(d,"changedAt"))}`),p.push(` ${n.label(Kv(f(r,"destinationCoolingEndsAt"),r.coolingActive))}: ${zn(f(r,"destinationCoolingEndsAt"))}`),p.push(` ${n.label("Ready for payouts")}: ${j0(l)}`),p.push(` ${n.label("Minimum withdrawal")}: ${V9(r)}`),p.push(` ${n.label("Status")}: ${vw(f(r,"status"))}`),p.push(` ${n.label("Account details submitted")}: ${j0(r.detailsSubmitted)}`),p.push(` ${n.label("Currency")}: ${vw(f(r,"currency")?.toUpperCase())}`),p.push(` ${n.label("Country")}: ${vw(f(r,"country")?.toUpperCase())}`),p.push(` ${n.label("Updated at")}: ${zn(f(r,"updatedAt"))}`),p.push("",n.section("Requirements")),p.push(` ${n.label("Currently due")}: ${ww(i)}`),p.push(` ${n.label("Past due")}: ${ww(o)}`),p.push(` ${n.label("Pending verification")}: ${ww(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(`
|
|
1237
|
+
`)}function U9(e,t,n){let r=zw(e),i=ve(e,"withdrawableBalanceCents"),o=Mf(e),s=[`${n.ok("OK")} ${t}`,"",n.section("Earnings Summary")];s.push(` ${n.label("Withdrawable now")}: ${le(Math.max(0,i),r)}`),o&&s.push(` ${o}`),s.push(` ${n.label("Gross sales")}: ${le(ve(e,"successfulSalesCents"),r)}`),s.push(` ${n.label("Platform fees")}: ${le(ve(e,"platformFeeCents"),r)}`),s.push(` ${n.label("Refunds requested")}: ${le(ve(e,"refundRequestedCents"),r)}`),s.push(` ${n.label("Refunded")}: ${le(ve(e,"refundedCents"),r)}`),(ve(e,"disputedCents")>0||$r(e,"disputedCount")>0)&&s.push(` ${n.label("Disputed (held)")}: ${le(ve(e,"disputedCents"),r)} (${$r(e,"disputedCount")})`),(ve(e,"chargebackCents")>0||$r(e,"chargebackCount")>0)&&s.push(` ${n.label("Charged back")}: ${le(ve(e,"chargebackCents"),r)} (${$r(e,"chargebackCount")})`),ve(e,"reversedCreatorShareCents")>0&&s.push(` ${n.label("Creator share reversed")}: \u2212${le(ve(e,"reversedCreatorShareCents"),r)}`),ve(e,"disputeFeeDebitsCents")>0&&s.push(` ${n.label("Dispute fees charged")}: \u2212${le(ve(e,"disputeFeeDebitsCents"),r)}`),ve(e,"estimatedAvailableCents")<0&&s.push(" Negative balance: future earnings repay this debt before payouts resume."),$r(e,"disputeFeeReviewCount")>0&&s.push(" Dispute fee reconciliation is pending; payouts are on hold."),s.push(` ${n.label("Estimated after holds clear")}: ${le(ve(e,"estimatedAvailableCents"),r)}`),s.push(` ${n.label("Held balance")}: ${le(ve(e,"heldBalanceCents"),r)}`);let a=f(e,"nextScheduledReleaseAt");return a&&s.push(` ${n.label("Next scheduled release")}: ${zn(a)}`),s.push(` ${n.label("Refund exposure")}: ${le(ve(e,"refundExposureCents"),r)}`),s.push("",n.section("Activity")),s.push(` ${n.label("Successful purchases")}: ${$r(e,"successfulPurchaseCount")}`),s.push(` ${n.label("Refund requests")}: ${$r(e,"refundRequestedCount")}`),s.push(` ${n.label("Pending payouts")}: ${le(ve(e,"pendingPayoutCents"),r)}`),s.push(` ${n.label("Completed payouts")}: ${le(ve(e,"completedPayoutCents"),r)}`),s.push("",n.section("Guidance")),i>0?(s.push("1. You have a withdrawable balance available."),s.push("2. Confirm payout setup is ready before requesting withdrawal.")):(s.push(o?"1. Withdrawals resume once future earnings cover the recovery amount above and any holds clear.":"1. No withdrawable balance yet."),o||s.push($r(e,"successfulPurchaseCount")>0?`2. ${le(ve(e,"heldBalanceCents"),r)} held${f(e,"nextScheduledReleaseAt")?` until the next scheduled release at ${zn(f(e,"nextScheduledReleaseAt"))}`:"; release timing depends on maturity and outstanding holds"}.`:"2. Sales will appear here after paid purchases settle.")),s.push("",n.section("Next")),i>0&&s.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${i}`),s.push(` ${n.arrow} skills-layer creator payout-profile`),s.push(` ${n.arrow} skills-layer creator payouts`),s.join(`
|
|
1238
|
+
`)}function q9(e,t,n){let r=Array.isArray(e.results)?e.results:[],i=zw(e,r),o=ve(e,"withdrawableBalanceCents"),s=[`${n.ok("OK")} ${t}`,"",n.section("Payout History")];s.push(` ${n.label("Withdrawable now")}: ${le(Math.max(0,o),i)}`);let a=Mf(e);return a&&s.push(` ${a}`),s.push(` ${n.label("Pending payouts")}: ${hw(e,"pendingPayoutCents",i)}`),s.push(` ${n.label("Completed payouts")}: ${hw(e,"completedPayoutCents",i)}`),s.push("",n.section(`Requests (${r.length})`)),r.length===0?s.push(` ${n.muted("No payout requests yet.")}`):(r.slice(0,Ue).forEach((l,c)=>{if(!O(l)){s.push(`${c+1}. ${Pt("",l)}`);return}let u=zw(l,void 0,i),d=f(l,"payoutId")??f(l,"id")??`Payout ${c+1}`,p=f(l,"status")??"unknown",m=hw(l,"amountCents",u),g=f(l,"requestedAt"),h=f(l,"completedAt"),y=f(l,"reason");s.push(`${c+1}. ${d}`),s.push(` ${n.label("Amount")}: ${m}; ${n.label("Status")}: ${Gv(p)}`);let w=Uv(l);w&&s.push(` ${w}`),g&&s.push(` ${n.label("Requested")}: ${zn(g)}`),h&&s.push(` ${n.label(p==="failed"?"Returned":"Completed")}: ${zn(h)}`),y&&s.push(` ${n.label("Reason")}: ${y}`)}),r.length>Ue&&s.push(` ${n.muted(`... ${r.length-Ue} more`)}`)),s.push("",n.section("Guidance")),r.length===0?s.push("1. Payouts appear here after you request a withdrawal."):s.push("1. Use this history to track requested, processing, paid, or failed payouts."),s.push("2. Check payout profile if setup or verification looks incomplete."),s.push("",n.section("Next")),o>0&&s.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${o}`),s.push(` ${n.arrow} skills-layer creator earnings`),s.push(` ${n.arrow} skills-layer creator payout-profile`),s.join(`
|
|
1239
|
+
`)}function zw(e,t,n="USD"){let r=f(e,"currency");if(r)return r.toUpperCase();let i=t?.find(O);if(i){let o=f(i,"currency");if(o)return o.toUpperCase()}return n}function ve(e,t){return K(e,t)??0}function $r(e,t){return K(e,t)??0}function hw(e,t,n){return le(ve(e,t),n)}function yw(e,t){return(rn(e,t)??[]).map(n=>n.replace(/[._-]+/gu," "))}function ww(e){return e.length>0?e.join(", "):"none"}function j0(e){return e===!0?"yes":e===!1?"no":"unknown"}function vw(e){return e??"none"}function V9(e){let t=K(e,"minimumWithdrawalAmountCents");return t===void 0?"none":le(t,"usd")}function de(e){let t=e?.renderMode??zi([],{},{stdinIsTty:!1,stdoutIsTty:!1,stderrIsTty:!1}).mode,n=Hl(t);return{ok:n.success,section:n.heading,label:n.label,muted:n.muted,arrow:n.info("->")}}function G9(e,t){let n=[],r=H9(e,t);r.length>0&&n.push(...r);let i=z9(e,t);i.length>0&&n.push(...i);for(let[o,s]of Y9(e))if(Array.isArray(s))n.push(...K9(o,s,t));else if(O(s)){let a=Bl(s);a&&n.push(` ${t.label(Hw(o))}: ${a}`)}else n.push(` ${t.label(Hw(o))}: ${Pt(o,s)}`);return n}function z9(e,t){let n=L(e,"effectiveness");if(!n)return[];let r=f(n,"label"),i=f(n,"latestSummaryStatus"),o=K(n,"evidenceCount"),s=L(n,"score"),a=s?K(s,"overallScore"):void 0,l=s?K(s,"effectiveScorePercent"):void 0,c=s?L(s,"components"):void 0,u=c?K(c,"passRate"):void 0,d=c?K(c,"coverageRatio"):void 0;if(!r&&i===void 0&&o===void 0&&a===void 0)return[];let p=[t.section("Effectiveness")];if(r&&p.push(` ${t.label("Label")}: ${r}`),i&&p.push(` ${t.label("Latest summary")}: ${i}`),o!==void 0&&p.push(` ${t.label("Evidence count")}: ${o}`),Array.isArray(n.assessmentCoverage))for(let m of n.assessmentCoverage)O(m)&&typeof m.assessedRanges=="number"&&typeof m.availableRanges=="number"&&typeof m.untestedRanges=="number"&&p.push(` ${t.label("Assessment scope")}: ${m.assessedRanges} of ${m.availableRanges} source ranges assessed; ${m.untestedRanges} untested. Score applies to the sample.`);return l!==void 0?p.push(` ${t.label("Effectiveness rating")}: ${U0(l)}`):a!==void 0&&p.push(` ${t.label("Effectiveness rating")}: ${U0(a*100)}`),u!==void 0&&p.push(` ${t.label("Pass rate")}: ${u}`),d!==void 0&&p.push(` ${t.label("Coverage")}: ${d}`),p}function U0(e){let t=Math.round(e*10)/10;return`${Number.isInteger(t)?t.toFixed(0):t.toFixed(1)}%`}function K9(e,t,n){let r=Z9(e),i=[n.section(`${r} (${t.length})`)];return t.length===0?(i.push(` ${n.muted("No entries.")}`),i):(t.slice(0,Ue).forEach((o,s)=>{i.push(...CT(o,s,n))}),t.length>Ue&&i.push(` ${n.muted(`... ${t.length-Ue} more`)}`),i)}function CT(e,t,n){if(!O(e))return[`${t+1}. ${Pt("",e)}`];let r=Kw(e)??ue(Bl(e))??`Item ${t+1}`,i=[`${t+1}. ${r}`],o=xT(e);o&&i.push(` ${o}`);let s=Bl(e);return s&&i.push(` ${s}`),i}function H9(e,t){let n=R3(e,t);if(n.length>0)return n;let r=L(e,"capabilityProfile"),i=r?f(r,"runtimeRisk"):void 0;return i?[t.section("Trust"),` ${t.label("Runtime risk")}: ${i}`]:[]}function W9(e,t,n){let r=de(n),i=f(e,"skillSlug")??t,o=f(e,"runtimeRisk")??(L(e,"capabilityProfile")?f(L(e,"capabilityProfile"),"runtimeRisk"):void 0),s=[`${r.ok("OK")} Creator security report loaded.`,"",r.section("Creator Security")];o&&s.push(` ${r.label("Runtime risk")}: ${o}`);let a=f(e,"recommendation");a&&s.push(` ${r.label("Recommendation")}: ${a}`),s.push(` ${r.label("Skill")}: ${i}`);let l=f(e,"version");l&&s.push(` ${r.label("Version")}: ${l}`);let c=["semantic","review","no","reviewable","findings"].join("_"),u=ps(e.reviewDegradedReasons).includes(c),d=ps(e.trustBadges).filter(w=>w==="capability-mismatch"),p=ps(e.trustBadges).filter(w=>w!=="capability-mismatch");(u||d.length>0)&&(s.push("",r.section("Creator Notes")),u&&s.push("1. Semantic review was not needed because there were no reviewable findings."),d.forEach((w,b)=>{s.push(`${u?b+2:b+1}. ${w==="capability-mismatch"?"Capability declaration needs review.":w}`)})),p.length>0&&(s.push("",r.section(`Trust badges (${p.length})`)),p.slice(0,Ue).forEach((w,b)=>s.push(`${b+1}. ${w}`)));let m=Array.isArray(e.findings)?e.findings:[];s.push("",r.section(`Findings (${m.length})`)),m.length===0?s.push(` ${r.muted("No entries.")}`):m.slice(0,Ue).forEach((w,b)=>{s.push(...CT(w,b,r))}),s.push("",r.section("Next"));let g=L(e,"artifactReviewDecision"),h=(g?f(g,"reasonCode"):void 0)??f(e,"reasonCode"),y=(g?f(g,"status"):void 0)??f(e,"status");return h==="content_adjudication_insufficient_evidence"||h==="security_manual_review_required"?s.push(` ${r.arrow} No action needed while an admin reviews it; creator status shows the decision.`):y==="approved"||y==="available"?s.push(` ${r.arrow} No action is needed: this version's security review is approved.`):h==="dependency_lockfile_required"?(s.push(` ${r.arrow} Add package-lock.json or npm-shrinkwrap.json (or pin Python requirements with ==), then submit again:`),s.push(` ${r.arrow} skills-layer creator submit-version ${i} <path-or-source> --version ${l??"<version>"} --replace-unpublished`)):h==="dependency_audit_incomplete"?s.push(` ${r.arrow} The dependency audit is queued; publication continues when it finishes.`):s.push(` ${r.arrow} skills-layer creator rescan-security ${i}`),s.push(` ${r.arrow} skills-layer creator status ${i}`),s.push(` ${r.arrow} skills-layer trust ${i}`),s.join(`
|
|
1240
|
+
`)}function J9(e,t,n){let i=L(e,"report")??e,o=de(n),s=i.securityScore,a=f(i,"generatedAt")??f(i,"reportGeneratedAt"),l=Array.isArray(i.findings)?i.findings:void 0,c=[`${o.ok("OK")} Security rescan requested.`,"",o.section("Creator Security")];return c.push(` ${o.label("Skill")}: ${f(i,"skillSlug")??t}`),l&&c.push(` ${o.label("Findings")}: ${l.length}`),a&&c.push(` ${o.label("Generated at")}: ${a}`),c.push("",o.section("Next")),c.push(` ${o.arrow} skills-layer creator security-report ${t}`),c.push(` ${o.arrow} skills-layer creator status ${t}`),c.join(`
|
|
1241
|
+
`)}function Y9(e){return Object.entries(e).filter(([t,n])=>AT(t,n))}function AT(e,t){let n=e.toLowerCase();return n==="status"||n==="securityscore"||n==="recommendation"||n==="capabilityprofile"||n==="securityposture"||n==="trust"||n==="effectiveness"||n.includes("apikey")||n.includes("secret")||n.includes("token")||n==="content"?!1:t!==void 0}function Bl(e){let n=[["id","id"],["name","name"],["keyPrefix","prefix"],["slug","slug"],["skillSlug","skill"],["currentVersion","version"],["version","version"],["category","category"],["skillType","type"],["type","type"],["visibility","visibility"],["status","status"],["count","count"],["email","email"],["role","role"],["selectedBackend","backend"],["selectedBaseUrl","base url"],["path","path"],["downloadUrl","download url"],["authorizationUrl","authorization url"],["checkoutUrl","checkout url"],["url","url"],["issueId","issue"],["reviewId","review"],["purchaseId","purchase"],["workspaceId","workspace"],["clientId","client"],["environment","environment"],["expiresAt","expires"],["lastUsedAt","last used on (UTC day)"],["revocable","revocable"],["revokeCommand","revoke"],["approvalId","approval"],["source","source"],["scope","scope"],["agent","agent"],["bytes","bytes"],["fileCount","file count"],["bodyWordCount","body words"]].flatMap(([i,o])=>{if(!AT(i,e[i]))return[];let s=e[i];return s===void 0?[]:[`${o}: ${Pt(i,s)}`]}),r=L(e,"securityPosture");if(r){let i=f(r,"label"),o=f(r,"runtimeRisk");i&&n.push(`trust: ${i}`),o&&n.push(`risk: ${o}`)}return n.join("; ")}function xT(e){return f(e,"shortDescription")??f(e,"summary")??f(e,"description")??f(e,"message")}function Kw(e){return f(e,"displayName")??f(e,"name")??f(e,"title")??f(e,"slug")??f(e,"skillSlug")??f(e,"code")??f(e,"id")}function Pt(e,t){return e==="lastUsedAt"&&typeof t=="string"?t.slice(0,10):e==="downloadUrl"?"<hidden; use --json or --output>":typeof t=="string"?e.toLowerCase()==="category"?IT(t):ys(t):typeof t=="number"||typeof t=="boolean"?String(t):t===null?"none":Array.isArray(t)?`${t.length} item${t.length===1?"":"s"}`:O(t)?Bl(t)||"details available with --json":String(t)}function IT(e){return mC(e)}function ys(e){let t=e.replace(/\s+/gu," ").trim();return t.length>160?`${t.slice(0,157)}...`:t}function Z9(e){return $f(Hw(e))}function Hw(e){return e.replace(/([a-z0-9])([A-Z])/gu,"$1 $2").replace(/[_-]+/gu," ").toLowerCase()}function X9(e){if(e.verificationStatus==="unverified"&&e.publiclyDiscoverable===!1)return["Review the locally installed files before use; they remain Unverified / Unscored.","A public listing requires successful evaluation and final publication authority; held reviews are not automatic approval."];let t=Q9(e),n=t?[`skills-layer show ${t}`,`skills-layer trust ${t}`,`skills-layer install ${t}`]:[],r=typeof e.downloadUrl=="string",i=Array.isArray(e.materializedWrites)&&e.materializedWrites.length>0;return r&&n.push("Use --output <path> to write exports without printing temporary download URLs"),i&&n.push("Review the materialized files in this workspace"),e.valid===!0&&n.push("skills-layer creator submit <path> --dry-run"),n}function Q9(e){let t=f(e,"skillSlug")??f(e,"slug");if(t)return t;let n=e.results;if(Array.isArray(n)){for(let r of n)if(O(r)){let i=f(r,"skillSlug")??f(r,"slug");if(i)return i}}}function O(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function P(e,t,n=[]){e=$t(e);let r=eJ(e,n);return r?S(r.payload,e,t,r.reasonCode):t?S({status:"error",reasonCode:"command_failed",error:e},e,t,"command_failed"):{exitCode:1,stdout:"",stderr:Vi(e)}}function eJ(e,t){if(/Local bundle rejected \(canonical_bundle_rejected\)/iu.test(e))return{reasonCode:"canonical_bundle_rejected",payload:{status:"error",reasonCode:"canonical_bundle_rejected",nextAction:"bundle.fix",nextStep:"Correct the listed bundle issues and run `skills-layer validate <path>`."}};if(/An installed skill must contain a readable root SKILL\.md/u.test(e))return{reasonCode:"installed_bundle_root_skill_missing",payload:{status:"error",reasonCode:"installed_bundle_root_skill_missing",nextAction:"issue",nextStep:"Nothing was installed. Tell the publisher with `skills-layer issue`, or choose another skill."}};if(/Invalid or expired recovery code/iu.test(e))return{reasonCode:"recovery_code_invalid_or_expired",payload:{status:"error",reasonCode:"recovery_code_invalid_or_expired",nextAction:"auth.recover",nextStep:"Request a fresh recovery code and complete recovery before it expires."}};let n=/^(?<provider>google|github|gitlab|microsoft) auth is not configured$/iu.exec(e);if(n?.groups?.provider)return{reasonCode:"social_provider_not_configured",payload:{status:"error",reasonCode:"social_provider_not_configured",provider:n.groups.provider.toLowerCase(),nextAction:"login",nextStep:"Choose a configured sign-in method or ask the platform operator to configure this provider."}};if(/^Search results do not include /u.test(e))return{reasonCode:"search_selection_not_found",payload:{status:"not_found",reasonCode:"search_selection_not_found",nextAction:"search",nextStep:"Run search again with a matching query or choose one of the returned skill slugs."}};if(/^workspace installs require --workspace <workspace-id>\.$/u.test(e))return{reasonCode:"workspace_required",payload:{status:"error",error:e,reasonCode:"workspace_required",nextAction:"workspace.current",nextStep:"Pass --workspace <workspace-id> using an accessible workspace."}};let r=/^Unsupported skill type "(?<skillType>[^"]+)"\./u.exec(e);if(r?.groups?.skillType)return{reasonCode:"unsupported_skill_type",payload:{status:"error",reasonCode:"unsupported_skill_type",providedSkillType:r.groups.skillType,acceptedValues:["standalone","workflow","workflow_automation","mcp_enhanced"],nextAction:"creator.init",nextStep:"Choose one of the supported skill types."}};let i=/^(?<code>EACCES|EPERM|EROFS):\s*(?<detail>.+)$/iu.exec(e);if(i?.groups){let y=i.groups.code.toUpperCase(),w=/'(?<path>[^']+)'/u.exec(e)?.groups?.path;return{reasonCode:"local_filesystem_permission_denied",payload:{status:"error",reasonCode:"local_filesystem_permission_denied",code:y,...w?{path:w}:{},nextAction:"check_local_permissions",nextStep:"Check the local path permissions, choose a writable installed skill directory, or rerun the command from a workspace you can write to."}}}let o=/^--(?<flag>[a-z0-9-]+) must be valid JSON\.$/iu.exec(e);if(o?.groups){let y=o.groups.flag;return{reasonCode:"invalid_json",payload:{status:"error",reasonCode:"invalid_json",flag:y,nextAction:"fix_json_flag",nextStep:`Provide valid JSON for --${y}.`}}}let s=/^Unknown flag --(?<flag>[a-z0-9-]+)\.$/iu.exec(e);if(s?.groups)return{reasonCode:"unknown_flag",payload:{status:"error",reasonCode:"unknown_flag",flag:s.groups.flag,nextAction:"help",nextStep:"Run `skills-layer <command> --help` to see supported flags for that command."}};let a=/^(?<command>.+?) --(?<flag>[a-z0-9-]+) must be one of: (?<accepted>.+?)\.$/iu.exec(e);if(a?.groups){let y=a.groups.flag,w=a.groups.accepted.split(",").map(b=>b.trim()).filter(Boolean);return{reasonCode:`invalid_${y.replace(/-/gu,"_")}`,payload:{status:"error",reasonCode:`invalid_${y.replace(/-/gu,"_")}`,command:a.groups.command,flag:y,acceptedValues:w,nextAction:a.groups.command.replace(/\s+/gu,"."),nextStep:`Use --${y} with one of: ${w.join(", ")}.`}}}let l=/^Unknown (?<namespace>.+?) command "(?<subcommand>.*?)"\.$/u.exec(e);if(l?.groups){let y=l.groups.namespace.trim(),w=l.groups.subcommand;return{reasonCode:"unknown_subcommand",payload:{status:"error",reasonCode:"unknown_subcommand",namespace:y,subcommand:w,nextAction:`${y.replace(/\s+/gu,".")}.help`,nextStep:`Run \`skills-layer ${y} --help\` to see supported ${y} commands.`}}}if(e.startsWith("Flag --"))return{reasonCode:"flag_value_missing",payload:{status:"error",reasonCode:"flag_value_missing",nextStep:"Supply a value for the flag. To clear a profile field, use its --clear-<field> option."}};let c=RC(t,e);if(c)return{reasonCode:"missing_required_argument",payload:{status:"error",reasonCode:"missing_required_argument",...c}};let u=/^(?<command>(?!-).+?) requires (?<argument>.+?)\.$/u.exec(e);if(!u?.groups)return;let d=u.groups.command.trim(),p=u.groups.argument.trim(),m=tJ(p),g=/--(?<name>[a-z0-9-]+)/iu.exec(p)?.groups?.name,h=g?`--${g} <value>`:`<${m}>`;return{reasonCode:"missing_required_argument",payload:{status:"error",reasonCode:"missing_required_argument",command:d,argument:m,nextAction:d.replace(/\s+/gu,"."),nextStep:`Run \`skills-layer ${d} ${h}\`.`}}}function tJ(e){let t=e.replace(/^(?:a|an|the)\s+/iu,"");if(/^two or more skill slugs$/iu.test(t))return"two-or-more-skill-slugs";let n=/--(?<name>[a-z0-9-]+)/iu.exec(t)?.groups?.name;return n||(/<(?<name>[^>]+)>/u.exec(t)?.groups?.name??t).replace(/\s+or\s+.*$/iu,"").replace(/[^a-z0-9]+/giu,"-").replace(/^-+|-+$/gu,"").toLowerCase()||"argument"}function S(e,t,n,r){let i=Sf(e,!n),o=Ud(r??f(i,"reasonCode")),s={schemaVersion:H0,status:nJ(f(i,"status"),o.defaultStatus),summary:t,why:f(i,"why")??null,nextAction:f(i,"nextAction")??null,nextStep:f(i,"nextStep")??null,data:i,warnings:Array.isArray(i.warnings)?i.warnings:[],links:Array.isArray(i.links)?i.links:[],reasonCode:o.reasonCode,reasonFamily:o.family,handoff:i.handoff??null},a=n?JSON.stringify(s,null,2):"";return{exitCode:1,stdout:a,stderr:n?a:Vi(rJ(s,t))}}function nJ(e,t){return!e||!/^[a-z][a-z0-9_]*$/u.test(e)||e==="approved"||e==="published"?t:e}function rJ(e,t){let n=f(e,"summary")??t,r=f(e,"reasonCode"),i=f(e,"why"),o=f(e,"nextStep"),s=L(e,"data"),a=s?f(s,"requestId")??f(s,"operationId"):void 0,l=iJ(r,n),c=[l];l!==n&&c.push(n),c.push("","Unchanged",` No Skills Layer state was changed by this ${r==="setup_cancelled"?"cancelled":"failed"} command.`),i&&i!==n&&c.push("","Why",` ${i}`);let d=(s&&Array.isArray(s.blockingFindings)?s.blockingFindings:[]).flatMap(p=>{if(!O(p)||typeof p.code!="string"||!/^[A-Za-z0-9_-]{1,128}$/u.test(p.code))return[];let m=typeof p.path=="string"?p.path.replace(/[\p{Cc}\p{Cf}]/gu,"").slice(0,256):"",g=Number.isSafeInteger(p.lineNumber)&&Number(p.lineNumber)>0?`:${p.lineNumber}`:"";return[` ${p.code}${m?` \u2014 ${m}${g}`:""}`]}).slice(0,12);if(d.length>0&&c.push("","Blocking checks",...d),o){let p=/`(?<command>skills-layer(?: [^`]+)?)`/u.exec(o)?.groups?.command;c.push("","Next",` ${p??o}`)}else{let p=/`(?<command>skills-layer(?: [^`]+)?)`/u.exec(n)?.groups?.command;c.push("","Next",` ${p??"skills-layer --help"}`)}return a&&c.push("",`Reference ${a}`),c.join(`
|
|
1242
|
+
`)}function iJ(e,t){if(e==="missing_required_argument")return"Required information is missing";if(e==="unknown_flag")return"That option is not supported";if(e==="invalid_json")return"That JSON value could not be read";if(e==="local_filesystem_permission_denied")return"Skills Layer cannot write to that location";if(e==="login_required")return"Sign in required";if(e==="social_identity_link_required")return"Secure account connection required";let n=t.split(`
|
|
1243
|
+
`,1)[0]?.trim();return n&&n.length<=72?n:"Skills Layer could not complete the command"}function Fi(e,t){let n=vT(e.details);if(n)return R(n,String(n.message),t);let r=e.details??{};if(e.status===401&&!f(r,"reasonCode")){let a=f(r,"error")??"Login required.",l=f(r,"nextAction")??"login",c=f(r,"nextStep")??"Run `skills-layer login` to sign in, then retry this command.",u=/[.!?]$/u.test(a)?a:`${a}.`;return S({status:"login_required",reasonCode:"login_required",error:a,nextAction:l,nextStep:c},`${u} ${c}`,t,"login_required")}let i=f(r,"reasonCode");if(i){let a=O(r.data)?r.data:null,c=a!==null&&("summary"in r||"data"in r)?a:r,u=f(c,"error")??f(r,"error")??f(c,"reason")??f(r,"reason")??f(c,"message")??f(r,"message")??f(r,"summary")??e.message,d=Ud(i,{httpStatus:e.status}),p=u==="Request failed"||u==="Request failed."?d.safeSummary:u;return S({...c,status:f(r,"status")??f(c,"status")??(e.status===404?"not_found":"error"),nextAction:f(c,"nextAction")??f(r,"nextAction"),nextStep:f(c,"nextStep")??f(r,"nextStep"),warnings:Array.isArray(c.warnings)?c.warnings:r.warnings,links:Array.isArray(c.links)?c.links:r.links,handoff:c.handoff??r.handoff,reasonCode:i},[p,Vv(c.eligibleAt??r.eligibleAt),jv(c)].filter(Boolean).join(`
|
|
1244
|
+
`),t,i)}let o=oJ(e);if(o)return S(o.payload,o.message,t,o.reasonCode);let s=Ud(null,{httpStatus:e.status});return S({status:s.defaultStatus,reasonCode:s.reasonCode,error:f(r,"error")??e.message,...Array.isArray(r.issues)?{issues:r.issues}:{},...O(r.validation)?{validation:r.validation}:{},nextAction:f(r,"nextAction")??(e.status===404?"help":null),nextStep:f(r,"nextStep")??(e.status===404?"Check the identifier or list the resources visible to this account.":null)},f(r,"error")??e.message,t,s.reasonCode)}function oJ(e){let t=f(e.details??{},"error")??e.message,n=t.toLowerCase();return n.includes("invalid or expired recovery code")?{reasonCode:"recovery_code_invalid_or_expired",message:"The recovery code is invalid or expired.",payload:{status:"error",reasonCode:"recovery_code_invalid_or_expired",nextAction:"auth.recover",nextStep:"Request a fresh recovery code and complete recovery before it expires."}}:/^(?:google|github|gitlab|microsoft) auth is not configured$/u.test(n)?{reasonCode:"social_provider_not_configured",message:"The selected social provider is not configured.",payload:{status:"error",reasonCode:"social_provider_not_configured",nextAction:"login",nextStep:"Choose a configured sign-in method or ask the platform operator to configure this provider."}}:e.status===403?{reasonCode:"permission_denied",message:"This credential cannot access the requested resource.",payload:{status:"error",reasonCode:"permission_denied",nextAction:null,nextStep:null}}:e.status===404&&n.includes("source connection")?{reasonCode:"source_connection_not_found",message:"Source connection not found.",payload:{status:"not_found",error:t,reasonCode:"source_connection_not_found",nextAction:"source.connection.start",nextStep:"Check the source connection id, or start a new source connection."}}:e.status===404&&n.includes("approval request")?{reasonCode:"approval_request_not_found",message:"Approval request not found.",payload:{status:"not_found",error:t,reasonCode:"approval_request_not_found",nextAction:"approval.request.status",nextStep:"Check the approval request id, or rerun the workflow that created the approval request."}}:e.status===404&&(n.includes("purchase")||n.includes("invoice"))?{reasonCode:"purchase_not_found",message:"Purchase not found.",payload:{status:"not_found",error:t,reasonCode:"purchase_not_found",nextAction:"purchases.list",nextStep:"Run `skills-layer purchases list` to find a valid purchase id."}}:e.status===404&&(n.includes("security report")||n.includes("trust report"))?{reasonCode:"trust_report_not_found",message:"Platform Score report not found.",payload:{status:"not_found",error:t,reasonCode:"trust_report_not_found",nextAction:"trust",nextStep:"Run `skills-layer show <skill-slug>` to confirm the skill exists, then retry trust after the Platform Score report is generated."}}:e.status===404&&n.includes("help topic")?{reasonCode:"help_topic_not_found",message:"Help topic not found.",payload:{status:"not_found",error:t,reasonCode:"help_topic_not_found",nextAction:"help",nextStep:"Run `skills-layer help full` or `skills-layer --help` to see available topics."}}:e.status===404&&n.includes("skill")?{reasonCode:"skill_not_found",message:"Skill not found.",payload:{status:"not_found",error:t,reasonCode:"skill_not_found",nextAction:"search",nextStep:"Run `skills-layer search <query>` to find a valid skill slug before retrying."}}:e.status===404?n.includes("download exported bundle")?{reasonCode:"resource_not_found",message:t,payload:{status:"not_found",error:t,reasonCode:"resource_not_found",nextAction:"export",nextStep:"Request a fresh export URL and retry the download."}}:{reasonCode:"resource_not_found",message:"The requested resource was not found.",payload:{status:"not_found",reasonCode:"resource_not_found",nextAction:"help",nextStep:"Check the identifier or list the resources visible to this account."}}:null}async function se(e){try{return JSON.parse(await on(e,"utf8"))}catch{return null}}function RT(e,t){e.runtimeWarnings.push(t),e.invocationArgs.includes("--json")||process.stderr.write(`${t}
|
|
1245
|
+
`)}async function $v(e,t){try{let n=await up(()=>on(e.paths.pendingRevocationsPath,"utf8"),o=>RT(e,o));if(n.preserved)return!1;let r=n.entries,i=yc(t);return await _e(e.paths.pendingRevocationsPath,lp(p_(r,i))),!0}catch{return!1}}async function sJ(e,t){let n=await up(()=>on(e.paths.pendingRevocationsPath,"utf8"),a=>RT(e,a));if(n.preserved)return{attempted:0,completed:0,remaining:0};let r=n.entries;if(r.length===0)return await Ae(e.paths.pendingRevocationsPath,{force:!0}),{attempted:0,completed:0,remaining:0};let i=r.filter(a=>a.baseUrl===Hr(t.baseUrl)&&a.userId===t.userId),o=r.filter(a=>a.baseUrl!==Hr(t.baseUrl)||a.userId!==t.userId),s=0;for(let a of i)try{await pp(l=>E({...e,baseUrl:a.baseUrl,apiKey:t.apiKey},"/api/v1/me/session/revoke",{method:"POST",headers:U(t.apiKey),body:JSON.stringify(l)}),m_(a)),s+=1}catch{o.push(a)}return o.length===0?await Ae(e.paths.pendingRevocationsPath,{force:!0}):await _e(e.paths.pendingRevocationsPath,lp(o)),{attempted:i.length,completed:s,remaining:o.length}}async function aJ(e,t){let n=await se(e);return n?gP(n,{env:t.env,platform:t.platform,store:t.credentialStore}):null}async function Vl(e,t,n){let r=await mP(t,{env:n.env,platform:n.platform,store:n.credentialStore,profile:ye(e)});await _e(e,r),t.apiKey&&(t.credentialStorage=r.credentialStorage??"local_file_locked")}async function _e(e,t){await Ui(ye(e)),await Jw(e,`${JSON.stringify(t,null,2)}
|
|
1246
|
+
`,{encoding:"utf8",mode:384}),await qi(e,384)}async function Ui(e){await Ti(e,{recursive:!0,mode:448}),await qi(e,448)}async function qi(e,t){if(process.platform!=="win32")try{await vK(e,t)}catch{}}async function q0(e,t){await Ti(ye(e),{recursive:!0}),await Jw(e,t,"utf8")}async function Tf(e,t){let n=ye(e);await Ti(n,{recursive:!0});let r=z(n,`.${$e(e)}.tmp-${ke(12).toString("hex")}`),i;try{i=await $i(r,"wx",384),await i.writeFile(t),await i.sync(),await i.close(),i=void 0,await Li(r,e),await qi(e,384),await Tv(n)}catch(o){throw await i?.close().catch(()=>{}),await Ae(r,{force:!0}).catch(()=>{}),o}}function lJ(e=process.stdin,t=process.stdout,n=bK){return async r=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive prompt is not available in this environment.");let i=n({input:e,output:t});try{return(await i.question(r)).trim()}finally{i.close()}}}function cJ(e=process.stdin,t=process.stdout){return async(n,r)=>{if(r.length===0)throw new Error("Interactive selection has no available options.");if(!e.isTTY||!t.isTTY)throw new Error("Interactive selection is not available in this environment.");return vE(n,r,{input:e,output:t})}}function uJ(e){return async t=>{let n=e==="win32"?{file:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:e==="darwin"?{file:"open",args:[t]}:{file:"xdg-open",args:[t]};return new Promise(r=>{try{let i=G0(n.file,n.args,{detached:!0,stdio:"ignore"});i.on("error",()=>r(!1)),i.unref(),r(!0)}catch{r(!1)}})}}function rt(e,t){let n={};for(let r of t){let i=e[r];i!==void 0&&i!==!1&&(r.endsWith("Cents")||r==="rating"?n[r]=Number(i):n[r]=i)}return W(n)}function dJ(e){let t=e.results;return Array.isArray(t)?t.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let r=f(n,"slug")??f(n,"skillSlug");return r?[r]:[]}):[]}function fJ(e){let t=v(e)??"auto";return t==="auto"||t==="required"||t==="optional"||t==="off"?{status:"ok",policy:t}:{status:"invalid",message:"guardian check --cloud-trust-ledger must be one of: auto, required, optional, off."}}function W(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function It(e,t){let n=v(e);return n?pJ(n,t):void 0}function pJ(e,t){try{return JSON.parse(e)}catch{throw new Error(`--${t} must be valid JSON.`)}}function dt(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t.apiKey,delete t[["ad","min","Api","Key"].join("")],t}function Ww(e){let t=dt(e);for(let n of["role","roles","verifiedAt","expiresAt","userId","tenantId","linkedAccount","linkedIdentity","createdUser"])delete t[n];return t}function F(e,t){let n=v(e);if(!n)throw new Error(t);return n}function v(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function ue(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function f(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function K(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim().length>0){let r=Number(n);return Number.isFinite(r)?r:void 0}}function L(e,t){let n=e[t];return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function rn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function he(e,t){let n=e[t];return Array.isArray(n)?n:void 0}function mJ(e){return L(e,"data")??e}function gJ(e){let t=Array.isArray(e)?e:typeof e=="string"?[e]:[];return[...new Set(t.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))]}function be(e,t,n){let r=v(n);r&&e.set(t,r)}function Re(e){let t=e.toString();return t?`?${t}`:""}function kn(e){return e.replace(/\/+$/u,"")}function V0(e){let t=kn(e.trim());try{let n=new URL(t);if(n.protocol==="https:"&&(n.hostname==="staging.findfigg.co.uk"||n.hostname==="api.staging.findfigg.co.uk"))return"https://staging.findfigg.co.uk"}catch{return t}return t}function Nl(e,t){return V0(e)===V0(t)}function at(e){if(kn(e)===Zw)return"cloud";try{let t=new URL(e);return t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="::1"||t.hostname==="[::1]"?"local":"custom"}catch{return"custom"}}function PT(e){return e.includes("/")||e.startsWith(".")||/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e)}function tt(e,t){return Gn(e,t)}function $f(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var hJ={github:"GitHub",gitlab:"GitLab",google:"Google",microsoft:"Microsoft"};function ET(e){return hJ[e.toLowerCase()]??$f(e)}function ne(e){return e instanceof Error?e.message:String(e)}function DT(e,t){let n=[],r=v(t.limit);if(r){let i=Number(r);if(!Number.isInteger(i)||i<1)return"--limit must be a positive whole number; the maximum is 20.";e.set("limit",String(Math.min(20,i))),i>20&&n.push("limit was clamped to 20; the maximum is 20.")}for(let[i,o]of[["cursor","cursor"],["category","category"],["publisher","publisher"],["price","price"],["minimumScore","minimum-score"],["minimumStars","minimum-stars"],["badge","badge"],["sort","sort"],["agent","agent"],["capability","capability"],["trust","trust"],["runtimeRisk","runtime-risk"],["securityCapability","security-capability"]])be(e,o,t[i]);return n}export{GT as PUBLIC_CLI_HELP_AUDIT_CHECK_COUNT,VT as PUBLIC_CLI_HELP_BRANCH_ROUTES,qT as PUBLIC_CLI_HELP_GOAL_ROUTES,Xl as PUBLIC_CLI_HELP_PATH_NAMES,I8 as adaptClaudeCodeHookEvent,UT as createCliProgress,PW as createGuardianNativeHookScript,MT as createRevealSkipController,nae as executePublicCli,zi as prepareCliPresentation,Wl as resolveCliCommandName,Sf as sanitizePublicCliOutput,_3 as sourceInstallHumanSummary,jT as writeCliResult};
|