buddy-agent-harness 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/.cursor-plugin/plugin.json +1 -1
  4. package/CHANGELOG.md +44 -0
  5. package/dist/cli.mjs +2166 -702
  6. package/dist/index.d.mts +10 -3
  7. package/dist/index.d.mts.map +1 -1
  8. package/dist/index.mjs +597 -431
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/skill-scripts/doctor.mjs +74 -67
  11. package/dist/skill-scripts/init.mjs +74 -67
  12. package/dist/skill-scripts/mcp.mjs +74 -67
  13. package/llms.txt +8 -6
  14. package/package.json +5 -4
  15. package/plugin.json +1 -1
  16. package/skills/doctor-buddy-agent-harness/README.md +1 -1
  17. package/skills/doctor-buddy-agent-harness/SKILL.md +9 -2
  18. package/skills/doctor-buddy-agent-harness/references/worktrees.md +17 -0
  19. package/skills/doctor-buddy-agent-harness/scripts/doctor.mjs +74 -67
  20. package/skills/enhance/SKILL.md +18 -10
  21. package/skills/enhance/references/agent-worktrees.md +59 -0
  22. package/skills/enhance/references/list-identifiers.history.md +9 -1
  23. package/skills/enhance/references/list-identifiers.md +6 -9
  24. package/skills/enhance/references/references-as-links.history.md +9 -0
  25. package/skills/enhance/references/references-as-links.md +76 -0
  26. package/skills/enhance/scripts/doctor.mjs +74 -67
  27. package/skills/init-buddy-agent-harness/SKILL.md +8 -5
  28. package/skills/init-buddy-agent-harness/references/agent-worktrees.md +59 -0
  29. package/skills/init-buddy-agent-harness/scripts/doctor.mjs +74 -67
  30. package/skills/init-buddy-agent-harness/scripts/init.mjs +74 -67
  31. package/skills/repair/README.md +2 -2
  32. package/skills/repair/SKILL.md +3 -3
  33. package/skills/repair/scripts/doctor.mjs +74 -67
  34. package/skills/repair/scripts/mcp.mjs +74 -67
  35. package/src/cli.ts +13 -3
  36. package/src/command-output/command-output.ts +28 -5
  37. package/src/dep-plugins/dep-plugins.command.ts +4 -0
  38. package/src/diagnose-bridges/doctor-guidance.ts +66 -1
  39. package/src/diagnose-bridges/doctor.command.ts +69 -49
  40. package/src/diagnose-bridges/git-bridge-state.ts +5 -0
  41. package/src/diagnose-worktrees/diagnose-worktrees.ts +69 -0
  42. package/src/governance-overrides/governance.command.ts +13 -8
  43. package/src/index.ts +1 -0
  44. package/src/initialize-harnesses/init.command.ts +9 -3
  45. package/src/project-mcp/mcp.command.ts +15 -9
  46. package/src/reconcile-mcp/reconcile.command.ts +17 -11
  47. package/src/references/references.ts +1 -0
@@ -4,43 +4,48 @@
4
4
  // Runs `buddy-agent-harness init` from this bundle against the current working
5
5
  // directory. Nothing outside this file is read.
6
6
 
7
- import{createRequire as e}from"node:module";import{cpSync as t,existsSync as n,lstatSync as r,mkdirSync as i,readFileSync as a,readdirSync as o,readlinkSync as s,realpathSync as c,rmSync as l,rmdirSync as u,statSync as d,symlinkSync as f,writeFileSync as p}from"node:fs";import{inspect as m,styleText as h}from"node:util";import{homedir as g,platform as _}from"node:os";import{basename as v,dirname as y,extname as b,isAbsolute as x,join as S,posix as C,relative as w,resolve as T,sep as E,win32 as D}from"node:path";import{readFile as O,readdir as ee}from"node:fs/promises";import{execFileSync as k}from"node:child_process";import{fileURLToPath as te}from"node:url";var ne=Object.defineProperty,__name=(e,t)=>ne(e,`name`,{value:t,configurable:!0});const re=Symbol.for(`clibuilder.ref`),A=Symbol.for(`clibuilder.placeholder`);function isRef(e){return typeof e==`object`&&!!e&&e[re]===!0}function refArgs(e){let t=[];for(let[n,r]of Object.entries(e.options))for(let e of Array.isArray(r)?r:[r])e!==void 0&&e!==!1&&(t.push(`--${n}`),e!==!0&&t.push(shellQuote(e)));return t}function refHelp(e,t){return t?`Run \`${e}\` to ${t}`:`Run \`${e}\``}function renderHelp(e,t=bareResolver,n=`help`){let r=[],i=[];for(let a of e){if(!isRef(a)){r.push(a);continue}let e=t(a);e!==void 0&&(n===`next`?i.push({run:e,why:a.why??``}):r.push(refHelp(e,a.why)))}return{help:r,next:i}}function bareResolver(e){return[e.path,...refArgs(e)].join(` `)}function shellQuote(e){if(typeof e==`object`&&e&&A in e)return`<${e[A]}>`;let t=String(e);return/^[\w./:@%+=,-]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}var ie;const j={success:0,error:1,usage:2},ae=Symbol.for(`clibuilder.CliError`),oe=Symbol.for(`clibuilder.CliError.reported`),se=Symbol.for(`clibuilder.CliError.helpLines`),ce=[`error`,`code`,`help`];var M=class CliError extends Error{static reported(e=j.error,t=`the error was already reported`){let n=new CliError(t,{exitCode:e});return n[oe]=!0,n}constructor(e,t){let n=typeof e==`string`?{...t,message:e}:e;super(n.message),this.name=`CliError`,this[ie]=!0,this.exitCode=validateExitCode(n.exitCode??j.error),this.code=validateCode(n.code??`error`),this.details=validateDetails(n.details??{});let r=n.help===void 0?[]:Array.isArray(n.help)?[...n.help]:[n.help];this[se]=r,this.help=r.map(e=>isRef(e)?refHelp(bareResolver(e),e.why):e),this.cause=n.cause}};ie=ae;function isCliError(e){return!!e&&typeof e==`object`&&e[ae]===!0}function helpLinesOf(e){return e[se]??e.help??[]}function isReportedCliError(e){return e[oe]===!0}function validateExitCode(e){if(Number.isInteger(e)&&e>=1&&e<=255)return e;throw RangeError(`CliError exitCode must be an integer from 1 to 255, received ${e}`)}function validateCode(e){if(/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e))return e;throw RangeError(`CliError code must be a kebab-case string such as "not-found", received "${e}"`)}function validateDetails(e){for(let t of ce)if(t in e)throw RangeError(`CliError details may not have the key "${t}"`);return{...e}}function command(e){return e}function takesValue$1(e){let t=e.kind===`array`?e.element:e;return!(t.kind===`boolean`||t.kind===`literal`&&typeof t.value==`boolean`)}__name(takesValue$1,`takesValue`);function describeConstraint(e){switch(e.kind){case`string`:return e.pattern?`string ${e.pattern}`:`string`;case`number`:case`int`:return`${e.kind}${describeRange(e.min,e.max)}`;case`boolean`:case`json`:return e.kind;case`literal`:return String(e.value);case`enum`:return e.values.join(`|`);case`custom`:return`value`;case`array`:return describeConstraint(e.element)}}function describeRange(e,t){return e!==void 0&&t!==void 0?` ${e}..${t}`:e===void 0?t===void 0?``:` <=${t}`:` >=${e}`}const le=Symbol.for(`args-minus.descriptor`),ue={[le]:1,optional(){return create({...this,isOptional:!0})},check(e){let t=typeof e==`function`?{type:`fn`,fn:e}:{type:`schema`,schema:e};if(typeof e!=`function`&&!isStandardSchema(e))throw TypeError(`check() takes a function or a Standard Schema`);return create({...this,checks:[...this.checks,t]})}};function create(e){return Object.freeze(Object.assign(Object.create(ue),e))}function make(e){return create({...e,isOptional:!1,checks:Object.freeze([])})}function isStandardSchema(e){let t=e?.[`~standard`];return typeof t==`object`&&!!t&&typeof t.validate==`function`}function checkBounds(e,t,n){let{min:r,max:i}=t??{};for(let[t,a]of[[`min`,r],[`max`,i]])if(a!==void 0){if(typeof a!=`number`||Number.isNaN(a))throw TypeError(`${e}: ${t} must be a number`);if(n&&Number.isFinite(a)&&!Number.isInteger(a))throw RangeError(`${e}: ${t} must be an integer, got ${a}`)}if(r!==void 0&&i!==void 0&&r>i)throw RangeError(`${e}: min (${r}) is greater than max (${i})`);return{...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}}function string(e){let t=e?.pattern;if(t!==void 0&&!(t instanceof RegExp))throw TypeError(`t.string: pattern must be a RegExp`);return make(t===void 0?{kind:`string`}:{kind:`string`,pattern:t})}function json(e){if(e===void 0)return make({kind:`json`});if(!isStandardSchema(e))throw TypeError(`t.json: schema must be a Standard Schema`);return make({kind:`json`,schema:e})}const N={string,number(e){return make({kind:`number`,...checkBounds(`t.number`,e,!1)})},int(e){return make({kind:`int`,...checkBounds(`t.int`,e,!0)})},boolean(){return make({kind:`boolean`})},literal(e){let t=typeof e;if(!(t===`string`||t===`boolean`||t===`number`&&Number.isFinite(e)))throw TypeError(`t.literal: value must be a string, a finite number or a boolean, got ${String(e)}`);return make({kind:`literal`,value:e})},enum(e){if(!Array.isArray(e)||e.length===0)throw TypeError(`t.enum: values must be a non-empty array`);for(let t of e)if(typeof t!=`string`)throw TypeError(`t.enum: values must be strings, got ${String(t)}`);return make({kind:`enum`,values:Object.freeze([...e])})},array(e){let t=e;if(!isDescriptor(t))throw TypeError(`t.array: element must be a descriptor`);if(t.kind===`array`)throw TypeError(`t.array: element cannot be an array`);if(t.isOptional)throw TypeError(`t.array: element cannot be optional`);return make({kind:`array`,element:e})},custom(e){if(typeof e!=`function`)throw TypeError(`t.custom: convert must be a function`);return make({kind:`custom`,convert:e})},json};function isDescriptor(e){return typeof e==`object`&&!!e&&e[le]===1&&typeof e.kind==`string`}String.prototype.charCodeAt;const de=String.prototype.slice;Array.prototype.forEach,Array.prototype.map,Array.prototype.reduce;const fe=Array.prototype.slice,pe=Array.prototype.push,me={modifiers:`-`,terminator:`--`};function resolveGrammar(e){let t=new Set,n=e?.modifiers??me.modifiers;for(let e of typeof n==`string`?Array.from(n):n){if(e.length!==1||e===`=`)throw Error(`Invalid modifier '${e}': a modifier must be a single character other than '='`);t.add(e)}if(t.size===0)throw Error(`At least one modifier is required`);let r=e?.terminator??me.terminator;if(r===``)throw Error(`The terminator must not be empty`);return{modifiers:t,terminator:r}}function trimModifiers(e,t){let n=0;for(;n<e.length&&t.has(e[n]);)n++;return[de.call(e,n),n]}function tokenizeArgs(e,t){let{modifiers:n,terminator:r}=resolveGrammar(t),i=[],a=0,o=fe.call(e);for(;o.length>0;){let e=o.shift();if(e===r){pe.call(i,{kind:`option-terminator`,index:a}),a++,pe.apply(i,o.map((e,t)=>({kind:`positional`,index:a+t,value:e})));break}let[t,s]=trimModifiers(e,n);if(s===0||!t)pe.call(i,{kind:`positional`,index:a,value:t||e});else{let n=t.indexOf(`=`),[r,o]=n===-1?[t,void 0]:[de.call(t,0,n),de.call(t,n+1)];pe.call(i,{kind:`option`,index:a,name:r,dashes:s,raw:e,value:o})}a++}return i}var ParseArgsError=class extends Error{constructor(e,t,n,r={}){super(e),Object.defineProperty(this,"option",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"input",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"kind",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"issues",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"detail",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=`ParseArgsError`,this.kind=r.kind??`invalid-value`,this.index=r.index,this.issues=r.issues,this.value=r.value,this.detail=r.detail??e}};function parseArgs(e){let t=parse$1(e),n=t.next();for(;!n.done;){let{value:e,option:r}=n.value;if(isThenable(e))throw e.then(void 0,()=>{}),t.return(void 0),Error(`Option '${r}' has an asynchronous converter or check: use parseArgsAsync() to parse it`);n=t.next(e)}return n.value}async function parseArgsAsync(e){let t=parse$1(e),n=t.next();for(;!n.done;)n=await Promise.resolve(n.value.value).then(e=>t.next(e),e=>t.throw(e));return n.value}function isThenable(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&typeof e.then==`function`}function*parse$1(e){let t=tokenizeArgs(e.args,e.grammar),n=e.options;checkDeclarations(n);let r=canonicalNames(n),i=Object.create(null),a=Object.create(null),o=[],s=[],c=t.slice();for(;c.length>0;){let t=c.shift();switch(t.kind){case`positional`:checkPositional(e,t.value),o.push(t.value);break;case`option`:{let o=t.dashes===1?Array.from(t.name):[t.name];for(let s=0;s<o.length;s++){let l=o[s],u=s===o.length-1,d=r.get(l)??l,f=n?.[d];if(e.strict&&!f)throw new ParseArgsError(`Unknown option '${l}' (from '${t.raw}')`,l,t.raw,{kind:`unknown-option`});if(!u&&f&&takesValue(f))throw new ParseArgsError(`Invalid option group '${t.raw}': '${l}' takes a value, so it can only be the last option in a group`,d,t.raw,{kind:`invalid-group`,detail:`takes a value, so it can only be the last option in a group`});let p=u?t.value??takeFollowingValue(f,c):void 0;if(f&&isDescriptor(f.type)){let e=f.type;if(e.kind===`array`){let n=i[d]??(i[d]=[]);(a[d]??(a[d]=[])).push(t.raw);let r={name:d,label:`${d}[${n.length}]`,index:n.length,token:t};n.push(yield*convertAndCheck(e.element,p,r))}else i[d]=yield*convertAndCheck(e,p,{name:d,label:d,index:void 0,token:t});continue}let m=convert(f,d,p,t);f?.multiple?(i[d]??(i[d]=[])).push(m):i[d]=m}break}case`option-terminator`:for(let t of c)checkPositional(e,t.value);s.push(...c.map(e=>e.value)),c.length=0}}for(let[e,t]of Object.entries(n??{})){let n=isDescriptor(t.type)?t.type:void 0;if(i[e]!==void 0){if(n?.kind===`array`){let t=a[e].join(` `);yield*runChecks(n,i[e],e,(n,r)=>usageError(e,e,t,n,{issues:r}))}continue}if(t.default!==void 0)n&&(yield*checkDefault(t,e)),i[e]=Array.isArray(t.default)?[...t.default]:t.default;else if(n&&!n.isOptional)throw new ParseArgsError(`Missing required option '${e}'`,e,``,{kind:`missing-option`,detail:`a value is required`})}let l={_:o,__:s,options:i};return e.tokens&&(l.tokens=t),l}__name(parse$1,`parse`);function checkDeclarations(e){for(let[t,n]of Object.entries(e??{})){let e=n.type;if(typeof e==`object`&&e&&!isDescriptor(e))throw TypeError(`Option '${t}' has a type that is neither a type name nor a descriptor from t`);if(isDescriptor(e)&&n.multiple!==void 0)throw TypeError(`Option '${t}' cannot set 'multiple' with a descriptor: use t.array(element)`)}}function checkPositional(e,t){if(e.allowPositionals===!1)throw new ParseArgsError(`Unexpected positional argument '${t}'`,void 0,t,{kind:`unexpected-positional`})}function canonicalNames(e){let t=new Map;if(!e)return t;for(let n of Object.keys(e))t.set(n,n);for(let[n,r]of Object.entries(e)){let e=r.alias;for(let r of e===void 0?[]:Array.isArray(e)?e:[e]){let e=t.get(r);if(e!==void 0&&e!==n)throw Error(`Alias '${r}' of option '${n}' is already used by option '${e}'`);t.set(r,n)}}return t}function elementOf(e){return e.kind===`array`?e.element:e}function takesValue(e){if(!isDescriptor(e.type))return e.type!==`boolean`;let t=elementOf(e.type);return!(t.kind===`boolean`||t.kind===`literal`&&typeof t.value==`boolean`)}function isNumeric(e){if(!isDescriptor(e.type))return e.type===`number`;let t=elementOf(e.type);return t.kind===`number`||t.kind===`int`||t.kind===`literal`&&typeof t.value==`number`}function takeFollowingValue(e,t){if(!e||!takesValue(e))return;let n=t[0];if(n){if(n.kind===`positional`)return t.shift(),n.value;if(n.kind===`option`&&isNumeric(e)&&Number.isFinite(toNumber(n.raw)))return t.shift(),n.raw}}function convert(e,t,n,r){if(!e)return n??!0;switch(e.type){case`boolean`:return convertBoolean(t,n,r);case`number`:return convertNumber(t,n,r);default:if(n===void 0)throw invalid(t,`a value is required`,r,`missing-value`);return n}}function invalid(e,t,n,r,i){return new ParseArgsError(`Invalid value for option '${e}': ${t} (from '${n.raw}')`,e,n.raw,{kind:r,value:i,detail:t})}function toNumber(e){return e.trim()===``?NaN:Number(e)}function convertNumber(e,t,n){if(t===void 0)throw invalid(e,`a number is required`,n,`missing-value`);let r=toNumber(t);if(!Number.isFinite(r))throw invalid(e,t,n,`invalid-value`,t);return r}function convertBoolean(e,t,n){if(t===void 0)return!0;if(t===`false`||t===`f`||t===`0`)return!1;if(t===`true`||t===`t`)return!0;let r=toNumber(t);if(!Number.isNaN(r))return r>0;throw invalid(e,t,n,`invalid-value`,t)}function usageError(e,t,n,r,i,a=r){return new ParseArgsError(`Invalid value for option '${t}': ${a} (from '${n}')`,e,n,{...i,detail:r})}function*convertAndCheck(e,t,n){let fail=(e,r,i)=>usageError(n.name,n.label,n.token.raw,e,{index:n.index,issues:r,value:t},i),r=yield*convertDescriptor(e,t,n,fail);return yield*runChecks(e,r,n.label,fail),r}function quote$1(e){return`'${e}'`}__name(quote$1,`quote`);function describeExpected(e){switch(e.kind){case`string`:return`a string matching ${e.pattern}`;case`number`:case`int`:{let t=e.kind===`int`?`an integer`:`a number`;return e.min!==void 0&&e.max!==void 0?`${t} from ${e.min} to ${e.max}`:e.min===void 0?e.max===void 0?t:`${t} of at most ${e.max}`:`${t} of at least ${e.min}`}case`boolean`:return`no value, true or false`;case`literal`:return typeof e.value==`string`?quote$1(e.value):String(e.value);case`enum`:return`one of ${e.values.map(quote$1).join(`, `)}`}}function*convertDescriptor(e,t,n,r){let expected=e=>r(`expected ${describeExpected(e)}`,void 0,`expected ${describeExpected(e)}, got ${quote$1(t)}`);if(e.kind===`boolean`||e.kind===`literal`&&typeof e.value==`boolean`){let n=t===void 0||t===`true`||t!==`false`&&void 0;if(n===void 0||e.kind===`literal`&&n!==e.value)throw t===void 0?r(`expected ${describeExpected(e)}`,void 0,`expected ${describeExpected(e)}, got no value`):expected(e);return n}if(t===void 0)throw usageError(n.name,n.label,n.token.raw,`a value is required`,{kind:`missing-value`,index:n.index});switch(e.kind){case`string`:if(e.pattern&&(e.pattern.lastIndex=0,!e.pattern.test(t)))throw expected(e);return t;case`number`:case`int`:{let n=toNumber(t);if(!Number.isFinite(n)||e.kind===`int`&&!Number.isInteger(n)||e.min!==void 0&&n<e.min||e.max!==void 0&&n>e.max)throw expected(e);return n}case`literal`:{let n=typeof e.value==`number`?toNumber(t):t;if(n!==e.value)throw expected(e);return n}case`enum`:if(!e.values.includes(t))throw expected(e);return t;case`custom`:try{return yield{value:e.convert(t),option:n.label}}catch(e){throw usageFailure(e,r)}case`json`:{let i;try{i=JSON.parse(t)}catch{throw r(`not valid JSON`,void 0,`${quote$1(t)} is not valid JSON`)}if(!e.schema)return i;let a=yield{value:e.schema[`~standard`].validate(i),option:n.label};if(a.issues)throw r(`does not match the expected shape`,a.issues);return a.value}}}function usageFailure(e,t){return e instanceof Error&&e.constructor===Error?t(e.message):e}function*runChecks(e,t,n,r){for(let i of e.checks)if(i.type===`fn`){let e=yield{value:i.fn(t),option:n};if(e===!1)throw r(`failed a check`);if(typeof e==`string`)throw r(e)}else{let e=yield{value:i.schema[`~standard`].validate(t),option:n};if(e.issues)throw r(`failed a check`,e.issues)}}const he=new WeakMap;function*checkDefault(e,t){if(he.has(e))return;let n=e.type,failFor=e=>t=>Error(`The default of option '${e}' failed a check${t===`failed a check`?``:`: ${t}`}`);if(n.kind===`array`){let r=e.default;for(let e=0;e<r.length;e++){let i=`${t}[${e}]`;yield*runChecks(n.element,r[e],i,failFor(i))}}yield*runChecks(n,e.default,t,failFor(t)),he.set(e,!0)}const ge=new WeakMap;function lookupCommand(e,t,n){let r=matchCommand(e,createPathCursor(t,n)),[i,a]=assignOptionValues(t,r,n);return processCommand(r,i,a)}function matchCommand(e,t){if(e.commands){let n=e.commands,r=t.peek(e);for(let e=n.length-1;e>=0;e--){let i=n[e];if(!i.name)return i;if(r===i.name||i.alias?.includes(r))return t.consume(),i.commands?matchCommand(i,t):i}}return e}function createPathCursor(e,t){let n=ge.get(e)??[],r,i=-1,a=0;return{peek(o){if(r=void 0,i<0){if(a<e._.length)return(r=[e._,a])[0][a];i=0,a=-1}for(;t&&i<n.length;){let e=n[i];if(a<0){let n=lookupOptions(t,e.key)[1];if(!n)return;a=countFollowing(lookupOptions(o,e.key)[1]??n,e)}if(a<e.following.length)return(r=[e.following,a])[0][a];i++,a=-1}},consume(){r[0].splice(r[1],1)}}}function assignOptionValues(e,t,n){let r=ge.get(e);if(!r)return[e,void 0];let i={},a=[],o=[];for(let e of r){let r=lookupOptions(t,e.key)[1],s=countFollowing(r??(n&&lookupOptions(n,e.key)[1]),e),c=e.following.slice(0,s);r&&o.push({key:e.key,tokens:[e.raw,...c]}),a.push(...e.following.slice(s));let l=e.inline.length+c.length>0?[...e.inline,...c]:[`true`];i[e.key]=[...i[e.key]??[],...l]}let s={...e,_:[...e._,...a]};for(let t of Object.keys(i))e[t]&&(s[t]=i[t]);return[s,o]}function countFollowing(e,t){return e?t.inline.length===0&&takesValue$1(optionType(e))?1:0:t.following.length}const _e=N.boolean().optional(),ve=N.string();function optionType(e){return e.type??_e}function processCommand(e,t,n){return collectDescriptorOptions(checkConflicts(fillInputOptions(fillArguments({command:e,rawArgs:t,args:{_:[]},errors:[],descriptors:[]}))),n)}function fillArguments(e){let t=e.command,n=[...e.rawArgs._],r=t.arguments||[];for(let t of r){let r=t.type??ve;if(n.length===0){r.isOptional||e.errors.push({type:`missing-argument`,name:t.name});continue}let i=r.kind===`array`?n.splice(0):[n.shift()];e.descriptors.push({type:`argument`,name:t.name,descriptor:r,values:i})}return n.length>0&&e.errors.push({type:`extra-arguments`,name:t.name,values:n}),e}function fillInputOptions(e){for(let t of Object.keys(e.rawArgs)){if(t===`_`)continue;if(/^-/.test(t)){e.errors.push({type:`invalid-key`,key:t});continue}let[n,r]=lookupOptions(e.command,t);if(!n){e.errors.push({type:`invalid-key`,key:t});continue}let i=optionType(r),a=e.rawArgs[t];i.kind!==`array`&&a.length>1&&e.errors.push({type:`expect-single`,key:t,keyKind:i.kind,value:a})}return e}function checkConflicts(e){let t=e.command.options;if(!t)return e;let n=new Map;for(let t of Object.keys(e.rawArgs)){let[r]=lookupOptions(e.command,t);r&&!n.has(r)&&n.set(r,t)}let r=[...n.keys()];for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){let[o,s]=[r[i],r[a]];if(!t[o].conflicts?.includes(s)&&!t[s].conflicts?.includes(o))continue;let[c,l]=t[o].conflicts?.includes(s)?[o,s]:[s,o];e.errors.push({type:`conflicting-options`,key:n.get(c),conflictsWith:n.get(l)})}return e}function collectDescriptorOptions(e,t){let n=e.command.options??{};for(let r of Object.keys(n)){let i=n[r],a=Object.keys(e.rawArgs).filter(t=>t!==`_`&&lookupOptions(e.command,t)[0]===r);e.errors.some(e=>e.type===`expect-single`&&a.includes(e.key))||e.descriptors.push({type:`option`,name:r,entry:{...i,type:optionType(i)},occurrences:t?t.filter(e=>a.includes(e.key)):a.flatMap(t=>e.rawArgs[t].map(e=>({key:t,tokens:[`--${r}=${e}`]})))})}return e}function lookupOptions(e,t){let n=e.options;if(!n)return[];let r=n[t];if(r)return[t,r];let i=Object.keys(n).find(e=>{let r=n[e];return r.alias?r.alias.some(e=>e===t||e.alias===t):!1});return i?[i,n[i]]:[]}const ye={comma:`,`,tab:` `,pipe:`|`},be=ye.comma;function escapeString(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`).replace(/[\u0000-\u001F]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function isBooleanOrNullLiteral(e){return e===`true`||e===`false`||e===`null`}function setOwnProperty(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}const xe=RegExp(`(?:^?|\\n) *#`);var RawString=class{constructor(e){if(xe.test(e))throw TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(e)}`);this.value=e}};function isRawString(e){return e instanceof RawString}const Se=/[\uD800-\uDFFF]/;function normalizeValue(e){if(e===null)return null;if(isRawString(e))return e;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return normalizeValue(t)}if(typeof e==`string`)return assertNoLoneSurrogate(e,`string value`),e;if(typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(normalizeValue);if(e instanceof Set)return Array.from(e).map(normalizeValue);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),normalizeValue(t)]));if(isPlainObject(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(assertNoLoneSurrogate(n,`object key`),setOwnProperty(t,n,normalizeValue(e[n])));return t}return null}function assertNoLoneSurrogate(e,t){if(Se.test(e))for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<55296||r>57343)continue;let i=r<=56319,a=e.charCodeAt(n+1);if(i&&a>=56320&&a<=57343){n++;continue}throw TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${r.toString(16).toUpperCase()} at index ${n}`)}}function isJsonPrimitive(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function isEncodablePrimitive(e){return isJsonPrimitive(e)||isRawString(e)}function isJsonArray(e){return Array.isArray(e)}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!isRawString(e)}function isEmptyObject(e){return Object.keys(e).length===0}function isPlainObject(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function isArrayOfPrimitives(e){return e.length===0||e.every(e=>isEncodablePrimitive(e))}function isArrayOfArrays(e){return e.length===0||e.every(e=>isJsonArray(e))}function isArrayOfObjects(e){return e.length===0||e.every(e=>isJsonObject(e))}const Ce=/^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;function assertValidDelimiter(e){if(!Object.values(ye).includes(e))throw TypeError(`Invalid delimiter ${JSON.stringify(e)}. Valid delimiters are: comma (,), tab (\\t), pipe (|)`)}function isValidUnquotedKey(e){return/^[A-Z_][\w.]*$/i.test(e)}function isSafeUnquoted(e,t=be){return!(!e||/^[ \t]|[ \t]$/.test(e)||isBooleanOrNullLiteral(e)||isNumericLike(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`)||e.startsWith(`#`))}function isNumericLike(e){return Ce.test(e)}function encodePrimitive(e,t){return isRawString(e)?e.value:e===null?`null`:typeof e==`boolean`||typeof e==`number`?String(e):encodeStringLiteral(e,t)}function encodeStringLiteral(e,t=be){return isSafeUnquoted(e,t)?e:`"${escapeString(e)}"`}function encodeKey(e){return isValidUnquotedKey(e)?e:`"${escapeString(e)}"`}function encodeAndJoinPrimitives(e,t=be){return e.map(e=>encodePrimitive(e,t)).join(t)}function formatHeader(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;return n!=null&&(a+=encodeKey(n)),a+=`[${e}${t?.keyed?`:`:``}${i===be?``:i}]`,r&&(a+=`{${formatFieldSegment(r,i)}}`),a+=`:`,a}function formatFieldSegment(e,t){return e.map(e=>encodeKey(e.name)+(e.children?`{${formatFieldSegment(e.children,t)}}`:``)).join(t)}function extractTabularFields(e){if(e.length===0)return;let t=Object.keys(e[0]);if(t.length===0)return;for(let n of e){if(Object.keys(n).length!==t.length)return;for(let e of t)if(!Object.hasOwn(n,e))return}let n=[];for(let r of t){let t=classifyColumn(r,e.map(e=>e[r]));if(!t)return;n.push(t)}return n}function extractKeyedTabularFields(e){let t=Object.values(e);if(!(t.length<2)&&t.every(e=>isJsonObject(e)&&!isEmptyObject(e)))return extractTabularFields(t)}function collectRowLeaves(e,t){let n=[];return collectLeafValues(e,t,n),n}function classifyColumn(e,t){if(t.every(e=>isEncodablePrimitive(e)))return{name:e};if(!t.every(e=>isJsonObject(e)&&!isEmptyObject(e)))return;let n=extractTabularFields(t);if(n)return{name:e,children:n}}function collectLeafValues(e,t,n){for(let r of t){let t=e[r.name];r.children?collectLeafValues(t,r.children,n):n.push(t)}}function*encodeJsonValue(e,t,n){if(isEncodablePrimitive(e)){let n=encodePrimitive(e,t.delimiter);n!==``&&(yield n);return}if(isJsonArray(e))yield*encodeArrayLines(void 0,e,n,t);else if(isJsonObject(e)){let r=extractKeyedTabularFields(e);if(r){yield*encodeKeyedObjectLines(void 0,e,r,n,t);return}yield*encodeObjectLines(e,n,t)}}function*encodeObjectLines(e,t,n){for(let[r,i]of Object.entries(e))yield*encodeKeyValuePairLines(r,i,t,n)}function*encodeKeyValuePairLines(e,t,n,r){let i=encodeKey(e);if(isEncodablePrimitive(t))yield indentedLine(n,`${i}: ${encodePrimitive(t,r.delimiter)}`,r.indentSize);else if(isJsonArray(t))yield*encodeArrayLines(e,t,n,r);else if(isJsonObject(t)){let a=extractKeyedTabularFields(t);if(a){yield*encodeKeyedObjectLines(e,t,a,n,r);return}yield indentedLine(n,`${i}:`,r.indentSize),isEmptyObject(t)||(yield*encodeObjectLines(t,n+1,r))}}function*encodeKeyedObjectLines(e,t,n,r,i){let a=Object.entries(t);yield indentedLine(r,formatHeader(a.length,{key:e,fields:n,delimiter:i.delimiter,keyed:!0}),i.indentSize),yield*encodeKeyedEntryRowsLines(a,n,r+1,i)}function*encodeKeyedEntryRowsLines(e,t,n,r){for(let[i,a]of e){let e=collectRowLeaves(a,t);yield indentedLine(n,`${encodeKey(i)}: ${encodeAndJoinPrimitives(e,r.delimiter)}`,r.indentSize)}}function*encodeArrayLines(e,t,n,r){if(t.length===0){yield indentedLine(n,e==null?`[]`:`${encodeKey(e)}: []`,r.indentSize);return}if(isArrayOfPrimitives(t)){yield indentedLine(n,encodeInlineArrayLine(t,r.delimiter,e),r.indentSize);return}if(isArrayOfArrays(t)&&t.every(e=>isArrayOfPrimitives(e))){yield*encodeArrayOfArraysAsListItemsLines(e,t,n,r);return}if(isArrayOfObjects(t)){let i=extractTabularFields(t);i?yield*encodeArrayOfObjectsAsTabularLines(e,t,i,n,r):yield*encodeMixedArrayAsListItemsLines(e,t,n,r);return}yield*encodeMixedArrayAsListItemsLines(e,t,n,r)}function*encodeArrayOfArraysAsListItemsLines(e,t,n,r){yield indentedLine(n,formatHeader(t.length,{key:e,delimiter:r.delimiter}),r.indentSize);for(let e of t)if(isArrayOfPrimitives(e)){let t=encodeInlineArrayLine(e,r.delimiter);yield indentedListItem(n+1,t,r.indentSize)}}function encodeInlineArrayLine(e,t,n){let r=formatHeader(e.length,{key:n,delimiter:t}),i=encodeAndJoinPrimitives(e,t);return e.length===0?r:`${r} ${i}`}function*encodeArrayOfObjectsAsTabularLines(e,t,n,r,i){yield indentedLine(r,formatHeader(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indentSize),yield*writeTabularRowsLines(t,n,r+1,i)}function*writeTabularRowsLines(e,t,n,r){for(let i of e)yield indentedLine(n,encodeAndJoinPrimitives(collectRowLeaves(i,t),r.delimiter),r.indentSize)}function*encodeMixedArrayAsListItemsLines(e,t,n,r){yield indentedLine(n,formatHeader(t.length,{key:e,delimiter:r.delimiter}),r.indentSize);for(let e of t)yield*encodeListItemValueLines(e,n+1,r)}function*encodeObjectAsListItemLines(e,t,n){if(isEmptyObject(e)){yield indentedLine(t,`-`,n.indentSize);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(isJsonArray(a)&&isArrayOfObjects(a)){let e=extractTabularFields(a);if(e){yield indentedListItem(t,formatHeader(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indentSize),yield*writeTabularRowsLines(a,e,t+2,n),o.length>0&&(yield*encodeObjectLines(Object.fromEntries(o),t+1,n));return}}if(isJsonObject(a)){let e=extractKeyedTabularFields(a);if(e){let r=Object.entries(a);yield indentedListItem(t,formatHeader(r.length,{key:i,fields:e,delimiter:n.delimiter,keyed:!0}),n.indentSize),yield*encodeKeyedEntryRowsLines(r,e,t+2,n),o.length>0&&(yield*encodeObjectLines(Object.fromEntries(o),t+1,n));return}}let s=encodeKey(i);if(isEncodablePrimitive(a))yield indentedListItem(t,`${s}: ${encodePrimitive(a,n.delimiter)}`,n.indentSize);else if(isJsonArray(a)){if(a.length===0)yield indentedListItem(t,`${s}: []`,n.indentSize);else if(isArrayOfPrimitives(a))yield indentedListItem(t,`${s}${encodeInlineArrayLine(a,n.delimiter)}`,n.indentSize);else{yield indentedListItem(t,`${s}${formatHeader(a.length,{delimiter:n.delimiter})}`,n.indentSize);for(let e of a)yield*encodeListItemValueLines(e,t+2,n)}}else isJsonObject(a)&&(yield indentedListItem(t,`${s}:`,n.indentSize),isEmptyObject(a)||(yield*encodeObjectLines(a,t+2,n)));o.length>0&&(yield*encodeObjectLines(Object.fromEntries(o),t+1,n))}function*encodeListItemValueLines(e,t,n){if(isEncodablePrimitive(e))yield indentedListItem(t,encodePrimitive(e,n.delimiter),n.indentSize);else if(isJsonArray(e)){if(isArrayOfPrimitives(e))yield indentedListItem(t,encodeInlineArrayLine(e,n.delimiter),n.indentSize);else{yield indentedListItem(t,formatHeader(e.length,{delimiter:n.delimiter}),n.indentSize);for(let r of e)yield*encodeListItemValueLines(r,t+1,n)}}else isJsonObject(e)&&(yield*encodeObjectAsListItemLines(e,t,n))}function indentedLine(e,t,n){return` `.repeat(n*e)+t}function indentedListItem(e,t,n){return indentedLine(e,`- `+t,n)}function applyReplacer(e,t){let n=t(``,e,[]);return n===void 0?transformChildren(e,t,[]):transformReplaced(e,n,t,[])}function transformReplaced(e,t,n,r){return isRawString(t)&&!isEncodablePrimitive(e)?transformChildren(e,n,r):transformChildren(normalizeValue(t),n,r)}function transformChildren(e,t,n){return isJsonObject(e)?transformObject(e,t,n):isJsonArray(e)?transformArray(e,t,n):e}function transformObject(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&setOwnProperty(r,i,transformReplaced(a,o,t,e))}return r}function transformArray(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);s!==void 0&&r.push(transformReplaced(a,s,t,o))}return r}function encode$1(e,t){return Array.from(encodeLines(e,t)).join(`
8
- `)}__name(encode$1,`encode`);function encodeLines(e,t){let n=normalizeValue(e),r=resolveOptions(t);return encodeJsonValue(r.replacer?applyReplacer(n,r.replacer):n,r,0)}function resolveOptions(e){let t=e?.delimiter??be;return assertValidDelimiter(t),{indentSize:e?.indentSize??e?.indent??2,delimiter:t,replacer:e?.replacer}}function isRecord$3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}__name(isRecord$3,`isRecord`);function cell(e){return e===void 0?``:String(e)}function table(e){let t=[...new Set(e.flatMap(e=>Object.keys(e)))],n=t.map(t=>Math.max(t.length,...e.map(e=>cell(e[t]).length))),line=e=>` ${e.map((e,t)=>e.padEnd(n[t])).join(` `)}`.trimEnd();return[line(t),...e.map(e=>line(t.map(t=>cell(e[t]))))]}function renderText(e){let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>{if(!Array.isArray(t))return[`${e}: ${isRecord$3(t)?JSON.stringify(t):String(t)}`];if(!t.length)return[`${e}: (none)`];let n=t.every(isRecord$3)?table(t):t.map(e=>` - ${String(e)}`);return[`${e}:`,...n]});return t.flatMap((e,n)=>{let r=t[n-1];return r&&(r.length>1||e.length>1)?[``,...e]:e}).join(`
9
- `)}const we=[`toon`,`json`,`text`];function encode(e,t){return t===`json`?JSON.stringify(e):t===`text`?renderText(e):encode$1(e)}function errorOutput({message:e,code:t,details:n,help:r}){let i={error:e,code:t,...n};return r&&r.length>0&&(i.help=[...r]),i}const Te=Symbol.for(`clibuilder.global-format`),Ee=Symbol.for(`clibuilder.defers-to-global-format`);function getBaseCommand(e,t){return command({name:``,description:e,options:{help:{type:N.boolean().optional(),description:`Print help message`,alias:[`h`]},version:{type:N.boolean().optional(),description:`Print the CLI version`,alias:[`v`]},verbose:{type:N.boolean().optional(),description:`Turn on verbose logging`,alias:[`V`]},silent:{type:N.boolean().optional(),description:`Turn off logging`},"debug-cli":{type:N.boolean().optional(),description:`Display clibuilder debug messages`},...t?.options,format:formatEntry(t?.format??`toon`)},commands:[]})}function formatEntry(e){return Object.defineProperty({type:N.enum(we),description:`Output format: 'toon' for agents, 'json' to pipe, 'text' for humans`,default:e},Te,{value:!0})}function isGlobalFormatEntry(e){return!!e&&e[Te]===!0}function yieldToGlobalFormat(e){let[t,n]=lookupOptions(e,`format`);if(!t||isGlobalFormatEntry(n))return e;if(!n[Ee]){let n=e.name?`command '${e.name}'`:`the default command`;throw Error(`${n} declares its own option '${t}', which conflicts with the global --format option. Delete the local declaration and read this.format in run() instead. See docs/rfcs/axi-native.md section 3.4: https://github.com/clibuilder/clibuilder/blob/main/docs/rfcs/axi-native.md#34---format-is-not-first-class-6394`)}let{[t]:r,...i}=e.options;return{...e,options:i}}function defineKey(e){return{id:e,kind:`value`}}function createRegistry(){let e=new Map,t=new Map;function get(n){return n.kind===`collection`?t.get(n.id)??[]:e.get(n.id)?.value}return{register(n,r,i){if(r.kind===`collection`){let e=t.get(r.id)??[];return e.push({source:n,value:i}),t.set(r.id,e),{accepted:!0}}let a=e.get(r.id);return a?{accepted:!1,source:a.source}:(e.set(r.id,{source:n,value:i}),{accepted:!0})},get,has(n){return n.kind===`collection`?t.has(n.id):e.has(n.id)},describe(n){if(n.kind===`collection`)return(t.get(n.id)??[]).map(({source:e})=>e);let r=e.get(n.id)?.source;return r?[r]:[]}}}const De=defineKey(`clibuilder.config`);function parseArgv(e){let t=[],n=e.slice(2).reduce((e,n)=>(e.args.__?e.args.__.push(n):isOption(n)?(isInOptionState(e)&&(e=endOption(e)),e=startOption(e,n,t)):isInOptionState(e)?(e.values.push(n),t[t.length-1].following.push(n)):n===`--`?e.args.__=[]:e.args._.push(n),e),{args:{_:[]},key:``,values:[]}),r=(isInOptionState(n)?endOption(n):n).args;return ge.set(r,t),r}function isInOptionState(e){return!!e.key}function isOption(e){return e.startsWith(`-`)&&/\w+/.test(e)}function startOption(e,t,n){return e=/^-\w+/.test(t)?startSingleCharacterOptions(e,t,n):startMultiCharacterOptions(e,t),n.push({key:e.key,raw:t,inline:[...e.values],following:[]}),e}function startSingleCharacterOptions(e,t,n){let r=t.indexOf(`=`),[i,a]=r>0?[t.slice(1,r),[t.slice(r+1)]]:[t.slice(1),[]],o=i.split(``),s=o.pop();for(let e of o)n.push({key:e,raw:t,inline:[`true`],following:[]});return e=addBooleanOptions(e,o),e.key=s,e.values=a,e}function addBooleanOptions(e,t){return t.length<=0?e:(e.key=t.pop(),e.values=[`true`],addBooleanOptions(endOption(e),t))}function startMultiCharacterOptions(e,t){let n=t.indexOf(`=`);return n>0?(e.key=t.slice(2,n),e.values=[t.slice(n+1)]):(e.key=t.slice(2),e.values=[]),e}function endOption(e){let{key:t,values:n}=e,r={...e.args};return r[t]||(r[t]=[]),n.length===0?r[t].push(`true`):r[t].push(...n),{args:r,key:``,values:[]}}const Oe=new WeakMap;async function convertDescriptors(e){for(let t of e.descriptors)try{assign(e,t,await parseArgsAsync(configOf(t)))}catch(n){report$1(e,t,n)}}function convertDescriptorsSync(e){for(let t of e.descriptors)try{assign(e,t,parseArgs(configOf(t)))}catch(n){report$1(e,t,n)}}function peekFlags(e,t){let n={...e,args:{...e.args},errors:[],descriptors:e.descriptors.filter(e=>e.type===`option`&&t.includes(e.name)&&e.entry.type.kind===`boolean`&&e.entry.type.checks.length===0)};return convertDescriptorsSync(n),n.args}function configOf(e){return e.type===`option`?{args:e.occurrences.flatMap(e=>e.tokens),options:{[e.name]:declarationOf(e.entry)}}:{args:e.values.map(t=>`--${e.name}=${t}`),options:{[e.name]:{type:e.descriptor}}}}function assign(e,t,{options:n}){n[t.name]!==void 0&&(e.args[t.name]=n[t.name])}function report$1(e,t,n){if(!(n instanceof ParseArgsError))throw n;e.errors.push(toUsageError(n,t))}__name(report$1,`report`);function declarationOf(e){let t=Oe.get(e);if(!t){let n=e.alias?.map(e=>typeof e==`string`?e:e.alias);t={type:e.type,...n?{alias:n}:{},...e.default===void 0?{}:{default:e.default}},Oe.set(e,t)}return t}function toUsageError(e,t){if(e.kind===`missing-option`)return{type:`missing-argument`,name:t.name};let n=t.type===`option`?t.entry.type:t.descriptor,r=n.kind===`array`?n.element:n;return{type:`invalid-value`,key:keyOf(e,t),message:e.detail,value:e.value??(e.kind===`invalid-value`?rawValues(t):void 0),keyKind:n.kind,constraint:describeConstraint(r),...r.kind===`enum`?{allowed:r.values}:{},...e.index===void 0?{}:{index:e.index}}}function keyOf(e,t){if(t.type===`argument`)return t.name;let n=t.occurrences;return(e.index===void 0?n[n.length-1]:n[e.index])?.key??t.name}function rawValues(e){return e.type===`argument`?e.values:e.occurrences.map(e=>e.tokens.join(` `))}const ke=Symbol.for(`clibuilder.answer`);function result(e,t={}){return{[ke]:`result`,value:e,help:helpLines(t.help),render:t.render}}function document(e){return{[ke]:`document`,value:String(e)}}function empty(e,t={}){return{[ke]:`empty`,value:String(e),help:helpLines(t.help)}}function isAnswer(e){return typeof e==`object`&&!!e&&typeof e[ke]==`string`}function answerValue(e){return isAnswer(e)?e.value:e}function printAnswer(e,t,n={}){if(e===void 0)return;let tail=e=>renderHelp(e,n.resolve,n.refs);if(!isAnswer(e))return print(e,tail([]),t);switch(e[ke]){case`written`:return;case`document`:return line(e.value);case`empty`:return line(encode(withHelp({empty:e.value},tail(e.help)),t));case`result`:{let n=e.render?.[t];return n?withRenderedHelp(n(e.value),tail(e.help),t):print(e.value,tail(e.help),t)}}}function print(e,t,n){return typeof e==`string`?withRenderedHelp(e,t,n):line(encode(withHelp(toRecord(e),t),n))}function withRenderedHelp(e,t,n){let r=withHelp({},t);return Object.keys(r).length===0?line(e):line(`${e}${e.endsWith(`
7
+ import{createRequire as e}from"node:module";import{cpSync as t,existsSync as n,lstatSync as r,mkdirSync as i,readFileSync as a,readdirSync as o,readlinkSync as s,realpathSync as c,renameSync as l,rmSync as u,rmdirSync as d,statSync as f,symlinkSync as p,writeFileSync as m}from"node:fs";import{inspect as h,styleText as g}from"node:util";import{homedir as _,platform as v}from"node:os";import{basename as y,dirname as b,extname as x,isAbsolute as S,join as C,posix as w,relative as T,resolve as E,sep as D,win32 as O}from"node:path";import{readFile as k,readdir as ee}from"node:fs/promises";import{execFileSync as A}from"node:child_process";import{fileURLToPath as te}from"node:url";var ne=Object.defineProperty,__name=(e,t)=>ne(e,`name`,{value:t,configurable:!0});const re=Symbol.for(`clibuilder.ref`),ie=Symbol.for(`clibuilder.placeholder`);function ref(e,t={},n){let r=e.trim().split(/\s+/).filter(Boolean);if(r.length===0)throw TypeError(`ref() needs a command path, such as "task get"`);return{[re]:!0,path:r.join(` `),options:{...t},why:n}}function isRef(e){return typeof e==`object`&&!!e&&e[re]===!0}function refArgs(e){let t=[];for(let[n,r]of Object.entries(e.options))for(let e of Array.isArray(r)?r:[r])e!==void 0&&e!==!1&&(t.push(`--${n}`),e!==!0&&t.push(shellQuote(e)));return t}function refHelp(e,t){return t?`Run \`${e}\` to ${t}`:`Run \`${e}\``}function renderHelp(e,t=bareResolver,n=`help`){let r=[],i=[];for(let a of e){if(!isRef(a)){r.push(a);continue}let e=t(a);e!==void 0&&(n===`next`?i.push({run:e,why:a.why??``}):r.push(refHelp(e,a.why)))}return{help:r,next:i}}function bareResolver(e){return[e.path,...refArgs(e)].join(` `)}function shellQuote(e){if(typeof e==`object`&&e&&ie in e)return`<${e[ie]}>`;let t=String(e);return/^[\w./:@%+=,-]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}var ae;const j={success:0,error:1,usage:2},oe=Symbol.for(`clibuilder.CliError`),se=Symbol.for(`clibuilder.CliError.reported`),ce=Symbol.for(`clibuilder.CliError.helpLines`),le=[`error`,`code`,`help`];var M=class CliError extends Error{static reported(e=j.error,t=`the error was already reported`){let n=new CliError(t,{exitCode:e});return n[se]=!0,n}constructor(e,t){let n=typeof e==`string`?{...t,message:e}:e;super(n.message),this.name=`CliError`,this[ae]=!0,this.exitCode=validateExitCode$1(n.exitCode??j.error),this.code=validateCode(n.code??`error`),this.details=validateDetails(n.details??{});let r=n.help===void 0?[]:Array.isArray(n.help)?[...n.help]:[n.help];this[ce]=r,this.help=r.map(e=>isRef(e)?refHelp(bareResolver(e),e.why):e),this.cause=n.cause}};ae=oe;function isCliError(e){return!!e&&typeof e==`object`&&e[oe]===!0}function helpLinesOf(e){return e[ce]??e.help??[]}function isReportedCliError(e){return e[se]===!0}function validateExitCode$1(e){if(Number.isInteger(e)&&e>=1&&e<=255)return e;throw RangeError(`CliError exitCode must be an integer from 1 to 255, received ${e}`)}__name(validateExitCode$1,`validateExitCode`);function validateCode(e){if(/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e))return e;throw RangeError(`CliError code must be a kebab-case string such as "not-found", received "${e}"`)}function validateDetails(e){for(let t of le)if(t in e)throw RangeError(`CliError details may not have the key "${t}"`);return{...e}}function command(e){return e}function takesValue$1(e){let t=e.kind===`array`?e.element:e;return!(t.kind===`boolean`||t.kind===`literal`&&typeof t.value==`boolean`)}__name(takesValue$1,`takesValue`);function describeConstraint(e){switch(e.kind){case`string`:return e.pattern?`string ${e.pattern}`:`string`;case`number`:case`int`:return`${e.kind}${describeRange(e.min,e.max)}`;case`boolean`:case`json`:return e.kind;case`literal`:return String(e.value);case`enum`:return e.values.join(`|`);case`custom`:return`value`;case`array`:return describeConstraint(e.element)}}function describeRange(e,t){return e!==void 0&&t!==void 0?` ${e}..${t}`:e===void 0?t===void 0?``:` <=${t}`:` >=${e}`}function getProp$1(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}__name(getProp$1,`getProp`);function setProp(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}const ue=Symbol.for(`args-minus.descriptor`),de={[ue]:1,optional(){return create({...this,isOptional:!0})},check(e){let t=typeof e==`function`?{type:`fn`,fn:e}:{type:`schema`,schema:e};if(typeof e!=`function`&&!isStandardSchema(e))throw TypeError(`check() takes a function or a Standard Schema`);return create({...this,checks:[...this.checks,t]})}};function create(e){return Object.freeze(Object.assign(Object.create(de),e))}function make(e){return create({...e,isOptional:!1,checks:Object.freeze([])})}function isStandardSchema(e){let t=e?.[`~standard`];return typeof t==`object`&&!!t&&typeof t.validate==`function`}function checkBounds(e,t,n){let{min:r,max:i}=t??{};for(let[t,a]of[[`min`,r],[`max`,i]])if(a!==void 0){if(typeof a!=`number`||Number.isNaN(a))throw TypeError(`${e}: ${t} must be a number`);if(n&&Number.isFinite(a)&&!Number.isInteger(a))throw RangeError(`${e}: ${t} must be an integer, got ${a}`)}if(r!==void 0&&i!==void 0&&r>i)throw RangeError(`${e}: min (${r}) is greater than max (${i})`);return{...r===void 0?{}:{min:r},...i===void 0?{}:{max:i}}}function string(e){let t=e?.pattern;if(t!==void 0&&!(t instanceof RegExp))throw TypeError(`t.string: pattern must be a RegExp`);return make(t===void 0?{kind:`string`}:{kind:`string`,pattern:t})}function json(e){if(e===void 0)return make({kind:`json`});if(!isStandardSchema(e))throw TypeError(`t.json: schema must be a Standard Schema`);return make({kind:`json`,schema:e})}const N={string,number(e){return make({kind:`number`,...checkBounds(`t.number`,e,!1)})},int(e){return make({kind:`int`,...checkBounds(`t.int`,e,!0)})},boolean(){return make({kind:`boolean`})},literal(e){let t=typeof e;if(!(t===`string`||t===`boolean`||t===`number`&&Number.isFinite(e)))throw TypeError(`t.literal: value must be a string, a finite number or a boolean, got ${String(e)}`);return make({kind:`literal`,value:e})},enum(e){if(!Array.isArray(e)||e.length===0)throw TypeError(`t.enum: values must be a non-empty array`);for(let t of e)if(typeof t!=`string`)throw TypeError(`t.enum: values must be strings, got ${String(t)}`);return make({kind:`enum`,values:Object.freeze([...e])})},array(e){let t=e;if(!isDescriptor(t))throw TypeError(`t.array: element must be a descriptor`);if(t.kind===`array`)throw TypeError(`t.array: element cannot be an array`);if(t.isOptional)throw TypeError(`t.array: element cannot be optional`);return make({kind:`array`,element:e})},custom(e){if(typeof e!=`function`)throw TypeError(`t.custom: convert must be a function`);return make({kind:`custom`,convert:e})},json};function isDescriptor(e){return typeof e==`object`&&!!e&&e[ue]===1&&typeof e.kind==`string`}String.prototype.charCodeAt;const fe=String.prototype.slice;Array.prototype.forEach,Array.prototype.map,Array.prototype.reduce;const pe=Array.prototype.slice,me=Array.prototype.push,he={modifiers:`-`,terminator:`--`};function resolveGrammar(e){let t=new Set,n=e?.modifiers??he.modifiers;for(let e of typeof n==`string`?Array.from(n):n){if(e.length!==1||e===`=`)throw Error(`Invalid modifier '${e}': a modifier must be a single character other than '='`);t.add(e)}if(t.size===0)throw Error(`At least one modifier is required`);let r=e?.terminator??he.terminator;if(r===``)throw Error(`The terminator must not be empty`);return{modifiers:t,terminator:r}}function trimModifiers(e,t){let n=0;for(;n<e.length&&t.has(e[n]);)n++;return[fe.call(e,n),n]}function tokenizeArgs(e,t){let{modifiers:n,terminator:r}=resolveGrammar(t),i=[],a=0,o=pe.call(e);for(;o.length>0;){let e=o.shift();if(e===r){me.call(i,{kind:`option-terminator`,index:a}),a++,me.apply(i,o.map((e,t)=>({kind:`positional`,index:a+t,value:e})));break}let[t,s]=trimModifiers(e,n);if(s===0||!t)me.call(i,{kind:`positional`,index:a,value:t||e});else{let n=t.indexOf(`=`),[r,o]=n===-1?[t,void 0]:[fe.call(t,0,n),fe.call(t,n+1)];me.call(i,{kind:`option`,index:a,name:r,dashes:s,raw:e,value:o})}a++}return i}var ParseArgsError=class extends Error{constructor(e,t,n,r={}){super(e),Object.defineProperty(this,"option",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"input",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"kind",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"issues",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"detail",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=`ParseArgsError`,this.kind=r.kind??`invalid-value`,this.index=r.index,this.issues=r.issues,this.value=r.value,this.detail=r.detail??e}};function parseArgs(e){let t=parse$1(e),n=t.next();for(;!n.done;){let{value:e,option:r}=n.value;if(isThenable(e))throw e.then(void 0,()=>{}),t.return(void 0),Error(`Option '${r}' has an asynchronous converter or check: use parseArgsAsync() to parse it`);n=t.next(e)}return n.value}async function parseArgsAsync(e){let t=parse$1(e),n=t.next();for(;!n.done;)n=await Promise.resolve(n.value.value).then(e=>t.next(e),e=>t.throw(e));return n.value}function isThenable(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&typeof e.then==`function`}function*parse$1(e){let t=tokenizeArgs(e.args,e.grammar),n=e.options;checkDeclarations(n);let r=canonicalNames(n),i=Object.create(null),a=Object.create(null),o=[],s=[],c=t.slice();for(;c.length>0;){let t=c.shift();switch(t.kind){case`positional`:checkPositional(e,t.value),o.push(t.value);break;case`option`:{let o=t.dashes===1?Array.from(t.name):[t.name];for(let s=0;s<o.length;s++){let l=o[s],u=s===o.length-1,d=r.get(l)??l,f=n&&getProp(n,d);if(e.strict&&!f)throw new ParseArgsError(`Unknown option '${l}' (from '${t.raw}')`,l,t.raw,{kind:`unknown-option`});if(!u&&f&&takesValue(f))throw new ParseArgsError(`Invalid option group '${t.raw}': '${l}' takes a value, so it can only be the last option in a group`,d,t.raw,{kind:`invalid-group`,detail:`takes a value, so it can only be the last option in a group`});let p=u?t.value??takeFollowingValue(f,c):void 0;if(f&&isDescriptor(f.type)){let e=f.type;if(e.kind===`array`){let n=i[d]??(i[d]=[]);(a[d]??(a[d]=[])).push(t.raw);let r={name:d,label:`${d}[${n.length}]`,index:n.length,token:t};n.push(yield*convertAndCheck(e.element,p,r))}else i[d]=yield*convertAndCheck(e,p,{name:d,label:d,index:void 0,token:t});continue}let m=convert(f,d,p,t);f?.multiple?(i[d]??(i[d]=[])).push(m):i[d]=m}break}case`option-terminator`:for(let t of c)checkPositional(e,t.value);s.push(...c.map(e=>e.value)),c.length=0}}for(let[e,t]of Object.entries(n??{})){let n=isDescriptor(t.type)?t.type:void 0;if(i[e]!==void 0){if(n?.kind===`array`){let t=a[e].join(` `);yield*runChecks(n,i[e],e,(n,r)=>usageError(e,e,t,n,{issues:r}))}continue}if(t.default!==void 0)n&&(yield*checkDefault(t,e)),i[e]=Array.isArray(t.default)?[...t.default]:t.default;else if(n&&!n.isOptional)throw new ParseArgsError(`Missing required option '${e}'`,e,``,{kind:`missing-option`,detail:`a value is required`})}let l={_:o,__:s,options:i};return e.tokens&&(l.tokens=t),l}__name(parse$1,`parse`);function getProp(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function checkDeclarations(e){for(let[t,n]of Object.entries(e??{})){let e=n.type;if(typeof e==`object`&&e&&!isDescriptor(e))throw TypeError(`Option '${t}' has a type that is neither a type name nor a descriptor from t`);if(isDescriptor(e)&&n.multiple!==void 0)throw TypeError(`Option '${t}' cannot set 'multiple' with a descriptor: use t.array(element)`)}}function checkPositional(e,t){if(e.allowPositionals===!1)throw new ParseArgsError(`Unexpected positional argument '${t}'`,void 0,t,{kind:`unexpected-positional`})}function canonicalNames(e){let t=new Map;if(!e)return t;for(let n of Object.keys(e))t.set(n,n);for(let[n,r]of Object.entries(e)){let e=r.alias;for(let r of e===void 0?[]:Array.isArray(e)?e:[e]){let e=t.get(r);if(e!==void 0&&e!==n)throw Error(`Alias '${r}' of option '${n}' is already used by option '${e}'`);t.set(r,n)}}return t}function elementOf(e){return e.kind===`array`?e.element:e}function takesValue(e){if(!isDescriptor(e.type))return e.type!==`boolean`;let t=elementOf(e.type);return!(t.kind===`boolean`||t.kind===`literal`&&typeof t.value==`boolean`)}function isNumeric(e){if(!isDescriptor(e.type))return e.type===`number`;let t=elementOf(e.type);return t.kind===`number`||t.kind===`int`||t.kind===`literal`&&typeof t.value==`number`}function takeFollowingValue(e,t){if(!e||!takesValue(e))return;let n=t[0];if(n){if(n.kind===`positional`)return t.shift(),n.value;if(n.kind===`option`&&isNumeric(e)&&Number.isFinite(toNumber(n.raw)))return t.shift(),n.raw}}function convert(e,t,n,r){if(!e)return n??!0;switch(e.type){case`boolean`:return convertBoolean(t,n,r);case`number`:return convertNumber(t,n,r);default:if(n===void 0)throw invalid(t,`a value is required`,r,`missing-value`);return n}}function invalid(e,t,n,r,i){return new ParseArgsError(`Invalid value for option '${e}': ${t} (from '${n.raw}')`,e,n.raw,{kind:r,value:i,detail:t})}function toNumber(e){return e.trim()===``?NaN:Number(e)}function convertNumber(e,t,n){if(t===void 0)throw invalid(e,`a number is required`,n,`missing-value`);let r=toNumber(t);if(!Number.isFinite(r))throw invalid(e,t,n,`invalid-value`,t);return r}function convertBoolean(e,t,n){if(t===void 0)return!0;if(t===`false`||t===`f`||t===`0`)return!1;if(t===`true`||t===`t`)return!0;let r=toNumber(t);if(!Number.isNaN(r))return r>0;throw invalid(e,t,n,`invalid-value`,t)}function usageError(e,t,n,r,i,a=r){return new ParseArgsError(`Invalid value for option '${t}': ${a} (from '${n}')`,e,n,{...i,detail:r})}function*convertAndCheck(e,t,n){let fail=(e,r,i)=>usageError(n.name,n.label,n.token.raw,e,{index:n.index,issues:r,value:t},i),r=yield*convertDescriptor(e,t,n,fail);return yield*runChecks(e,r,n.label,fail),r}function quote$1(e){return`'${e}'`}__name(quote$1,`quote`);function describeExpected(e){switch(e.kind){case`string`:return`a string matching ${e.pattern}`;case`number`:case`int`:{let t=e.kind===`int`?`an integer`:`a number`;return e.min!==void 0&&e.max!==void 0?`${t} from ${e.min} to ${e.max}`:e.min===void 0?e.max===void 0?t:`${t} of at most ${e.max}`:`${t} of at least ${e.min}`}case`boolean`:return`no value, true or false`;case`literal`:return typeof e.value==`string`?quote$1(e.value):String(e.value);case`enum`:return`one of ${e.values.map(quote$1).join(`, `)}`}}function*convertDescriptor(e,t,n,r){let expected=e=>r(`expected ${describeExpected(e)}`,void 0,`expected ${describeExpected(e)}, got ${quote$1(t)}`);if(e.kind===`boolean`||e.kind===`literal`&&typeof e.value==`boolean`){let n=t===void 0||t===`true`||t!==`false`&&void 0;if(n===void 0||e.kind===`literal`&&n!==e.value)throw t===void 0?r(`expected ${describeExpected(e)}`,void 0,`expected ${describeExpected(e)}, got no value`):expected(e);return n}if(t===void 0)throw usageError(n.name,n.label,n.token.raw,`a value is required`,{kind:`missing-value`,index:n.index});switch(e.kind){case`string`:if(e.pattern&&(e.pattern.lastIndex=0,!e.pattern.test(t)))throw expected(e);return t;case`number`:case`int`:{let n=toNumber(t);if(!Number.isFinite(n)||e.kind===`int`&&!Number.isInteger(n)||e.min!==void 0&&n<e.min||e.max!==void 0&&n>e.max)throw expected(e);return n}case`literal`:{let n=typeof e.value==`number`?toNumber(t):t;if(n!==e.value)throw expected(e);return n}case`enum`:if(!e.values.includes(t))throw expected(e);return t;case`custom`:try{return yield{value:e.convert(t),option:n.label}}catch(e){throw usageFailure(e,r)}case`json`:{let i;try{i=JSON.parse(t)}catch{throw r(`not valid JSON`,void 0,`${quote$1(t)} is not valid JSON`)}if(!e.schema)return i;let a=yield{value:e.schema[`~standard`].validate(i),option:n.label};if(a.issues)throw r(`does not match the expected shape`,a.issues);return a.value}}}function usageFailure(e,t){return e instanceof Error&&e.constructor===Error?t(e.message):e}function*runChecks(e,t,n,r){for(let i of e.checks)if(i.type===`fn`){let e=yield{value:i.fn(t),option:n};if(e===!1)throw r(`failed a check`);if(typeof e==`string`)throw r(e)}else{let e=yield{value:i.schema[`~standard`].validate(t),option:n};if(e.issues)throw r(`failed a check`,e.issues)}}const ge=new WeakMap;function*checkDefault(e,t){if(ge.has(e))return;let n=e.type,failFor=e=>t=>Error(`The default of option '${e}' failed a check${t===`failed a check`?``:`: ${t}`}`);if(n.kind===`array`){let r=e.default;for(let e=0;e<r.length;e++){let i=`${t}[${e}]`;yield*runChecks(n.element,r[e],i,failFor(i))}}yield*runChecks(n,e.default,t,failFor(t)),ge.set(e,!0)}const _e=new WeakMap;function lookupCommand(e,t,n){let r=matchCommand(e,createPathCursor(t,n)),[i,a]=assignOptionValues(t,r,n);return processCommand(r,i,a)}function matchCommand(e,t){if(e.commands){let n=e.commands,r=t.peek(e);for(let e=n.length-1;e>=0;e--){let i=n[e];if(!i.name)return i;if(r===i.name||i.alias?.includes(r))return t.consume(),i.commands?matchCommand(i,t):i}}return e}function createPathCursor(e,t){let n=_e.get(e)??[],r,i=-1,a=0;return{peek(o){if(r=void 0,i<0){if(a<e._.length)return(r=[e._,a])[0][a];i=0,a=-1}for(;t&&i<n.length;){let e=n[i];if(a<0){let n=lookupOptions(t,e.key)[1];if(!n)return;a=countFollowing(lookupOptions(o,e.key)[1]??n,e)}if(a<e.following.length)return(r=[e.following,a])[0][a];i++,a=-1}},consume(){r[0].splice(r[1],1)}}}function assignOptionValues(e,t,n){let r=_e.get(e);if(!r)return[e,void 0];let i={},a=[],o=[];for(let e of r){let r=lookupOptions(t,e.key)[1],s=countFollowing(r??(n&&lookupOptions(n,e.key)[1]),e),c=e.following.slice(0,s);r&&o.push({key:e.key,tokens:[e.raw,...c]}),a.push(...e.following.slice(s));let l=e.inline.length+c.length>0?[...e.inline,...c]:[`true`];setProp(i,e.key,[...getProp$1(i,e.key)??[],...l])}let s={...e,_:[...e._,...a]};for(let t of Object.keys(i))getProp$1(e,t)&&setProp(s,t,i[t]);return[s,o]}function countFollowing(e,t){return e?t.inline.length===0&&takesValue$1(optionType(e))?1:0:t.following.length}const ve=N.boolean().optional(),ye=N.string();function optionType(e){return e.type??ve}function processCommand(e,t,n){return collectDescriptorOptions(checkConflicts(fillInputOptions(fillArguments({command:e,rawArgs:t,args:{_:[]},errors:[],descriptors:[]}))),n)}function fillArguments(e){let t=e.command,n=[...e.rawArgs._],r=t.arguments||[];for(let t of r){let r=t.type??ye;if(n.length===0){r.isOptional||e.errors.push({type:`missing-argument`,name:t.name});continue}let i=r.kind===`array`?n.splice(0):[n.shift()];e.descriptors.push({type:`argument`,name:t.name,descriptor:r,values:i})}return n.length>0&&e.errors.push({type:`extra-arguments`,name:t.name,values:n}),e}function fillInputOptions(e){for(let t of Object.keys(e.rawArgs)){if(t===`_`)continue;if(/^-/.test(t)){e.errors.push({type:`invalid-key`,key:t});continue}let[n,r]=lookupOptions(e.command,t);if(!n){e.errors.push({type:`invalid-key`,key:t});continue}let i=optionType(r),a=e.rawArgs[t];i.kind!==`array`&&a.length>1&&e.errors.push({type:`expect-single`,key:t,keyKind:i.kind,value:a})}return e}function checkConflicts(e){let t=e.command.options;if(!t)return e;let n=new Map;for(let t of Object.keys(e.rawArgs)){let[r]=lookupOptions(e.command,t);r&&!n.has(r)&&n.set(r,t)}let r=[...n.keys()];for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){let[o,s]=[r[i],r[a]];if(!t[o].conflicts?.includes(s)&&!t[s].conflicts?.includes(o))continue;let[c,l]=t[o].conflicts?.includes(s)?[o,s]:[s,o];e.errors.push({type:`conflicting-options`,key:n.get(c),conflictsWith:n.get(l)})}return e}function collectDescriptorOptions(e,t){let n=e.command.options??{};for(let r of Object.keys(n)){let i=n[r],a=Object.keys(e.rawArgs).filter(t=>t!==`_`&&lookupOptions(e.command,t)[0]===r);e.errors.some(e=>e.type===`expect-single`&&a.includes(e.key))||e.descriptors.push({type:`option`,name:r,entry:{...i,type:optionType(i)},occurrences:t?t.filter(e=>a.includes(e.key)):a.flatMap(t=>e.rawArgs[t].map(e=>({key:t,tokens:[`--${r}=${e}`]})))})}return e}function lookupOptions(e,t){let n=e.options;if(!n)return[];let r=getProp$1(n,t);if(r)return[t,r];let i=Object.keys(n).find(e=>{let r=n[e];return r.alias?r.alias.some(e=>e===t||e.alias===t):!1});return i?[i,n[i]]:[]}const be={comma:`,`,tab:` `,pipe:`|`},xe=be.comma;function escapeString(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`).replace(/[\u0000-\u001F]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function isBooleanOrNullLiteral(e){return e===`true`||e===`false`||e===`null`}function setOwnProperty(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}const Se=RegExp(`(?:^?|\\n) *#`);var RawString=class{constructor(e){if(Se.test(e))throw TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(e)}`);this.value=e}};function rawString(e){return new RawString(e)}function isRawString(e){return e instanceof RawString}const Ce=/[\uD800-\uDFFF]/;function normalizeValue(e){if(e===null)return null;if(isRawString(e))return e;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return normalizeValue(t)}if(typeof e==`string`)return assertNoLoneSurrogate(e,`string value`),e;if(typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(normalizeValue);if(e instanceof Set)return Array.from(e).map(normalizeValue);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),normalizeValue(t)]));if(isPlainObject(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(assertNoLoneSurrogate(n,`object key`),setOwnProperty(t,n,normalizeValue(e[n])));return t}return null}function assertNoLoneSurrogate(e,t){if(Ce.test(e))for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r<55296||r>57343)continue;let i=r<=56319,a=e.charCodeAt(n+1);if(i&&a>=56320&&a<=57343){n++;continue}throw TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${r.toString(16).toUpperCase()} at index ${n}`)}}function isJsonPrimitive(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function isEncodablePrimitive(e){return isJsonPrimitive(e)||isRawString(e)}function isJsonArray(e){return Array.isArray(e)}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!isRawString(e)}function isEmptyObject(e){return Object.keys(e).length===0}function isPlainObject(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function isArrayOfPrimitives(e){return e.length===0||e.every(e=>isEncodablePrimitive(e))}function isArrayOfArrays(e){return e.length===0||e.every(e=>isJsonArray(e))}function isArrayOfObjects(e){return e.length===0||e.every(e=>isJsonObject(e))}const we=/^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;function assertValidDelimiter(e){if(!Object.values(be).includes(e))throw TypeError(`Invalid delimiter ${JSON.stringify(e)}. Valid delimiters are: comma (,), tab (\\t), pipe (|)`)}function isValidUnquotedKey(e){return/^[A-Z_][\w.]*$/i.test(e)}function isSafeUnquoted(e,t=xe){return!(!e||/^[ \t]|[ \t]$/.test(e)||isBooleanOrNullLiteral(e)||isNumericLike(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`)||e.startsWith(`#`))}function isNumericLike(e){return we.test(e)}function encodePrimitive(e,t){return isRawString(e)?e.value:e===null?`null`:typeof e==`boolean`||typeof e==`number`?String(e):encodeStringLiteral(e,t)}function encodeStringLiteral(e,t=xe){return isSafeUnquoted(e,t)?e:`"${escapeString(e)}"`}function encodeKey(e){return isValidUnquotedKey(e)?e:`"${escapeString(e)}"`}function encodeAndJoinPrimitives(e,t=xe){return e.map(e=>encodePrimitive(e,t)).join(t)}function formatHeader(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;return n!=null&&(a+=encodeKey(n)),a+=`[${e}${t?.keyed?`:`:``}${i===xe?``:i}]`,r&&(a+=`{${formatFieldSegment(r,i)}}`),a+=`:`,a}function formatFieldSegment(e,t){return e.map(e=>encodeKey(e.name)+(e.children?`{${formatFieldSegment(e.children,t)}}`:``)).join(t)}function extractTabularFields(e){if(e.length===0)return;let t=Object.keys(e[0]);if(t.length===0)return;for(let n of e){if(Object.keys(n).length!==t.length)return;for(let e of t)if(!Object.hasOwn(n,e))return}let n=[];for(let r of t){let t=classifyColumn(r,e.map(e=>e[r]));if(!t)return;n.push(t)}return n}function extractKeyedTabularFields(e){let t=Object.values(e);if(!(t.length<2)&&t.every(e=>isJsonObject(e)&&!isEmptyObject(e)))return extractTabularFields(t)}function collectRowLeaves(e,t){let n=[];return collectLeafValues(e,t,n),n}function classifyColumn(e,t){if(t.every(e=>isEncodablePrimitive(e)))return{name:e};if(!t.every(e=>isJsonObject(e)&&!isEmptyObject(e)))return;let n=extractTabularFields(t);if(n)return{name:e,children:n}}function collectLeafValues(e,t,n){for(let r of t){let t=e[r.name];r.children?collectLeafValues(t,r.children,n):n.push(t)}}function*encodeJsonValue(e,t,n){if(isEncodablePrimitive(e)){let n=encodePrimitive(e,t.delimiter);n!==``&&(yield n);return}if(isJsonArray(e))yield*encodeArrayLines(void 0,e,n,t);else if(isJsonObject(e)){let r=extractKeyedTabularFields(e);if(r){yield*encodeKeyedObjectLines(void 0,e,r,n,t);return}yield*encodeObjectLines(e,n,t)}}function*encodeObjectLines(e,t,n){for(let[r,i]of Object.entries(e))yield*encodeKeyValuePairLines(r,i,t,n)}function*encodeKeyValuePairLines(e,t,n,r){let i=encodeKey(e);if(isEncodablePrimitive(t))yield indentedLine(n,`${i}: ${encodePrimitive(t,r.delimiter)}`,r.indentSize);else if(isJsonArray(t))yield*encodeArrayLines(e,t,n,r);else if(isJsonObject(t)){let a=extractKeyedTabularFields(t);if(a){yield*encodeKeyedObjectLines(e,t,a,n,r);return}yield indentedLine(n,`${i}:`,r.indentSize),isEmptyObject(t)||(yield*encodeObjectLines(t,n+1,r))}}function*encodeKeyedObjectLines(e,t,n,r,i){let a=Object.entries(t);yield indentedLine(r,formatHeader(a.length,{key:e,fields:n,delimiter:i.delimiter,keyed:!0}),i.indentSize),yield*encodeKeyedEntryRowsLines(a,n,r+1,i)}function*encodeKeyedEntryRowsLines(e,t,n,r){for(let[i,a]of e){let e=collectRowLeaves(a,t);yield indentedLine(n,`${encodeKey(i)}: ${encodeAndJoinPrimitives(e,r.delimiter)}`,r.indentSize)}}function*encodeArrayLines(e,t,n,r){if(t.length===0){yield indentedLine(n,e==null?`[]`:`${encodeKey(e)}: []`,r.indentSize);return}if(isArrayOfPrimitives(t)){yield indentedLine(n,encodeInlineArrayLine(t,r.delimiter,e),r.indentSize);return}if(isArrayOfArrays(t)&&t.every(e=>isArrayOfPrimitives(e))){yield*encodeArrayOfArraysAsListItemsLines(e,t,n,r);return}if(isArrayOfObjects(t)){let i=extractTabularFields(t);i?yield*encodeArrayOfObjectsAsTabularLines(e,t,i,n,r):yield*encodeMixedArrayAsListItemsLines(e,t,n,r);return}yield*encodeMixedArrayAsListItemsLines(e,t,n,r)}function*encodeArrayOfArraysAsListItemsLines(e,t,n,r){yield indentedLine(n,formatHeader(t.length,{key:e,delimiter:r.delimiter}),r.indentSize);for(let e of t)if(isArrayOfPrimitives(e)){let t=encodeInlineArrayLine(e,r.delimiter);yield indentedListItem(n+1,t,r.indentSize)}}function encodeInlineArrayLine(e,t,n){let r=formatHeader(e.length,{key:n,delimiter:t}),i=encodeAndJoinPrimitives(e,t);return e.length===0?r:`${r} ${i}`}function*encodeArrayOfObjectsAsTabularLines(e,t,n,r,i){yield indentedLine(r,formatHeader(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indentSize),yield*writeTabularRowsLines(t,n,r+1,i)}function*writeTabularRowsLines(e,t,n,r){for(let i of e)yield indentedLine(n,encodeAndJoinPrimitives(collectRowLeaves(i,t),r.delimiter),r.indentSize)}function*encodeMixedArrayAsListItemsLines(e,t,n,r){yield indentedLine(n,formatHeader(t.length,{key:e,delimiter:r.delimiter}),r.indentSize);for(let e of t)yield*encodeListItemValueLines(e,n+1,r)}function*encodeObjectAsListItemLines(e,t,n){if(isEmptyObject(e)){yield indentedLine(t,`-`,n.indentSize);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(isJsonArray(a)&&isArrayOfObjects(a)){let e=extractTabularFields(a);if(e){yield indentedListItem(t,formatHeader(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indentSize),yield*writeTabularRowsLines(a,e,t+2,n),o.length>0&&(yield*encodeObjectLines(Object.fromEntries(o),t+1,n));return}}if(isJsonObject(a)){let e=extractKeyedTabularFields(a);if(e){let r=Object.entries(a);yield indentedListItem(t,formatHeader(r.length,{key:i,fields:e,delimiter:n.delimiter,keyed:!0}),n.indentSize),yield*encodeKeyedEntryRowsLines(r,e,t+2,n),o.length>0&&(yield*encodeObjectLines(Object.fromEntries(o),t+1,n));return}}let s=encodeKey(i);if(isEncodablePrimitive(a))yield indentedListItem(t,`${s}: ${encodePrimitive(a,n.delimiter)}`,n.indentSize);else if(isJsonArray(a)){if(a.length===0)yield indentedListItem(t,`${s}: []`,n.indentSize);else if(isArrayOfPrimitives(a))yield indentedListItem(t,`${s}${encodeInlineArrayLine(a,n.delimiter)}`,n.indentSize);else{yield indentedListItem(t,`${s}${formatHeader(a.length,{delimiter:n.delimiter})}`,n.indentSize);for(let e of a)yield*encodeListItemValueLines(e,t+2,n)}}else isJsonObject(a)&&(yield indentedListItem(t,`${s}:`,n.indentSize),isEmptyObject(a)||(yield*encodeObjectLines(a,t+2,n)));o.length>0&&(yield*encodeObjectLines(Object.fromEntries(o),t+1,n))}function*encodeListItemValueLines(e,t,n){if(isEncodablePrimitive(e))yield indentedListItem(t,encodePrimitive(e,n.delimiter),n.indentSize);else if(isJsonArray(e)){if(isArrayOfPrimitives(e))yield indentedListItem(t,encodeInlineArrayLine(e,n.delimiter),n.indentSize);else{yield indentedListItem(t,formatHeader(e.length,{delimiter:n.delimiter}),n.indentSize);for(let r of e)yield*encodeListItemValueLines(r,t+1,n)}}else isJsonObject(e)&&(yield*encodeObjectAsListItemLines(e,t,n))}function indentedLine(e,t,n){return` `.repeat(n*e)+t}function indentedListItem(e,t,n){return indentedLine(e,`- `+t,n)}function applyReplacer(e,t){let n=t(``,e,[]);return n===void 0?transformChildren(e,t,[]):transformReplaced(e,n,t,[])}function transformReplaced(e,t,n,r){return isRawString(t)&&!isEncodablePrimitive(e)?transformChildren(e,n,r):transformChildren(normalizeValue(t),n,r)}function transformChildren(e,t,n){return isJsonObject(e)?transformObject(e,t,n):isJsonArray(e)?transformArray(e,t,n):e}function transformObject(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&setOwnProperty(r,i,transformReplaced(a,o,t,e))}return r}function transformArray(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);s!==void 0&&r.push(transformReplaced(a,s,t,o))}return r}function encode$1(e,t){return Array.from(encodeLines(e,t)).join(`
8
+ `)}__name(encode$1,`encode`);function encodeLines(e,t){let n=normalizeValue(e),r=resolveOptions(t);return encodeJsonValue(r.replacer?applyReplacer(n,r.replacer):n,r,0)}function resolveOptions(e){let t=e?.delimiter??xe;return assertValidDelimiter(t),{indentSize:e?.indentSize??e?.indent??2,delimiter:t,replacer:e?.replacer}}function isRecord$3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}__name(isRecord$3,`isRecord`);function cell$1(e){return e===void 0?``:String(e)}__name(cell$1,`cell`);function table(e){let t=[...new Set(e.flatMap(e=>Object.keys(e)))],n=t.map(t=>Math.max(t.length,...e.map(e=>cell$1(e[t]).length))),line=e=>` ${e.map((e,t)=>e.padEnd(n[t])).join(` `)}`.trimEnd();return[line(t),...e.map(e=>line(t.map(t=>cell$1(e[t]))))]}function renderText(e){let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>{if(!Array.isArray(t))return[`${e}: ${isRecord$3(t)?JSON.stringify(t):String(t)}`];if(!t.length)return[`${e}: (none)`];let n=t.every(isRecord$3)?table(t):t.map(e=>` - ${String(e)}`);return[`${e}:`,...n]});return t.flatMap((e,n)=>{let r=t[n-1];return r&&(r.length>1||e.length>1)?[``,...e]:e}).join(`
9
+ `)}const Te=[`toon`,`json`,`text`];function encode(e,t){return t===`json`?JSON.stringify(e):t===`text`?renderText(e):encode$1(e,{replacer:plainLine})}function plainLine(e,t,n){return typeof t!=`string`||n.length===0||n.some(e=>typeof e==`number`)?t:readsBackAsIs(t)?rawString(t):t}function readsBackAsIs(e){return e===``||e===`[]`||e.startsWith(`"`)||e.startsWith(`#`)||/^\s|\s$/.test(e)||hasControlCharacter(e)||e===`true`||e===`false`||e===`null`?!1:!/^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(e)}function hasControlCharacter(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!0}return!1}function errorOutput({message:e,code:t,details:n,help:r}){let i={error:e,code:t,...n};return r&&r.length>0&&(i.help=[...r]),i}const Ee=Symbol.for(`clibuilder.global-format`),De=Symbol.for(`clibuilder.defers-to-global-format`);function getBaseCommand(e,t){return command({name:``,description:e,options:{help:{type:N.boolean().optional(),description:`Print help message`,alias:[`h`]},version:{type:N.boolean().optional(),description:`Print the CLI version`,alias:[`v`]},verbose:{type:N.boolean().optional(),description:`Turn on verbose logging`,alias:[`V`]},silent:{type:N.boolean().optional(),description:`Turn off logging`},"debug-cli":{type:N.boolean().optional(),description:`Display clibuilder debug messages`},...t?.options,format:formatEntry(t?.format??`toon`)},commands:[]})}function formatEntry(e){return Object.defineProperty({type:N.enum(Te),description:`Output format: 'toon' for agents, 'json' to pipe, 'text' for humans`,default:e},Ee,{value:!0})}function isGlobalFormatEntry(e){return!!e&&e[Ee]===!0}function yieldToGlobalFormat(e){let[t,n]=lookupOptions(e,`format`);if(!t||isGlobalFormatEntry(n))return e;if(!n[De]){let n=e.name?`command '${e.name}'`:`the default command`;throw Error(`${n} declares its own option '${t}', which conflicts with the global --format option. Delete the local declaration and read this.format in run() instead. See docs/rfcs/axi-native.md section 3.4: https://github.com/clibuilder/clibuilder/blob/main/docs/rfcs/axi-native.md#34---format-is-not-first-class-6394`)}let{[t]:r,...i}=e.options;return{...e,options:i}}function defineKey(e){return{id:e,kind:`value`}}function createRegistry(){let e=new Map,t=new Map;function get(n){return n.kind===`collection`?t.get(n.id)??[]:e.get(n.id)?.value}return{register(n,r,i){if(r.kind===`collection`){let e=t.get(r.id)??[];return e.push({source:n,value:i}),t.set(r.id,e),{accepted:!0}}let a=e.get(r.id);return a?{accepted:!1,source:a.source}:(e.set(r.id,{source:n,value:i}),{accepted:!0})},get,has(n){return n.kind===`collection`?t.has(n.id):e.has(n.id)},describe(n){if(n.kind===`collection`)return(t.get(n.id)??[]).map(({source:e})=>e);let r=e.get(n.id)?.source;return r?[r]:[]}}}const Oe=defineKey(`clibuilder.config`);function parseArgv(e){let t=[],n=e.slice(2).reduce((e,n)=>(e.args.__?e.args.__.push(n):isOption(n)?(isInOptionState(e)&&(e=endOption(e)),e=startOption(e,n,t)):isInOptionState(e)?(e.values.push(n),t[t.length-1].following.push(n)):n===`--`?e.args.__=[]:e.args._.push(n),e),{args:{_:[]},key:``,values:[]}),r=(isInOptionState(n)?endOption(n):n).args;return _e.set(r,t),r}function isInOptionState(e){return!!e.key}function isOption(e){return e.startsWith(`-`)&&/\w+/.test(e)}function startOption(e,t,n){return e=/^-\w+/.test(t)?startSingleCharacterOptions(e,t,n):startMultiCharacterOptions(e,t),n.push({key:e.key,raw:t,inline:[...e.values],following:[]}),e}function startSingleCharacterOptions(e,t,n){let r=t.indexOf(`=`),[i,a]=r>0?[t.slice(1,r),[t.slice(r+1)]]:[t.slice(1),[]],o=i.split(``),s=o.pop();for(let e of o)n.push({key:e,raw:t,inline:[`true`],following:[]});return e=addBooleanOptions(e,o),e.key=s,e.values=a,e}function addBooleanOptions(e,t){return t.length<=0?e:(e.key=t.pop(),e.values=[`true`],addBooleanOptions(endOption(e),t))}function startMultiCharacterOptions(e,t){let n=t.indexOf(`=`);return n>0?(e.key=t.slice(2,n),e.values=[t.slice(n+1)]):(e.key=t.slice(2),e.values=[]),e}function endOption(e){let{key:t,values:n}=e,r={...e.args},i=getProp$1(r,t)??[];return n.length===0?i.push(`true`):i.push(...n),setProp(r,t,i),{args:r,key:``,values:[]}}const ke=new WeakMap;async function convertDescriptors(e){for(let t of e.descriptors)try{assign(e,t,await parseArgsAsync(configOf(t)))}catch(n){report$1(e,t,n)}}function convertDescriptorsSync(e){for(let t of e.descriptors)try{assign(e,t,parseArgs(configOf(t)))}catch(n){report$1(e,t,n)}}function peekFlags(e,t){let n={...e,args:{...e.args},errors:[],descriptors:e.descriptors.filter(e=>e.type===`option`&&t.includes(e.name)&&e.entry.type.kind===`boolean`&&e.entry.type.checks.length===0)};return convertDescriptorsSync(n),n.args}function configOf(e){return e.type===`option`?{args:e.occurrences.flatMap(e=>e.tokens),options:{[e.name]:declarationOf(e.entry)}}:{args:e.values.map(t=>`--${e.name}=${t}`),options:{[e.name]:{type:e.descriptor}}}}function assign(e,t,{options:n}){n[t.name]!==void 0&&setProp(e.args,t.name,n[t.name])}function report$1(e,t,n){if(!(n instanceof ParseArgsError))throw n;e.errors.push(toUsageError(n,t))}__name(report$1,`report`);function declarationOf(e){let t=ke.get(e);if(!t){let n=e.alias?.map(e=>typeof e==`string`?e:e.alias);t={type:e.type,...n?{alias:n}:{},...e.default===void 0?{}:{default:e.default}},ke.set(e,t)}return t}function toUsageError(e,t){if(e.kind===`missing-option`)return{type:`missing-argument`,name:t.name};let n=t.type===`option`?t.entry.type:t.descriptor,r=n.kind===`array`?n.element:n;return{type:`invalid-value`,key:keyOf(e,t),message:e.detail,value:e.value??(e.kind===`invalid-value`?rawValues(t):void 0),keyKind:n.kind,constraint:describeConstraint(r),...r.kind===`enum`?{allowed:r.values}:{},...e.index===void 0?{}:{index:e.index}}}function keyOf(e,t){if(t.type===`argument`)return t.name;let n=t.occurrences;return(e.index===void 0?n[n.length-1]:n[e.index])?.key??t.name}function rawValues(e){return e.type===`argument`?e.values:e.occurrences.map(e=>e.tokens.join(` `))}const Ae=Symbol.for(`clibuilder.answer`);function result(e,t={}){return{[Ae]:`result`,value:e,help:helpLines(t.help),render:t.render,exitCode:validateExitCode(t.exitCode)}}function document(e,t={}){return{[Ae]:`document`,value:String(e),exitCode:validateExitCode(t.exitCode)}}function empty(e,t={}){return{[Ae]:`empty`,value:String(e),help:helpLines(t.help)}}function isAnswer(e){return typeof e==`object`&&!!e&&typeof e[Ae]==`string`}function answerValue(e){return isAnswer(e)?e.value:e}function answerExitCode(e){if(!isAnswer(e))return 0;let t=e.exitCode;return typeof t==`number`?t:0}function printAnswer(e,t,n={}){if(e===void 0)return;let tail=e=>renderHelp(e,n.resolve,n.refs),withVerbs=(e,t)=>n.verbs&&!hasOwnCommands(e)?[...t,n.verbs]:t;if(!isAnswer(e))return print(e,tail([]),t);switch(e[Ae]){case`written`:return;case`document`:return line(e.value);case`empty`:return line(encode(withHelp({empty:e.value},tail(withVerbs(e.value,e.help))),t));case`result`:{let n=e.render?.[t];return n?withRenderedHelp(n(e.value),tail(withVerbs(e.value,e.help)),t):print(e.value,tail(withVerbs(e.value,e.help)),t)}}}function hasOwnCommands(e){return typeof e==`object`&&!!e&&`commands`in e}function print(e,t,n){return typeof e==`string`?withRenderedHelp(e,t,n):line(encode(withHelp(toRecord(e),t),n))}function withRenderedHelp(e,t,n){let r=withHelp({},t);return Object.keys(r).length===0?line(e):line(`${e}${e.endsWith(`
10
10
  `)?`
11
11
  `:`
12
12
 
13
- `}${encode(r,n)}`)}function toRecord(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{result:e}}function withHelp(e,{help:t,next:n}){if(t.length===0&&n.length===0)return e;let r={...e};return t.length>0&&(delete r.help,r.help=t),n.length>0&&(delete r.next,r.next=n),r}function helpLines(e){return e===void 0?[]:Array.isArray(e)?[...e]:[e]}function line(e){return e.endsWith(`
13
+ `}${encode(r,n)}`)}function toRecord(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{result:e}}function withHelp(e,{help:t,next:n}){if(t.length===0&&n.length===0)return e;let r={...e};return t.length>0&&(delete r.help,r.help=t),n.length>0&&(delete r.next,r.next=n),r}function helpLines(e){return e===void 0?[]:Array.isArray(e)?[...e]:[e]}function validateExitCode(e){if(e===void 0)return 0;if(Number.isInteger(e)&&e>=0&&e<=255)return e;throw RangeError(`an answer's exitCode must be an integer from 0 to 255, received ${e}`)}function line(e){return e.endsWith(`
14
14
  `)?e:`${e}\n`}function formatLookupError(e,t){switch(e.type){case`invalid-key`:return`unknown option ${formatOption(e.key)}`;case`missing-argument`:return`missing required ${formatKey$1(e.name,t,`argument`)}`;case`extra-arguments`:return`unexpected argument${e.values.length>1?`s`:``}: ${e.values.join(`, `)}`;case`invalid-value`:{let n=e.index===void 0?``:`[${e.index}]`,r=e.value===void 0?``:`, received "${e.value}"`;return`invalid value for ${formatKey$1(e.key,t)}${n}: ${e.message}${r}`}case`conflicting-options`:return`option ${formatOption(e.key)} cannot be used with option ${formatOption(e.conflictsWith)}`;case`expect-single`:return`${formatKey$1(e.key,t)} expects a single value, received: ${toArray$1(e.value).join(`, `)}`}}function formatKey$1(e,t,n=`option`){return t.arguments?.some(t=>t.name===e)||n===`argument`&&!t.options?.[e]?`argument <${e}>`:`option ${formatOption(e)}`}__name(formatKey$1,`formatKey`);function formatOption(e){return e.length===1?`-${e}`:`--${e}`}function toArray$1(e){return Array.isArray(e)?e:[e]}__name(toArray$1,`toArray`);function wrap(e,t){let n=[``];for(let r of e.split(/(\S+\s+)/)){if(r===``)continue;let e=r.replace(/\t/g,` `),i=n.length-1;if(n[i].length+e.length>t){n[i]=n[i].replace(/\s+$/,``);for(let t of e.split(`
15
15
  `))n.push(t.replace(/^\s+/,``))}else if(e.includes(`
16
16
  `)){let[t,...r]=e.split(`
17
17
  `);n[i]+=t;for(let e of r)n.push(e.replace(/^\s+/,``))}else n[i]+=e}return n.join(`
18
- `)}function generateHelpMessage(e,t){return`
19
- ${[generateUsageSection(e,t),generateDescriptionSection(t),generateCommandsSection(t),generateArgumentsSection(t),generateOptionsSection(t),generateAliasSection(t),generateConfigSection(t),generateExamplesSection(t)].filter(e=>!!e).join(`
18
+ `)}function generateHelpMessage(e,t,n){return`
19
+ ${[generateUsageSection(e,t),generateDescriptionSection(t),generateCommandsSection(t,n?.signatures??!1),generateArgumentsSection(t),generateOptionsSection(t),generateAliasSection(t),generateConfigSection(t),generateExamplesSection(t)].filter(e=>!!e).join(`
20
20
 
21
21
  `)}
22
- `}function generateUsageSection(e,t){let n=getCommandNameChain(e,t),r=t.commands&&t.commands.length>0,i=`Usage: ${n.join(` `)}${r?` <command>`:``}`;if(t.arguments&&(i+=t.arguments.some(e=>isRequired(e,!0))?` <arguments>`:` [arguments]`),t.options){let e=t.options;i+=Object.keys(e).some(t=>isRequired(e[t],!1))?` <options>`:` [options]`}return i}function isRequired({type:e,default:t},n){return e?!e.isOptional&&t===void 0:n}function generateDescriptionSection(e){return e.description?` ${e.description}`:``}function getCommandNameChain(e,t){let n=[t];for(;t.parent;)n.unshift(t.parent),t=t.parent;return[e,...n.map(e=>e.name).filter(e=>e)]}function generateCommandsSection(e){let t=getCommandsNamesAndAlias(e.commands);return t.length===0?``:`Commands:
23
- ${wrap(t.join(`, `),80)}
22
+ `}function generateUsageSection(e,t){let n=getCommandNameChain(e,t),r=t.commands&&t.commands.length>0,i=`Usage: ${n.join(` `)}${r?` <command>`:``}`;if(t.arguments&&(i+=t.arguments.some(e=>isRequired(e,!0))?` <arguments>`:` [arguments]`),hasOptions(t)){let e=t.options;i+=Object.keys(e).some(t=>isRequired(e[t],!1))?` <options>`:` [options]`}return i}function hasOptions(e){return!!e.options&&Object.keys(e.options).length>0}function commandSignature(e){let t=(e.arguments??[]).filter(e=>isRequired(e,!0)).map(e=>`<${e.name}>`);return[e.name,...t].join(` `)}function isRequired({type:e,default:t},n){return e?!e.isOptional&&t===void 0:n}function generateDescriptionSection(e){return e.description?` ${e.description}`:``}function getCommandNameChain(e,t){let n=[t];for(;t.parent;)n.unshift(t.parent),t=t.parent;return[e,...n.map(e=>e.name).filter(e=>e)]}function commandFullSignature(e){let t=[e.alias?.length?`${e.name} (${e.alias.join(`|`)})`:e.name];e.commands&&e.commands.length>0&&t.push(`<command>`);for(let n of e.arguments??[])t.push(n.type?formatArgumentDescriptor(n.name,n.type):`<${n.name}>`);if(hasOptions(e)){let n=e.options;for(let e in n)t.push(formatKeyValue(e,n[e]))}return t.join(` `)}function generateCommandsSection(e,t){let n=e.commands??[];if(n.length===0)return``;if(!t)return`Commands:
23
+ ${wrap(n.map(e=>e.alias?`${e.name} (${e.alias.join(`|`)})`:e.name).join(`, `),80)}
24
24
 
25
- ${(e.name?`${e.name} <command> -h`:` <command> -h`).padEnd(25)}Get help for <command>`}function getCommandsNamesAndAlias(e){let t=[];return e&&e.forEach(e=>{e.alias?t.push(`${e.name} (${e.alias.join(`|`)})`):t.push(e.name)}),t}function generateArgumentsSection(e){if(!e.arguments)return``;let t=`Arguments:
25
+ ${(e.name?`${e.name} <command> -h`:` <command> -h`).padEnd(25)}Get help for <command>`;let r=n.map(commandFullSignature),i=Math.max(23,...r.map(e=>e.length+2));return`Commands:
26
+ ${n.map((e,t)=>{let n=e.description?.split(`
27
+ `)[0]??``;return` ${r[t].padEnd(i)}${n}`.trimEnd()}).join(`
28
+ `)}
29
+
30
+ ${(e.name?`${e.name} <command> -h`:` <command> -h`).padEnd(25)}Get help for <command>`}function generateArgumentsSection(e){if(!e.arguments)return``;let t=`Arguments:
26
31
  `,n=[],r=0;e.arguments.forEach(e=>{let t=e.type?formatArgumentDescriptor(e.name,e.type):`<${e.name}>`;r=Math.max(r,t.length),n.push([t,e.description||``])});let i=Math.max(23,r+2);return t+=n.map(e=>` ${e[0].padEnd(i)}${e[1]}`.trimEnd()).join(`
27
- `),t}function generateOptionsSection(e){if(!e.options)return``;let t=`Options:
28
- `,n=[],r=0;for(let t in e.options){let i=e.options[t],a=formatKeyValue(t,i),o=formatDescription(i,conflictsOf(t,e.options));n.push([a,o]),r=Math.max(r,a.length)}let i=Math.max(23,r+2);return t+=n.map(e=>` ${e[0].padEnd(i)}${e[1]}`).join(`
32
+ `),t}function generateOptionsSection(e){if(!hasOptions(e))return``;let t=`Options:
33
+ `,n=[],r=0,i=e.options;for(let e in i){let t=i[e],a=formatKeyValue(e,t),o=formatDescription(t,conflictsOf(e,i));n.push([a,o]),r=Math.max(r,a.length)}let a=Math.max(23,r+2);return t+=n.map(e=>` ${e[0].padEnd(a)}${e[1]}`).join(`
29
34
  `),t}function formatKeyValue(e,t){let n=[...t.alias?t.alias.map(e=>typeof e==`string`?e:e.hidden?void 0:e.alias).filter(e=>e):[],e].sort((e,t)=>e.length-t.length).map(e=>e.length===1?`-${e}`:`--${e}`).join(`|`);return t.type?formatOptionDescriptor(n,t.type,isRequired(t,!1)):`[${n}]`}function formatOptionDescriptor(e,t,n){let r=`${e}${takesValue$1(t)?` <${describeConstraint(t)}>`:``}${t.kind===`array`?`...`:``}`;return n?r:`[${r}]`}function formatArgumentDescriptor(e,t){let n=`${e}: ${describeConstraint(t)}${t.kind===`array`?`...`:``}`;return t.isOptional?`[${n}]`:`<${n}>`}function formatDescription(e,t){let n=typeof e.default==`string`?`'${e.default}'`:e.default,r=e.default?`${e.description} (default ${n})`:e.description;return t.length===0?r:`${r} (conflicts with ${t.map(e=>e.length===1?`-${e}`:`--${e}`).join(`, `)})`}function conflictsOf(e,t){return Object.keys(t).filter(n=>n!==e&&(t[e].conflicts?.includes(n)||t[n].conflicts?.includes(e)))}function generateAliasSection(e){return e.alias?`Alias:
30
35
  ${wrap(e.alias.join(`, `),80)}`:``}function generateConfigSection(e){let t=describeConfig(e);return t===void 0?``:`Config:
31
36
  ${t}`}function describeConfig(e){if(e.config)return describeStandardConfig(e.config)}function generateExamplesSection(e){return!e.examples||e.examples.length===0?``:`Examples:
32
37
  ${e.examples.map(e=>` ${e.description}\n ${e.command}`).join(`
33
- `)}`}function describeStandardConfig(e){let t=e[`~standard`]?.jsonSchema;if(t)try{return describeJsonSchema(t.input({target:`draft-2020-12`}))}catch{return}}function describeJsonSchema(e){if(Array.isArray(e.enum))return e.enum.map(e=>JSON.stringify(e)).join(` | `);if(`const`in e)return JSON.stringify(e.const);let t=e.anyOf??e.oneOf;if(Array.isArray(t))return t.map(describeJsonSchema).join(` | `);switch(e.type){case`object`:{let t=e.properties??{},n=e.required??[],r=Object.keys(t).map(e=>`${e}${n.includes(e)?``:`?`}: ${describeJsonSchema(t[e])}`);return r.length===0?`{}`:`{ ${r.join(`, `)} }`}case`array`:{let t=e.items&&typeof e.items==`object`?e.items:{};return t.type===`object`?`Array<${describeJsonSchema(t)}>`:`${describeJsonSchema(t)}[]`}case`string`:case`boolean`:case`number`:case`null`:return e.type;case`integer`:return`number`;default:return`unknown`}}function generateHelpModel(e,t,n){let r={name:getCommandNameChain(e,t).join(` `),usage:generateUsageSection(e,t).slice(7)};t.description&&(r.description=t.description),t.alias&&t.alias.length>0&&(r.aliases=[...t.alias]),t.commands&&t.commands.length>0&&(r.commands=t.commands.map(e=>{let t={name:e.name};e.alias&&e.alias.length>0&&(t.aliases=[...e.alias]);let n=e.description?.split(`
34
- `)[0];return n&&(t.description=n),t})),t.arguments&&t.arguments.length>0&&(r.arguments=t.arguments.map(e=>{let t={name:e.name,required:isRequired(e,!0),...describeType(e.type)};return e.description&&(t.description=e.description),t}));let i=!t.parent&&!t.name,a=optionModels(t.options,i?Object.keys(n):[]);a.length>0&&(r.options=a);let o=describeConfig(t);return o!==void 0&&(r.config=o),t.examples&&t.examples.length>0&&(r.examples=t.examples.map(({command:e,description:t})=>({command:e,description:t}))),r.globalOptions=optionModels(n,[]),r}function optionModels(e,t){return e?Object.keys(e).filter(e=>!t.includes(e)).map(t=>{let n=e[t],r={name:t},i=(n.alias??[]).map(e=>typeof e==`string`?e:e.hidden?void 0:e.alias).filter(e=>!!e);i.length>0&&(r.aliases=i),Object.assign(r,describeType(n.type)),r.required=isRequired(n,!1),n.default!==void 0&&(r.default=n.default),n.description&&(r.description=n.description);let a=conflictsOf(t,e);return a.length>0&&(r.conflicts=a),r}):[]}function describeType(e){return e?describeData(e):{}}function describeData(e){switch(e.kind){case`string`:return e.pattern?{type:`string`,pattern:String(e.pattern)}:{type:`string`};case`number`:case`int`:{let t={type:e.kind};return e.min!==void 0&&(t.min=e.min),e.max!==void 0&&(t.max=e.max),t}case`literal`:return{type:`literal`,values:[e.value]};case`enum`:return{type:`enum`,values:[...e.values]};case`array`:return{...describeData(e.element),array:!0};default:return{type:e.kind}}}const Ae={"invalid-key":0,"conflicting-options":1,"invalid-value":2,"expect-single":3,"missing-argument":4,"extra-arguments":5};function topUsageError(e){return e.reduce((e,t)=>!e||Ae[t.type]<Ae[e.type]?t:e,void 0)}const je={"invalid-key":`unknown-option`,"conflicting-options":`conflicting-options`,"invalid-value":`invalid-value`,"expect-single":`expect-single`,"missing-argument":`missing-argument`,"extra-arguments":`extra-arguments`};function usageErrorCode(e){return je[e.type]}function describeUsageError(e,t,n,r=!0){let i=generateUsageSection(n,t),a=formatLookupError(e,t),o=usageErrorCode(e);switch(e.type){case`invalid-key`:return{message:a,code:o,details:{option:optionName(e.key)},help:[i,optionsHelp(t,n,r)]};case`conflicting-options`:return{message:a,code:o,details:{option:optionName(e.key),conflictsWith:optionName(e.conflictsWith)},help:[i]};case`invalid-value`:{let n=keyName(e.key,t);return{message:a,code:o,details:{...n.details,...e.value===void 0?{}:{value:rawValue(e.value)}},help:[i,...valueHelp(e,n.label)]}}case`expect-single`:return{message:a,code:o,details:{...keyName(e.key,t).details,value:toArray(e.value).map(String)},help:[i]};case`missing-argument`:return!t.arguments?.some(t=>t.name===e.name)&&t.options?.[e.name]?{message:a,code:o,details:{option:optionName(e.name)},help:[i,optionsHelp(t,n,r)]}:{message:a,code:o,details:{argument:e.name},help:[i,argumentsHelp(t,n)]};case`extra-arguments`:return{message:a,code:o,details:{arguments:e.values},help:[i,argumentsHelp(t,n)]}}}function describeMissingCommand(e,t){let n=commandName(e,t),r=(e.commands??[]).map(e=>e.name);return{message:`missing command for \`${n}\``,code:`missing-command`,details:{command:n},help:[generateUsageSection(t,e),r.length>0?`valid commands for \`${n}\`: ${r.join(`, `)}`:`\`${n}\` has no commands (--help always allowed)`]}}function optionName(e){return e.length===1?`-${e}`:`--${e}`}function keyName(e,t){return t.arguments?.some(t=>t.name===e)?{label:`<${e}>`,details:{argument:e}}:{label:optionName(e),details:{option:optionName(e)}}}function commandName(e,t){let n=[];for(let t=e;t;t=t.parent)t.name&&n.unshift(t.name);return[t,...n].join(` `)}function isOptional(e){return!!e?.isOptional}function argumentsHelp(e,t){let n=e.name||t,r=(e.commands??[]).map(e=>e.name);if(!e.arguments?.length&&r.length>0)return`valid commands for \`${n}\`: ${r.join(`, `)}`;let i=(e.arguments??[]).map(e=>isOptional(e.type)?`[${e.name}]`:`<${e.name}>`);return i.length>0?`\`${n}\` takes: ${i.join(` `)}`:`\`${n}\` takes no arguments`}function optionsHelp(e,t,n){let r=e.name||t,i=Object.keys(e.options??{}).map(optionName),a=n?` (--help always allowed)`:``;return i.length>0?`valid options for \`${r}\`: ${i.join(`, `)}${a}`:`\`${r}\` takes no options${a}`}function valueHelp(e,t){let n=e.index===void 0?``:`[${e.index}]`,r=e.value===void 0?``:` (received ${toArray(e.value).map(quote).join(`, `)})`;return e.allowed?.length?[`allowed for ${t}${n}: ${e.allowed.join(`, `)}${r}`]:e.constraint?[`expected for ${t}${n}: ${e.constraint}${r}`]:[]}function rawValue(e){return Array.isArray(e)?e.map(String):String(e)}function quote(e){return`"${String(e)}"`}function toArray(e){return Array.isArray(e)?e:[e]}function state(e){let{name:t,description:n=``,version:r}=e;return{name:t,description:n,version:r,displayLevel:`info`,command:getBaseCommand(n,{format:e.format})}}function resolveGlobalOptions(e,t,n){let r=lookupCommand(e,t);convertDescriptorsSync(r);let{args:i,errors:a}=r,o=a.filter(t=>`key`in t&&isDeclared(e,t.key)).map(withAllowedFormats(e)),s=!o.some(t=>`key`in t&&isGlobalFormatKey(e,t.key));return{help:i.help,version:i.version,verbose:i.verbose,silent:i.silent,"debug-cli":i[`debug-cli`],values:i,format:s&&i.format||n,errors:o}}function resolveUsageErrors(e,t,n,r){return e.flatMap(e=>!(`key`in e)||!isDeclared(n,e.key)||isOwn(t,e.key)?[e]:r.errors.filter(t=>`key`in t&&t.key===e.key)).map(withCode)}function withCode(e){return Object.defineProperty(e,"code",{value:usageErrorCode(e),enumerable:!1,configurable:!0})}function isDeclared(e,t){return lookupOptions(e,t).length>0}function isOwn(e,t){let[n,r]=lookupOptions(e,t);return!!n&&!isGlobalFormatEntry(r)}function isGlobalFormatKey(e,t){return isGlobalFormatEntry(lookupOptions(e,t)[1])}function withAllowedFormats(e){return t=>t.type===`invalid-value`&&isGlobalFormatKey(e,t.key)?{...t,allowed:we}:t}function builder(e,t){let n=state(t),r=t.format??`toon`,i=t.output??`axi`,a=t.refs??`help`;if(a!==`help`&&a!==`next`)throw TypeError(`cli({ refs }) must be 'help' or 'next', received ${String(a)}`);if(!we.includes(r))throw TypeError(`cli({ format }) must be one of ${we.join(`, `)}, received ${String(r)}`);let o=n.description,s=createRegistry(),c=new Map,l=[],u={},d={},f=[],p=n.command.options,m,h=!1;return{name:n.name,version:n.version||``,description:o,default(e){return n.command=adjust(n.command,{...n.command,...e}),delete this.default,{...this,parse}},command(e){return n.command.commands.push(adjust(n.command,e)),{...this,parse}},use(e){return l.push(e),{...this,parse}}};function extend(){return m??=(async()=>{let t={host:{name:n.name,version:n.version||``},cwd:e.cwd,ui:createExtensionUI(e,n),registry:s,shared:{get:e=>c.get(e.id),set(e,t){c.set(e.id,t)},has:e=>c.has(e.id)},addCommand(e){n.command.commands.push(adjust(n.command,e))},addGlobalOption(e,t,n){u[e]=t,d[e]=n},beforeRun(e){f.push(e)},async resolveConfig(){return h=!0,c.get(De.id)??{config:void 0,source:{type:`none`},candidates:[]}}};for(let e of l)await e(t);listGlobalOptions(),warnUnloadedPlugins()})()}function listGlobalOptions(){if(Object.keys(u).length===0)return;let{format:e,...t}=p;for(let e of Object.keys(p))delete p[e];Object.assign(p,t,u,{format:e})}function warnUnloadedPlugins(){let t=c.get(De.id)?.config?.plugins;!h&&Array.isArray(t)&&t.length!==0&&e.ui.warn(`the config lists plugins, but this cli loads none. Plugin loading moved out of clibuilder 12 into @clibuilder/plugins: add .use(plugins()) to the cli.`)}async function parse(a){if(isBareVersion(a)){e.writeStdout(`${n.version||`not versioned`}\n`);return}e.ui.debug(`argv:`,a.join(` `));let o=parseArgv(a);await extend();let l=getBaseCommand(n.description,{format:r,options:u}),p=resolveGlobalOptions(l,o,r);p.silent&&(delete o.silent,n.displayLevel=`none`),p.verbose&&(delete o.verbose,n.displayLevel=`debug`),p[`debug-cli`]&&(delete o[`debug-cli`],n.displayLevel=`trace`),e.ui.displayLevel=n.displayLevel,e.ui.dump();for(let t of Object.keys(d)){let r=p.values[t];if(r===void 0)continue;let a=createCommandUI(e,n,n.command);return answer(await d[t]({value:r,format:p.format,output:i,ui:a}),p.format)}let m=lookupCommand(n.command,o,l),{args:h,command:g}=m,_=peekFlags(m,[`help`,`version`]);if(p.version||_.version)return i===`axi`?writeVersion():createCommandInstance(e,n,m.command,s).ui.showVersion();if(p.help||_.help)return i===`axi`?writeHelp(m.command,l,p.format):createCommandInstance(e,n,m.command,s).ui.showHelp();await convertDescriptors(m);let v=resolveUsageErrors(m.errors,g,l,p);if(v.length>0){let r=createCommandInstance(e,n,m.command,s).ui,a=findUsageErrorHandler(g)??t.onUsageError;if(a){let e=await a(v,{command:g,ui:r,format:p.format,exitCode:j.usage});return exit(typeof e==`number`?e:j.usage)}if(i===`axi`)return writeReport(describeUsageError(topUsageError(v),g,n.name),p.format),exit(j.usage);for(let e of v)r.error(formatLookupError(e,g));return r.showHelp(),exit(j.usage)}if(g.config&&!c.has(De.id)){let e=g.name?`command '${g.name}'`:`the default command`;throw Error(`${e} declares config, but the cli does not load config. Add .use(config()) from 'clibuilder/config' to the cli.`)}if(f.length>0){let t=createCommandInstance(e,n,m.command,s).ui,r={command:g,config:n.config,format:p.format,output:i,ui:t};try{for(let e of f)await e(r)}catch(e){if(!isCliError(e))throw e;return reportCliError(e,p.format,t),exit(e.exitCode)}n.config=r.config}let y=createCommandInstance(e,n,g,s,p.format,i);if(!y.run)return i===`axi`?writeReport(describeMissingCommand(g,n.name),p.format):y.ui.showHelp(),exit(j.usage);i===`axi`&&(y.ui.showHelp=()=>writeHelp(g,l,p.format),y.ui.showVersion=()=>writeVersion());try{return answer(await y.run(h),p.format)}catch(e){if(!isCliError(e))throw e;return reportCliError(e,p.format,y.ui),exit(e.exitCode)}}function reportCliError(t,n,r){if(isReportedCliError(t))return;let{help:a}=renderHelp(helpLinesOf(t),resolveRef);if(i===`axi`){let i=errorOutput({message:t.message,code:t.code??`error`,details:t.details,help:a});e.writeStdout(`${encode(i,n)}\n`),r.debug(t);return}r.error(t.message);for(let e of a)r.error(e)}function writeReport(t,n){e.writeStdout(`${encode(errorOutput(t),n)}\n`)}function answer(t,n){if(i===`axi`){let r=printAnswer(t,n,{resolve:resolveRef,refs:a});r!==void 0&&e.writeStdout(r)}return answerValue(t)}function writeHelp(t,r,i){e.writeStdout(i===`text`?`${generateHelpMessage(n.name,t)}\n`:`${encode(generateHelpModel(n.name,t,r.options),i)}\n`)}function resolveRef(e){let t=n.command;for(let r of e.path.split(` `)){let i=t.commands?.find(e=>e.name===r||e.alias?.includes(r));if(!i)throw TypeError(`ref('${e.path}'): ${n.name} has no command "${e.path}"`);t=i}for(let r of Object.keys(e.options))if(!(t.options?.[r]||n.command.options?.[r]))throw TypeError(`ref('${e.path}'): the command has no option "${r}"`);return[n.name,e.path,...refArgs(e)].join(` `)}function writeVersion(){e.writeStdout(`${n.version||`not versioned`}\n`)}function exit(t){return e.exit(t),t}function adjust(e,t){return adjustCommand(e,t)}}function isBareVersion(e){let t=e.slice(2);return t.length===1&&(t[0]===`--version`||t[0]===`-v`)}function createExtensionUI(e,t){let n=e.ui;return{get displayLevel(){return n.displayLevel},set displayLevel(e){n.displayLevel=e},info:(...e)=>n.info(...e),warn:(...e)=>n.warn(...e),error:(...e)=>n.error(...e),debug:(...e)=>n.debug(...e),showHelp:()=>n.showHelp(t.name,t.command),showVersion:()=>n.showVersion(t.version)}}function findUsageErrorHandler(e){for(let t=e;t;t=t.parent)if(t.onUsageError)return t.onUsageError}function createCommandInstance(e,t,n,r,i=`toon`,a=`axi`){return{...n,run:n.run,ui:createCommandUI(e,t,n),format:i,output:a,config:t.config,cwd:e.cwd,registry:r}}function createCommandUI(e,t,n){let r=e.createCommandUI(n.name||t.name);return r.displayLevel=t.displayLevel,{...r,showVersion:()=>r.showVersion(t.version),showHelp:()=>r.showHelp(t.name,n)}}function adjustCommand(e,t){return t=yieldToGlobalFormat(t),t.name&&(t.parent=e),t.commands&&(t.commands=t.commands.map(e=>adjustCommand(t,e))),t}function createBuilderUI(e){let t=!0,n=[];return{...e,get displayLevel(){return e.displayLevel},set displayLevel(t){e.displayLevel=t},debug:(...r)=>t?n.push([`debug`,r]):e.debug(...r),info:(...r)=>t?n.push([`info`,r]):e.info(...r),warn:(...r)=>t?n.push([`warn`,r]):e.warn(...r),error:(...r)=>t?n.push([`error`,r]):e.error(...r),dump:()=>{t=!1;for(let[t,r]of n.splice(0))e[t](...r)}}}const Me={console:{debug:`stdout`,info:`stdout`,warn:`stderr`,error:`stderr`,answer:`stdout`},axi:{debug:`stderr`,info:`stderr`,warn:`stderr`,error:`stderr`,answer:`stdout`}},Ne={none:0,info:1,debug:2,trace:3},Pe={error:1,warn:1,info:1,answer:1,debug:2},Fe={error:`red`,warn:`yellow`};function createStreamUI(e,t){let n=`info`,r=Me[t];function write(t,i){if(Pe[t]>Ne[n])return;let a=e[r[t]],o=formatLine(i,a.colour),s=Fe[t];a.write(`${s&&a.colour?h(s,o,{validateStream:!1}):o}\n`)}return{get displayLevel(){return n},set displayLevel(e){n=e},debug:(...e)=>write(`debug`,e),info:(...e)=>write(`info`,e),warn:(...e)=>write(`warn`,e),error:(...e)=>write(`error`,e),showHelp(e,t){write(`answer`,[generateHelpMessage(e,t)])},showVersion(e){write(`answer`,[e||`not versioned`])}}}function formatLine(e,t){return e.map(e=>typeof e==`object`&&e?m(e,{colors:t}):e).join(` `)}function shouldColour(e,t=process.env){if(!e.isTTY)return!1;let n=t.FORCE_COLOR;return n===void 0?t.NO_COLOR?!1:typeof e.hasColors!=`function`||e.hasColors(t):n!==`0`&&n!==`false`}function createSinks(e,t=process.env){return e.stdout===process.stdout&&handleEpipe(process.stdout),{stdout:createSink(e.stdout,t),stderr:createSink(e.stderr,t)}}function createSink(e,t){return{colour:shouldColour(e,t),write(t){Le.has(e)||e.write(t)}}}const Ie=new WeakSet,Le=new WeakSet;function handleEpipe(e){Ie.has(e)||(Ie.add(e),e.on(`error`,t=>{if(t?.code!==`EPIPE`)throw t;Le.add(e),process.exitCode=0}))}function context(e={}){let t=process.cwd(),n=createSinks(e.streams??{stdout:process.stdout,stderr:process.stderr}),r=e.output??`axi`;return{cwd:t,exit(e){process.exitCode=e},writeStdout(e){n.stdout.write(e)},createCommandUI(){return createStreamUI(n,r)},ui:createBuilderUI(createStreamUI(n,r))}}function cli(e){return builder(context({streams:e.streams,output:e.output}),e)}function fail(e,t){throw isCliError(e)?e:(process.stderr.write(`error: ${e instanceof Error?e.message:t}\n`),M.reported(j.error))}function answerThenFail(e,t){let n=printAnswer(e,t);throw n!==void 0&&process.stdout.write(n),M.reported(j.error)}function collapseHome$1(e,t){return e&&t.startsWith(e+E)?`~${t.slice(e.length)}`:t}__name(collapseHome$1,`collapseHome`);function displayBinPath(e,t){return t?collapseHome$1(e,t):`buddy-agent-harness`}var __commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Re=e(import.meta.url);async function readText(e){try{return await O(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}}function stripJsonComments$1(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`"`){let r=n+1;for(;r<e.length&&e[r]!==`"`;)r+=e[r]===`\\`?2:1;t+=e.slice(n,r+1),n=r+1}else if(r===`/`&&e[n+1]===`/`)for(;n<e.length&&e[n]!==`
35
- `;)n++;else if(r===`/`&&e[n+1]===`*`){let t=e.indexOf(`*/`,n+2);n=t===-1?e.length:t+2}else t+=r,n++}return t.replace(/,(\s*[}\]])/g,`$1`)}__name(stripJsonComments$1,`stripJsonComments`);function isRecord$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function declaredDependencies(e){if(!e||typeof e!=`object`)return[];let t=e,n=new Set;for(let e of[`dependencies`,`devDependencies`]){let r=t[e];if(r&&typeof r==`object`)for(let e of Object.keys(r))n.add(e)}return[...n].sort()}function ancestorCandidates(e,t){let n=t.split(`/`),r=[],i=e;for(;;){r.push(S(i,`node_modules`,...n));let e=y(i);if(e===i)break;i=e}return r}function packageDir(t,r){try{let n=e(r);return y(n.resolve(`${t}/package.json`))}catch{}for(let e of ancestorCandidates(y(r),t))if(n(S(e,`package.json`)))return e}const ze=[`plugin.json`,`.claude-plugin/plugin.json`,`.cursor-plugin/plugin.json`,`.codex-plugin/plugin.json`,`.github/plugin.json`,`.github/plugin/plugin.json`];function firstManifest(e){for(let t of ze){let n;try{n=JSON.parse(a(S(e,t),`utf8`))}catch{continue}if(isRecord$1(n)&&typeof n.name==`string`&&n.name)return n}}function pluginManifestName(e){return firstManifest(e)?.name}function pluginManifestVersion(e){let t=firstManifest(e)?.version;return typeof t==`string`&&t?t:void 0}function packageVersion(e){try{let t=JSON.parse(a(S(e,`package.json`),`utf8`)),n=isRecord$1(t)?t.version:void 0;return typeof n==`string`&&n?n:void 0}catch{return}}function pluginVersion(e,t){return t||pluginManifestVersion(e)||packageVersion(e)}var P=__commonJSMin((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),isAlias=e=>!!e&&typeof e==`object`&&e[s]===t,isDocument=e=>!!e&&typeof e==`object`&&e[s]===n,isMap=e=>!!e&&typeof e==`object`&&e[s]===r,isPair=e=>!!e&&typeof e==`object`&&e[s]===i,isScalar=e=>!!e&&typeof e==`object`&&e[s]===a,isSeq=e=>!!e&&typeof e==`object`&&e[s]===o;function isCollection(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function isNode(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}let hasAnchor=e=>(isScalar(e)||isCollection(e))&&!!e.anchor;e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=hasAnchor,e.isAlias=isAlias,e.isCollection=isCollection,e.isDocument=isDocument,e.isMap=isMap,e.isNode=isNode,e.isPair=isPair,e.isScalar=isScalar,e.isSeq=isSeq})),Be=__commonJSMin((e=>{var t=P();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function visit(e,n){let r=initVisitor(n);t.isDocument(e)?visit_(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):visit_(null,e,r,Object.freeze([]))}visit.BREAK=n,visit.SKIP=r,visit.REMOVE=i;function visit_(e,r,a,o){let s=callVisitor(e,r,a,o);if(t.isNode(s)||t.isPair(s))return replaceNode(e,o,s),visit_(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=visit_(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=visit_(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=visit_(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}async function visitAsync(e,n){let r=initVisitor(n);t.isDocument(e)?await visitAsync_(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await visitAsync_(null,e,r,Object.freeze([]))}visitAsync.BREAK=n,visitAsync.SKIP=r,visitAsync.REMOVE=i;async function visitAsync_(e,r,a,o){let s=await callVisitor(e,r,a,o);if(t.isNode(s)||t.isPair(s))return replaceNode(e,o,s),visitAsync_(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await visitAsync_(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await visitAsync_(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await visitAsync_(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function initVisitor(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 callVisitor(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function replaceNode(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=visit,e.visitAsync=visitAsync})),Ve=__commonJSMin((e=>{var t=P(),n=Be();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},escapeTagName=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var i=class Directives{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Directives.defaultYaml,e),this.tags=Object.assign({},Directives.defaultTags,t)}clone(){let e=new Directives(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new Directives(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:Directives.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},Directives.defaultTags)}return e}add(e,t){this.atNextDocument&&=(this.yaml={explicit:Directives.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},Directives.defaultTags),!1);let n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case`%TAG`:{if(n.length!==2&&(t(0,`%TAG directive should contain exactly two parts`),n.length<2))return!1;let[e,r]=n;return this.tags[e]=r,!0}case`%YAML`:{if(this.yaml.explicit=!0,n.length!==1)return t(0,`%YAML directive should contain exactly one part`),!1;let[e]=n;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let n=/^\d+\.\d+$/.test(e);return t(6,`Unsupported YAML version ${e}`,n),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+escapeTagName(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
36
- `)}};i.defaultYaml={explicit:!1,version:`1.2`},i.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=i})),He=__commonJSMin((e=>{var t=P(),n=Be();function anchorIsValid(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function anchorNames(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function findNewAnchor(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function createNodeAnchors(e,n){let r=[],i=new Map,a=null;return{onAnchor:t=>{r.push(t),a??=anchorNames(e);let i=findNewAnchor(n,a);return a.add(i),i},setAnchors:()=>{for(let e of r){let n=i.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:i}}e.anchorIsValid=anchorIsValid,e.anchorNames=anchorNames,e.createNodeAnchors=createNodeAnchors,e.findNewAnchor=findNewAnchor})),Ue=__commonJSMin((e=>{function applyReviver(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=applyReviver(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=applyReviver(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=applyReviver(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=applyReviver(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}e.applyReviver=applyReviver})),F=__commonJSMin((e=>{var t=P();function toJS(e,n,r){if(Array.isArray(e))return e.map((e,t)=>toJS(e,String(t),r));if(e&&typeof e.toJSON==`function`){if(!r||!t.hasAnchor(e))return e.toJSON(n,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=e=>{i.res=e,delete r.onCreate};let a=e.toJSON(n,r);return r.onCreate&&r.onCreate(a),a}return typeof e==`bigint`&&!r?.keep?Number(e):e}e.toJS=toJS})),We=__commonJSMin((e=>{var t=Ue(),n=P(),r=F(),NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}};e.NodeBase=NodeBase})),Ge=__commonJSMin((e=>{var t=He(),n=Be(),r=P(),i=We(),a=F(),Alias=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(r>=0&&(i.count+=1,i.aliasCount===0&&(i.aliasCount=getAliasCount(n,o,e)),i.count*i.aliasCount>r))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return o}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function getAliasCount(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=getAliasCount(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=getAliasCount(e,t.key,n),i=getAliasCount(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=Alias})),I=__commonJSMin((e=>{var t=P(),n=We(),r=F();let isScalarValue=e=>!e||typeof e!=`function`&&typeof e!=`object`;var Scalar=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED=`BLOCK_FOLDED`,Scalar.BLOCK_LITERAL=`BLOCK_LITERAL`,Scalar.PLAIN=`PLAIN`,Scalar.QUOTE_DOUBLE=`QUOTE_DOUBLE`,Scalar.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=Scalar,e.isScalarValue=isScalarValue})),Ke=__commonJSMin((e=>{var t=Ge(),n=P(),r=I();function findTagObject(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function createNode(e,i,a){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=a.schema[n.MAP].createNode?.(a.schema,null,a);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:o,onAnchor:s,onTagObj:c,schema:l,sourceObjects:u}=a,d;if(o&&e&&typeof e==`object`){if(d=u.get(e),d)return d.anchor??(d.anchor=s(e)),new t.Alias(d.anchor);d={anchor:null,node:null},u.set(e,d)}i?.startsWith(`!!`)&&(i=`tag:yaml.org,2002:`+i.slice(2));let f=findTagObject(e,i,l.tags);if(!f){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return d&&(d.node=t),t}f=e instanceof Map?l[n.MAP]:Symbol.iterator in Object(e)?l[n.SEQ]:l[n.MAP]}c&&(c(f),delete a.onTagObj);let p=f?.createNode?f.createNode(a.schema,e,a):typeof f?.nodeClass?.from==`function`?f.nodeClass.from(a.schema,e,a):new r.Scalar(e);return i?p.tag=i:f.default||(p.tag=f.tag),d&&(d.node=p),p}e.createNode=createNode})),qe=__commonJSMin((e=>{var t=Ke(),n=P(),r=We();function collectionFromPath(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let isEmptyPath=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;var Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(isEmptyPath(e))this.add(t);else{let[r,...i]=e,a=this.get(r,!0);if(n.isCollection(a))a.addIn(i,t);else if(a===void 0&&this.schema)this.set(r,collectionFromPath(this.schema,i,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...i]=e;if(i.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(i,t);else if(e===void 0&&this.schema)this.set(r,collectionFromPath(this.schema,i,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};e.Collection=Collection,e.collectionFromPath=collectionFromPath,e.isEmptyPath=isEmptyPath})),Je=__commonJSMin((e=>{let stringifyComment=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function indentComment(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}let lineComment=(e,t,n)=>e.endsWith(`
38
+ `)}`}function describeStandardConfig(e){let t=e[`~standard`]?.jsonSchema;if(t)try{return describeJsonSchema(t.input({target:`draft-2020-12`}))}catch{return}}function describeJsonSchema(e){if(Array.isArray(e.enum))return e.enum.map(e=>JSON.stringify(e)).join(` | `);if(`const`in e)return JSON.stringify(e.const);let t=e.anyOf??e.oneOf;if(Array.isArray(t))return t.map(describeJsonSchema).join(` | `);switch(e.type){case`object`:{let t=e.properties??{},n=e.required??[],r=Object.keys(t).map(e=>`${e}${n.includes(e)?``:`?`}: ${describeJsonSchema(t[e])}`);return r.length===0?`{}`:`{ ${r.join(`, `)} }`}case`array`:{let t=e.items&&typeof e.items==`object`?e.items:{};return t.type===`object`?`Array<${describeJsonSchema(t)}>`:`${describeJsonSchema(t)}[]`}case`string`:case`boolean`:case`number`:case`null`:return e.type;case`integer`:return`number`;default:return`unknown`}}function generateHelpModel(e,t,n){let r={name:getCommandNameChain(e,t).join(` `),usage:generateUsageSection(e,t).slice(7)};t.description&&(r.description=t.description),t.alias&&t.alias.length>0&&(r.aliases=[...t.alias]),t.commands&&t.commands.length>0&&(r.commands=t.commands.map(e=>{let t={name:e.name,usage:commandFullSignature({...e,alias:void 0})};e.alias&&e.alias.length>0&&(t.aliases=[...e.alias]);let n=e.description?.split(`
39
+ `)[0];return n&&(t.description=n),t})),t.arguments&&t.arguments.length>0&&(r.arguments=t.arguments.map(e=>{let t={name:e.name,required:isRequired(e,!0),...describeType(e.type)};return e.description&&(t.description=e.description),t}));let i=!t.parent&&!t.name,a=optionModels(t.options,i?Object.keys(n):[]);a.length>0&&(r.options=a);let o=describeConfig(t);if(o!==void 0&&(r.config=o),t.examples&&t.examples.length>0&&(r.examples=t.examples.map(({command:e,description:t})=>({command:e,description:t}))),i)r.globalOptions=optionModels(n,[]);else{let e=Object.keys(n).filter(e=>e!==`help`&&e!==`format`);r.globalOptions=optionModels(n,e),e.length>0&&(r.otherGlobalOptions=e)}return r}function optionModels(e,t){return e?Object.keys(e).filter(e=>!t.includes(e)).map(t=>{let n=e[t],r={name:t},i=(n.alias??[]).map(e=>typeof e==`string`?e:e.hidden?void 0:e.alias).filter(e=>!!e);i.length>0&&(r.aliases=i),Object.assign(r,describeType(n.type)),r.required=isRequired(n,!1),n.default!==void 0&&(r.default=n.default),n.description&&(r.description=n.description);let a=conflictsOf(t,e);return a.length>0&&(r.conflicts=a),r}):[]}function describeType(e){return e?describeData(e):{}}function describeData(e){switch(e.kind){case`string`:return e.pattern?{type:`string`,pattern:String(e.pattern)}:{type:`string`};case`number`:case`int`:{let t={type:e.kind};return e.min!==void 0&&(t.min=e.min),e.max!==void 0&&(t.max=e.max),t}case`literal`:return{type:`literal`,values:[e.value]};case`enum`:return{type:`enum`,values:[...e.values]};case`array`:return{...describeData(e.element),array:!0};default:return{type:e.kind}}}function tabularHelpModel(e){let t={...e};for(let n of[`commands`,`arguments`,`options`,`examples`,`globalOptions`]){let r=e[n];r&&(t[n]=uniformRows(r))}return t}function uniformRows(e){let t=[];for(let n of e)for(let e of Object.keys(n))t.includes(e)||t.push(e);return e.map(e=>Object.fromEntries(t.map(t=>[t,cell(e[t])])))}function cell(e){return e===void 0?null:Array.isArray(e)?e.map(String).join(`,`):typeof e==`object`&&e?JSON.stringify(e):e}const je={"invalid-key":0,"conflicting-options":1,"invalid-value":2,"expect-single":3,"missing-argument":4,"extra-arguments":5};function topUsageError(e){return e.reduce((e,t)=>!e||je[t.type]<je[e.type]?t:e,void 0)}const Me={"invalid-key":`unknown-option`,"conflicting-options":`conflicting-options`,"invalid-value":`invalid-value`,"expect-single":`expect-single`,"missing-argument":`missing-argument`,"extra-arguments":`extra-arguments`};function usageErrorCode(e){return Me[e.type]}function describeUsageError(e,t,n,r=!0){let i=generateUsageSection(n,t),a=formatLookupError(e,t),o=usageErrorCode(e);switch(e.type){case`invalid-key`:return{message:a,code:o,details:{option:optionName(e.key)},help:[i,optionsHelp(t,n,r)]};case`conflicting-options`:return{message:a,code:o,details:{option:optionName(e.key),conflictsWith:optionName(e.conflictsWith)},help:[i]};case`invalid-value`:{let n=keyName(e.key,t);return{message:a,code:o,details:{...n.details,...e.value===void 0?{}:{value:rawValue(e.value)}},help:[i,...valueHelp(e,n.label)]}}case`expect-single`:return{message:a,code:o,details:{...keyName(e.key,t).details,value:toArray(e.value).map(String)},help:[i]};case`missing-argument`:return!t.arguments?.some(t=>t.name===e.name)&&t.options?.[e.name]?{message:a,code:o,details:{option:optionName(e.name)},help:[i,optionsHelp(t,n,r)]}:{message:a,code:o,details:{argument:e.name},help:[i,argumentsHelp(t,n)]};case`extra-arguments`:return{message:a,code:o,details:{arguments:e.values},help:[i,argumentsHelp(t,n)]}}}function describeMissingCommand(e,t){let n=commandName(e,t),r=(e.commands??[]).map(commandSignature);return{message:`missing command for \`${n}\``,code:`missing-command`,details:{command:n},help:[generateUsageSection(t,e),r.length>0?`valid commands for \`${n}\`: ${r.join(`, `)}`:`\`${n}\` has no commands (--help always allowed)`]}}function optionName(e){return e.length===1?`-${e}`:`--${e}`}function keyName(e,t){return t.arguments?.some(t=>t.name===e)?{label:`<${e}>`,details:{argument:e}}:{label:optionName(e),details:{option:optionName(e)}}}function commandName(e,t){let n=[];for(let t=e;t;t=t.parent)t.name&&n.unshift(t.name);return[t,...n].join(` `)}function isOptional(e){return!!e?.isOptional}function argumentsHelp(e,t){let n=e.name||t,r=(e.commands??[]).map(commandSignature);if(!e.arguments?.length&&r.length>0)return`valid commands for \`${n}\`: ${r.join(`, `)}`;let i=(e.arguments??[]).map(e=>isOptional(e.type)?`[${e.name}]`:`<${e.name}>`);return i.length>0?`\`${n}\` takes: ${i.join(` `)}`:`\`${n}\` takes no arguments`}function optionsHelp(e,t,n){let r=e.name||t,i=Object.keys(e.options??{}).map(optionName),a=n?` (--help always allowed)`:``;return i.length>0?`valid options for \`${r}\`: ${i.join(`, `)}${a}`:`\`${r}\` takes no options${a}`}function valueHelp(e,t){let n=e.index===void 0?``:`[${e.index}]`,r=e.value===void 0?``:` (received ${toArray(e.value).map(quote).join(`, `)})`;return e.allowed?.length?[`allowed for ${t}${n}: ${e.allowed.join(`, `)}${r}`]:e.constraint?[`expected for ${t}${n}: ${e.constraint}${r}`]:[]}function rawValue(e){return Array.isArray(e)?e.map(String):String(e)}function quote(e){return`"${String(e)}"`}function toArray(e){return Array.isArray(e)?e:[e]}function state(e){let{name:t,description:n=``,version:r}=e;return{name:t,description:n,version:r,displayLevel:`info`,command:getBaseCommand(n,{format:e.format})}}function resolveGlobalOptions(e,t,n){let r=lookupCommand(e,t);convertDescriptorsSync(r);let{args:i,errors:a}=r,o=a.filter(t=>`key`in t&&isDeclared(e,t.key)).map(withAllowedFormats(e)),s=!o.some(t=>`key`in t&&isGlobalFormatKey(e,t.key));return{help:i.help,version:i.version,verbose:i.verbose,silent:i.silent,"debug-cli":i[`debug-cli`],values:i,format:s&&i.format||n,errors:o}}function resolveUsageErrors(e,t,n,r){return e.flatMap(e=>!(`key`in e)||!isDeclared(n,e.key)||isOwn(t,e.key)?[e]:r.errors.filter(t=>`key`in t&&t.key===e.key)).map(withCode)}function withCode(e){return Object.defineProperty(e,"code",{value:usageErrorCode(e),enumerable:!1,configurable:!0})}function isDeclared(e,t){return lookupOptions(e,t).length>0}function isOwn(e,t){let[n,r]=lookupOptions(e,t);return!!n&&!isGlobalFormatEntry(r)}function isGlobalFormatKey(e,t){return isGlobalFormatEntry(lookupOptions(e,t)[1])}function withAllowedFormats(e){return t=>t.type===`invalid-value`&&isGlobalFormatKey(e,t.key)?{...t,allowed:Te}:t}function builder(e,t){let n=state(t),r=t.format??`toon`,i=t.output??`axi`,a=t.refs??`help`;if(a!==`help`&&a!==`next`)throw TypeError(`cli({ refs }) must be 'help' or 'next', received ${String(a)}`);if(!Te.includes(r))throw TypeError(`cli({ format }) must be one of ${Te.join(`, `)}, received ${String(r)}`);let o=n.description,s=createRegistry(),c=new Map,l=[],u={},d={},f=[],p=n.command.options,m,h=!1;return{name:n.name,version:n.version||``,description:o,default(e){return n.command=adjust(n.command,{...n.command,...e}),delete this.default,{...this,parse}},command(e){return n.command.commands.push(adjust(n.command,e)),{...this,parse}},use(e){return l.push(e),{...this,parse}}};function extend(){return m??=(async()=>{let t={host:{name:n.name,version:n.version||``},cwd:e.cwd,ui:createExtensionUI(e,n),registry:s,shared:{get:e=>c.get(e.id),set(e,t){c.set(e.id,t)},has:e=>c.has(e.id)},addCommand(e){n.command.commands.push(adjust(n.command,e))},addGlobalOption(e,t,n){u[e]=t,d[e]=n},beforeRun(e){f.push(e)},async resolveConfig(){return h=!0,c.get(Oe.id)??{config:void 0,source:{type:`none`},candidates:[]}}};for(let e of l)await e(t);listGlobalOptions(),warnUnloadedPlugins()})()}function listGlobalOptions(){if(Object.keys(u).length===0)return;let{format:e,...t}=p;for(let e of Object.keys(p))delete p[e];Object.assign(p,t,u,{format:e})}function warnUnloadedPlugins(){let t=c.get(Oe.id)?.config?.plugins;!h&&Array.isArray(t)&&t.length!==0&&e.ui.warn(`the config lists plugins, but this cli loads none. Plugin loading moved out of clibuilder 12 into @clibuilder/plugins: add .use(plugins()) to the cli.`)}async function parse(a){if(isBareVersion(a)){e.writeStdout(`${n.version||`not versioned`}\n`);return}e.ui.debug(`argv:`,a.join(` `));let o=parseArgv(a);await extend();let l=getBaseCommand(n.description,{format:r,options:u}),p=resolveGlobalOptions(l,o,r);p.silent&&(delete o.silent,n.displayLevel=`none`),p.verbose&&(delete o.verbose,n.displayLevel=`debug`),p[`debug-cli`]&&(delete o[`debug-cli`],n.displayLevel=`trace`),e.ui.displayLevel=n.displayLevel,e.ui.dump();for(let t of Object.keys(d)){let r=p.values[t];if(r===void 0)continue;let a=createCommandUI(e,n,n.command);return answer(await d[t]({value:r,format:p.format,output:i,ui:a}),p.format)}let m=lookupCommand(n.command,o,l),{args:h,command:g}=m,_=peekFlags(m,[`help`,`version`]);if(p.version||_.version)return i===`axi`?writeVersion():createCommandInstance(e,n,m.command,s).ui.showVersion();if(p.help||_.help)return i===`axi`?writeHelp(m.command,l,p.format):createCommandInstance(e,n,m.command,s).ui.showHelp();await convertDescriptors(m);let v=resolveUsageErrors(m.errors,g,l,p);if(v.length>0){let r=createCommandInstance(e,n,m.command,s).ui,a=findUsageErrorHandler(g)??t.onUsageError;if(a){let e=await a(v,{command:g,ui:r,format:p.format,exitCode:j.usage});return exit(typeof e==`number`?e:j.usage)}if(i===`axi`)return writeReport(describeUsageError(topUsageError(v),g,n.name),p.format),exit(j.usage);for(let e of v)r.error(formatLookupError(e,g));return r.showHelp(),exit(j.usage)}if(g.config&&!c.has(Oe.id)){let e=g.name?`command '${g.name}'`:`the default command`;throw Error(`${e} declares config, but the cli does not load config. Add .use(config()) from 'clibuilder/config' to the cli.`)}if(f.length>0){let t=createCommandInstance(e,n,m.command,s).ui,r={command:g,config:n.config,format:p.format,output:i,ui:t};try{for(let e of f)await e(r)}catch(e){if(!isCliError(e))throw e;return reportCliError(e,p.format,t,g),exit(e.exitCode)}n.config=r.config}let y=createCommandInstance(e,n,g,s,p.format,i);if(!y.run)return i===`axi`?writeReport(describeMissingCommand(g,n.name),p.format):y.ui.showHelp(),exit(j.usage);i===`axi`&&(y.ui.showHelp=()=>writeHelp(g,l,p.format),y.ui.showVersion=()=>writeVersion());try{return answer(await y.run(h),p.format,g)}catch(e){if(!isCliError(e))throw e;return reportCliError(e,p.format,y.ui,g),exit(e.exitCode)}}function reportCliError(t,n,r,a){if(isReportedCliError(t))return;let{help:o}=renderHelp(helpLinesOf(t),e=>resolveRef(e,a));if(i===`axi`){let i=errorOutput({message:t.message,code:t.code??`error`,details:t.details,help:o});e.writeStdout(`${encode(i,n)}\n`),r.debug(t);return}r.error(t.message);for(let e of o)r.error(e)}function writeReport(t,n){e.writeStdout(`${encode(errorOutput(t),n)}\n`)}function answer(t,r,o){if(i===`axi`){let i=o?.commands?.length?`valid commands for \`${commandName(o,n.name)}\`: ${o.commands.map(commandSignature).join(`, `)}`:void 0,s=printAnswer(t,r,{resolve:e=>resolveRef(e,o),refs:a,verbs:i});s!==void 0&&e.writeStdout(s)}let s=answerExitCode(t);return s!==j.success&&e.exit(s),answerValue(t)}function helpModel(e,t,r){let i=generateHelpModel(n.name,e,t.options);return r===`toon`?tabularHelpModel(i):i}function writeHelp(t,r,i){e.writeStdout(i===`text`?`${generateHelpMessage(n.name,t,{signatures:!0})}\n`:`${encode(helpModel(t,r,i),i)}\n`)}function resolveRef(e,t){let r=e.path.split(` `),i;for(let e of scopesOf(t)){let t=walk(e,r);if(t){i={command:t,scope:e};break}}if(!i)throw TypeError(`ref('${e.path}'): ${n.name} has no command "${e.path}"`);let{command:a,scope:o}=i;for(let t of Object.keys(e.options))if(!(a.options?.[t]||n.command.options?.[t]))throw TypeError(`ref('${e.path}'): the command has no option "${t}"`);return[n.name,...pathOf(o),e.path,...refArgs(e)].join(` `)}function scopesOf(e){let t=[];for(let n=e?.parent;n?.parent;n=n.parent)t.push(n);return t.push(n.command),t}function walk(e,t){let n=e;for(let e of t)if(n=n.commands?.find(t=>t.name===e||t.alias?.includes(e)),!n)return;return n}function pathOf(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name);return t}function writeVersion(){e.writeStdout(`${n.version||`not versioned`}\n`)}function exit(t){return e.exit(t),t}function adjust(e,t){return adjustCommand(e,t)}}function isBareVersion(e){let t=e.slice(2);return t.length===1&&(t[0]===`--version`||t[0]===`-v`)}function createExtensionUI(e,t){let n=e.ui;return{get displayLevel(){return n.displayLevel},set displayLevel(e){n.displayLevel=e},info:(...e)=>n.info(...e),warn:(...e)=>n.warn(...e),error:(...e)=>n.error(...e),debug:(...e)=>n.debug(...e),showHelp:()=>n.showHelp(t.name,t.command),showVersion:()=>n.showVersion(t.version)}}function findUsageErrorHandler(e){for(let t=e;t;t=t.parent)if(t.onUsageError)return t.onUsageError}function createCommandInstance(e,t,n,r,i=`toon`,a=`axi`){return{...n,run:n.run,ui:createCommandUI(e,t,n),format:i,output:a,config:t.config,cwd:e.cwd,registry:r}}function createCommandUI(e,t,n){let r=e.createCommandUI(n.name||t.name);return r.displayLevel=t.displayLevel,{...r,showVersion:()=>r.showVersion(t.version),showHelp:()=>r.showHelp(t.name,n)}}function adjustCommand(e,t){return t=yieldToGlobalFormat(t),t.name&&(t.parent=e),t.commands&&(t.commands=t.commands.map(e=>adjustCommand(t,e))),t}function createBuilderUI(e){let t=!0,n=[];return{...e,get displayLevel(){return e.displayLevel},set displayLevel(t){e.displayLevel=t},debug:(...r)=>t?n.push([`debug`,r]):e.debug(...r),info:(...r)=>t?n.push([`info`,r]):e.info(...r),warn:(...r)=>t?n.push([`warn`,r]):e.warn(...r),error:(...r)=>t?n.push([`error`,r]):e.error(...r),dump:()=>{t=!1;for(let[t,r]of n.splice(0))e[t](...r)}}}const Ne={console:{debug:`stdout`,info:`stdout`,warn:`stderr`,error:`stderr`,answer:`stdout`},axi:{debug:`stderr`,info:`stderr`,warn:`stderr`,error:`stderr`,answer:`stdout`}},Pe={none:0,info:1,debug:2,trace:3},Fe={error:1,warn:1,info:1,answer:1,debug:2},Ie={error:`red`,warn:`yellow`};function createStreamUI(e,t){let n=`info`,r=Ne[t];function write(t,i){if(Fe[t]>Pe[n])return;let a=e[r[t]],o=formatLine(i,a.colour),s=Ie[t];a.write(`${s&&a.colour?g(s,o,{validateStream:!1}):o}\n`)}return{get displayLevel(){return n},set displayLevel(e){n=e},debug:(...e)=>write(`debug`,e),info:(...e)=>write(`info`,e),warn:(...e)=>write(`warn`,e),error:(...e)=>write(`error`,e),showHelp(e,t){write(`answer`,[generateHelpMessage(e,t)])},showVersion(e){write(`answer`,[e||`not versioned`])}}}function formatLine(e,t){return e.map(e=>typeof e==`object`&&e?h(e,{colors:t}):e).join(` `)}function shouldColour(e,t=process.env){if(!e.isTTY)return!1;let n=t.FORCE_COLOR;return n===void 0?t.NO_COLOR?!1:typeof e.hasColors!=`function`||e.hasColors(t):n!==`0`&&n!==`false`}function createSinks(e,t=process.env){return e.stdout===process.stdout&&handleEpipe(process.stdout),{stdout:createSink(e.stdout,t),stderr:createSink(e.stderr,t)}}function createSink(e,t){return{colour:shouldColour(e,t),write(t){Re.has(e)||e.write(t)}}}const Le=new WeakSet,Re=new WeakSet;function handleEpipe(e){Le.has(e)||(Le.add(e),e.on(`error`,t=>{if(t?.code!==`EPIPE`)throw t;Re.add(e),process.exitCode=0}))}function context(e={}){let t=process.cwd(),n=createSinks(e.streams??{stdout:process.stdout,stderr:process.stderr}),r=e.output??`axi`;return{cwd:t,exit(e){process.exitCode=e},writeStdout(e){n.stdout.write(e)},createCommandUI(){return createStreamUI(n,r)},ui:createBuilderUI(createStreamUI(n,r))}}function cli(e){return builder(context({streams:e.streams,output:e.output}),e)}function collapseHome$2(e,t=_()){let n=e.slice(t.length);return!t||!e.startsWith(t)||n!==``&&n[0]!==`/`&&n[0]!==`\\`?e:`~${n}`}__name(collapseHome$2,`collapseHome`);function homeHeader(e){return{bin:collapseHome$2(e.bin??process.argv[1]??``,e.home??_()),description:e.description}}function truncateList(e,t){let n=e.length,r=t.full?[...e]:e.slice(0,t.limit);return{items:r,count:`${r.length} of ${n} total`,total:n,truncated:r.length<n}}const ze={type:N.boolean().optional(),description:`Show the complete output instead of truncating it`};var __commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Be=e(import.meta.url);async function readText(e){try{return await k(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw e}}function stripJsonComments$1(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`"`){let r=n+1;for(;r<e.length&&e[r]!==`"`;)r+=e[r]===`\\`?2:1;t+=e.slice(n,r+1),n=r+1}else if(r===`/`&&e[n+1]===`/`)for(;n<e.length&&e[n]!==`
40
+ `;)n++;else if(r===`/`&&e[n+1]===`*`){let t=e.indexOf(`*/`,n+2);n=t===-1?e.length:t+2}else t+=r,n++}return t.replace(/,(\s*[}\]])/g,`$1`)}__name(stripJsonComments$1,`stripJsonComments`);function isRecord$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function declaredDependencies(e){if(!e||typeof e!=`object`)return[];let t=e,n=new Set;for(let e of[`dependencies`,`devDependencies`]){let r=t[e];if(r&&typeof r==`object`)for(let e of Object.keys(r))n.add(e)}return[...n].sort()}function ancestorCandidates(e,t){let n=t.split(`/`),r=[],i=e;for(;;){r.push(C(i,`node_modules`,...n));let e=b(i);if(e===i)break;i=e}return r}function packageDir(t,r){try{let n=e(r);return b(n.resolve(`${t}/package.json`))}catch{}for(let e of ancestorCandidates(b(r),t))if(n(C(e,`package.json`)))return e}const Ve=[`plugin.json`,`.claude-plugin/plugin.json`,`.cursor-plugin/plugin.json`,`.codex-plugin/plugin.json`,`.github/plugin.json`,`.github/plugin/plugin.json`];function firstManifest(e){for(let t of Ve){let n;try{n=JSON.parse(a(C(e,t),`utf8`))}catch{continue}if(isRecord$1(n)&&typeof n.name==`string`&&n.name)return n}}function pluginManifestName(e){return firstManifest(e)?.name}function pluginManifestVersion(e){let t=firstManifest(e)?.version;return typeof t==`string`&&t?t:void 0}function packageVersion(e){try{let t=JSON.parse(a(C(e,`package.json`),`utf8`)),n=isRecord$1(t)?t.version:void 0;return typeof n==`string`&&n?n:void 0}catch{return}}function pluginVersion(e,t){return t||pluginManifestVersion(e)||packageVersion(e)}var P=__commonJSMin((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),isAlias=e=>!!e&&typeof e==`object`&&e[s]===t,isDocument=e=>!!e&&typeof e==`object`&&e[s]===n,isMap=e=>!!e&&typeof e==`object`&&e[s]===r,isPair=e=>!!e&&typeof e==`object`&&e[s]===i,isScalar=e=>!!e&&typeof e==`object`&&e[s]===a,isSeq=e=>!!e&&typeof e==`object`&&e[s]===o;function isCollection(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function isNode(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}let hasAnchor=e=>(isScalar(e)||isCollection(e))&&!!e.anchor;e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=hasAnchor,e.isAlias=isAlias,e.isCollection=isCollection,e.isDocument=isDocument,e.isMap=isMap,e.isNode=isNode,e.isPair=isPair,e.isScalar=isScalar,e.isSeq=isSeq})),He=__commonJSMin((e=>{var t=P();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function visit(e,n){let r=initVisitor(n);t.isDocument(e)?visit_(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):visit_(null,e,r,Object.freeze([]))}visit.BREAK=n,visit.SKIP=r,visit.REMOVE=i;function visit_(e,r,a,o){let s=callVisitor(e,r,a,o);if(t.isNode(s)||t.isPair(s))return replaceNode(e,o,s),visit_(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=visit_(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=visit_(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=visit_(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}async function visitAsync(e,n){let r=initVisitor(n);t.isDocument(e)?await visitAsync_(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await visitAsync_(null,e,r,Object.freeze([]))}visitAsync.BREAK=n,visitAsync.SKIP=r,visitAsync.REMOVE=i;async function visitAsync_(e,r,a,o){let s=await callVisitor(e,r,a,o);if(t.isNode(s)||t.isPair(s))return replaceNode(e,o,s),visitAsync_(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await visitAsync_(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await visitAsync_(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await visitAsync_(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function initVisitor(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 callVisitor(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function replaceNode(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=visit,e.visitAsync=visitAsync})),Ue=__commonJSMin((e=>{var t=P(),n=He();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},escapeTagName=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var i=class Directives{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Directives.defaultYaml,e),this.tags=Object.assign({},Directives.defaultTags,t)}clone(){let e=new Directives(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new Directives(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:Directives.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},Directives.defaultTags)}return e}add(e,t){this.atNextDocument&&=(this.yaml={explicit:Directives.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},Directives.defaultTags),!1);let n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case`%TAG`:{if(n.length!==2&&(t(0,`%TAG directive should contain exactly two parts`),n.length<2))return!1;let[e,r]=n;return this.tags[e]=r,!0}case`%YAML`:{if(this.yaml.explicit=!0,n.length!==1)return t(0,`%YAML directive should contain exactly one part`),!1;let[e]=n;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let n=/^\d+\.\d+$/.test(e);return t(6,`Unsupported YAML version ${e}`,n),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+escapeTagName(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
41
+ `)}};i.defaultYaml={explicit:!1,version:`1.2`},i.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=i})),We=__commonJSMin((e=>{var t=P(),n=He();function anchorIsValid(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function anchorNames(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function findNewAnchor(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function createNodeAnchors(e,n){let r=[],i=new Map,a=null;return{onAnchor:t=>{r.push(t),a??=anchorNames(e);let i=findNewAnchor(n,a);return a.add(i),i},setAnchors:()=>{for(let e of r){let n=i.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:i}}e.anchorIsValid=anchorIsValid,e.anchorNames=anchorNames,e.createNodeAnchors=createNodeAnchors,e.findNewAnchor=findNewAnchor})),Ge=__commonJSMin((e=>{function applyReviver(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=applyReviver(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=applyReviver(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=applyReviver(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=applyReviver(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}e.applyReviver=applyReviver})),F=__commonJSMin((e=>{var t=P();function toJS(e,n,r){if(Array.isArray(e))return e.map((e,t)=>toJS(e,String(t),r));if(e&&typeof e.toJSON==`function`){if(!r||!t.hasAnchor(e))return e.toJSON(n,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=e=>{i.res=e,delete r.onCreate};let a=e.toJSON(n,r);return r.onCreate&&r.onCreate(a),a}return typeof e==`bigint`&&!r?.keep?Number(e):e}e.toJS=toJS})),Ke=__commonJSMin((e=>{var t=Ge(),n=P(),r=F(),NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}};e.NodeBase=NodeBase})),qe=__commonJSMin((e=>{var t=We(),n=He(),r=P(),i=Ke(),a=F(),Alias=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(r>=0&&(i.count+=1,i.aliasCount===0&&(i.aliasCount=getAliasCount(n,o,e)),i.count*i.aliasCount>r))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return o}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function getAliasCount(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=getAliasCount(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=getAliasCount(e,t.key,n),i=getAliasCount(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=Alias})),I=__commonJSMin((e=>{var t=P(),n=Ke(),r=F();let isScalarValue=e=>!e||typeof e!=`function`&&typeof e!=`object`;var Scalar=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED=`BLOCK_FOLDED`,Scalar.BLOCK_LITERAL=`BLOCK_LITERAL`,Scalar.PLAIN=`PLAIN`,Scalar.QUOTE_DOUBLE=`QUOTE_DOUBLE`,Scalar.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=Scalar,e.isScalarValue=isScalarValue})),Je=__commonJSMin((e=>{var t=qe(),n=P(),r=I();function findTagObject(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function createNode(e,i,a){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=a.schema[n.MAP].createNode?.(a.schema,null,a);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:o,onAnchor:s,onTagObj:c,schema:l,sourceObjects:u}=a,d;if(o&&e&&typeof e==`object`){if(d=u.get(e),d)return d.anchor??(d.anchor=s(e)),new t.Alias(d.anchor);d={anchor:null,node:null},u.set(e,d)}i?.startsWith(`!!`)&&(i=`tag:yaml.org,2002:`+i.slice(2));let f=findTagObject(e,i,l.tags);if(!f){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return d&&(d.node=t),t}f=e instanceof Map?l[n.MAP]:Symbol.iterator in Object(e)?l[n.SEQ]:l[n.MAP]}c&&(c(f),delete a.onTagObj);let p=f?.createNode?f.createNode(a.schema,e,a):typeof f?.nodeClass?.from==`function`?f.nodeClass.from(a.schema,e,a):new r.Scalar(e);return i?p.tag=i:f.default||(p.tag=f.tag),d&&(d.node=p),p}e.createNode=createNode})),Ye=__commonJSMin((e=>{var t=Je(),n=P(),r=Ke();function collectionFromPath(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let isEmptyPath=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;var Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(isEmptyPath(e))this.add(t);else{let[r,...i]=e,a=this.get(r,!0);if(n.isCollection(a))a.addIn(i,t);else if(a===void 0&&this.schema)this.set(r,collectionFromPath(this.schema,i,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...i]=e;if(i.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(i,t);else if(e===void 0&&this.schema)this.set(r,collectionFromPath(this.schema,i,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};e.Collection=Collection,e.collectionFromPath=collectionFromPath,e.isEmptyPath=isEmptyPath})),Xe=__commonJSMin((e=>{let stringifyComment=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function indentComment(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}let lineComment=(e,t,n)=>e.endsWith(`
37
42
  `)?indentComment(n,t):n.includes(`
38
43
  `)?`
39
- `+indentComment(n,t):(e.endsWith(` `)?``:` `)+n;e.indentComment=indentComment,e.lineComment=lineComment,e.stringifyComment=stringifyComment})),Ye=__commonJSMin((e=>{let t=`block`,n=`quoted`;function foldFlowLines(e,r,i=`flow`,{indentAtStart:a,lineWidth:o=80,minContentWidth:s=20,onFold:c,onOverflow:l}={}){if(!o||o<0)return e;o<s&&(s=0);let u=Math.max(1+s,1+o-r.length);if(e.length<=u)return e;let d=[],f={},p=o-r.length;typeof a==`number`&&(a>o-Math.max(2,s)?d.push(0):p=o-a);let m,h,g=!1,_=-1,v=-1,y=-1;i===t&&(_=consumeMoreIndentedLines(e,_,r.length),_!==-1&&(p=_+u));for(let a;a=e[_+=1];){if(i===n&&a===`\\`){switch(v=_,e[_+1]){case`x`:_+=3;break;case`u`:_+=5;break;case`U`:_+=9;break;default:_+=1}y=_}if(a===`
44
+ `+indentComment(n,t):(e.endsWith(` `)?``:` `)+n;e.indentComment=indentComment,e.lineComment=lineComment,e.stringifyComment=stringifyComment})),Ze=__commonJSMin((e=>{let t=`block`,n=`quoted`;function foldFlowLines(e,r,i=`flow`,{indentAtStart:a,lineWidth:o=80,minContentWidth:s=20,onFold:c,onOverflow:l}={}){if(!o||o<0)return e;o<s&&(s=0);let u=Math.max(1+s,1+o-r.length);if(e.length<=u)return e;let d=[],f={},p=o-r.length;typeof a==`number`&&(a>o-Math.max(2,s)?d.push(0):p=o-a);let m,h,g=!1,_=-1,v=-1,y=-1;i===t&&(_=consumeMoreIndentedLines(e,_,r.length),_!==-1&&(p=_+u));for(let a;a=e[_+=1];){if(i===n&&a===`\\`){switch(v=_,e[_+1]){case`x`:_+=3;break;case`u`:_+=5;break;case`U`:_+=9;break;default:_+=1}y=_}if(a===`
40
45
  `)i===t&&(_=consumeMoreIndentedLines(e,_,r.length)),p=_+r.length+u,m=void 0;else{if(a===` `&&h&&h!==` `&&h!==`
41
46
  `&&h!==` `){let t=e[_+1];t&&t!==` `&&t!==`
42
47
  `&&t!==` `&&(m=_)}if(_>=p){if(m)d.push(m),p=m+u,m=void 0;else if(i===n){for(;h===` `||h===` `;)h=a,a=e[_+=1],g=!0;let t=_>y+1?_-2:v-1;if(f[t])return e;d.push(t),f[t]=!0,p=t+u,m=void 0}else g=!0}}h=a}if(g&&l&&l(),d.length===0)return e;c&&c();let b=e.slice(0,d[0]);for(let t=0;t<d.length;++t){let a=d[t],o=d[t+1]||e.length;a===0?b=`\n${r}${e.slice(0,o)}`:(i===n&&f[a]&&(b+=`${e[a]}\\`),b+=`\n${r}${e.slice(a+1,o)}`)}return b}function consumeMoreIndentedLines(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
43
- `);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=t,e.FOLD_FLOW=`flow`,e.FOLD_QUOTED=n,e.foldFlowLines=foldFlowLines})),Xe=__commonJSMin((e=>{var t=I(),n=Ye();let getFoldOptions=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),containsDocumentMarker=e=>/^(%|---|\.\.\.)/m.test(e);function lineLengthOverLimit(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
48
+ `);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=t,e.FOLD_FLOW=`flow`,e.FOLD_QUOTED=n,e.foldFlowLines=foldFlowLines})),Qe=__commonJSMin((e=>{var t=I(),n=Ze();let getFoldOptions=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),containsDocumentMarker=e=>/^(%|---|\.\.\.)/m.test(e);function lineLengthOverLimit(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
44
49
  `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function doubleQuotedString(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,a=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(containsDocumentMarker(e)?` `:``),s=``,c=0;for(let e=0,t=r[e];t;t=r[++e])if(t===` `&&r[e+1]===`\\`&&r[e+2]===`n`&&(s+=r.slice(c,e)+`\\ `,e+=1,c=e,t=`\\`),t===`\\`)switch(r[e+1]){case`u`:{s+=r.slice(c,e);let t=r.substr(e+2,4);switch(t){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:t.substr(0,2)===`00`?s+=`\\x`+t.substr(2):s+=r.substr(e,6)}e+=5,c=e+1}break;case`n`:if(i||r[e+2]===`"`||r.length<a)e+=1;else{for(s+=r.slice(c,e)+`
45
50
 
46
51
  `;r[e+2]===`\\`&&r[e+3]===`n`&&r[e+4]!==`"`;)s+=`
@@ -58,29 +63,29 @@ ${e.examples.map(e=>` ${e.description}\n ${e.command}`).join(`
58
63
  $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${f}`),r=!1,s=getFoldOptions(o,!0);l!==`folded`&&i!==t.Scalar.BLOCK_FOLDED&&(s.onOverflow=()=>{r=!0});let c=n.foldFlowLines(`${x}${e}${g}`,f,n.FOLD_BLOCK,s);if(!r)return`>${S}\n${f}${c}`}return a=a.replace(/\n+/g,`$&${f}`),`|${S}\n${f}${x}${a}${g}`}function plainString(e,r,i,a){let{type:o,value:s}=e,{actualString:c,implicitKey:l,indent:u,indentStep:d,inFlow:f}=r;if(l&&s.includes(`
59
64
  `)||f&&/[[\]{},]/.test(s))return quotedString(s,r);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return l||f||!s.includes(`
60
65
  `)?quotedString(s,r):blockString(e,r,i,a);if(!l&&!f&&o!==t.Scalar.PLAIN&&s.includes(`
61
- `))return blockString(e,r,i,a);if(containsDocumentMarker(s)){if(u===``)return r.forceBlockIndent=!0,blockString(e,r,i,a);if(l&&u===d)return quotedString(s,r)}let p=s.replace(/\n+/g,`$&\n${u}`);if(c){let test=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(p),{compat:e,tags:t}=r.doc.schema;if(t.some(test)||e?.some(test))return quotedString(s,r)}return l?p:n.foldFlowLines(p,u,n.FOLD_FLOW,getFoldOptions(r,!1))}function stringifyString(e,n,r,i){let{implicitKey:a,inFlow:o}=n,s=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:c}=e;c!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(c=t.Scalar.QUOTE_DOUBLE);let _stringify=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||o?quotedString(s.value,n):blockString(s,n,r,i);case t.Scalar.QUOTE_DOUBLE:return doubleQuotedString(s.value,n);case t.Scalar.QUOTE_SINGLE:return singleQuotedString(s.value,n);case t.Scalar.PLAIN:return plainString(s,n,r,i);default:return null}},l=_stringify(c);if(l===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(l=_stringify(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}e.stringifyString=stringifyString})),Ze=__commonJSMin((e=>{var t=He(),n=P(),r=Je(),i=Xe();function createStringifyContext(e,t){let n=Object.assign({blockQuote:!0,commentString:r.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),i;switch(n.collectionStyle){case`block`:i=!1;break;case`flow`:i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:i,options:n}}function getTagObject(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let r,i;if(n.isScalar(t)){i=t.value;let n=e.filter(e=>e.identify?.(i));if(n.length>1){let e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else i=t,r=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!r){let e=i?.constructor?.name??(i===null?`null`:typeof i);throw Error(`Tag not resolved for ${e} value`)}return r}function stringifyProps(e,r,{anchors:i,doc:a}){if(!a.directives)return``;let o=[],s=(n.isScalar(e)||n.isCollection(e))&&e.anchor;s&&t.anchorIsValid(s)&&(i.add(s),o.push(`&${s}`));let c=e.tag??(r.default?null:r.tag);return c&&o.push(a.directives.tagString(c)),o.join(` `)}function stringify(e,t,r,a){if(n.isPair(e))return e.toString(t,r,a);if(n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw 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 o,s=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>o=e});o??=getTagObject(t.doc.schema.tags,s);let c=stringifyProps(s,o,t);c.length>0&&(t.indentAtStart=(t.indentAtStart??0)+c.length+1);let l=typeof o.stringify==`function`?o.stringify(s,t,r,a):n.isScalar(s)?i.stringifyString(s,t,r,a):s.toString(t,r,a);return c?n.isScalar(s)||l[0]===`{`||l[0]===`[`?`${c} ${l}`:`${c}\n${t.indent}${l}`:l}e.createStringifyContext=createStringifyContext,e.stringify=stringify})),Qe=__commonJSMin((e=>{var t=P(),n=I(),r=Ze(),i=Je();function stringifyPair({key:e,value:a},o,s,c){let{allNullValues:l,doc:u,indent:d,indentStep:f,options:{commentString:p,indentSeq:m,simpleKeys:h}}=o,g=t.isNode(e)&&e.comment||null;if(h){if(g)throw Error(`With simple keys, key nodes cannot have comments`);if(t.isCollection(e)||!t.isNode(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let _=!h&&(!e||g&&a==null&&!o.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:typeof e==`object`));o=Object.assign({},o,{allNullValues:!1,implicitKey:!_&&(h||!l),indent:d+f});let v=!1,y=!1,b=r.stringify(e,o,()=>v=!0,()=>y=!0);if(!_&&!o.inFlow&&b.length>1024){if(h)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);_=!0}if(o.inFlow){if(l||a==null)return v&&s&&s(),b===``?`?`:_?`? ${b}`:b}else if(l&&!h||a==null&&_)return b=`? ${b}`,g&&!v?b+=i.lineComment(b,o.indent,p(g)):y&&c&&c(),b;v&&(g=null),_?(g&&(b+=i.lineComment(b,o.indent,p(g))),b=`? ${b}\n${d}:`):(b=`${b}:`,g&&(b+=i.lineComment(b,o.indent,p(g))));let x,S,C;t.isNode(a)?(x=!!a.spaceBefore,S=a.commentBefore,C=a.comment):(x=!1,S=null,C=null,a&&typeof a==`object`&&(a=u.createNode(a))),o.implicitKey=!1,!_&&!g&&t.isScalar(a)&&(o.indentAtStart=b.length+1),y=!1,!m&&f.length>=2&&!o.inFlow&&!_&&t.isSeq(a)&&!a.flow&&!a.tag&&!a.anchor&&(o.indent=o.indent.substring(2));let w=!1,T=r.stringify(a,o,()=>w=!0,()=>y=!0),E=` `;if(g||x||S){if(E=x?`
66
+ `))return blockString(e,r,i,a);if(containsDocumentMarker(s)){if(u===``)return r.forceBlockIndent=!0,blockString(e,r,i,a);if(l&&u===d)return quotedString(s,r)}let p=s.replace(/\n+/g,`$&\n${u}`);if(c){let test=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(p),{compat:e,tags:t}=r.doc.schema;if(t.some(test)||e?.some(test))return quotedString(s,r)}return l?p:n.foldFlowLines(p,u,n.FOLD_FLOW,getFoldOptions(r,!1))}function stringifyString(e,n,r,i){let{implicitKey:a,inFlow:o}=n,s=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:c}=e;c!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(c=t.Scalar.QUOTE_DOUBLE);let _stringify=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||o?quotedString(s.value,n):blockString(s,n,r,i);case t.Scalar.QUOTE_DOUBLE:return doubleQuotedString(s.value,n);case t.Scalar.QUOTE_SINGLE:return singleQuotedString(s.value,n);case t.Scalar.PLAIN:return plainString(s,n,r,i);default:return null}},l=_stringify(c);if(l===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(l=_stringify(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}e.stringifyString=stringifyString})),$e=__commonJSMin((e=>{var t=We(),n=P(),r=Xe(),i=Qe();function createStringifyContext(e,t){let n=Object.assign({blockQuote:!0,commentString:r.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),i;switch(n.collectionStyle){case`block`:i=!1;break;case`flow`:i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:i,options:n}}function getTagObject(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let r,i;if(n.isScalar(t)){i=t.value;let n=e.filter(e=>e.identify?.(i));if(n.length>1){let e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else i=t,r=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!r){let e=i?.constructor?.name??(i===null?`null`:typeof i);throw Error(`Tag not resolved for ${e} value`)}return r}function stringifyProps(e,r,{anchors:i,doc:a}){if(!a.directives)return``;let o=[],s=(n.isScalar(e)||n.isCollection(e))&&e.anchor;s&&t.anchorIsValid(s)&&(i.add(s),o.push(`&${s}`));let c=e.tag??(r.default?null:r.tag);return c&&o.push(a.directives.tagString(c)),o.join(` `)}function stringify(e,t,r,a){if(n.isPair(e))return e.toString(t,r,a);if(n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw 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 o,s=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>o=e});o??=getTagObject(t.doc.schema.tags,s);let c=stringifyProps(s,o,t);c.length>0&&(t.indentAtStart=(t.indentAtStart??0)+c.length+1);let l=typeof o.stringify==`function`?o.stringify(s,t,r,a):n.isScalar(s)?i.stringifyString(s,t,r,a):s.toString(t,r,a);return c?n.isScalar(s)||l[0]===`{`||l[0]===`[`?`${c} ${l}`:`${c}\n${t.indent}${l}`:l}e.createStringifyContext=createStringifyContext,e.stringify=stringify})),et=__commonJSMin((e=>{var t=P(),n=I(),r=$e(),i=Xe();function stringifyPair({key:e,value:a},o,s,c){let{allNullValues:l,doc:u,indent:d,indentStep:f,options:{commentString:p,indentSeq:m,simpleKeys:h}}=o,g=t.isNode(e)&&e.comment||null;if(h){if(g)throw Error(`With simple keys, key nodes cannot have comments`);if(t.isCollection(e)||!t.isNode(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let _=!h&&(!e||g&&a==null&&!o.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:typeof e==`object`));o=Object.assign({},o,{allNullValues:!1,implicitKey:!_&&(h||!l),indent:d+f});let v=!1,y=!1,b=r.stringify(e,o,()=>v=!0,()=>y=!0);if(!_&&!o.inFlow&&b.length>1024){if(h)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);_=!0}if(o.inFlow){if(l||a==null)return v&&s&&s(),b===``?`?`:_?`? ${b}`:b}else if(l&&!h||a==null&&_)return b=`? ${b}`,g&&!v?b+=i.lineComment(b,o.indent,p(g)):y&&c&&c(),b;v&&(g=null),_?(g&&(b+=i.lineComment(b,o.indent,p(g))),b=`? ${b}\n${d}:`):(b=`${b}:`,g&&(b+=i.lineComment(b,o.indent,p(g))));let x,S,C;t.isNode(a)?(x=!!a.spaceBefore,S=a.commentBefore,C=a.comment):(x=!1,S=null,C=null,a&&typeof a==`object`&&(a=u.createNode(a))),o.implicitKey=!1,!_&&!g&&t.isScalar(a)&&(o.indentAtStart=b.length+1),y=!1,!m&&f.length>=2&&!o.inFlow&&!_&&t.isSeq(a)&&!a.flow&&!a.tag&&!a.anchor&&(o.indent=o.indent.substring(2));let w=!1,T=r.stringify(a,o,()=>w=!0,()=>y=!0),E=` `;if(g||x||S){if(E=x?`
62
67
  `:``,S){let e=p(S);E+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?E===`
63
68
  `&&C&&(E=`
64
69
 
65
70
  `):E+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
66
71
  `),n=t!==-1,r=o.inFlow??a.flow??a.items.length===0;if(n||!r){let r=!1;if(n&&(e===`&`||e===`!`)){let n=T.indexOf(` `);e===`&`&&n!==-1&&n<t&&T[n+1]===`!`&&(n=T.indexOf(` `,n+1)),(n===-1||t<n)&&(r=!0)}r||(E=`\n${o.indent}`)}}else(T===``||T[0]===`
67
- `)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=stringifyPair})),$e=__commonJSMin((e=>{var t=Re(`process`);function debug(e,...t){e===`debug`&&console.log(...t)}function warn(e,n){(e===`debug`||e===`warn`)&&(typeof t.emitWarning==`function`?t.emitWarning(n):console.warn(n))}e.debug=debug,e.warn=warn})),et=__commonJSMin((e=>{var t=P(),n=I();let r={identify:e=>e===`<<`||typeof e==`symbol`&&e.description===`<<`,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(`<<`)),{addToJSMap:addMergeToJSMap}),stringify:()=>`<<`},isMergeKey=(e,i)=>(r.identify(i)||t.isScalar(i)&&(!i.type||i.type===n.Scalar.PLAIN)&&r.identify(i.value))&&e?.doc.schema.tags.some(e=>e.tag===r.tag&&e.default);function addMergeToJSMap(e,n,r){let i=resolveAliasValue(e,r);if(t.isSeq(i))for(let t of i.items)mergeValue(e,n,t);else if(Array.isArray(i))for(let t of i)mergeValue(e,n,t);else mergeValue(e,n,i)}function mergeValue(e,n,r){let i=resolveAliasValue(e,r);if(!t.isMap(i))throw Error(`Merge sources must be maps or map aliases`);let a=i.toJSON(null,e,Map);for(let[e,t]of a)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}function resolveAliasValue(e,n){return e&&t.isAlias(n)?n.resolve(e.doc,e):n}e.addMergeToJSMap=addMergeToJSMap,e.isMergeKey=isMergeKey,e.merge=r})),tt=__commonJSMin((e=>{var t=$e(),n=et(),r=Ze(),i=P(),a=F();function addPairToJSMap(e,t,{key:r,value:o}){if(i.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,o);else{let n=a.toJS(r,``,e);if(t instanceof Map)t.set(n,a.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=stringifyKey(r,n,e),s=a.toJS(o,i,e);i in t?Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[i]=s}}return t}function stringifyKey(e,n,a){if(n===null)return``;if(typeof n!=`object`)return String(n);if(i.isNode(e)&&a?.doc){let n=r.createStringifyContext(a.doc,{});n.anchors=new Set;for(let e of a.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!a.mapKeyWarned){let e=JSON.stringify(i);e.length>40&&(e=e.substring(0,36)+`..."`),t.warn(a.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),a.mapKeyWarned=!0}return i}return JSON.stringify(n)}e.addPairToJSMap=addPairToJSMap})),L=__commonJSMin((e=>{var t=Ke(),n=Qe(),r=tt(),i=P();function createPair(e,n,r){return new a(t.createNode(e,void 0,r),t.createNode(n,void 0,r))}var a=class Pair{constructor(e,t=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return i.isNode(t)&&(t=t.clone(e)),i.isNode(n)&&(n=n.clone(e)),new Pair(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=a,e.createPair=createPair})),nt=__commonJSMin((e=>{var t=P(),n=Ze(),r=Je();function stringifyCollection(e,t,n){return(t.inFlow??e.flow?stringifyFlowCollection:stringifyBlockCollection)(e,t,n)}function stringifyBlockCollection({comment:e,items:i},a,{blockItemPrefix:o,flowChars:s,itemIndent:c,onChompKeep:l,onComment:u}){let{indent:d,options:{commentString:f}}=a,p=Object.assign({},a,{indent:c,type:null}),m=!1,h=[];for(let e=0;e<i.length;++e){let s=i[e],l=null;if(t.isNode(s))!m&&s.spaceBefore&&h.push(``),addCommentBefore(a,h,s.commentBefore,m),s.comment&&(l=s.comment);else if(t.isPair(s)){let e=t.isNode(s.key)?s.key:null;e&&(!m&&e.spaceBefore&&h.push(``),addCommentBefore(a,h,e.commentBefore,m))}m=!1;let u=n.stringify(s,p,()=>l=null,()=>m=!0);l&&(u+=r.lineComment(u,c,f(l))),m&&l&&(m=!1),h.push(o+u)}let g;if(h.length===0)g=s.start+s.end;else{g=h[0];for(let e=1;e<h.length;++e){let t=h[e];g+=t?`\n${d}${t}`:`
72
+ `)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=stringifyPair})),tt=__commonJSMin((e=>{var t=Be(`process`);function debug(e,...t){e===`debug`&&console.log(...t)}function warn(e,n){(e===`debug`||e===`warn`)&&(typeof t.emitWarning==`function`?t.emitWarning(n):console.warn(n))}e.debug=debug,e.warn=warn})),nt=__commonJSMin((e=>{var t=P(),n=I();let r={identify:e=>e===`<<`||typeof e==`symbol`&&e.description===`<<`,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(`<<`)),{addToJSMap:addMergeToJSMap}),stringify:()=>`<<`},isMergeKey=(e,i)=>(r.identify(i)||t.isScalar(i)&&(!i.type||i.type===n.Scalar.PLAIN)&&r.identify(i.value))&&e?.doc.schema.tags.some(e=>e.tag===r.tag&&e.default);function addMergeToJSMap(e,n,r){let i=resolveAliasValue(e,r);if(t.isSeq(i))for(let t of i.items)mergeValue(e,n,t);else if(Array.isArray(i))for(let t of i)mergeValue(e,n,t);else mergeValue(e,n,i)}function mergeValue(e,n,r){let i=resolveAliasValue(e,r);if(!t.isMap(i))throw Error(`Merge sources must be maps or map aliases`);let a=i.toJSON(null,e,Map);for(let[e,t]of a)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}function resolveAliasValue(e,n){return e&&t.isAlias(n)?n.resolve(e.doc,e):n}e.addMergeToJSMap=addMergeToJSMap,e.isMergeKey=isMergeKey,e.merge=r})),rt=__commonJSMin((e=>{var t=tt(),n=nt(),r=$e(),i=P(),a=F();function addPairToJSMap(e,t,{key:r,value:o}){if(i.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,o);else{let n=a.toJS(r,``,e);if(t instanceof Map)t.set(n,a.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=stringifyKey(r,n,e),s=a.toJS(o,i,e);i in t?Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[i]=s}}return t}function stringifyKey(e,n,a){if(n===null)return``;if(typeof n!=`object`)return String(n);if(i.isNode(e)&&a?.doc){let n=r.createStringifyContext(a.doc,{});n.anchors=new Set;for(let e of a.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!a.mapKeyWarned){let e=JSON.stringify(i);e.length>40&&(e=e.substring(0,36)+`..."`),t.warn(a.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),a.mapKeyWarned=!0}return i}return JSON.stringify(n)}e.addPairToJSMap=addPairToJSMap})),L=__commonJSMin((e=>{var t=Je(),n=et(),r=rt(),i=P();function createPair(e,n,r){return new a(t.createNode(e,void 0,r),t.createNode(n,void 0,r))}var a=class Pair{constructor(e,t=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return i.isNode(t)&&(t=t.clone(e)),i.isNode(n)&&(n=n.clone(e)),new Pair(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=a,e.createPair=createPair})),it=__commonJSMin((e=>{var t=P(),n=$e(),r=Xe();function stringifyCollection(e,t,n){return(t.inFlow??e.flow?stringifyFlowCollection:stringifyBlockCollection)(e,t,n)}function stringifyBlockCollection({comment:e,items:i},a,{blockItemPrefix:o,flowChars:s,itemIndent:c,onChompKeep:l,onComment:u}){let{indent:d,options:{commentString:f}}=a,p=Object.assign({},a,{indent:c,type:null}),m=!1,h=[];for(let e=0;e<i.length;++e){let s=i[e],l=null;if(t.isNode(s))!m&&s.spaceBefore&&h.push(``),addCommentBefore(a,h,s.commentBefore,m),s.comment&&(l=s.comment);else if(t.isPair(s)){let e=t.isNode(s.key)?s.key:null;e&&(!m&&e.spaceBefore&&h.push(``),addCommentBefore(a,h,e.commentBefore,m))}m=!1;let u=n.stringify(s,p,()=>l=null,()=>m=!0);l&&(u+=r.lineComment(u,c,f(l))),m&&l&&(m=!1),h.push(o+u)}let g;if(h.length===0)g=s.start+s.end;else{g=h[0];for(let e=1;e<h.length;++e){let t=h[e];g+=t?`\n${d}${t}`:`
68
73
  `}}return e?(g+=`
69
74
  `+r.indentComment(f(e),d),u&&u()):m&&l&&l(),g}function stringifyFlowCollection({items:e},i,{flowChars:a,itemIndent:o}){let{indent:s,indentStep:c,flowCollectionPadding:l,options:{commentString:u}}=i;o+=c;let d=Object.assign({},i,{indent:o,inFlow:!0,type:null}),f=!1,p=0,m=[];for(let a=0;a<e.length;++a){let s=e[a],c=null;if(t.isNode(s))s.spaceBefore&&m.push(``),addCommentBefore(i,m,s.commentBefore,!1),s.comment&&(c=s.comment);else if(t.isPair(s)){let e=t.isNode(s.key)?s.key:null;e&&(e.spaceBefore&&m.push(``),addCommentBefore(i,m,e.commentBefore,!1),e.comment&&(f=!0));let n=t.isNode(s.value)?s.value:null;n?(n.comment&&(c=n.comment),n.commentBefore&&(f=!0)):s.value==null&&e?.comment&&(c=e.comment)}c&&(f=!0);let l=n.stringify(s,d,()=>c=null);f||=m.length>p||l.includes(`
70
75
  `),a<e.length-1?l+=`,`:i.options.trailingComma&&(i.options.lineWidth>0&&(f||=m.reduce((e,t)=>e+t.length+2,2)+(l.length+2)>i.options.lineWidth),f&&(l+=`,`)),c&&(l+=r.lineComment(l,o,u(c))),m.push(l),p=m.length}let{start:h,end:g}=a;if(m.length===0)return h+g;if(!f){let e=m.reduce((e,t)=>e+t.length+2,2);f=i.options.lineWidth>0&&e>i.options.lineWidth}if(f){let e=h;for(let t of m)e+=t?`\n${c}${s}${t}`:`
71
- `;return`${e}\n${s}${g}`}return`${h}${l}${m.join(` `)}${l}${g}`}function addCommentBefore({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=stringifyCollection})),R=__commonJSMin((e=>{var t=nt(),n=tt(),r=qe(),i=P(),a=L(),o=I();function findPair(e,t){let n=i.isScalar(t)?t.value:t;for(let r of e)if(i.isPair(r)&&(r.key===t||r.key===n||i.isScalar(r.key)&&r.key.value===n))return r}var YAMLMap=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(i.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),add=(e,s)=>{if(typeof i==`function`)s=i.call(t,e,s);else if(Array.isArray(i)&&!i.includes(e))return;(s!==void 0||r)&&o.items.push(a.createPair(e,s,n))};if(t instanceof Map)for(let[e,n]of t)add(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))add(e,t[e]);return typeof e.sortMapEntries==`function`&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;n=i.isPair(e)?e:!e||typeof e!=`object`||!(`key`in e)?new a.Pair(e,e?.value):new a.Pair(e.key,e.value);let r=findPair(this.items,n.key),s=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);i.isScalar(r.value)&&o.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(s){let e=this.items.findIndex(e=>s(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=findPair(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=findPair(this.items,e)?.value;return(!t&&i.isScalar(n)?n.value:n)??void 0}has(e){return!!findPair(this.items,e)}set(e,t){this.add(new a.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let e of this.items)n.addPairToJSMap(t,i,e);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let e of this.items)if(!i.isPair(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),t.stringifyCollection(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:r,onComment:n})}};e.YAMLMap=YAMLMap,e.findPair=findPair})),rt=__commonJSMin((e=>{var t=P(),n=R();e.map={collection:`map`,default:!0,nodeClass:n.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(e,n){return t.isMap(e)||n(`Expected a mapping for this tag`),e},createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)}})),z=__commonJSMin((e=>{var t=Ke(),n=nt(),r=qe(),i=P(),a=I(),o=F(),YAMLSeq=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(i.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=asItemIndex(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=asItemIndex(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&i.isScalar(r)?r.value:r}has(e){let t=asItemIndex(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=asItemIndex(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];i.isScalar(r)&&a.isScalarValue(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(o.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,a=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let o of n){if(typeof i==`function`){let t=n instanceof Set?o:String(e++);o=i.call(n,t,o)}a.items.push(t.createNode(o,void 0,r))}}return a}};function asItemIndex(e){let t=i.isScalar(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=YAMLSeq})),it=__commonJSMin((e=>{var t=P(),n=z();e.seq={collection:`seq`,default:!0,nodeClass:n.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(e,n){return t.isSeq(e)||n(`Expected a sequence for this tag`),e},createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)}})),ot=__commonJSMin((e=>{var t=Xe();e.string={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,n,r,i){return n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,i)}}})),st=__commonJSMin((e=>{var t=I();let n={identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>typeof e==`string`&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n})),ct=__commonJSMin((e=>{var t=I();let n={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},r){return e&&n.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?r.options.trueStr:r.options.falseStr}};e.boolTag=n})),lt=__commonJSMin((e=>{function stringifyNumber({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 a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}e.stringifyNumber=stringifyNumber})),ut=__commonJSMin((e=>{var t=I(),n=lt();let r={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]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let n=new t.Scalar(parseFloat(e)),r=e.indexOf(`.`);return r!==-1&&e[e.length-1]===`0`&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber},e.floatExp={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():n.stringifyNumber(e)}},e.floatNaN=r})),dt=__commonJSMin((e=>{var t=lt();let intIdentify=e=>typeof e==`bigint`||Number.isInteger(e),intResolve=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function intStringify(e,n,r){let{value:i}=e;return intIdentify(i)&&i>=0?r+i.toString(n):t.stringifyNumber(e)}e.int={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:t.stringifyNumber},e.intHex={identify:e=>intIdentify(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,`0x`)},e.intOct={identify:e=>intIdentify(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>intResolve(e,2,8,n),stringify:e=>intStringify(e,8,`0o`)}})),ft=__commonJSMin((e=>{var t=rt(),n=st(),r=it(),i=ot(),a=ct(),o=ut(),s=dt();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),pt=__commonJSMin((e=>{var t=I(),n=rt(),r=it();function intIdentify(e){return typeof e==`bigint`||Number.isInteger(e)}let stringifyJSON=({value:e})=>JSON.stringify(e),i=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:stringifyJSON},{identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:stringifyJSON},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:stringifyJSON},{identify:intIdentify,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})=>intIdentify(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:stringifyJSON}];e.schema=[n.map,r.seq].concat(i,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),mt=__commonJSMin((e=>{var t=Re(`buffer`),n=I(),r=Xe();e.binary={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,n){if(typeof t.Buffer==`function`)return t.Buffer.from(e,`base64`);if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return n(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:i,value:a},o,s,c){if(!a)return``;let l=a,u;if(typeof t.Buffer==`function`)u=l instanceof t.Buffer?l.toString(`base64`):t.Buffer.from(l.buffer).toString(`base64`);else if(typeof btoa==`function`){let e=``;for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);u=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(i??=n.Scalar.BLOCK_LITERAL,i!==n.Scalar.QUOTE_DOUBLE){let e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),t=Math.ceil(u.length/e),r=Array(t);for(let n=0,i=0;n<t;++n,i+=e)r[n]=u.substr(i,e);u=r.join(i===n.Scalar.BLOCK_LITERAL?`
72
- `:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),ht=__commonJSMin((e=>{var t=P(),n=L(),r=I(),i=z();function resolvePairs(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function createPairs(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}let a={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:resolvePairs,createNode:createPairs};e.createPairs=createPairs,e.pairs=a,e.resolvePairs=resolvePairs})),gt=__commonJSMin((e=>{var t=P(),n=F(),r=R(),i=z(),a=ht(),o=class YAMLOMap extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=YAMLOMap.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;let s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),_t=__commonJSMin((e=>{var t=I();function boolStringify({value:e,source:t},i){return t&&(e?n:r).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}let n={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 t.Scalar(!0),stringify:boolStringify},r={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 t.Scalar(!1),stringify:boolStringify};e.falseTag=r,e.trueTag=n})),vt=__commonJSMin((e=>{var t=I(),n=lt();let r={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]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={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():n.stringifyNumber(e)}},e.floatNaN=r})),yt=__commonJSMin((e=>{var t=lt();let intIdentify=e=>typeof e==`bigint`||Number.isInteger(e);function intResolve(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}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function intStringify(e,n,r){let{value:i}=e;if(intIdentify(i)){let e=i.toString(n);return i<0?`-`+r+e.substr(1):r+e}return t.stringifyNumber(e)}let n={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>intResolve(e,2,2,n),stringify:e=>intStringify(e,2,`0b`)},r={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>intResolve(e,1,8,n),stringify:e=>intStringify(e,8,`0`)},i={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:t.stringifyNumber},a={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,`0x`)};e.int=i,e.intBin=n,e.intHex=a,e.intOct=r})),bt=__commonJSMin((e=>{var t=P(),n=L(),r=R(),i=class YAMLSet extends r.YAMLMap{constructor(e){super(e),this.tag=YAMLSet.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;let a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),xt=__commonJSMin((e=>{var t=lt();function parseSexagesimal(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,num=e=>t?BigInt(e):Number(e),i=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*num(60)+num(t),num(0));return n===`-`?num(-1)*i:i}function stringifySexagesimal(e){let{value:n}=e,num=e=>e;if(typeof n==`bigint`)num=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let r=``;n<0&&(r=`-`,n*=num(-1));let i=num(60),a=[n%i];return n<60?a.unshift(0):(n=(n-a[0])/i,a.unshift(n%i),n>=60&&(n=(n-a[0])/i,a.unshift(n))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}let n={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})=>parseSexagesimal(e,n),stringify:stringifySexagesimal},r={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=>parseSexagesimal(e,!1),stringify:stringifySexagesimal},i={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(i.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,a,o,s,c]=t.map(Number),l=t[7]?Number((t[7]+`00`).substr(1,3)):0,u=Date.UTC(n,r-1,a,o||0,s||0,c||0,l),d=t[8];if(d&&d!==`Z`){let e=parseSexagesimal(d,!1);Math.abs(e)<30&&(e*=60),u-=6e4*e}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=r,e.intTime=n,e.timestamp=i})),St=__commonJSMin((e=>{var t=rt(),n=st(),r=it(),i=ot(),a=mt(),o=_t(),s=vt(),c=yt(),l=et(),u=gt(),d=ht(),f=bt(),p=xt();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),Ct=__commonJSMin((e=>{var t=rt(),n=st(),r=it(),i=ot(),a=ct(),o=ut(),s=dt(),c=ft(),l=pt(),u=mt(),d=et(),f=gt(),p=ht(),m=St(),h=bt(),g=xt();let _=new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function getTags(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=getTags})),wt=__commonJSMin((e=>{var t=P(),n=rt(),r=it(),i=ot(),a=Ct();let sortMapEntriesByKey=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class Schema{constructor({compat:e,customTags:o,merge:s,resolveKnownTags:c,schema:l,sortMapEntries:u,toStringDefaults:d}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof l==`string`&&l||`core`,this.knownTags=c?a.coreKnownTags:{},this.tags=a.getTags(o,this.name,s),this.toStringOptions=d??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof u==`function`?u:u===!0?sortMapEntriesByKey:null}clone(){let e=Object.create(Schema.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}})),Tt=__commonJSMin((e=>{var t=P(),n=Ze(),r=Je();function stringifyDocument(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
76
+ `;return`${e}\n${s}${g}`}return`${h}${l}${m.join(` `)}${l}${g}`}function addCommentBefore({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=stringifyCollection})),R=__commonJSMin((e=>{var t=it(),n=rt(),r=Ye(),i=P(),a=L(),o=I();function findPair(e,t){let n=i.isScalar(t)?t.value:t;for(let r of e)if(i.isPair(r)&&(r.key===t||r.key===n||i.isScalar(r.key)&&r.key.value===n))return r}var YAMLMap=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(i.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),add=(e,s)=>{if(typeof i==`function`)s=i.call(t,e,s);else if(Array.isArray(i)&&!i.includes(e))return;(s!==void 0||r)&&o.items.push(a.createPair(e,s,n))};if(t instanceof Map)for(let[e,n]of t)add(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))add(e,t[e]);return typeof e.sortMapEntries==`function`&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;n=i.isPair(e)?e:!e||typeof e!=`object`||!(`key`in e)?new a.Pair(e,e?.value):new a.Pair(e.key,e.value);let r=findPair(this.items,n.key),s=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);i.isScalar(r.value)&&o.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(s){let e=this.items.findIndex(e=>s(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=findPair(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=findPair(this.items,e)?.value;return(!t&&i.isScalar(n)?n.value:n)??void 0}has(e){return!!findPair(this.items,e)}set(e,t){this.add(new a.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let e of this.items)n.addPairToJSMap(t,i,e);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let e of this.items)if(!i.isPair(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),t.stringifyCollection(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:r,onComment:n})}};e.YAMLMap=YAMLMap,e.findPair=findPair})),ot=__commonJSMin((e=>{var t=P(),n=R();e.map={collection:`map`,default:!0,nodeClass:n.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(e,n){return t.isMap(e)||n(`Expected a mapping for this tag`),e},createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)}})),z=__commonJSMin((e=>{var t=Je(),n=it(),r=Ye(),i=P(),a=I(),o=F(),YAMLSeq=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(i.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=asItemIndex(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=asItemIndex(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&i.isScalar(r)?r.value:r}has(e){let t=asItemIndex(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=asItemIndex(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];i.isScalar(r)&&a.isScalarValue(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(o.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,a=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let o of n){if(typeof i==`function`){let t=n instanceof Set?o:String(e++);o=i.call(n,t,o)}a.items.push(t.createNode(o,void 0,r))}}return a}};function asItemIndex(e){let t=i.isScalar(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=YAMLSeq})),st=__commonJSMin((e=>{var t=P(),n=z();e.seq={collection:`seq`,default:!0,nodeClass:n.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(e,n){return t.isSeq(e)||n(`Expected a sequence for this tag`),e},createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)}})),ct=__commonJSMin((e=>{var t=Qe();e.string={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,n,r,i){return n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,i)}}})),lt=__commonJSMin((e=>{var t=I();let n={identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>typeof e==`string`&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n})),ut=__commonJSMin((e=>{var t=I();let n={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},r){return e&&n.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?r.options.trueStr:r.options.falseStr}};e.boolTag=n})),dt=__commonJSMin((e=>{function stringifyNumber({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 a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}e.stringifyNumber=stringifyNumber})),ft=__commonJSMin((e=>{var t=I(),n=dt();let r={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]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let n=new t.Scalar(parseFloat(e)),r=e.indexOf(`.`);return r!==-1&&e[e.length-1]===`0`&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber},e.floatExp={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():n.stringifyNumber(e)}},e.floatNaN=r})),pt=__commonJSMin((e=>{var t=dt();let intIdentify=e=>typeof e==`bigint`||Number.isInteger(e),intResolve=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function intStringify(e,n,r){let{value:i}=e;return intIdentify(i)&&i>=0?r+i.toString(n):t.stringifyNumber(e)}e.int={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:t.stringifyNumber},e.intHex={identify:e=>intIdentify(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,`0x`)},e.intOct={identify:e=>intIdentify(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>intResolve(e,2,8,n),stringify:e=>intStringify(e,8,`0o`)}})),mt=__commonJSMin((e=>{var t=ot(),n=lt(),r=st(),i=ct(),a=ut(),o=ft(),s=pt();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),ht=__commonJSMin((e=>{var t=I(),n=ot(),r=st();function intIdentify(e){return typeof e==`bigint`||Number.isInteger(e)}let stringifyJSON=({value:e})=>JSON.stringify(e),i=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:stringifyJSON},{identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:stringifyJSON},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:stringifyJSON},{identify:intIdentify,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})=>intIdentify(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:stringifyJSON}];e.schema=[n.map,r.seq].concat(i,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),gt=__commonJSMin((e=>{var t=Be(`buffer`),n=I(),r=Qe();e.binary={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,n){if(typeof t.Buffer==`function`)return t.Buffer.from(e,`base64`);if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return n(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:i,value:a},o,s,c){if(!a)return``;let l=a,u;if(typeof t.Buffer==`function`)u=l instanceof t.Buffer?l.toString(`base64`):t.Buffer.from(l.buffer).toString(`base64`);else if(typeof btoa==`function`){let e=``;for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);u=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(i??=n.Scalar.BLOCK_LITERAL,i!==n.Scalar.QUOTE_DOUBLE){let e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),t=Math.ceil(u.length/e),r=Array(t);for(let n=0,i=0;n<t;++n,i+=e)r[n]=u.substr(i,e);u=r.join(i===n.Scalar.BLOCK_LITERAL?`
77
+ `:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),_t=__commonJSMin((e=>{var t=P(),n=L(),r=I(),i=z();function resolvePairs(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function createPairs(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}let a={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:resolvePairs,createNode:createPairs};e.createPairs=createPairs,e.pairs=a,e.resolvePairs=resolvePairs})),vt=__commonJSMin((e=>{var t=P(),n=F(),r=R(),i=z(),a=_t(),o=class YAMLOMap extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=YAMLOMap.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;let s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),yt=__commonJSMin((e=>{var t=I();function boolStringify({value:e,source:t},i){return t&&(e?n:r).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}let n={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 t.Scalar(!0),stringify:boolStringify},r={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 t.Scalar(!1),stringify:boolStringify};e.falseTag=r,e.trueTag=n})),bt=__commonJSMin((e=>{var t=I(),n=dt();let r={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]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={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():n.stringifyNumber(e)}},e.floatNaN=r})),xt=__commonJSMin((e=>{var t=dt();let intIdentify=e=>typeof e==`bigint`||Number.isInteger(e);function intResolve(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}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function intStringify(e,n,r){let{value:i}=e;if(intIdentify(i)){let e=i.toString(n);return i<0?`-`+r+e.substr(1):r+e}return t.stringifyNumber(e)}let n={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>intResolve(e,2,2,n),stringify:e=>intStringify(e,2,`0b`)},r={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>intResolve(e,1,8,n),stringify:e=>intStringify(e,8,`0`)},i={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>intResolve(e,0,10,n),stringify:t.stringifyNumber},a={identify:intIdentify,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>intResolve(e,2,16,n),stringify:e=>intStringify(e,16,`0x`)};e.int=i,e.intBin=n,e.intHex=a,e.intOct=r})),St=__commonJSMin((e=>{var t=P(),n=L(),r=R(),i=class YAMLSet extends r.YAMLMap{constructor(e){super(e),this.tag=YAMLSet.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;let a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),Ct=__commonJSMin((e=>{var t=dt();function parseSexagesimal(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,num=e=>t?BigInt(e):Number(e),i=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*num(60)+num(t),num(0));return n===`-`?num(-1)*i:i}function stringifySexagesimal(e){let{value:n}=e,num=e=>e;if(typeof n==`bigint`)num=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let r=``;n<0&&(r=`-`,n*=num(-1));let i=num(60),a=[n%i];return n<60?a.unshift(0):(n=(n-a[0])/i,a.unshift(n%i),n>=60&&(n=(n-a[0])/i,a.unshift(n))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}let n={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})=>parseSexagesimal(e,n),stringify:stringifySexagesimal},r={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=>parseSexagesimal(e,!1),stringify:stringifySexagesimal},i={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(i.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,a,o,s,c]=t.map(Number),l=t[7]?Number((t[7]+`00`).substr(1,3)):0,u=Date.UTC(n,r-1,a,o||0,s||0,c||0,l),d=t[8];if(d&&d!==`Z`){let e=parseSexagesimal(d,!1);Math.abs(e)<30&&(e*=60),u-=6e4*e}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=r,e.intTime=n,e.timestamp=i})),wt=__commonJSMin((e=>{var t=ot(),n=lt(),r=st(),i=ct(),a=gt(),o=yt(),s=bt(),c=xt(),l=nt(),u=vt(),d=_t(),f=St(),p=Ct();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),Tt=__commonJSMin((e=>{var t=ot(),n=lt(),r=st(),i=ct(),a=ut(),o=ft(),s=pt(),c=mt(),l=ht(),u=gt(),d=nt(),f=vt(),p=_t(),m=wt(),h=St(),g=Ct();let _=new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function getTags(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=getTags})),Et=__commonJSMin((e=>{var t=P(),n=ot(),r=st(),i=ct(),a=Tt();let sortMapEntriesByKey=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class Schema{constructor({compat:e,customTags:o,merge:s,resolveKnownTags:c,schema:l,sortMapEntries:u,toStringDefaults:d}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof l==`string`&&l||`core`,this.knownTags=c?a.coreKnownTags:{},this.tags=a.getTags(o,this.name,s),this.toStringOptions=d??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof u==`function`?u:u===!0?sortMapEntriesByKey:null}clone(){let e=Object.create(Schema.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}})),Dt=__commonJSMin((e=>{var t=P(),n=$e(),r=Xe();function stringifyDocument(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
73
78
  `)?(a.push(`...`),a.push(r.indentComment(t,``))):a.push(`... ${t}`)}else a.push(`...`)}else{let t=e.comment;t&&l&&(t=t.replace(/^\n+/,``)),t&&((!l||u)&&a[a.length-1]!==``&&a.push(``),a.push(r.indentComment(c(t),``)))}return a.join(`
74
79
  `)+`
75
- `}e.stringifyDocument=stringifyDocument})),Et=__commonJSMin((e=>{var t=Ge(),n=qe(),r=P(),i=L(),a=F(),o=wt(),s=Tt(),c=He(),l=Ue(),u=Ke(),d=Ve(),f=class Document{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;typeof t==`function`||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new d.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(Document.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=r.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){assertCollection(this.contents)&&this.contents.add(e)}addIn(e,t){assertCollection(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){let t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||`a`,t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let i;if(typeof t==`function`)e=t.call({"":e},``,e),i=t;else if(Array.isArray(t)){let keyToStr=e=>typeof e==`number`||e instanceof String||e instanceof Number,e=t.filter(keyToStr).map(String);e.length>0&&(t=t.concat(e)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:d,tag:f}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:h}=c.createNodeAnchors(this,o||`a`),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:p,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:h},_=u.createNode(e,f,g);return s&&r.isCollection(_)&&(_.flow=!0),m(),_}createPair(e,t,n={}){let r=this.createNode(e,null,n),a=this.createNode(t,null,n);return new i.Pair(r,a)}delete(e){return assertCollection(this.contents)?this.contents.delete(e):!1}deleteIn(e){return n.isEmptyPath(e)?this.contents!=null&&(this.contents=null,!0):assertCollection(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return r.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return n.isEmptyPath(e)?this.contents!==void 0:r.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=n.collectionFromPath(this.schema,[e],t):assertCollection(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):assertCollection(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new d.Directives({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new d.Directives({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new o.Schema(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},c=a.toJS(this.contents,t??``,s);if(typeof i==`function`)for(let{count:e,res:t}of s.anchors.values())i(t,e);return typeof o==`function`?l.applyReviver(o,{"":c},``,c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return s.stringifyDocument(this,e)}};function assertCollection(e){if(r.isCollection(e))return!0;throw Error(`Expected a YAML collection as document contents`)}e.Document=f})),Dt=__commonJSMin((e=>{var YAMLError=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},YAMLParseError=class extends YAMLError{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},YAMLWarning=class extends YAMLError{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}};let prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
76
- `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};e.YAMLError=YAMLError,e.YAMLParseError=YAMLParseError,e.YAMLWarning=YAMLWarning,e.prettifyError=prettifyError})),Ot=__commonJSMin((e=>{function resolveProps(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}e.resolveProps=resolveProps})),kt=__commonJSMin((e=>{function containsNewline(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
77
- `))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 e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(containsNewline(t.key)||containsNewline(t.value))return!0}return!1;default:return!0}}e.containsNewline=containsNewline})),At=__commonJSMin((e=>{var t=kt();function flowIndentCheck(e,n,r){if(n?.type===`flow-collection`){let i=n.end[0];i.indent===e&&(i.source===`]`||i.source===`}`)&&t.containsNewline(n)&&r(i,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}e.flowIndentCheck=flowIndentCheck})),jt=__commonJSMin((e=>{var t=P();function mapIncludes(e,n,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let a=typeof i==`function`?i:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>a(e.key,r))}e.mapIncludes=mapIncludes})),Mt=__commonJSMin((e=>{var t=L(),n=R(),r=Ot(),i=kt(),a=At(),o=jt();let s=`All mapping items must start at the same column`;function resolveBlockMap({composeNode:e,composeEmptyNode:c},l,u,d,f){let p=new((f?.nodeClass)??n.YAMLMap)(l.schema);l.atRoot&&=!1;let m=u.offset,h=null;for(let n of u.items){let{start:f,key:g,sep:_,value:v}=n,y=r.resolveProps(f,{indicator:`explicit-key-ind`,next:g??_?.[0],offset:m,onError:d,parentIndent:u.indent,startOnNewline:!0}),b=!y.found;if(b){if(g&&(g.type===`block-seq`?d(m,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in g&&g.indent!==u.indent&&d(m,`BAD_INDENT`,s)),!y.anchor&&!y.tag&&!_){h=y.end,y.comment&&(p.comment?p.comment+=`
80
+ `}e.stringifyDocument=stringifyDocument})),Ot=__commonJSMin((e=>{var t=qe(),n=Ye(),r=P(),i=L(),a=F(),o=Et(),s=Dt(),c=We(),l=Ge(),u=Je(),d=Ue(),f=class Document{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;typeof t==`function`||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new d.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(Document.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=r.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){assertCollection(this.contents)&&this.contents.add(e)}addIn(e,t){assertCollection(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){let t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||`a`,t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let i;if(typeof t==`function`)e=t.call({"":e},``,e),i=t;else if(Array.isArray(t)){let keyToStr=e=>typeof e==`number`||e instanceof String||e instanceof Number,e=t.filter(keyToStr).map(String);e.length>0&&(t=t.concat(e)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:d,tag:f}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:h}=c.createNodeAnchors(this,o||`a`),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:p,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:h},_=u.createNode(e,f,g);return s&&r.isCollection(_)&&(_.flow=!0),m(),_}createPair(e,t,n={}){let r=this.createNode(e,null,n),a=this.createNode(t,null,n);return new i.Pair(r,a)}delete(e){return assertCollection(this.contents)?this.contents.delete(e):!1}deleteIn(e){return n.isEmptyPath(e)?this.contents!=null&&(this.contents=null,!0):assertCollection(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return r.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return n.isEmptyPath(e)?this.contents!==void 0:r.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=n.collectionFromPath(this.schema,[e],t):assertCollection(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):assertCollection(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new d.Directives({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new d.Directives({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new o.Schema(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},c=a.toJS(this.contents,t??``,s);if(typeof i==`function`)for(let{count:e,res:t}of s.anchors.values())i(t,e);return typeof o==`function`?l.applyReviver(o,{"":c},``,c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return s.stringifyDocument(this,e)}};function assertCollection(e){if(r.isCollection(e))return!0;throw Error(`Expected a YAML collection as document contents`)}e.Document=f})),kt=__commonJSMin((e=>{var YAMLError=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},YAMLParseError=class extends YAMLError{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},YAMLWarning=class extends YAMLError{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}};let prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
81
+ `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};e.YAMLError=YAMLError,e.YAMLParseError=YAMLParseError,e.YAMLWarning=YAMLWarning,e.prettifyError=prettifyError})),At=__commonJSMin((e=>{function resolveProps(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}e.resolveProps=resolveProps})),jt=__commonJSMin((e=>{function containsNewline(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
82
+ `))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 e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(containsNewline(t.key)||containsNewline(t.value))return!0}return!1;default:return!0}}e.containsNewline=containsNewline})),Mt=__commonJSMin((e=>{var t=jt();function flowIndentCheck(e,n,r){if(n?.type===`flow-collection`){let i=n.end[0];i.indent===e&&(i.source===`]`||i.source===`}`)&&t.containsNewline(n)&&r(i,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}e.flowIndentCheck=flowIndentCheck})),Nt=__commonJSMin((e=>{var t=P();function mapIncludes(e,n,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let a=typeof i==`function`?i:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>a(e.key,r))}e.mapIncludes=mapIncludes})),Pt=__commonJSMin((e=>{var t=L(),n=R(),r=At(),i=jt(),a=Mt(),o=Nt();let s=`All mapping items must start at the same column`;function resolveBlockMap({composeNode:e,composeEmptyNode:c},l,u,d,f){let p=new((f?.nodeClass)??n.YAMLMap)(l.schema);l.atRoot&&=!1;let m=u.offset,h=null;for(let n of u.items){let{start:f,key:g,sep:_,value:v}=n,y=r.resolveProps(f,{indicator:`explicit-key-ind`,next:g??_?.[0],offset:m,onError:d,parentIndent:u.indent,startOnNewline:!0}),b=!y.found;if(b){if(g&&(g.type===`block-seq`?d(m,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in g&&g.indent!==u.indent&&d(m,`BAD_INDENT`,s)),!y.anchor&&!y.tag&&!_){h=y.end,y.comment&&(p.comment?p.comment+=`
78
83
  `+y.comment:p.comment=y.comment);continue}(y.newlineAfterProp||i.containsNewline(g))&&d(g??f[f.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else y.found?.indent!==u.indent&&d(m,`BAD_INDENT`,s);l.atKey=!0;let x=y.end,S=g?e(l,g,y,d):c(l,x,f,null,y,d);l.schema.compat&&a.flowIndentCheck(u.indent,g,d),l.atKey=!1,o.mapIncludes(l,p.items,S)&&d(x,`DUPLICATE_KEY`,`Map keys must be unique`);let C=r.resolveProps(_??[],{indicator:`map-value-ind`,next:v,offset:S.range[2],onError:d,parentIndent:u.indent,startOnNewline:!g||g.type===`block-scalar`});if(m=C.end,C.found){b&&(v?.type===`block-map`&&!C.hasNewline&&d(m,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),l.options.strict&&y.start<C.found.offset-1024&&d(S.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let r=v?e(l,v,C,d):c(l,m,_,null,C,d);l.schema.compat&&a.flowIndentCheck(u.indent,v,d),m=r.range[2];let i=new t.Pair(S,r);l.options.keepSourceTokens&&(i.srcToken=n),p.items.push(i)}else{b&&d(S.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),C.comment&&(S.comment?S.comment+=`
79
- `+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=resolveBlockMap})),Nt=__commonJSMin((e=>{var t=z(),n=Ot(),r=At();function resolveBlockSeq({composeNode:e,composeEmptyNode:i},a,o,s,c){let l=new((c?.nodeClass)??t.YAMLSeq)(a.schema);a.atRoot&&=!1,a.atKey&&=!1;let u=o.offset,d=null;for(let{start:t,value:c}of o.items){let f=n.resolveProps(t,{indicator:`seq-item-ind`,next:c,offset:u,onError:s,parentIndent:o.indent,startOnNewline:!0});if(!f.found){if(f.anchor||f.tag||c)c?.type===`block-seq`?s(f.end,`BAD_INDENT`,`All sequence items must start at the same column`):s(u,`MISSING_CHAR`,`Sequence item without - indicator`);else{d=f.end,f.comment&&(l.comment=f.comment);continue}}let p=c?e(a,c,f,s):i(a,f.end,t,null,f,s);a.schema.compat&&r.flowIndentCheck(o.indent,c,s),u=p.range[2],l.items.push(p)}return l.range=[o.offset,u,d??u],l}e.resolveBlockSeq=resolveBlockSeq})),Pt=__commonJSMin((e=>{function resolveEnd(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}e.resolveEnd=resolveEnd})),Ft=__commonJSMin((e=>{var t=P(),n=L(),r=R(),i=z(),a=Pt(),o=Ot(),s=kt(),c=jt();let l=`Block collections are not allowed within flow collections`,isBlock=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function resolveFlowCollection({composeNode:e,composeEmptyNode:u},d,f,p,m){let h=f.start.source===`{`,g=h?`flow map`:`flow sequence`,_=new((m?.nodeClass)??(h?r.YAMLMap:i.YAMLSeq))(d.schema);_.flow=!0;let v=d.atRoot;v&&(d.atRoot=!1),d.atKey&&=!1;let y=f.offset+f.start.source.length;for(let i=0;i<f.items.length;++i){let a=f.items[i],{start:m,key:v,sep:b,value:x}=a,S=o.resolveProps(m,{flow:g,indicator:`explicit-key-ind`,next:v??b?.[0],offset:y,onError:p,parentIndent:f.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!b&&!x){i===0&&S.comma?p(S.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${g}`):i<f.items.length-1&&p(S.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${g}`),S.comment&&(_.comment?_.comment+=`
84
+ `+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=resolveBlockMap})),Ft=__commonJSMin((e=>{var t=z(),n=At(),r=Mt();function resolveBlockSeq({composeNode:e,composeEmptyNode:i},a,o,s,c){let l=new((c?.nodeClass)??t.YAMLSeq)(a.schema);a.atRoot&&=!1,a.atKey&&=!1;let u=o.offset,d=null;for(let{start:t,value:c}of o.items){let f=n.resolveProps(t,{indicator:`seq-item-ind`,next:c,offset:u,onError:s,parentIndent:o.indent,startOnNewline:!0});if(!f.found){if(f.anchor||f.tag||c)c?.type===`block-seq`?s(f.end,`BAD_INDENT`,`All sequence items must start at the same column`):s(u,`MISSING_CHAR`,`Sequence item without - indicator`);else{d=f.end,f.comment&&(l.comment=f.comment);continue}}let p=c?e(a,c,f,s):i(a,f.end,t,null,f,s);a.schema.compat&&r.flowIndentCheck(o.indent,c,s),u=p.range[2],l.items.push(p)}return l.range=[o.offset,u,d??u],l}e.resolveBlockSeq=resolveBlockSeq})),It=__commonJSMin((e=>{function resolveEnd(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}e.resolveEnd=resolveEnd})),Lt=__commonJSMin((e=>{var t=P(),n=L(),r=R(),i=z(),a=It(),o=At(),s=jt(),c=Nt();let l=`Block collections are not allowed within flow collections`,isBlock=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function resolveFlowCollection({composeNode:e,composeEmptyNode:u},d,f,p,m){let h=f.start.source===`{`,g=h?`flow map`:`flow sequence`,_=new((m?.nodeClass)??(h?r.YAMLMap:i.YAMLSeq))(d.schema);_.flow=!0;let v=d.atRoot;v&&(d.atRoot=!1),d.atKey&&=!1;let y=f.offset+f.start.source.length;for(let i=0;i<f.items.length;++i){let a=f.items[i],{start:m,key:v,sep:b,value:x}=a,S=o.resolveProps(m,{flow:g,indicator:`explicit-key-ind`,next:v??b?.[0],offset:y,onError:p,parentIndent:f.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!b&&!x){i===0&&S.comma?p(S.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${g}`):i<f.items.length-1&&p(S.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${g}`),S.comment&&(_.comment?_.comment+=`
80
85
  `+S.comment:_.comment=S.comment),y=S.end;continue}!h&&d.options.strict&&s.containsNewline(v)&&p(v,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(i===0)S.comma&&p(S.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${g}`);else if(S.comma||p(S.start,`MISSING_CHAR`,`Missing , between ${g} items`),S.comment){let e=``;loop:for(let t of m)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let n=_.items[_.items.length-1];t.isPair(n)&&(n=n.value??n.key),n.comment?n.comment+=`
81
86
  `+e:n.comment=e,S.comment=S.comment.substring(e.length+1)}}if(!h&&!b&&!S.found){let t=x?e(d,x,S,p):u(d,S.end,b,null,S,p);_.items.push(t),y=t.range[2],isBlock(x)&&p(t.range,`BLOCK_IN_FLOW`,l)}else{d.atKey=!0;let t=S.end,i=v?e(d,v,S,p):u(d,t,m,null,S,p);isBlock(v)&&p(i.range,`BLOCK_IN_FLOW`,l),d.atKey=!1;let s=o.resolveProps(b??[],{flow:g,indicator:`map-value-ind`,next:x,offset:i.range[2],onError:p,parentIndent:f.indent,startOnNewline:!1});if(s.found){if(!h&&!S.found&&d.options.strict){if(b)for(let e of b){if(e===s.found)break;if(e.type===`newline`){p(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}S.start<s.found.offset-1024&&p(s.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]===`:`?p(x,`MISSING_CHAR`,`Missing space after : in ${g}`):p(s.start,`MISSING_CHAR`,`Missing , or : between ${g} items`));let C=x?e(d,x,s,p):s.found?u(d,s.end,b,null,s,p):null;C?isBlock(x)&&p(C.range,`BLOCK_IN_FLOW`,l):s.comment&&(i.comment?i.comment+=`
82
87
  `+s.comment:i.comment=s.comment);let w=new n.Pair(i,C);if(d.options.keepSourceTokens&&(w.srcToken=a),h){let e=_;c.mapIncludes(d,e.items,i)&&p(t,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(w)}else{let e=new r.YAMLMap(d.schema);e.flow=!0,e.items.push(w);let t=(C??i).range;e.range=[i.range[0],t[1],t[2]],_.items.push(e)}y=C?C.range[2]:s.end}}let b=h?`}`:`]`,[x,...S]=f.end,C=y;if(x?.source===b)C=x.offset+x.source.length;else{let e=g[0].toUpperCase()+g.substring(1),t=v?`${e} must end with a ${b}`:`${e} in block collection must be sufficiently indented and end with a ${b}`;p(y,v?`MISSING_CHAR`:`BAD_INDENT`,t),x&&x.source.length!==1&&S.unshift(x)}if(S.length>0){let e=a.resolveEnd(S,C,d.options.strict,p);e.comment&&(_.comment?_.comment+=`
83
- `+e.comment:_.comment=e.comment),_.range=[f.offset,C,e.offset]}else _.range=[f.offset,C,C];return _}e.resolveFlowCollection=resolveFlowCollection})),It=__commonJSMin((e=>{var t=P(),n=I(),r=R(),i=z(),a=Mt(),o=Nt(),s=Ft();function resolveCollection(e,t,n,r,i,c){let l=n.type===`block-map`?a.resolveBlockMap(e,t,n,r,c):n.type===`block-seq`?o.resolveBlockSeq(e,t,n,r,c):s.resolveFlowCollection(e,t,n,r,c),u=l.constructor;return i===`!`||i===u.tagName?(l.tag=u.tagName,l):(i&&(l.tag=i),l)}function composeCollection(e,a,o,s,c){let l=s.tag,u=l?a.directives.tagName(l.source,e=>c(l,`TAG_RESOLVE_FAILED`,e)):null;if(o.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=s,n=e&&l?e.offset>l.offset?e:l:e??l;n&&(!t||t.offset<n.offset)&&c(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let d=o.type===`block-map`?`map`:o.type===`block-seq`?`seq`:o.start.source===`{`?`map`:`seq`;if(!l||!u||u===`!`||u===r.YAMLMap.tagName&&d===`map`||u===i.YAMLSeq.tagName&&d===`seq`)return resolveCollection(e,a,o,c,u);let f=a.schema.tags.find(e=>e.tag===u&&e.collection===d);if(!f){let t=a.schema.knownTags[u];if(t?.collection===d)a.schema.tags.push(Object.assign({},t,{default:!1})),f=t;else return t?c(l,`BAD_COLLECTION_TYPE`,`${t.tag} used for ${d} collection, but expects ${t.collection??`scalar`}`,!0):c(l,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${u}`,!0),resolveCollection(e,a,o,c,u)}let p=resolveCollection(e,a,o,c,u,f),m=f.resolve?.(p,e=>c(l,`TAG_RESOLVE_FAILED`,e),a.options)??p,h=t.isNode(m)?m:new n.Scalar(m);return h.range=p.range,h.tag=u,f?.format&&(h.format=f.format),h}e.composeCollection=composeCollection})),Lt=__commonJSMin((e=>{var t=I();function resolveBlockScalar(e,n,r){let i=n.offset,a=parseBlockScalarHeader(n,e.options.strict,r);if(!a)return{value:``,type:null,comment:``,range:[i,i,i]};let o=a.mode===`>`?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,s=n.source?splitLines(n.source):[],c=s.length;for(let e=s.length-1;e>=0;--e){let t=s[e][1];if(t===``||t===`\r`)c=e;else break}if(c===0){let e=a.chomp===`+`&&s.length>0?`
88
+ `+e.comment:_.comment=e.comment),_.range=[f.offset,C,e.offset]}else _.range=[f.offset,C,C];return _}e.resolveFlowCollection=resolveFlowCollection})),Rt=__commonJSMin((e=>{var t=P(),n=I(),r=R(),i=z(),a=Pt(),o=Ft(),s=Lt();function resolveCollection(e,t,n,r,i,c){let l=n.type===`block-map`?a.resolveBlockMap(e,t,n,r,c):n.type===`block-seq`?o.resolveBlockSeq(e,t,n,r,c):s.resolveFlowCollection(e,t,n,r,c),u=l.constructor;return i===`!`||i===u.tagName?(l.tag=u.tagName,l):(i&&(l.tag=i),l)}function composeCollection(e,a,o,s,c){let l=s.tag,u=l?a.directives.tagName(l.source,e=>c(l,`TAG_RESOLVE_FAILED`,e)):null;if(o.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=s,n=e&&l?e.offset>l.offset?e:l:e??l;n&&(!t||t.offset<n.offset)&&c(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let d=o.type===`block-map`?`map`:o.type===`block-seq`?`seq`:o.start.source===`{`?`map`:`seq`;if(!l||!u||u===`!`||u===r.YAMLMap.tagName&&d===`map`||u===i.YAMLSeq.tagName&&d===`seq`)return resolveCollection(e,a,o,c,u);let f=a.schema.tags.find(e=>e.tag===u&&e.collection===d);if(!f){let t=a.schema.knownTags[u];if(t?.collection===d)a.schema.tags.push(Object.assign({},t,{default:!1})),f=t;else return t?c(l,`BAD_COLLECTION_TYPE`,`${t.tag} used for ${d} collection, but expects ${t.collection??`scalar`}`,!0):c(l,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${u}`,!0),resolveCollection(e,a,o,c,u)}let p=resolveCollection(e,a,o,c,u,f),m=f.resolve?.(p,e=>c(l,`TAG_RESOLVE_FAILED`,e),a.options)??p,h=t.isNode(m)?m:new n.Scalar(m);return h.range=p.range,h.tag=u,f?.format&&(h.format=f.format),h}e.composeCollection=composeCollection})),zt=__commonJSMin((e=>{var t=I();function resolveBlockScalar(e,n,r){let i=n.offset,a=parseBlockScalarHeader(n,e.options.strict,r);if(!a)return{value:``,type:null,comment:``,range:[i,i,i]};let o=a.mode===`>`?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,s=n.source?splitLines(n.source):[],c=s.length;for(let e=s.length-1;e>=0;--e){let t=s[e][1];if(t===``||t===`\r`)c=e;else break}if(c===0){let e=a.chomp===`+`&&s.length>0?`
84
89
  `.repeat(Math.max(1,s.length-1)):``,t=i+a.length;return n.source&&(t+=n.source.length),{value:e,type:o,comment:a.comment,range:[i,t,t]}}let l=n.indent+a.indent,u=n.offset+a.length,d=0;for(let t=0;t<c;++t){let[n,i]=s[t];if(i===``||i===`\r`)a.indent===0&&n.length>l&&(l=n.length);else{n.length<l&&r(u+n.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),a.indent===0&&(l=n.length),d=t,l===0&&!e.atRoot&&r(u,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}u+=n.length+i.length+1}for(let e=s.length-1;e>=c;--e)s[e][0].length>l&&(c=e+1);let f=``,p=``,m=!1;for(let e=0;e<d;++e)f+=s[e][0].slice(l)+`
85
90
  `;for(let e=d;e<c;++e){let[n,i]=s[e];u+=n.length+i.length+1;let c=i[i.length-1]===`\r`;if(c&&(i=i.slice(0,-1)),i&&n.length<l){let e=`Block scalar lines must not be less indented than their ${a.indent?`explicit indentation indicator`:`first line`}`;r(u-i.length-(c?2:1),`BAD_INDENT`,e),n=``}o===t.Scalar.BLOCK_LITERAL?(f+=p+n.slice(l)+i,p=`
86
91
  `):n.length>l||i[0]===` `?(p===` `?p=`
@@ -95,7 +100,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
95
100
  `+s[e][0].slice(l);f[f.length-1]!==`
96
101
  `&&(f+=`
97
102
  `);break;default:f+=`
98
- `}let h=i+a.length+n.source.length;return{value:f,type:o,comment:a.comment,range:[i,h,h]}}function parseBlockScalarHeader({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],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function splitLines(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=resolveBlockScalar})),Rt=__commonJSMin((e=>{var t=I(),n=Pt();function resolveFlowScalar(e,r,i){let{offset:a,type:o,source:s,end:c}=e,l,u,_onError=(e,t,n)=>i(a+e,t,n);switch(o){case`scalar`:l=t.Scalar.PLAIN,u=plainValue(s,_onError);break;case`single-quoted-scalar`:l=t.Scalar.QUOTE_SINGLE,u=singleQuotedValue(s,_onError);break;case`double-quoted-scalar`:l=t.Scalar.QUOTE_DOUBLE,u=doubleQuotedValue(s,_onError);break;default:return i(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${o}`),{value:``,type:null,comment:``,range:[a,a+s.length,a+s.length]}}let d=a+s.length,f=n.resolveEnd(c,d,r,i);return{value:u,type:l,comment:f.comment,range:[a,d,f.offset]}}function plainValue(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]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),unfoldLines(e)}function singleQuotedValue(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),unfoldLines(e.slice(1,-1)).replace(/''/g,`'`)}function unfoldLines(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
103
+ `}let h=i+a.length+n.source.length;return{value:f,type:o,comment:a.comment,range:[i,h,h]}}function parseBlockScalarHeader({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],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function splitLines(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=resolveBlockScalar})),Bt=__commonJSMin((e=>{var t=I(),n=It();function resolveFlowScalar(e,r,i){let{offset:a,type:o,source:s,end:c}=e,l,u,_onError=(e,t,n)=>i(a+e,t,n);switch(o){case`scalar`:l=t.Scalar.PLAIN,u=plainValue(s,_onError);break;case`single-quoted-scalar`:l=t.Scalar.QUOTE_SINGLE,u=singleQuotedValue(s,_onError);break;case`double-quoted-scalar`:l=t.Scalar.QUOTE_DOUBLE,u=doubleQuotedValue(s,_onError);break;default:return i(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${o}`),{value:``,type:null,comment:``,range:[a,a+s.length,a+s.length]}}let d=a+s.length,f=n.resolveEnd(c,d,r,i);return{value:u,type:l,comment:f.comment,range:[a,d,f.offset]}}function plainValue(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]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),unfoldLines(e)}function singleQuotedValue(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),unfoldLines(e.slice(1,-1)).replace(/''/g,`'`)}function unfoldLines(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
99
104
  `?a+=o:o=`
100
105
  `:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function doubleQuotedValue(e,t){let n=``;for(let i=1;i<e.length-1;++i){let a=e[i];if(a!==`\r`||e[i+1]!==`
101
106
  `){if(a===`
@@ -108,10 +113,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
108
113
  `);)r===`
109
114
  `&&(n+=`
110
115
  `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}let r={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
111
- `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function parseCharCode(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=resolveFlowScalar})),zt=__commonJSMin((e=>{var t=P(),n=I(),r=Lt(),i=Rt();function composeScalar(e,a,o,s){let{value:c,type:l,comment:u,range:d}=a.type===`block-scalar`?r.resolveBlockScalar(e,a,s):i.resolveFlowScalar(a,e.options.strict,s),f=o?e.directives.tagName(o.source,e=>s(o,`TAG_RESOLVE_FAILED`,e)):null,p;p=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:f?findScalarTagByName(e.schema,c,f,o,s):a.type===`scalar`?findScalarTagByTest(e,c,a,s):e.schema[t.SCALAR];let m;try{let r=p.resolve(c,e=>s(o??a,`TAG_RESOLVE_FAILED`,e),e.options);m=t.isScalar(r)?r:new n.Scalar(r)}catch(e){let t=e instanceof Error?e.message:String(e);s(o??a,`TAG_RESOLVE_FAILED`,t),m=new n.Scalar(c)}return m.range=d,m.source=c,l&&(m.type=l),f&&(m.tag=f),p.format&&(m.format=p.format),u&&(m.comment=u),m}function findScalarTagByName(e,n,r,i,a){if(r===`!`)return e[t.SCALAR];let o=[];for(let t of e.tags)if(!t.collection&&t.tag===r){if(t.default&&t.test)o.push(t);else return t}for(let e of o)if(e.test?.test(n))return e;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(i,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${r}`,r!==`tag:yaml.org,2002:str`),e[t.SCALAR])}function findScalarTagByTest({atKey:e,directives:n,schema:r},i,a,o){let s=r.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(i))||r[t.SCALAR];if(r.compat){let e=r.compat.find(e=>e.default&&e.test?.test(i))??r[t.SCALAR];s.tag!==e.tag&&o(a,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${n.tagString(s.tag)} or ${n.tagString(e.tag)}`,!0)}return s}e.composeScalar=composeScalar})),Bt=__commonJSMin((e=>{function emptyScalarPosition(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}e.emptyScalarPosition=emptyScalarPosition})),Vt=__commonJSMin((e=>{var t=Ge(),n=P(),r=It(),i=zt(),a=Pt(),o=Bt();let s={composeNode,composeEmptyNode};function composeNode(e,t,a,o){let c=e.atKey,{spaceBefore:l,comment:u,anchor:d,tag:f}=a,p,m=!0;switch(t.type){case`alias`:p=composeAlias(e,t,o),(d||f)&&o(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`:p=i.composeScalar(e,t,f,o),d&&(p.anchor=d.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{p=r.composeCollection(s,e,t,a,o),d&&(p.anchor=d.source.substring(1))}catch(e){o(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:o(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),m=!1}return p??=composeEmptyNode(e,t.offset,void 0,null,a,o),d&&p.anchor===``&&o(d,`BAD_ALIAS`,`Anchor cannot be an empty string`),c&&e.options.stringKeys&&(!n.isScalar(p)||typeof p.value!=`string`||p.tag&&p.tag!==`tag:yaml.org,2002:str`)&&o(f??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),l&&(p.spaceBefore=!0),u&&(t.type===`scalar`&&t.source===``?p.comment=u:p.commentBefore=u),e.options.keepSourceTokens&&m&&(p.srcToken=t),p}function composeEmptyNode(e,t,n,r,{spaceBefore:a,comment:s,anchor:c,tag:l,end:u},d){let f={type:`scalar`,offset:o.emptyScalarPosition(t,n,r),indent:-1,source:``},p=i.composeScalar(e,f,l,d);return c&&(p.anchor=c.source.substring(1),p.anchor===``&&d(c,`BAD_ALIAS`,`Anchor cannot be an empty string`)),a&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=u),p}function composeAlias({options:e},{offset:n,source:r,end:i},o){let s=new t.Alias(r.substring(1));s.source===``&&o(n,`BAD_ALIAS`,`Alias cannot be an empty string`),s.source.endsWith(`:`)&&o(n+r.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let c=n+r.length,l=a.resolveEnd(i,c,e.strict,o);return s.range=[n,c,l.offset],l.comment&&(s.comment=l.comment),s}e.composeEmptyNode=composeEmptyNode,e.composeNode=composeNode})),Ht=__commonJSMin((e=>{var t=Et(),n=Vt(),r=Pt(),i=Ot();function composeDoc(e,a,{offset:o,start:s,value:c,end:l},u){let d=Object.assign({_directives:a},e),f=new t.Document(void 0,d),p={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},m=i.resolveProps(s,{indicator:`doc-start`,next:c??l?.[0],offset:o,onError:u,parentIndent:0,startOnNewline:!0});m.found&&(f.directives.docStart=!0,c&&(c.type===`block-map`||c.type===`block-seq`)&&!m.hasNewline&&u(m.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),f.contents=c?n.composeNode(p,c,m,u):n.composeEmptyNode(p,m.end,s,null,m,u);let h=f.contents.range[2],g=r.resolveEnd(l,h,!1,u);return g.comment&&(f.comment=g.comment),f.range=[o,h,g.offset],f}e.composeDoc=composeDoc})),Ut=__commonJSMin((e=>{var t=Re(`process`),n=Ve(),r=Et(),i=Dt(),a=P(),o=Ht(),s=Pt();function getErrorPos(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 parsePrelude(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
116
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function parseCharCode(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=resolveFlowScalar})),Vt=__commonJSMin((e=>{var t=P(),n=I(),r=zt(),i=Bt();function composeScalar(e,a,o,s){let{value:c,type:l,comment:u,range:d}=a.type===`block-scalar`?r.resolveBlockScalar(e,a,s):i.resolveFlowScalar(a,e.options.strict,s),f=o?e.directives.tagName(o.source,e=>s(o,`TAG_RESOLVE_FAILED`,e)):null,p;p=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:f?findScalarTagByName(e.schema,c,f,o,s):a.type===`scalar`?findScalarTagByTest(e,c,a,s):e.schema[t.SCALAR];let m;try{let r=p.resolve(c,e=>s(o??a,`TAG_RESOLVE_FAILED`,e),e.options);m=t.isScalar(r)?r:new n.Scalar(r)}catch(e){let t=e instanceof Error?e.message:String(e);s(o??a,`TAG_RESOLVE_FAILED`,t),m=new n.Scalar(c)}return m.range=d,m.source=c,l&&(m.type=l),f&&(m.tag=f),p.format&&(m.format=p.format),u&&(m.comment=u),m}function findScalarTagByName(e,n,r,i,a){if(r===`!`)return e[t.SCALAR];let o=[];for(let t of e.tags)if(!t.collection&&t.tag===r){if(t.default&&t.test)o.push(t);else return t}for(let e of o)if(e.test?.test(n))return e;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(i,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${r}`,r!==`tag:yaml.org,2002:str`),e[t.SCALAR])}function findScalarTagByTest({atKey:e,directives:n,schema:r},i,a,o){let s=r.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(i))||r[t.SCALAR];if(r.compat){let e=r.compat.find(e=>e.default&&e.test?.test(i))??r[t.SCALAR];s.tag!==e.tag&&o(a,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${n.tagString(s.tag)} or ${n.tagString(e.tag)}`,!0)}return s}e.composeScalar=composeScalar})),Ht=__commonJSMin((e=>{function emptyScalarPosition(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}e.emptyScalarPosition=emptyScalarPosition})),Ut=__commonJSMin((e=>{var t=qe(),n=P(),r=Rt(),i=Vt(),a=It(),o=Ht();let s={composeNode,composeEmptyNode};function composeNode(e,t,a,o){let c=e.atKey,{spaceBefore:l,comment:u,anchor:d,tag:f}=a,p,m=!0;switch(t.type){case`alias`:p=composeAlias(e,t,o),(d||f)&&o(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`:p=i.composeScalar(e,t,f,o),d&&(p.anchor=d.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{p=r.composeCollection(s,e,t,a,o),d&&(p.anchor=d.source.substring(1))}catch(e){o(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:o(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),m=!1}return p??=composeEmptyNode(e,t.offset,void 0,null,a,o),d&&p.anchor===``&&o(d,`BAD_ALIAS`,`Anchor cannot be an empty string`),c&&e.options.stringKeys&&(!n.isScalar(p)||typeof p.value!=`string`||p.tag&&p.tag!==`tag:yaml.org,2002:str`)&&o(f??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),l&&(p.spaceBefore=!0),u&&(t.type===`scalar`&&t.source===``?p.comment=u:p.commentBefore=u),e.options.keepSourceTokens&&m&&(p.srcToken=t),p}function composeEmptyNode(e,t,n,r,{spaceBefore:a,comment:s,anchor:c,tag:l,end:u},d){let f={type:`scalar`,offset:o.emptyScalarPosition(t,n,r),indent:-1,source:``},p=i.composeScalar(e,f,l,d);return c&&(p.anchor=c.source.substring(1),p.anchor===``&&d(c,`BAD_ALIAS`,`Anchor cannot be an empty string`)),a&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=u),p}function composeAlias({options:e},{offset:n,source:r,end:i},o){let s=new t.Alias(r.substring(1));s.source===``&&o(n,`BAD_ALIAS`,`Alias cannot be an empty string`),s.source.endsWith(`:`)&&o(n+r.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let c=n+r.length,l=a.resolveEnd(i,c,e.strict,o);return s.range=[n,c,l.offset],l.comment&&(s.comment=l.comment),s}e.composeEmptyNode=composeEmptyNode,e.composeNode=composeNode})),Wt=__commonJSMin((e=>{var t=Ot(),n=Ut(),r=It(),i=At();function composeDoc(e,a,{offset:o,start:s,value:c,end:l},u){let d=Object.assign({_directives:a},e),f=new t.Document(void 0,d),p={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},m=i.resolveProps(s,{indicator:`doc-start`,next:c??l?.[0],offset:o,onError:u,parentIndent:0,startOnNewline:!0});m.found&&(f.directives.docStart=!0,c&&(c.type===`block-map`||c.type===`block-seq`)&&!m.hasNewline&&u(m.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),f.contents=c?n.composeNode(p,c,m,u):n.composeEmptyNode(p,m.end,s,null,m,u);let h=f.contents.range[2],g=r.resolveEnd(l,h,!1,u);return g.comment&&(f.comment=g.comment),f.range=[o,h,g.offset],f}e.composeDoc=composeDoc})),Gt=__commonJSMin((e=>{var t=Be(`process`),n=Ue(),r=Ot(),i=kt(),a=P(),o=Wt(),s=It();function getErrorPos(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 parsePrelude(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
112
117
 
113
118
  `:`
114
- `)+(a.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 Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=getErrorPos(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=parsePrelude(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:parsePrelude(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=getErrorPos(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(getErrorPos(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(getErrorPos(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(getErrorPos(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}};e.Composer=Composer})),Wt=__commonJSMin((e=>{var t=Lt(),n=Rt(),r=Dt(),i=Xe();function resolveAsScalar(e,i=!0,a){if(e){let _onError=(e,t,n)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(a)a(i,t,n);else throw new r.YAMLParseError([i,i+1],t,n)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return n.resolveFlowScalar(e,i,_onError);case`block-scalar`:return t.resolveBlockScalar({options:{strict:i}},e,_onError)}}return null}function createScalarToken(e,t){let{implicitKey:n=!1,indent:r,inFlow:a=!1,offset:o=-1,type:s=`PLAIN`}=t,c=i.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:`newline`,offset:-1,indent:r,source:`
119
+ `)+(a.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 Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=getErrorPos(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=parsePrelude(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:parsePrelude(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=getErrorPos(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(getErrorPos(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(getErrorPos(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(getErrorPos(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}};e.Composer=Composer})),Kt=__commonJSMin((e=>{var t=zt(),n=Bt(),r=kt(),i=Qe();function resolveAsScalar(e,i=!0,a){if(e){let _onError=(e,t,n)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(a)a(i,t,n);else throw new r.YAMLParseError([i,i+1],t,n)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return n.resolveFlowScalar(e,i,_onError);case`block-scalar`:return t.resolveBlockScalar({options:{strict:i}},e,_onError)}}return null}function createScalarToken(e,t){let{implicitKey:n=!1,indent:r,inFlow:a=!1,offset:o=-1,type:s=`PLAIN`}=t,c=i.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:`newline`,offset:-1,indent:r,source:`
115
120
  `}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
116
121
  `),t=c.substring(0,e),n=c.substring(e+1)+`
117
122
  `,i=[{type:`block-scalar-header`,offset:o,indent:r,source:t}];return addEndtoBlockProps(i,l)||i.push({type:`newline`,offset:-1,indent:r,source:`
@@ -119,9 +124,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
119
124
  `),r=t.substring(0,n),i=t.substring(n+1)+`
120
125
  `;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];addEndtoBlockProps(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
121
126
  `});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function addEndtoBlockProps(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 setFlowScalarValue(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 e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
122
- `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=createScalarToken,e.resolveAsScalar=resolveAsScalar,e.setScalarValue=setScalarValue})),Gt=__commonJSMin((e=>{let stringify=e=>`type`in e?stringifyToken(e):stringifyItem(e);function stringifyToken(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=stringifyToken(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=stringifyItem(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=stringifyItem(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=stringifyItem(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 stringifyItem({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=stringifyToken(t)),n)for(let e of n)i+=e.source;return r&&(i+=stringifyToken(r)),i}e.stringify=stringify})),Kt=__commonJSMin((e=>{let t=Symbol(`break visit`),n=Symbol(`skip children`),r=Symbol(`remove item`);function visit(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),_visit(Object.freeze([]),e,t)}visit.BREAK=t,visit.SKIP=n,visit.REMOVE=r,visit.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},visit.parentCollection=(e,t)=>{let n=visit.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function _visit(e,n,i){let a=i(n,e);if(typeof a==`symbol`)return a;for(let o of[`key`,`value`]){let s=n[o];if(s&&`items`in s){for(let n=0;n<s.items.length;++n){let a=_visit(Object.freeze(e.concat([[o,n]])),s.items[n],i);if(typeof a==`number`)n=a-1;else if(a===t)return t;else a===r&&(s.items.splice(n,1),--n)}typeof a==`function`&&o===`key`&&(a=a(n,e))}}return typeof a==`function`?a(n,e):a}e.visit=visit})),qt=__commonJSMin((e=>{var t=Wt(),n=Gt(),r=Kt();let isCollection=e=>!!e&&`items`in e,isScalar=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`);function prettyToken(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function tokenType(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
127
+ `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=createScalarToken,e.resolveAsScalar=resolveAsScalar,e.setScalarValue=setScalarValue})),qt=__commonJSMin((e=>{let stringify=e=>`type`in e?stringifyToken(e):stringifyItem(e);function stringifyToken(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=stringifyToken(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=stringifyItem(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=stringifyItem(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=stringifyItem(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 stringifyItem({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=stringifyToken(t)),n)for(let e of n)i+=e.source;return r&&(i+=stringifyToken(r)),i}e.stringify=stringify})),Jt=__commonJSMin((e=>{let t=Symbol(`break visit`),n=Symbol(`skip children`),r=Symbol(`remove item`);function visit(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),_visit(Object.freeze([]),e,t)}visit.BREAK=t,visit.SKIP=n,visit.REMOVE=r,visit.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},visit.parentCollection=(e,t)=>{let n=visit.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function _visit(e,n,i){let a=i(n,e);if(typeof a==`symbol`)return a;for(let o of[`key`,`value`]){let s=n[o];if(s&&`items`in s){for(let n=0;n<s.items.length;++n){let a=_visit(Object.freeze(e.concat([[o,n]])),s.items[n],i);if(typeof a==`number`)n=a-1;else if(a===t)return t;else a===r&&(s.items.splice(n,1),--n)}typeof a==`function`&&o===`key`&&(a=a(n,e))}}return typeof a==`function`?a(n,e):a}e.visit=visit})),Yt=__commonJSMin((e=>{var t=Kt(),n=qt(),r=Jt();let isCollection=e=>!!e&&`items`in e,isScalar=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`);function prettyToken(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function tokenType(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
123
128
  `:case`\r
124
- `: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}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=``,e.DOCUMENT=``,e.FLOW_END=``,e.SCALAR=``,e.isCollection=isCollection,e.isScalar=isScalar,e.prettyToken=prettyToken,e.tokenType=tokenType})),Jt=__commonJSMin((e=>{var t=qt();function isEmpty(e){switch(e){case void 0:case` `:case`
129
+ `: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}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=``,e.DOCUMENT=``,e.FLOW_END=``,e.SCALAR=``,e.isCollection=isCollection,e.isScalar=isScalar,e.prettyToken=prettyToken,e.tokenType=tokenType})),Xt=__commonJSMin((e=>{var t=Yt();function isEmpty(e){switch(e){case void 0:case` `:case`
125
130
  `:case`\r`:case` `:return!0;default:return!1}}let n=new Set(`0123456789ABCDEFabcdef`),r=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),i=new Set(`,[]{}`),a=new Set(` ,[]{}
126
131
  \r `),isNotAnchorChar=e=>!e||a.has(e);var Lexer=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(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
127
132
  `||t===`\r`&&this.buffer[e+1]===`
@@ -140,27 +145,27 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
140
145
  `,t=this.buffer[r+1]):n=r),t===`#`||e&&i.has(t))break;if(a===`
141
146
  `){let e=this.continueScalar(r+1);if(e===-1)break;r=Math.max(r,e-2)}}else{if(e&&i.has(a))break;n=r}return!a&&!this.atEnd?this.setNext(`plain-scalar`):(yield t.SCALAR,yield*this.pushToIndex(n+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(isNotAnchorChar),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(isEmpty(n)||t&&i.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!isEmpty(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(r.has(t))t=this.buffer[++e];else if(t===`%`&&n.has(this.buffer[e+1])&&n.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
142
147
  `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
143
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};e.Lexer=Lexer})),Yt=__commonJSMin((e=>{var LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};e.LineCounter=LineCounter})),Xt=__commonJSMin((e=>{var t=Re(`process`),n=qt(),r=Jt();function includesToken(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function findNonEmptyIndex(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 isFlowToken(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 getPrevProps(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 getFirstKeyStartProps(e){if(e.length===0)return[];let t=e.length;loop: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 loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function arrayPushArray(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 fixFlowSeqItems(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!includesToken(t.start,`explicit-key-ind`)&&!includesToken(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,isFlowToken(t.value)?t.value.end?arrayPushArray(t.value.end,t.sep):t.value.end=t.sep:arrayPushArray(t.start,t.sep),delete t.sep)}var Parser=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,t.env.LOG_TOKENS&&console.log(`|`,n.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=n.tokenType(e);if(!r){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(r===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=r,yield*this.step(),r){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.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 e=this.peek(1);if(this.type===`doc-end`&&e?.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(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&fixFlowSeqItems(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&findNonEmptyIndex(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.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 e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:findNonEmptyIndex(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=getFirstKeyStartProps(getPrevProps(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
148
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};e.Lexer=Lexer})),Zt=__commonJSMin((e=>{var LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};e.LineCounter=LineCounter})),Qt=__commonJSMin((e=>{var t=Be(`process`),n=Yt(),r=Xt();function includesToken(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function findNonEmptyIndex(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 isFlowToken(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 getPrevProps(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 getFirstKeyStartProps(e){if(e.length===0)return[];let t=e.length;loop: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 loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function arrayPushArray(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 fixFlowSeqItems(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!includesToken(t.start,`explicit-key-ind`)&&!includesToken(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,isFlowToken(t.value)?t.value.end?arrayPushArray(t.value.end,t.sep):t.value.end=t.sep:arrayPushArray(t.start,t.sep),delete t.sep)}var Parser=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,t.env.LOG_TOKENS&&console.log(`|`,n.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=n.tokenType(e);if(!r){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(r===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=r,yield*this.step(),r){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.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 e=this.peek(1);if(this.type===`doc-end`&&e?.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(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&fixFlowSeqItems(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&findNonEmptyIndex(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.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 e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:findNonEmptyIndex(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=getFirstKeyStartProps(getPrevProps(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
144
149
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
145
150
  `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){arrayPushArray(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,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(t.explicitKey){if(!t.sep){if(includesToken(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=getFirstKeyStartProps(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(isFlowToken(t.key)&&!includesToken(t.sep,`newline`)){let e=getFirstKeyStartProps(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):includesToken(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!includesToken(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){arrayPushArray(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||includesToken(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=getFirstKeyStartProps(getPrevProps(t));fixFlowSeqItems(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
146
151
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
147
- `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=getFirstKeyStartProps(getPrevProps(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=getFirstKeyStartProps(getPrevProps(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};e.Parser=Parser})),Zt=__commonJSMin((e=>{var t=Ut(),n=Et(),r=Dt(),i=$e(),a=P(),o=Yt(),s=Xt();function parseOptions(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function parseAllDocuments(e,n={}){let{lineCounter:i,prettyErrors:a}=parseOptions(n),o=new s.Parser(i?.addNewLine),c=new t.Composer(n),l=Array.from(c.compose(o.parse(e)));if(a&&i)for(let t of l)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return l.length>0?l:Object.assign([],{empty:!0},c.streamInfo())}function parseDocument(e,n={}){let{lineCounter:i,prettyErrors:a}=parseOptions(n),o=new s.Parser(i?.addNewLine),c=new t.Composer(n),l=null;for(let t of c.compose(o.parse(e),!0,e.length))if(!l)l=t;else if(l.options.logLevel!==`silent`){l.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(l.errors.forEach(r.prettifyError(e,i)),l.warnings.forEach(r.prettifyError(e,i))),l}function parse(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=parseDocument(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function stringify(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=parse,e.parseAllDocuments=parseAllDocuments,e.parseDocument=parseDocument,e.stringify=stringify})),Qt=__commonJSMin((e=>{var t=Ut(),n=Et(),r=wt(),i=Dt(),a=Ge(),o=P(),s=L(),c=I(),l=R(),u=z();qt();var d=Jt(),f=Yt(),p=Xt(),m=Zt(),h=Be();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();const $t=/^---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;function skillName(e){let t;try{t=a(S(e,`SKILL.md`),`utf8`)}catch{return}let n=$t.exec(t);if(n)try{let e=(0,Qt.parse)(n[1]);if(isRecord$1(e)&&typeof e.name==`string`&&e.name.trim())return e.name.trim()}catch{}return v(e)}function isDirectory$2(e){try{return d(e).isDirectory()}catch{return!1}}function skillsIn(e){let t=[],n=new Set,add=(e,r)=>{let i=e;try{i=c(e)}catch{}n.has(i)||(n.add(i),t.push({name:r,folder:i}))};for(let t of e){let e=skillName(t);if(e!==void 0){add(t,e);continue}let n;try{n=o(t)}catch{continue}for(let e of n.sort()){let n=S(t,e);if(!isDirectory$2(n))continue;let r=skillName(n);r!==void 0&&add(n,r)}}return t}const isOne=e=>e===`1`,isSet=e=>e!==``,en={name:`CLAUDECODE`,matches:isOne,description:`Claude Code sets CLAUDECODE=1 in subprocesses it spawns; IDE extensions also set it in integrated terminals`,research:`E-CC-D1`},tn=[{harness:`claude-code`,all:[en,{name:`CLAUDE_CODE_CHILD_SESSION`,matches:isOne,description:`Claude Code sets CLAUDE_CODE_CHILD_SESSION=1 for tool, hook, and status line subprocesses`,research:`E-CC-D3`}]},{harness:`claude-code`,all:[en,{name:`CLAUDE_CODE_SESSION_ID`,matches:isSet,description:`Claude Code sets CLAUDE_CODE_SESSION_ID in tool, hook, and stdio MCP server subprocesses`,research:`E-CC-D6`}]},{harness:`cursor`,all:[{name:`CURSOR_AGENT`,matches:isOne,description:`Cursor sets CURSOR_AGENT=1 on terminal commands its agent runs`,research:`E-CUR-D1`}]},{harness:`cursor`,all:[{name:`CURSOR_VERSION`,matches:isSet,description:`Cursor sets CURSOR_VERSION for hook commands`,research:`E-CUR-D10`},{name:`CURSOR_PROJECT_DIR`,matches:isSet,description:`Cursor sets CURSOR_PROJECT_DIR for hook commands`,research:`E-CUR-D10`}]},{harness:`codex`,all:[{name:`CODEX_THREAD_ID`,matches:isSet,description:`Codex injects CODEX_THREAD_ID into shell tool commands, even under a restrictive shell env policy`,research:`E-CODEX-D2`}]},{harness:`copilot-cli`,all:[{name:`COPILOT_CLI`,matches:isOne,description:`Copilot CLI sets COPILOT_CLI=1 in its subprocesses`,research:`E-COPILOT-D1`}]},{harness:`copilot-cli`,all:[{name:`COPILOT_AGENT_SESSION_ID`,matches:isSet,description:`Copilot CLI passes COPILOT_AGENT_SESSION_ID to shell commands and MCP servers`,research:`E-COPILOT-D2`}]},{harness:`copilot-cli`,all:[{name:`COPILOT_PLUGIN_ROOT`,matches:isSet,description:`Copilot CLI passes COPILOT_PLUGIN_ROOT to plugin hooks`,research:`E-COPILOT-D6`}]},{harness:`opencode`,all:[{name:`OPENCODE`,matches:isOne,description:`OpenCode sets OPENCODE=1 for shell tool commands and MCP servers; Kilo Code, its fork, sets it too`,research:`E-OC-D1`},{name:`OPENCODE_PID`,matches:isSet,description:`OpenCode sets OPENCODE_PID for shell tool commands and MCP servers; Kilo Code sets KILO_PID instead`,research:`E-OC-D2`}]},{harness:`kilo`,all:[{name:`KILO`,matches:isOne,description:`Kilo Code sets KILO=1 for shell tool commands and MCP servers`,research:`E-KILO-D2`},{name:`KILO_PID`,matches:isSet,description:`Kilo Code sets KILO_PID for shell tool commands and MCP servers`,research:`E-KILO-D1`}]},{harness:`gemini-cli`,all:[{name:`GEMINI_CLI`,matches:isOne,description:`Gemini CLI sets GEMINI_CLI=1 for shell tool commands and MCP stdio servers`,research:`E-GEM-D1`}]},{harness:`qwen-code`,all:[{name:`QWEN_CODE`,matches:isOne,description:`Qwen Code sets QWEN_CODE=1 for shell tool commands, not for MCP servers or hooks`,research:`E-QWEN-D1`}]},{harness:`vscode-copilot`,all:[{name:`COPILOT_AGENT`,matches:isOne,description:`VS Code 1.121+ sets COPILOT_AGENT=1 on terminals its Copilot agent runs commands in`,research:`E-VSC-D1`}]},{harness:`cline`,all:[{name:`CLINE_ACTIVE`,matches:e=>e===`true`,description:`Cline's VS Code extension sets CLINE_ACTIVE=true on the terminals it creates; the Cline CLI does not`,research:`E-CLINE-D1`}]},{harness:`crush`,all:[{name:`CRUSH`,matches:isOne,description:`Crush sets CRUSH=1 for bash tool and hook commands, not for MCP servers`,research:`E-CRUSH-D1`}]},{harness:`openhands`,all:[{name:`AI_AGENT`,matches:e=>e===`openhands`,description:`OpenHands (SDK 1.40.1 and later) sets AI_AGENT=openhands for terminal tool and hook commands when AI_AGENT is unset; other vendors use the name with other values`,research:`E-OH-D1`}]},{harness:`openhands`,all:[{name:`OPENHANDS_EVENT_TYPE`,matches:isSet,description:`OpenHands sets OPENHANDS_EVENT_TYPE for hook commands`,research:`E-OH-D4`},{name:`OPENHANDS_PROJECT_DIR`,matches:isSet,description:`OpenHands sets OPENHANDS_PROJECT_DIR for hook commands`,research:`E-OH-D4`}]},{harness:`augment`,all:[{name:`AUGMENT_HOOK_EVENT`,matches:isSet,description:`The Auggie CLI sets AUGMENT_HOOK_EVENT for hook commands; its shell commands carry no marker`,research:`E-AUG-D3`},{name:`AUGMENT_PROJECT_DIR`,matches:isSet,description:`The Auggie CLI sets AUGMENT_PROJECT_DIR for hook commands`,research:`E-AUG-D3`}]}];function detectHarness(e={}){let t=e.env??process.env,n=[],r=[];for(let e of tn){let i=e.all.filter(e=>{let n=t[e.name];return n!==void 0&&e.matches(n)});for(let t of i)n.some(n=>n.harness===e.harness&&n.signal===t.name)||n.push({harness:e.harness,signal:t.name,description:t.description,research:t.research});i.length===e.all.length&&!r.includes(e.harness)&&r.push(e.harness)}return{harness:r.length===1?r[0]:`unknown`,evidence:n,candidates:r}}function managedPolicyLocations(e,t={}){let n=t.platform??process.platform,r=t.env??process.env;return nn[e](n,r)}const joinFor=e=>e===`win32`?D.join:C.join,dirnameFor=e=>e===`win32`?D.dirname:C.dirname;function opencodeFamily(e,t,n,r){let i={darwin:`/Library/Application Support/${n}`,linux:`/etc/${n}`,win32:D.join(t.ProgramData??`C:\\ProgramData`,n)}[e];return[...when(e===`darwin`,{kind:`macos-managed-preferences`,location:`ai.opencode.managed`,description:`MDM configuration profile; outranks the managed config folder`,research:r.preferences}),...when(i!==void 0,{kind:`directory`,location:i??``,description:`Managed config files; outrank user and project config`,research:r.directory})]}function geminiFamily(e,t,n){let r=e===`darwin`||e===`win32`?n.dirs[e]:n.dirs.linux,i=t[n.settingsVariable]||joinFor(e)(r,`settings.json`),a=t[n.defaultsVariable]||joinFor(e)(dirnameFor(e)(i),`system-defaults.json`);return[{kind:`file`,location:i,description:`System settings; outrank user and workspace settings. ${n.settingsVariable} overrides the path`,research:n.research},{kind:`file`,location:a,description:`System defaults; user and workspace settings override them. ${n.defaultsVariable} overrides the path`,research:n.research}]}const when=(e,...t)=>e?t:[],nn={"claude-code":e=>{let t={darwin:`/Library/Application Support/ClaudeCode`,linux:`/etc/claude-code`,win32:`C:\\Program Files\\ClaudeCode`}[e],n=joinFor(e);return[{kind:`server`,location:`claude.ai admin console or a self-hosted Claude apps gateway`,description:`Server-managed settings; the highest-ranked managed source`,research:`E-CC-M6`},...when(e===`darwin`,{kind:`macos-managed-preferences`,location:`com.anthropic.claudecode`,description:`MDM configuration profile with the same top-level keys as managed-settings.json`,research:`E-CC-M6`}),...when(e===`win32`,{kind:`windows-registry`,location:`HKLM\\SOFTWARE\\Policies\\ClaudeCode`,description:`MDM or Group Policy; the Settings value holds managed-settings JSON`,research:`E-CC-M6`}),...when(t!==void 0,{kind:`file`,location:n(t??``,`managed-settings.json`),description:`Managed settings, same shape as settings.json`,research:`E-CC-M1`},{kind:`directory`,location:n(t??``,`managed-settings.d`),description:`Drop-in managed settings files, merged with managed-settings.json`,research:`E-CC-M1`},{kind:`file`,location:n(t??``,`managed-mcp.json`),description:`Managed MCP servers`,research:`E-CC-M1`}),...when(e===`win32`,{kind:`windows-registry`,location:`HKCU\\SOFTWARE\\Policies\\ClaudeCode`,description:`User-writable; used only when no other managed source delivers a policy key`,research:`E-CC-M6`})]},cursor:e=>{let t={darwin:`/Library/Application Support/Cursor/hooks.json`,linux:`/etc/cursor/hooks.json`,win32:`C:\\ProgramData\\Cursor\\hooks.json`}[e];return[...when(t!==void 0,{kind:`file`,location:t??``,description:`Enterprise hooks deployed by MDM; hooks only, not other enterprise settings`,research:`E-CUR-M1`}),{kind:`server`,location:`Cursor dashboard`,description:`Team hooks and other enterprise settings, synced from the dashboard`,research:`E-CUR-M1`}]},codex:(e,t)=>{let n={kind:`server`,location:`ChatGPT workspace admin settings`,description:`Cloud-managed requirements; outrank every local source`,research:`E-CODEX-M8`};return e===`win32`?[n,{kind:`file`,location:D.join(t.ProgramData??`C:\\ProgramData`,`OpenAI`,`Codex`,`requirements.toml`),description:`Admin-enforced requirements users cannot override`,research:`E-CODEX-M4`}]:[n,...when(e===`darwin`,{kind:`macos-managed-preferences`,location:`com.openai.codex`,description:`MDM keys requirements_toml_base64 (enforced) and config_toml_base64 (managed defaults)`,research:`E-CODEX-M6`}),{kind:`file`,location:`/etc/codex/requirements.toml`,description:`Admin-enforced requirements users cannot override`,research:`E-CODEX-M3`},{kind:`file`,location:`/etc/codex/managed_config.toml`,description:`Managed defaults; a user can override them within a session`,research:`E-CODEX-M2`},{kind:`file`,location:`/etc/codex/config.toml`,description:`System-wide config`,research:`E-CODEX-M1`}]},"copilot-cli":(e,t)=>{let n={darwin:`/Library/Application Support/GitHubCopilot/managed-settings.json`,linux:`/etc/github-copilot/managed-settings.json`,win32:D.join(t.ProgramFiles??`C:\\Program Files`,`GitHubCopilot`,`managed-settings.json`)}[e];return[...when(e===`darwin`,{kind:`macos-managed-preferences`,location:`com.github.copilot`,description:`MDM-managed settings; the highest-ranked source`,research:`E-COPILOT-M2`}),...when(e===`win32`,{kind:`windows-registry`,location:`HKLM\\SOFTWARE\\Policies\\GitHubCopilot`,description:`MDM-managed settings as REG_SZ values; the highest-ranked source`,research:`E-COPILOT-M2`}),{kind:`server`,location:`copilot/managed-settings.json in the enterprise's .github-private repository`,description:`Server-managed settings, fetched for the signed-in account`,research:`E-COPILOT-M3`},...when(n!==void 0,{kind:`file`,location:n??``,description:`File-based managed settings; on macOS and Linux it must be a root-owned regular file`,research:`E-COPILOT-M1`})]},opencode:(e,t)=>[...opencodeFamily(e,t,`opencode`,{directory:`E-OC-M1`,preferences:`E-OC-M1`}),{kind:`server`,location:`Remote config at the organization domain /.well-known/opencode`,description:`Organization defaults; the lowest-ranked config source, so user config overrides them`,research:`E-OC-M2`}],kilo:(e,t)=>opencodeFamily(e,t,`kilo`,{directory:`E-KILO-M1`,preferences:`E-KILO-M2`}),"gemini-cli":(e,t)=>geminiFamily(e,t,{settingsVariable:`GEMINI_CLI_SYSTEM_SETTINGS_PATH`,defaultsVariable:`GEMINI_CLI_SYSTEM_DEFAULTS_PATH`,dirs:{darwin:`/Library/Application Support/GeminiCli`,linux:`/etc/gemini-cli`,win32:`C:\\ProgramData\\gemini-cli`},research:`E-GEM-M1`}),"qwen-code":(e,t)=>geminiFamily(e,t,{settingsVariable:`QWEN_CODE_SYSTEM_SETTINGS_PATH`,defaultsVariable:`QWEN_CODE_SYSTEM_DEFAULTS_PATH`,dirs:{darwin:`/Library/Application Support/QwenCode`,linux:`/etc/qwen-code`,win32:`C:\\ProgramData\\qwen-code`},research:`E-QWEN-M1`}),"vscode-copilot":e=>[...when(e===`win32`,{kind:`windows-registry`,location:`Software\\Policies\\Microsoft\\VSCode`,description:`VS Code policies set by Group Policy (ADMX templates ship with VS Code)`,research:`E-VSC-M1`}),...when(e===`linux`,{kind:`file`,location:`/etc/vscode/policy.json`,description:`VS Code policies as JSON, read by VS Code 1.106 and later`,research:`E-VSC-M3`})],cline:()=>[{kind:`server`,location:`Cline Enterprise admin console`,description:`Provider, model, and tool policy pushed to clients; no local policy file is documented`,research:`E-CLINE-M1`}],crush:e=>when(e!==`win32`,{kind:`file`,location:`/etc/crush/crush.json`,description:`System config; the lowest-ranked source, so user and project config override it`,research:`E-CRUSH-M1`}),openhands:()=>[{kind:`server`,location:`OpenHands Cloud or Enterprise deployment`,description:`Organization controls held server-side; no local policy file is known`,research:`E-OH-D8`}],augment:(e,t)=>[{kind:`file`,location:e===`win32`?D.join(t.ProgramData||`C:\\ProgramData`,`augment`,`settings.json`):`/etc/augment/settings.json`,description:`System settings, read from the Auggie CLI bundle; its rank against user settings is not documented`,research:`E-AUG-M1`}]};function resolveHarnessEnvironment(e={}){return{env:e.env??process.env,homedir:e.homedir??g(),cwd:e.cwd??process.cwd(),platform:e.platform??process.platform}}function pluginStorage(e,t={}){return rn[e](resolveHarnessEnvironment(t))}const xdgConfig=({env:e,homedir:t})=>e.XDG_CONFIG_HOME||S(t,`.config`);function vscodeAgentPlugins({env:e,homedir:t,platform:n}){if(n===`win32`){let n=D.join(e.APPDATA||D.join(t,`AppData`,`Roaming`),`Code`);return{configDir:n,path:D.join(n,`agentPlugins`)}}let r=n===`darwin`?S(t,`Library`,`Application Support`,`Code`):S(t,`.config`,`Code`);return{configDir:r,path:S(r,`agentPlugins`)}}const rn={"claude-code":({env:e,homedir:t})=>{let n=e.CLAUDE_CONFIG_DIR||S(t,`.claude`),r=S(n,`plugins`);return{harness:`claude-code`,configDir:n,locations:[{kind:`plugin-cache`,path:S(r,`cache`),description:`Installed plugins as <marketplace>/<plugin>/<version>/`,research:`E-CC-P1`},{kind:`marketplaces`,path:S(r,`marketplaces`),description:`Marketplace checkouts`,research:`E-CC-P1`},{kind:`install-record`,path:S(r,`installed_plugins.json`),description:`Installs keyed by plugin@marketplace, each with scope, installPath, and version`,research:`E-CC-P2`},{kind:`enabled-record`,path:S(n,`settings.json`),description:`User settings; enabledPlugins maps plugin@marketplace to a boolean`,research:`E-CC-P3`}]}},cursor:({homedir:e})=>{let t=S(e,`.cursor`);return{harness:`cursor`,configDir:t,locations:[{kind:`local-plugins`,path:S(t,`plugins`,`local`),description:`Plugins under development, one folder each`,research:`E-CUR-P2`},{kind:`marketplaces`,path:S(t,`plugins`,`marketplaces`),description:`Marketplace checkouts`,research:`E-CUR-P3`}]}},codex:({env:e,homedir:t})=>{let n=e.CODEX_HOME||S(t,`.codex`);return{harness:`codex`,configDir:n,locations:[{kind:`plugin-cache`,path:S(n,`plugins`,`cache`),description:`Installed plugins as <marketplace>/<plugin>/<version>/`,research:`E-CODEX-P3`},{kind:`enabled-record`,path:S(n,`config.toml`),description:`User config; [plugins."<plugin>@<marketplace>"] tables carry enabled = <bool>`,research:`E-CODEX-P2`}]}},"copilot-cli":({env:e,homedir:t})=>{let n=e.COPILOT_HOME||S(t,`.copilot`);return{harness:`copilot-cli`,configDir:n,locations:[{kind:`installed-plugins`,path:S(n,`installed-plugins`),description:`Installed plugins as <marketplace>/<plugin>/, or _direct/<source-id>/ for direct installs`,research:`E-COPILOT-P9`},{kind:`install-record`,path:S(n,`config.json`),description:`Application state, including installedPlugins`,research:`E-COPILOT-P9`},{kind:`enabled-record`,path:S(n,`settings.json`),description:`User settings (JSON with comments); enabledPlugins maps plugin specs to a boolean`,research:`E-COPILOT-P4`}]}},opencode:e=>{let t=S(xdgConfig(e),`opencode`);return{harness:`opencode`,configDir:t,locations:[{kind:`local-plugins`,path:S(t,`plugins`),description:`JS/TS plugin modules loaded at startup; npm plugins are named in the plugin config array`,research:`E-OC-P2`}]}},kilo:e=>{let t=S(xdgConfig(e),`kilo`);return{harness:`kilo`,configDir:t,locations:[{kind:`local-plugins`,path:S(t,`plugin`),description:`JS/TS plugin modules loaded at startup; npm plugins are named in the plugin config array`,research:`E-KILO-P2`}]}},"gemini-cli":({env:e,homedir:t})=>{let n=S(e.GEMINI_CLI_HOME||t,`.gemini`),r=S(n,`extensions`);return{harness:`gemini-cli`,configDir:n,locations:[{kind:`installed-plugins`,path:r,description:`Installed extensions, one folder each with a gemini-extension.json manifest`,research:`E-GEM-P1`},{kind:`enabled-record`,path:S(r,`extension-enablement.json`),description:`Per-extension path-glob overrides that enable or disable it by folder, not a boolean`,research:`E-GEM-P3`}]}},"qwen-code":({env:e,homedir:t})=>{let n=e.QWEN_HOME||S(t,`.qwen`),r=S(n,`extensions`);return{harness:`qwen-code`,configDir:n,locations:[{kind:`installed-plugins`,path:r,description:`Installed extensions, one folder each with a qwen-extension.json manifest`,research:`E-QWEN-P1`},{kind:`enabled-record`,path:S(r,`extension-enablement.json`),description:`Extension enable/disable state, inherited from Gemini CLI's format`,research:`E-QWEN-P2`}]}},"vscode-copilot":e=>{let{configDir:t,path:n}=vscodeAgentPlugins(e);return{harness:`vscode-copilot`,configDir:t,locations:[{kind:`installed-plugins`,path:n,description:`Installed agent plugins as <host>/<org>/<repo>/`,research:`E-VSC-P3`}]}},cline:({homedir:e})=>{let t=S(e,`.cline`);return{harness:`cline`,configDir:t,locations:[{kind:`installed-plugins`,path:S(t,`plugins`,`_installed`),description:`Installed plugins, grouped by source: npm, git, remote, or local`,research:`E-CLINE-P3`}]}},crush:({env:e,homedir:t})=>({harness:`crush`,configDir:e.CRUSH_GLOBAL_CONFIG||S(e.XDG_CONFIG_HOME||S(t,`.config`),`crush`),locations:[]}),openhands:({env:e,homedir:t})=>{let n=e.OH_PERSISTENCE_DIR||e.OPENHANDS_PERSISTENCE_DIR||S(t,`.openhands`),r=S(n,`plugins`,`installed`);return{harness:`openhands`,configDir:n,locations:[{kind:`installed-plugins`,path:r,description:`Installed plugins, one folder each`,research:`E-OH-P3`},{kind:`enabled-record`,path:S(r,`.installed.json`),description:`Install metadata keyed by plugin name, each with enabled: <bool>`,research:`E-OH-P4`}]}},augment:({homedir:e})=>{let t=S(e,`.augment`);return{harness:`augment`,configDir:t,locations:[{kind:`marketplaces`,path:S(t,`plugins`,`marketplaces`),description:`Marketplace checkouts`,research:`E-AUG-P2`},{kind:`enabled-record`,path:S(t,`settings.json`),description:`User settings; enabledPlugins maps plugin@marketplace to a boolean`,research:`E-AUG-P4`}]}}};async function enabledPlugins(e,t={}){let n=cn[e](resolveHarnessEnvironment(t),t.managedSettingsPath),r=new Map,i=[];for(let e of n.sources){let t;try{let n=await readText(e.path);if(n===void 0){i.push({scope:e.scope,path:e.path,found:!1});continue}t=e.parse(n)}catch(t){i.push({scope:e.scope,path:e.path,found:!0,error:String(t)});continue}i.push({scope:e.scope,path:e.path,found:!0});for(let[n,i]of Object.entries(t))r.has(n)||r.set(n,{id:n,enabled:i,scope:e.scope,source:e.path})}return{harness:e,supported:n.supported,plugins:[...r.values()],sources:i,unread:n.unread,research:n.research}}function jsonEnabledPlugins(e){let t=JSON.parse(e),n=isRecord$1(t)?t.enabledPlugins:void 0;return isRecord$1(n)?Object.fromEntries(Object.entries(n).filter(e=>typeof e[1]==`boolean`)):{}}const an=/^\[\s*plugins\s*\.\s*(?:"([^"]*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*\]\s*(?:#.*)?$/,on=/^enabled\s*=\s*(true|false)\s*(?:#.*)?$/;function tomlEnabledPlugins(e){let t={},n;for(let r of e.split(/\r?\n/)){let e=r.trim();if(e.startsWith(`[`)){let t=an.exec(e);n=t?t[1]??t[2]??t[3]:void 0;continue}let i=n===void 0?null:on.exec(e);n!==void 0&&i&&(t[n]=i[1]===`true`)}return t}const sn={server:`server-managed settings`,"macos-managed-preferences":`MDM managed preferences`,"windows-registry":`Windows registry policy`,directory:`drop-in managed settings`,file:`managed file`};function unreadPolicy(e,t,n=[]){return e.filter(e=>e.location!==t&&!n.some(t=>e.location.endsWith(t))).map(e=>`${sn[e.kind]} (${e.location})`)}function managedFile(e,t){return e.find(e=>e.kind===`file`&&e.location.endsWith(t))?.location}function jsoncEnabledPlugins(e){return jsonEnabledPlugins(stripJsonComments$1(e))}const unsupported$1=(...e)=>({supported:!1,sources:[],unread:[],research:e}),cn={"claude-code":(e,t)=>{let{configDir:n}=pluginStorage(`claude-code`,e),r=managedPolicyLocations(`claude-code`,e),i=managedFile(r,`managed-settings.json`),a=t??i,o=S(e.cwd,`.claude`);return{supported:!0,sources:[...a===void 0?[]:[{scope:`managed`,path:a,parse:jsonEnabledPlugins}],{scope:`local`,path:S(o,`settings.local.json`),parse:jsonEnabledPlugins},{scope:`project`,path:S(o,`settings.json`),parse:jsonEnabledPlugins},{scope:`user`,path:S(n,`settings.json`),parse:jsonEnabledPlugins}],unread:unreadPolicy(r,i,[`managed-mcp.json`]),research:[`E-CC-P3`,`E-CC-P7`,`E-CC-M1`,`E-CC-M6`]}},cursor:()=>unsupported$1(),opencode:()=>unsupported$1(`E-OC-P3`),kilo:()=>unsupported$1(`E-KILO-P3`),"gemini-cli":()=>unsupported$1(`E-GEM-P3`),"qwen-code":()=>unsupported$1(`E-QWEN-P2`),"vscode-copilot":()=>unsupported$1(`E-VSC-P4`),cline:()=>unsupported$1(`E-CLINE-P4`),crush:()=>unsupported$1(`E-CRUSH-P2`),openhands:()=>unsupported$1(`E-OH-P4`),augment:()=>unsupported$1(`E-AUG-P4`),codex:e=>{let t=pluginStorage(`codex`,e);return{supported:!0,sources:[{scope:`user`,path:S(t.configDir,`config.toml`),parse:tomlEnabledPlugins}],unread:unreadPolicy(managedPolicyLocations(`codex`,e),void 0),research:[`E-CODEX-P2`,`E-CODEX-M7`]}},"copilot-cli":(e,t)=>{let n=pluginStorage(`copilot-cli`,e),r=managedPolicyLocations(`copilot-cli`,e),i=managedFile(r,`managed-settings.json`),a=t??i,o=S(e.cwd,`.github`,`copilot`),s=S(e.cwd,`.claude`);return{supported:!0,sources:[...a===void 0?[]:[{scope:`managed`,path:a,parse:jsoncEnabledPlugins}],{scope:`local`,path:S(o,`settings.local.json`),parse:jsoncEnabledPlugins},{scope:`project`,path:S(o,`settings.json`),parse:jsoncEnabledPlugins},{scope:`user`,path:S(n.configDir,`settings.json`),parse:jsoncEnabledPlugins}],unread:[...unreadPolicy(r,i),`Claude Code project settings (${S(s,`settings.json`)})`,`Claude Code local settings (${S(s,`settings.local.json`)})`],research:[`E-COPILOT-P4`,`E-COPILOT-M1`,`E-COPILOT-M2`,`E-COPILOT-M4`]}}};async function installedPlugins(e,t={}){let n=gn[e](resolveHarnessEnvironment(t)),r={harness:e,supported:n.supported,unread:n.unread,research:n.research};if(n.source===void 0)return{...r,plugins:[],unresolved:[],sources:[]};let i=n.source;try{let e=await n.read(i);return e===void 0?{...r,plugins:[],unresolved:[],sources:[{path:i,found:!1}]}:{...r,plugins:e.plugins,unresolved:e.unresolved??[],sources:[{path:i,found:!0}]}}catch(e){return{...r,plugins:[],unresolved:[],sources:[{path:i,found:!0,error:String(e)}]}}}const ln=[`managed`,`local`,`project`,`user`],optionalString=e=>typeof e==`string`&&e!==``?e:void 0;async function readClaudeInstalls(e){let t=await readText(e);if(t===void 0)return;let n=JSON.parse(t),r=isRecord$1(n)?n.plugins:void 0;if(!isRecord$1(r))return{plugins:[]};let i=[];for(let[e,t]of Object.entries(r))if(Array.isArray(t))for(let n of t){let t=isRecord$1(n)?optionalString(n.installPath):void 0;if(!isRecord$1(n)||t===void 0)continue;let r=optionalString(n.version),a=typeof n.scope==`string`&&ln.includes(n.scope)?n.scope:void 0,o=optionalString(n.projectPath);i.push({id:e,path:t,...r===void 0?{}:{version:r},...a===void 0?{}:{scope:a},...o===void 0?{}:{projectPath:o},research:[`E-CC-P2`]})}return{plugins:i}}async function readCopilotInstalls(e){let t=await readText(e);if(t===void 0)return;let n=JSON.parse(stripJsonComments$1(t)),r=isRecord$1(n)?n.installedPlugins:void 0;if(!Array.isArray(r))return{plugins:[]};let i=[];for(let e of r){if(!isRecord$1(e))continue;let t=optionalString(e.name),n=optionalString(e.cache_path);if(t===void 0||n===void 0)continue;let r=optionalString(e.marketplace),a=optionalString(e.version);i.push({id:r===void 0?t:`${t}@${r}`,path:n,...a===void 0?{}:{version:a},research:r===void 0?[`E-COPILOT-P10`,`E-COPILOT-P11`]:[`E-COPILOT-P10`]})}return{plugins:i}}const un=`local`,dn=/^[A-Za-z0-9_-]+$/,fn=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*$/,pn=/^[A-Za-z0-9._+-]+$/;async function readCodexInstalls(e){let t=await directories$1(e);if(t===void 0)return;let n=[],r=[];for(let i of t.filter(e=>dn.test(e)))for(let t of await directories$1(S(e,i))??[]){if(!fn.test(t))continue;let a=`${t}@${i}`,o=(await directories$1(S(e,i,t))??[]).filter(e=>pn.test(e)&&e!==`.`&&e!==`..`);if(o.length===0)continue;let s=activeCodexVersion(o);if(s===void 0){r.push(a);continue}n.push({id:a,path:S(e,i,t,s),version:s,research:[`E-CODEX-P3`,`E-CODEX-P8`]})}return{plugins:n,unresolved:r}}function activeCodexVersion(e){if(e.includes(un))return un;let t=e.filter(e=>parseSemver(e)!==void 0).length;if(!(e.length>2&&t!==0&&t!==e.length))return[...e].sort(compareCodexVersions).at(-1)}async function directories$1(e){try{return(await ee(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(e.code===`ENOENT`)return;throw e}}__name(directories$1,`directories`);const mn=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function parseSemver(e){let t=mn.exec(e);if(t)return{core:[t[1],t[2],t[3]],pre:t[4]===void 0?[]:t[4].split(`.`),build:t[5]===void 0?[]:t[5].split(`.`)}}function compareCodexVersions(e,t){let n=parseSemver(e),r=parseSemver(t);if(n===void 0||r===void 0)return compareStrings(e,t);for(let e=0;e<3;e++){let t=compareNumeric(n.core[e],r.core[e]);if(t!==0)return t}let i=n.pre.length===0||r.pre.length===0?r.pre.length-n.pre.length:compareIdentifiers(n.pre,r.pre);return i===0?compareIdentifiers(n.build,r.build):Math.sign(i)}const hn=/^\d+$/;function compareIdentifiers(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=hn.test(r),o=hn.test(i),s=a&&o?compareNumeric(r,i):a===o?compareStrings(r,i):a?-1:1;if(s!==0)return s}return e.length-t.length}function compareNumeric(e,t){let n=e.replace(/^0+(?=\d)/,``),r=t.replace(/^0+(?=\d)/,``);return n.length-r.length||compareStrings(n,r)||e.length-t.length}const compareStrings=(e,t)=>e<t?-1:+(e>t),B={supported:!1,read:async()=>void 0,unread:[],research:[]},gn={"claude-code":e=>({supported:!0,source:S(pluginStorage(`claude-code`,e).configDir,`plugins`,`installed_plugins.json`),read:readClaudeInstalls,unread:[],research:[`E-CC-P2`]}),codex:e=>({supported:!0,source:S(pluginStorage(`codex`,e).configDir,`plugins`,`cache`),read:readCodexInstalls,unread:[],research:[`E-CODEX-P3`,`E-CODEX-P8`]}),"copilot-cli":e=>{let{configDir:t}=pluginStorage(`copilot-cli`,e);return{supported:!0,source:S(t,`config.json`),read:readCopilotInstalls,unread:[`plugins from marketplaces added by local path (extraKnownMarketplaces in ${S(t,`settings.json`)})`],research:[`E-COPILOT-P10`,`E-COPILOT-P11`,`E-COPILOT-P12`,`E-COPILOT-P13`]}},cursor:()=>B,opencode:()=>B,kilo:()=>B,"gemini-cli":()=>B,"qwen-code":()=>B,"vscode-copilot":()=>B,cline:()=>B,crush:()=>B,openhands:()=>B,augment:()=>B};function skillsDirectories(e){switch(e){case`claude-code`:return{project:[`.claude/skills`],user:[`.claude/skills`],research:[`E-CC-L1`]};case`cursor`:return{project:[`.cursor/skills`,`.claude/skills`,`.codex/skills`,`.grok/skills`,`.agents/skills`],user:[`.cursor/skills`,`.claude/skills`,`.codex/skills`,`.grok/skills`,`.agents/skills`],research:[`E-CUR-L1`,`E-SR-CUR-10`]};case`codex`:return{project:[`.agents/skills`],user:[`.agents/skills`],research:[`E-CODEX-L1`]};case`copilot-cli`:return{project:[`.github/skills`,`.agents/skills`,`.claude/skills`],user:[`.copilot/skills`,`.agents/skills`],research:[`E-COPILOT-S5`,`E-SR-COPILOT-9`],relocatedBy:{variable:`COPILOT_HOME`,skills:`skills`}};case`vscode-copilot`:return{project:[`.github/skills`,`.claude/skills`,`.agents/skills`],user:[`.copilot/skills`,`.claude/skills`,`.agents/skills`],research:[`E-VSC-P1`]};case`opencode`:return{project:[`.opencode/skills`,`.claude/skills`,`.agents/skills`],user:[`.config/opencode/skills`,`.claude/skills`,`.agents/skills`],research:[`E-OC-S1`]};case`gemini-cli`:return{project:[`.agents/skills`,`.gemini/skills`],user:[`.agents/skills`,`.gemini/skills`],research:[`E-GEM-L1`]};case`cline`:return{project:[`.cline/skills`,`.clinerules/skills`,`.claude/skills`,`.agents/skills`],user:[`.cline/skills`,`.agents/skills`],research:[`E-CLINE-S1`,`E-CLINE-S3`]};case`augment`:return{project:[`.augment/skills`,`.claude/skills`,`.agents/skills`],user:[`.augment/skills`,`.claude/skills`,`.agents/skills`],research:[`E-AUG-S4`]};case`kilo`:return{project:[`.kilo/skills`,`.agents/skills`,`.claude/skills`],user:[`.kilo/skills`,`.agents/skills`,`.claude/skills`],research:[`E-KILO-L2`]};case`qwen-code`:case`crush`:case`openhands`:return}}const _n=[`claude-code`,`cursor`,`codex`,`copilot-cli`,`opencode`,`gemini-cli`];function adminSkillFolders(e,t,n={}){let r=n.ProgramData||`C:\\ProgramData`;switch(e){case`claude-code`:return t===`darwin`?[`/Library/Application Support/ClaudeCode/.claude/skills`]:t===`win32`?[D.join(`C:\\Program Files\\ClaudeCode`,`.claude`,`skills`)]:[`/etc/claude-code/.claude/skills`];case`codex`:return t===`win32`?[]:[`/etc/codex/skills`];case`opencode`:{let e=t===`darwin`?`/Library/Application Support/opencode`:t===`win32`?D.join(r,`opencode`):`/etc/opencode`,n=t===`win32`?D:{join:S};return[n.join(e,`skill`),n.join(e,`skills`)]}default:return[]}}function harnessSkillFolders(e,{chain:t,home:n,platform:r,env:i={}}){if(!_n.includes(e))return;let a=skillsDirectories(e);if(!a)return;let o=t.flatMap(e=>a.project.map(t=>S(e,t))),s=a.relocatedBy&&i[a.relocatedBy.variable],c=s&&T(s)!==S(n,`.copilot`)?[S(s,a.relocatedBy.skills)]:a.user.map(e=>S(n,e));return[...o,...c,...adminSkillFolders(e,r,i)]}function manifestSkills(e){for(let t of ze){let n;try{n=JSON.parse(a(S(e,t),`utf8`))}catch{continue}if(!isRecord$1(n))return;let r=n.skills;return typeof r==`string`?[r]:Array.isArray(r)&&r.every(e=>typeof e==`string`)?r:void 0}}function pluginSkillFolders(e,t){if(e===`opencode`)return[];let n=e===`gemini-cli`?void 0:manifestSkills(t),r=S(t,`skills`);if(!n)return[r];let i=n.map(e=>S(t,e));return e===`claude-code`?[r,...i]:i}function detectedHarnesses(e){return detectHarness({env:e}).candidates}const vn={"macos-managed-preferences":`a macOS managed-preferences domain delivered by MDM`,"windows-registry":`a Windows registry key delivered by MDM or Group Policy`,server:`server-side settings`};function skippedLayer(e,t,n,r){let i={tier:e,dir:t,skipped:n};return e===`plugin`&&(i.origin=`enabled`),r!==void 0&&(i.plugin=r),i}function managedFolders(e,t,n){let r=t===`win32`?D:C,i=managedPolicyLocations(e,{platform:t,env:n}),a=[...new Set(i.flatMap(({kind:e,location:t})=>e===`file`?[r.dirname(t)]:e===`directory`?[t]:[]))];return{read:a.filter(e=>!a.some(t=>e.startsWith(t+r.sep))).map(e=>r.join(e,`references`)),unread:i.flatMap(({kind:t,location:n})=>{let r=vn[t];return r?[{location:n,reason:`${e} keeps this policy in ${r}, which cannot be read locally`}]:[]})}}function harnessManagedLayers(e,t,n){let[r]=e;if(r===void 0)return[skippedLayer(`managed`,`(no harness detected)`,`no harness detected, so no managed folder is read`)];if(e.length>1)return[skippedLayer(`managed`,`(several harnesses detected)`,`detection names several harnesses (${e.join(`, `)}), so no managed folder is read`)];let{read:i,unread:a}=managedFolders(r,t,n);return[...i.map(e=>({tier:`managed`,dir:e})),...a.map(({location:e,reason:t})=>skippedLayer(`managed`,e,t))]}function activeInstall(e,t){for(let n of t){let t=e.find(({projectPath:e})=>e===n);if(t)return t}return e.find(({projectPath:e})=>e===void 0)}async function enabledPluginLayers(e,t,n){let r=[];for(let i of e){let[e,a]=await Promise.all([enabledPlugins(i,n),installedPlugins(i,n)]);if(!e.supported){r.push(skippedLayer(`plugin`,`(${i} enabled plugins)`,`${i} keeps no readable record of enabled plugins`));continue}e.unread.length&&r.push(skippedLayer(`plugin`,`(${i} plugin policy)`,`${e.unread.join(`; `)} may also enable or disable ${i} plugins`));for(let{id:n,enabled:o}of e.plugins){if(!o)continue;let e=n.split(`@`)[0],s=activeInstall(a.plugins.filter(e=>e.id===n),t);if(s){let t=pluginManifestName(s.path)??e;r.push({tier:`plugin`,dir:S(s.path,`references`),plugin:t,origin:`enabled`,version:pluginVersion(s.path,s.version)});continue}r.push(skippedLayer(`plugin`,`(${n})`,`enabled in ${i}, but no install folder for this project is recorded`,e))}}return r}const yn={"reference-missing":{kind:`status`,when:`no tier holds the name, or the plugin a qualified name asks for is not installed (UC1.1)`},"reference-removed":{kind:`status`,when:"a `missing` name a `remove` turned off (UC1.1, R49)"},"reference-ambiguous":{kind:`status`,when:`contributions that cannot be put in one order, or a name two names list as an alias (UC1.2, R98)`},"reference-invalid":{kind:`status`,when:`not a name (UC1.3, R1)`},"frontmatter-invalid":{kind:`warning`,when:`malformed frontmatter (R105)`},"merge-unknown":{kind:`warning`,when:"an unknown `merge` value (R7)"},"marker-unknown":{kind:`warning`,when:`an unknown merge marker (R7)`},"marker-unmatched":{kind:`warning`,when:`an explicit marker that matches nothing below (R7)`},"heading-repeated":{kind:`warning`,when:`a document repeating a heading (R7)`},"remove-body-ignored":{kind:`warning`,when:"a `remove` with a body (R49)"},"extends-invalid":{kind:`warning`,when:"a malformed `extends` (R106)"},"extends-self":{kind:`warning`,when:`a plugin listing itself (R54)`},"extends-step-missing":{kind:`warning`,when:`a step that cannot be used (R55)`},"extends-all-missing":{kind:`warning`,when:`every step cannot be used (R55)`},"extends-not-used":{kind:`warning`,when:"a lower `extends` that builds a different stack (R53); picks written under a managed `extends` that builds it (R109)"},"section-not-held":{kind:`warning`,when:"a `sections` entry the plugin does not hold (R52)"},"default-not-selected":{kind:`warning`,when:"a plugin answering over the default with no `extends` naming either, and no own `extends` of the plugin naming `default` (R56)"},"plugin-not-selected":{kind:`warning`,when:"a plugin holding the name that the `repo` or `user` `extends` building the stack neither places nor declines (R113)"},"default-folder-missing":{kind:`warning`,when:"a `--default` folder that does not exist (R41)"},"default-in-tier":{kind:`warning`,when:"a `<name>.default.md` in a tier folder (R51)"},"file-ignored":{kind:`warning`,when:`a second file for a name in one folder, one under an older name beside the new name's included (R67, R97)`},"format-mismatch":{kind:`warning`,when:`a Markdown contribution above a non-Markdown one (R68)`},"metadata-ignored":{kind:`warning`,when:"a misplaced metadata file, or a body, `merge`, or `implements` in one (R94)"},"project-section-key-ignored":{kind:`warning`,when:"`merge`, `extends`, `implements`, or `aliases` in a project section, or dropped from one `create --in --template` writes (R27, R110)"},"interface-not-composed":{kind:`warning`,when:"`extends`, `merge`, or a higher copy on an interface document (R14)"},"interface-check":{kind:`warning`,when:`a loaded document failing its interface check (R37)`},"base-moved":{kind:`warning`,when:"`check` on a plugin or default file whose extended base has a newer version (R86)"},"reference-stale":{kind:`warning`,when:`a generated document or project section with a changed or missing source (R101)`},"reference-renamed":{kind:`warning`,when:`a name or file under an older name, or an interface's older id (R96, R97)`},"alias-not-used":{kind:`warning`,when:`an alias a name holds as its own (R98)`},"alias-invalid":{kind:`warning`,when:`an invalid or misplaced alias (R96)`},"project-section-not-markdown":{kind:`warning`,when:`a Markdown project section for a name whose main document is not Markdown, or a non-Markdown file in a project folder (R99)`},"reference-hidden":{kind:`warning`,when:"a file hidden by a `replace` or `remove` above it: one `create` or `customize` wrote (R26), or one `check` finds (R112)"},"repo-hides-user":{kind:`warning`,when:"a `user` file this repository's `repo` contribution hides (R26, R112)"},"root-missing":{kind:`refused`,when:"a `--root` that does not exist (R12)"},"file-unreadable":{kind:`refused`,when:"a `--request` or `--body` file that cannot be read (R81, R82)"},"folder-invalid":{kind:`refused`,when:"a `--plugin` or `--default` folder that does not qualify (R24)"},"file-exists":{kind:`refused`,when:"`create` on a file with a body, or where the target folder holds a file answering the name in another form (R60)"},"extends-replace":{kind:`refused`,when:"a `--plugin` or `--default` file extending a plugin with `replace` (R103)"},"interface-invalid":{kind:`refused`,when:"`--implements` with an unknown interface (R28, R111)"},"interface-unknown":{kind:`refused`,when:"`implementations` of an unknown interface (R35)"},"template-title":{kind:`refused`,when:`a title template (R32)`},"template-invalid":{kind:`refused`,when:`an unreadable template, or one whose frontmatter is not a mapping (R32)`},"extends-file-invalid":{kind:`refused`,when:"an `--extends-file` that is unreadable or not a YAML `extends` list (R79)"},"step-invalid":{kind:`refused`,when:"a step neither `default` nor a plugin holding the name (R79)"},"no-selection":{kind:`notice`,when:"`--extends none` with no `extends` there: a no-op (R80)"},"body-not-generated":{kind:`refused`,when:"`--request` on a body that records no request (R82)"},"pick-required":{kind:`refused`,when:"`--request` without `--extends` on an `ambiguous` name (R82)"},"name-outside-interface":{kind:`refused`,when:"`customize --implements` on a name outside the interface's namespace (R111)"},"implements-required":{kind:`refused`,when:"`--request` without `--implements` on a `missing` name under a found interface's namespace (R111)"},"in-not-markdown":{kind:`refused`,when:"`create --in` or `customize --in` for a name whose main document is not Markdown, which has no project sections (R82)"},"in-folder-missing":{kind:`refused`,when:"`--in` on `create`, `customize`, or `delete` naming a folder that does not exist (J8)"},"in-folder-ignored":{kind:`refused`,when:"`--in` on `create`, `customize`, or `delete` naming a folder git ignores (J8)"},"no-file":{kind:`notice`,when:"`delete` with no file there: a no-op (R30)"},"name-missing":{kind:`usage`,when:`a command that needs a name, given none (UC1.7)`},"name-invalid":{kind:`usage`,when:"a write given a string that is not a name, such as `../x` (J1, R1)"},"reference-qualified":{kind:`usage`,when:`a qualified name given to a write (R25)`},"query-missing":{kind:`usage`,when:"`search` with an empty query (UC3.2)"},"change-missing":{kind:`usage`,when:"`customize` with neither `--extends` nor `--request` (R82)"},"options-conflict":{kind:`usage`,when:"flags that exclude each other, such as two of `--scope`, `--in`, `--plugin`, `--default` on `create` and `delete`, `--scope` with `--in` on `customize`, or `--merge` or `--extends` with `--in` (R24, R27, R82)"},"options-missing":{kind:`usage`,when:"a flag given without the one it needs: `--request` without `--body`, or the reverse (R82)"},"option-invalid":{kind:`usage`,when:"a flag given a value it does not accept, such as an unknown `--merge` operation (R27)"},"in-not-below-root":{kind:`usage`,when:"`--in` naming the root or a folder outside it (R24)"},"remove-with-template":{kind:`usage`,when:"`--merge remove` with `--template` (R27)"},"template-with-implements":{kind:`usage`,when:"`--template` with `--implements` (R28)"}};var ReferenceFailure=class extends Error{name=`ReferenceError`;code;usage;details;help;constructor(e,t,{details:n={},help:r}={}){super(t),this.code=e,this.usage=yn[e].kind===`usage`,this.details=n,this.help=r===void 0?[]:typeof r==`string`?[r]:[...r]}};function repoReferencesDir(e){return S(e,`.agents`,`references`)}function userReferencesDir(e){return S(e,`.agents`,`references`)}function readJson$1$1(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$1$1,`readJson$1`);function isDirectory$3(e){try{return d(e).isDirectory()}catch{return!1}}__name(isDirectory$3,`isDirectory`);function findRoot(e){let t=T(e);for(let e=t;;){if(n(S(e,`.git`)))return e;let r=y(e);if(r===e)return t;e=r}}function referenceRoot(e,t=process.cwd()){if(e===void 0)return findRoot(t);let n=T(t,e);if(!isDirectory$3(n))throw new ReferenceFailure(`root-missing`,`the root ${n} does not exist or is not a folder.`,{details:{root:n}});return n}function workingChain(e,t){let n=T(t),r=[];for(let t=T(e);;){if(r.push(t),t===n)return r;let e=y(t);if(e===t)return[n];t=e}}function canonical(e){try{return c(e)}catch{return e}}function dependencyPackages(e){let t=S(e,`package.json`),n=readJson$1$1(t);return n===void 0?[]:declaredDependencies(n).flatMap(e=>{let n=packageDir(e,t);return n?[n]:[]})}function dependencyLayers(e,t){let n=[];for(let r of e){if(t.has(canonical(r)))continue;let e=S(r,`references`);if(!isDirectory$3(e))continue;let i=pluginManifestName(r);n.push(i?{tier:`plugin`,dir:e,plugin:i,origin:`dependency`,version:pluginVersion(r)}:{tier:`plugin`,dir:e,origin:`dependency`,skipped:`not a plugin`})}return n}function holdsDefault(e){try{return o(S(e,`references`)).some(e=>e.endsWith(`.default.md`))}catch{return!1}}function skillDefaults(e,t,n){if(!e.length)return{skills:[],unverified:`no harness detected, so no skill folder is read and no skill's default is listed`};let r=[],i=[];for(let a of e){let e=harnessSkillFolders(a,t);if(!e){i.push(a);continue}r.push(...e,...n.flatMap(e=>pluginSkillFolders(a,e)))}let a=n.filter(e=>skillName(e)!==void 0),o=r.length?skillsIn([...r,...a]).filter(({folder:e})=>holdsDefault(e)):[];return i.length?{skills:o,unverified:`the skill folders ${i.join(`, `)} ${i.length===1?`reads are`:`read are`} not verified, so ${i.length===1?`its`:`their`} skills' defaults are not listed`}:{skills:o}}function defaultLayer(e){let t=S(e,`references`);return isDirectory$3(e)?{tier:`default`,dir:t,skill:skillName(e)??v(e)}:{tier:`default`,dir:t,skill:v(e),skipped:`no skill folder`,warning:{code:`default-folder-missing`,message:`the skill folder ${e} does not exist; the name resolves without its default`}}}async function referenceLayers$1({root:e,cwd:t=process.cwd(),home:n,platform:r,plugin:i,defaultSkill:a,env:o=process.env}){let s=referenceRoot(e,t),c=detectedHarnesses(o),l=workingChain(t,s),u=i&&canonical(i.root),d=await enabledPluginLayers(c,l,{env:o,homedir:n,cwd:s,platform:r}),f=dependencyPackages(s),p=[...i?[i.root]:[],...d.flatMap(({dir:e,skipped:t})=>t?[]:[y(e)]),...f.filter(e=>pluginManifestName(e))],m=skillDefaults(c,{chain:l,home:n,platform:r,env:o},p),h=i?[{tier:`plugin`,dir:S(i.root,`references`),plugin:i.name,origin:`host`,version:pluginVersion(i.root)}]:[],g=[...harnessManagedLayers(c,r,o),{tier:`repo`,dir:repoReferencesDir(s)},{tier:`user`,dir:userReferencesDir(n)},...h,...d.filter(e=>e.skipped||isDirectory$3(e.dir)&&canonical(y(e.dir))!==u),...dependencyLayers(f,new Set(u?[u]:[])),...a===void 0?[]:[defaultLayer(T(t,a))]],_=new Set,v=g.filter(({dir:e})=>!_.has(e)&&_.add(e)),b=[...h,...d.filter(({skipped:e})=>!e),...f.flatMap(e=>{let t=pluginManifestName(e);return t?[{tier:`plugin`,dir:e,plugin:t,origin:`dependency`,version:pluginVersion(e)}]:[]})].flatMap(({plugin:e,version:t,origin:n})=>e===void 0?[]:[{plugin:e,version:t,origin:n}]);return{layers:v,root:s,projects:new Map,harnesses:c,skills:m,plugins:b}}__name(referenceLayers$1,`referenceLayers`);const V=[{extension:`.json`,format:`json`},{extension:`.yaml`,format:`yaml`},{extension:`.yml`,format:`yaml`},{extension:`.toml`,format:`toml`},{extension:`.txt`,format:`txt`}];function formatOfFile(e){return V.find(({extension:t})=>e.endsWith(t))?.format??`markdown`}const H=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/i,bn=`.default`;function requireName(e){if(!e.trim())throw new ReferenceFailure(`name-missing`,`name a reference.`,{help:"Run `reference list` for every name."})}function parseReferenceName(e){let invalid=t=>({raw:e,name:e,invalid:t});if(e.endsWith(`.md`))return invalid(`"${e}" names a file. Ask for the reference by name, without the .md extension.`);let t=V.find(t=>e.endsWith(t.extension));if(t)return invalid(`"${e}" names a file. Ask for the reference by name, without the ${t.extension} extension.`);let n=e.split(`/`);if(n.length>2||e.includes(`\\`))return invalid(`"${e}" is a path. A name is letters, digits, hyphens, and dots, optionally after "<plugin>/".`);let[r,i]=n,a=i??r,o=i===void 0?void 0:r;return a.endsWith(`.default`)?invalid(`"${e}" names a skill's default file. Ask for "${a.slice(0,-8)}"; the default joins when its skill loads it.`):a.endsWith(`.meta`)?invalid(`"${e}" names a metadata file, which never answers a name. Ask for "${a.slice(0,-5)}".`):!H.test(a)||o!==void 0&&!H.test(o)?invalid(`"${e}" is not a reference name. A name is letters, digits, hyphens, and dots, optionally after "<plugin>/", where <plugin> is a plugin's manifest name.`):o===void 0?{raw:e,name:a}:{raw:e,name:a,plugin:o}}const xn=[`replace`,`patch`,`combine`,`remove`];function isMergeOperation(e){return xn.includes(e)}const Sn=/^---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;function parseDocument(e,t){let n=Sn.exec(e);if(!n)return{metadata:{},body:e};let r=e.slice(n[0].length);try{let e=(0,Qt.parse)(n[1]);if(e==null)return{metadata:{},body:r};if(isRecord$1(e))return{metadata:e,body:r}}catch{}return t(`frontmatter-invalid`,`frontmatter is not a YAML mapping; it is ignored`),{metadata:{},body:r}}function readMergeOperation(e,t){let n=e.merge;if(n!==void 0)return isMergeOperation(n)?n:(t(`merge-unknown`,`unknown merge "${String(n)}"; read as patch`),`patch`)}function hasBody(e){return stripMergeMarkers(e).trim().length>0}const Cn=/^\s*<!--\s*merge:\s*([\w-]*)\s*-->\s*$/,wn=/^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/,Tn=/^ {0,3}(`{3,}|~{3,})/;function fenceTracker(){let e;return t=>{if(e)return RegExp(`^ {0,3}${e[0]==="`"?"`":`~`}{${e.length},}\\s*$`).test(t)&&(e=void 0),!0;let n=Tn.exec(t);return n?(e=n[1],!0):!1}}function stripMergeMarkers(e){let t=fenceTracker();return e.split(`
148
- `).filter(e=>t(e)||!Cn.test(e)).join(`
152
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=getFirstKeyStartProps(getPrevProps(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=getFirstKeyStartProps(getPrevProps(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};e.Parser=Parser})),$t=__commonJSMin((e=>{var t=Gt(),n=Ot(),r=kt(),i=tt(),a=P(),o=Zt(),s=Qt();function parseOptions(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function parseAllDocuments(e,n={}){let{lineCounter:i,prettyErrors:a}=parseOptions(n),o=new s.Parser(i?.addNewLine),c=new t.Composer(n),l=Array.from(c.compose(o.parse(e)));if(a&&i)for(let t of l)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return l.length>0?l:Object.assign([],{empty:!0},c.streamInfo())}function parseDocument(e,n={}){let{lineCounter:i,prettyErrors:a}=parseOptions(n),o=new s.Parser(i?.addNewLine),c=new t.Composer(n),l=null;for(let t of c.compose(o.parse(e),!0,e.length))if(!l)l=t;else if(l.options.logLevel!==`silent`){l.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(l.errors.forEach(r.prettifyError(e,i)),l.warnings.forEach(r.prettifyError(e,i))),l}function parse(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=parseDocument(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function stringify(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=parse,e.parseAllDocuments=parseAllDocuments,e.parseDocument=parseDocument,e.stringify=stringify})),en=__commonJSMin((e=>{var t=Gt(),n=Ot(),r=Et(),i=kt(),a=qe(),o=P(),s=L(),c=I(),l=R(),u=z();Yt();var d=Xt(),f=Zt(),p=Qt(),m=$t(),h=He();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();const tn=/^---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;function skillName(e){let t;try{t=a(C(e,`SKILL.md`),`utf8`)}catch{return}let n=tn.exec(t);if(n)try{let e=(0,en.parse)(n[1]);if(isRecord$1(e)&&typeof e.name==`string`&&e.name.trim())return e.name.trim()}catch{}return y(e)}function isDirectory$2(e){try{return f(e).isDirectory()}catch{return!1}}function skillsIn(e){let t=[],n=new Set,add=(e,r)=>{let i=e;try{i=c(e)}catch{}n.has(i)||(n.add(i),t.push({name:r,folder:i}))};for(let t of e){let e=skillName(t);if(e!==void 0){add(t,e);continue}let n;try{n=o(t)}catch{continue}for(let e of n.sort()){let n=C(t,e);if(!isDirectory$2(n))continue;let r=skillName(n);r!==void 0&&add(n,r)}}return t}const isOne=e=>e===`1`,isSet=e=>e!==``,nn={name:`CLAUDECODE`,matches:isOne,description:`Claude Code sets CLAUDECODE=1 in subprocesses it spawns; IDE extensions also set it in integrated terminals`,research:`E-CC-D1`},rn=[{harness:`claude-code`,all:[nn,{name:`CLAUDE_CODE_CHILD_SESSION`,matches:isOne,description:`Claude Code sets CLAUDE_CODE_CHILD_SESSION=1 for tool, hook, and status line subprocesses`,research:`E-CC-D3`}]},{harness:`claude-code`,all:[nn,{name:`CLAUDE_CODE_SESSION_ID`,matches:isSet,description:`Claude Code sets CLAUDE_CODE_SESSION_ID in tool, hook, and stdio MCP server subprocesses`,research:`E-CC-D6`}]},{harness:`cursor`,all:[{name:`CURSOR_AGENT`,matches:isOne,description:`Cursor sets CURSOR_AGENT=1 on terminal commands its agent runs`,research:`E-CUR-D1`}]},{harness:`cursor`,all:[{name:`CURSOR_VERSION`,matches:isSet,description:`Cursor sets CURSOR_VERSION for hook commands`,research:`E-CUR-D10`},{name:`CURSOR_PROJECT_DIR`,matches:isSet,description:`Cursor sets CURSOR_PROJECT_DIR for hook commands`,research:`E-CUR-D10`}]},{harness:`codex`,all:[{name:`CODEX_THREAD_ID`,matches:isSet,description:`Codex injects CODEX_THREAD_ID into shell tool commands, even under a restrictive shell env policy`,research:`E-CODEX-D2`}]},{harness:`copilot-cli`,all:[{name:`COPILOT_CLI`,matches:isOne,description:`Copilot CLI sets COPILOT_CLI=1 in its subprocesses`,research:`E-COPILOT-D1`}]},{harness:`copilot-cli`,all:[{name:`COPILOT_AGENT_SESSION_ID`,matches:isSet,description:`Copilot CLI passes COPILOT_AGENT_SESSION_ID to shell commands and MCP servers`,research:`E-COPILOT-D2`}]},{harness:`copilot-cli`,all:[{name:`COPILOT_PLUGIN_ROOT`,matches:isSet,description:`Copilot CLI passes COPILOT_PLUGIN_ROOT to plugin hooks`,research:`E-COPILOT-D6`}]},{harness:`opencode`,all:[{name:`OPENCODE`,matches:isOne,description:`OpenCode sets OPENCODE=1 for shell tool commands and MCP servers; Kilo Code, its fork, sets it too`,research:`E-OC-D1`},{name:`OPENCODE_PID`,matches:isSet,description:`OpenCode sets OPENCODE_PID for shell tool commands and MCP servers; Kilo Code sets KILO_PID instead`,research:`E-OC-D2`}]},{harness:`kilo`,all:[{name:`KILO`,matches:isOne,description:`Kilo Code sets KILO=1 for shell tool commands and MCP servers`,research:`E-KILO-D2`},{name:`KILO_PID`,matches:isSet,description:`Kilo Code sets KILO_PID for shell tool commands and MCP servers`,research:`E-KILO-D1`}]},{harness:`gemini-cli`,all:[{name:`GEMINI_CLI`,matches:isOne,description:`Gemini CLI sets GEMINI_CLI=1 for shell tool commands and MCP stdio servers`,research:`E-GEM-D1`}]},{harness:`qwen-code`,all:[{name:`QWEN_CODE`,matches:isOne,description:`Qwen Code sets QWEN_CODE=1 for shell tool commands, not for MCP servers or hooks`,research:`E-QWEN-D1`}]},{harness:`vscode-copilot`,all:[{name:`COPILOT_AGENT`,matches:isOne,description:`VS Code 1.121+ sets COPILOT_AGENT=1 on terminals its Copilot agent runs commands in`,research:`E-VSC-D1`}]},{harness:`cline`,all:[{name:`CLINE_ACTIVE`,matches:e=>e===`true`,description:`Cline's VS Code extension sets CLINE_ACTIVE=true on the terminals it creates; the Cline CLI does not`,research:`E-CLINE-D1`}]},{harness:`crush`,all:[{name:`CRUSH`,matches:isOne,description:`Crush sets CRUSH=1 for bash tool and hook commands, not for MCP servers`,research:`E-CRUSH-D1`}]},{harness:`openhands`,all:[{name:`AI_AGENT`,matches:e=>e===`openhands`,description:`OpenHands (SDK 1.40.1 and later) sets AI_AGENT=openhands for terminal tool and hook commands when AI_AGENT is unset; other vendors use the name with other values`,research:`E-OH-D1`}]},{harness:`openhands`,all:[{name:`OPENHANDS_EVENT_TYPE`,matches:isSet,description:`OpenHands sets OPENHANDS_EVENT_TYPE for hook commands`,research:`E-OH-D4`},{name:`OPENHANDS_PROJECT_DIR`,matches:isSet,description:`OpenHands sets OPENHANDS_PROJECT_DIR for hook commands`,research:`E-OH-D4`}]},{harness:`augment`,all:[{name:`AUGMENT_HOOK_EVENT`,matches:isSet,description:`The Auggie CLI sets AUGMENT_HOOK_EVENT for hook commands; its shell commands carry no marker`,research:`E-AUG-D3`},{name:`AUGMENT_PROJECT_DIR`,matches:isSet,description:`The Auggie CLI sets AUGMENT_PROJECT_DIR for hook commands`,research:`E-AUG-D3`}]}];function detectHarness(e={}){let t=e.env??process.env,n=[],r=[];for(let e of rn){let i=e.all.filter(e=>{let n=t[e.name];return n!==void 0&&e.matches(n)});for(let t of i)n.some(n=>n.harness===e.harness&&n.signal===t.name)||n.push({harness:e.harness,signal:t.name,description:t.description,research:t.research});i.length===e.all.length&&!r.includes(e.harness)&&r.push(e.harness)}return{harness:r.length===1?r[0]:`unknown`,evidence:n,candidates:r}}function managedPolicyLocations(e,t={}){let n=t.platform??process.platform,r=t.env??process.env;return an[e](n,r)}const joinFor=e=>e===`win32`?O.join:w.join,dirnameFor=e=>e===`win32`?O.dirname:w.dirname;function opencodeFamily(e,t,n,r){let i={darwin:`/Library/Application Support/${n}`,linux:`/etc/${n}`,win32:O.join(t.ProgramData??`C:\\ProgramData`,n)}[e];return[...when(e===`darwin`,{kind:`macos-managed-preferences`,location:`ai.opencode.managed`,description:`MDM configuration profile; outranks the managed config folder`,research:r.preferences}),...when(i!==void 0,{kind:`directory`,location:i??``,description:`Managed config files; outrank user and project config`,research:r.directory})]}function geminiFamily(e,t,n){let r=e===`darwin`||e===`win32`?n.dirs[e]:n.dirs.linux,i=t[n.settingsVariable]||joinFor(e)(r,`settings.json`),a=t[n.defaultsVariable]||joinFor(e)(dirnameFor(e)(i),`system-defaults.json`);return[{kind:`file`,location:i,description:`System settings; outrank user and workspace settings. ${n.settingsVariable} overrides the path`,research:n.research},{kind:`file`,location:a,description:`System defaults; user and workspace settings override them. ${n.defaultsVariable} overrides the path`,research:n.research}]}const when=(e,...t)=>e?t:[],an={"claude-code":e=>{let t={darwin:`/Library/Application Support/ClaudeCode`,linux:`/etc/claude-code`,win32:`C:\\Program Files\\ClaudeCode`}[e],n=joinFor(e);return[{kind:`server`,location:`claude.ai admin console or a self-hosted Claude apps gateway`,description:`Server-managed settings; the highest-ranked managed source`,research:`E-CC-M6`},...when(e===`darwin`,{kind:`macos-managed-preferences`,location:`com.anthropic.claudecode`,description:`MDM configuration profile with the same top-level keys as managed-settings.json`,research:`E-CC-M6`}),...when(e===`win32`,{kind:`windows-registry`,location:`HKLM\\SOFTWARE\\Policies\\ClaudeCode`,description:`MDM or Group Policy; the Settings value holds managed-settings JSON`,research:`E-CC-M6`}),...when(t!==void 0,{kind:`file`,location:n(t??``,`managed-settings.json`),description:`Managed settings, same shape as settings.json`,research:`E-CC-M1`},{kind:`directory`,location:n(t??``,`managed-settings.d`),description:`Drop-in managed settings files, merged with managed-settings.json`,research:`E-CC-M1`},{kind:`file`,location:n(t??``,`managed-mcp.json`),description:`Managed MCP servers`,research:`E-CC-M1`}),...when(e===`win32`,{kind:`windows-registry`,location:`HKCU\\SOFTWARE\\Policies\\ClaudeCode`,description:`User-writable; used only when no other managed source delivers a policy key`,research:`E-CC-M6`})]},cursor:e=>{let t={darwin:`/Library/Application Support/Cursor/hooks.json`,linux:`/etc/cursor/hooks.json`,win32:`C:\\ProgramData\\Cursor\\hooks.json`}[e];return[...when(t!==void 0,{kind:`file`,location:t??``,description:`Enterprise hooks deployed by MDM; hooks only, not other enterprise settings`,research:`E-CUR-M1`}),{kind:`server`,location:`Cursor dashboard`,description:`Team hooks and other enterprise settings, synced from the dashboard`,research:`E-CUR-M1`}]},codex:(e,t)=>{let n={kind:`server`,location:`ChatGPT workspace admin settings`,description:`Cloud-managed requirements; outrank every local source`,research:`E-CODEX-M8`};return e===`win32`?[n,{kind:`file`,location:O.join(t.ProgramData??`C:\\ProgramData`,`OpenAI`,`Codex`,`requirements.toml`),description:`Admin-enforced requirements users cannot override`,research:`E-CODEX-M4`}]:[n,...when(e===`darwin`,{kind:`macos-managed-preferences`,location:`com.openai.codex`,description:`MDM keys requirements_toml_base64 (enforced) and config_toml_base64 (managed defaults)`,research:`E-CODEX-M6`}),{kind:`file`,location:`/etc/codex/requirements.toml`,description:`Admin-enforced requirements users cannot override`,research:`E-CODEX-M3`},{kind:`file`,location:`/etc/codex/managed_config.toml`,description:`Managed defaults; a user can override them within a session`,research:`E-CODEX-M2`},{kind:`file`,location:`/etc/codex/config.toml`,description:`System-wide config`,research:`E-CODEX-M1`}]},"copilot-cli":(e,t)=>{let n={darwin:`/Library/Application Support/GitHubCopilot/managed-settings.json`,linux:`/etc/github-copilot/managed-settings.json`,win32:O.join(t.ProgramFiles??`C:\\Program Files`,`GitHubCopilot`,`managed-settings.json`)}[e];return[...when(e===`darwin`,{kind:`macos-managed-preferences`,location:`com.github.copilot`,description:`MDM-managed settings; the highest-ranked source`,research:`E-COPILOT-M2`}),...when(e===`win32`,{kind:`windows-registry`,location:`HKLM\\SOFTWARE\\Policies\\GitHubCopilot`,description:`MDM-managed settings as REG_SZ values; the highest-ranked source`,research:`E-COPILOT-M2`}),{kind:`server`,location:`copilot/managed-settings.json in the enterprise's .github-private repository`,description:`Server-managed settings, fetched for the signed-in account`,research:`E-COPILOT-M3`},...when(n!==void 0,{kind:`file`,location:n??``,description:`File-based managed settings; on macOS and Linux it must be a root-owned regular file`,research:`E-COPILOT-M1`})]},opencode:(e,t)=>[...opencodeFamily(e,t,`opencode`,{directory:`E-OC-M1`,preferences:`E-OC-M1`}),{kind:`server`,location:`Remote config at the organization domain /.well-known/opencode`,description:`Organization defaults; the lowest-ranked config source, so user config overrides them`,research:`E-OC-M2`}],kilo:(e,t)=>opencodeFamily(e,t,`kilo`,{directory:`E-KILO-M1`,preferences:`E-KILO-M2`}),"gemini-cli":(e,t)=>geminiFamily(e,t,{settingsVariable:`GEMINI_CLI_SYSTEM_SETTINGS_PATH`,defaultsVariable:`GEMINI_CLI_SYSTEM_DEFAULTS_PATH`,dirs:{darwin:`/Library/Application Support/GeminiCli`,linux:`/etc/gemini-cli`,win32:`C:\\ProgramData\\gemini-cli`},research:`E-GEM-M1`}),"qwen-code":(e,t)=>geminiFamily(e,t,{settingsVariable:`QWEN_CODE_SYSTEM_SETTINGS_PATH`,defaultsVariable:`QWEN_CODE_SYSTEM_DEFAULTS_PATH`,dirs:{darwin:`/Library/Application Support/QwenCode`,linux:`/etc/qwen-code`,win32:`C:\\ProgramData\\qwen-code`},research:`E-QWEN-M1`}),"vscode-copilot":e=>[...when(e===`win32`,{kind:`windows-registry`,location:`Software\\Policies\\Microsoft\\VSCode`,description:`VS Code policies set by Group Policy (ADMX templates ship with VS Code)`,research:`E-VSC-M1`}),...when(e===`linux`,{kind:`file`,location:`/etc/vscode/policy.json`,description:`VS Code policies as JSON, read by VS Code 1.106 and later`,research:`E-VSC-M3`})],cline:()=>[{kind:`server`,location:`Cline Enterprise admin console`,description:`Provider, model, and tool policy pushed to clients; no local policy file is documented`,research:`E-CLINE-M1`}],crush:e=>when(e!==`win32`,{kind:`file`,location:`/etc/crush/crush.json`,description:`System config; the lowest-ranked source, so user and project config override it`,research:`E-CRUSH-M1`}),openhands:()=>[{kind:`server`,location:`OpenHands Cloud or Enterprise deployment`,description:`Organization controls held server-side; no local policy file is known`,research:`E-OH-D8`}],augment:(e,t)=>[{kind:`file`,location:e===`win32`?O.join(t.ProgramData||`C:\\ProgramData`,`augment`,`settings.json`):`/etc/augment/settings.json`,description:`System settings, read from the Auggie CLI bundle; its rank against user settings is not documented`,research:`E-AUG-M1`}]};function resolveHarnessEnvironment(e={}){return{env:e.env??process.env,homedir:e.homedir??_(),cwd:e.cwd??process.cwd(),platform:e.platform??process.platform}}function pluginStorage(e,t={}){return on[e](resolveHarnessEnvironment(t))}const xdgConfig=({env:e,homedir:t})=>e.XDG_CONFIG_HOME||C(t,`.config`);function vscodeAgentPlugins({env:e,homedir:t,platform:n}){if(n===`win32`){let n=O.join(e.APPDATA||O.join(t,`AppData`,`Roaming`),`Code`);return{configDir:n,path:O.join(n,`agentPlugins`)}}let r=n===`darwin`?C(t,`Library`,`Application Support`,`Code`):C(t,`.config`,`Code`);return{configDir:r,path:C(r,`agentPlugins`)}}const on={"claude-code":({env:e,homedir:t})=>{let n=e.CLAUDE_CONFIG_DIR||C(t,`.claude`),r=C(n,`plugins`);return{harness:`claude-code`,configDir:n,locations:[{kind:`plugin-cache`,path:C(r,`cache`),description:`Installed plugins as <marketplace>/<plugin>/<version>/`,research:`E-CC-P1`},{kind:`marketplaces`,path:C(r,`marketplaces`),description:`Marketplace checkouts`,research:`E-CC-P1`},{kind:`install-record`,path:C(r,`installed_plugins.json`),description:`Installs keyed by plugin@marketplace, each with scope, installPath, and version`,research:`E-CC-P2`},{kind:`enabled-record`,path:C(n,`settings.json`),description:`User settings; enabledPlugins maps plugin@marketplace to a boolean`,research:`E-CC-P3`}]}},cursor:({homedir:e})=>{let t=C(e,`.cursor`);return{harness:`cursor`,configDir:t,locations:[{kind:`local-plugins`,path:C(t,`plugins`,`local`),description:`Plugins under development, one folder each`,research:`E-CUR-P2`},{kind:`marketplaces`,path:C(t,`plugins`,`marketplaces`),description:`Marketplace checkouts`,research:`E-CUR-P3`}]}},codex:({env:e,homedir:t})=>{let n=e.CODEX_HOME||C(t,`.codex`);return{harness:`codex`,configDir:n,locations:[{kind:`plugin-cache`,path:C(n,`plugins`,`cache`),description:`Installed plugins as <marketplace>/<plugin>/<version>/`,research:`E-CODEX-P3`},{kind:`enabled-record`,path:C(n,`config.toml`),description:`User config; [plugins."<plugin>@<marketplace>"] tables carry enabled = <bool>`,research:`E-CODEX-P2`}]}},"copilot-cli":({env:e,homedir:t})=>{let n=e.COPILOT_HOME||C(t,`.copilot`);return{harness:`copilot-cli`,configDir:n,locations:[{kind:`installed-plugins`,path:C(n,`installed-plugins`),description:`Installed plugins as <marketplace>/<plugin>/, or _direct/<source-id>/ for direct installs`,research:`E-COPILOT-P9`},{kind:`install-record`,path:C(n,`config.json`),description:`Application state, including installedPlugins`,research:`E-COPILOT-P9`},{kind:`enabled-record`,path:C(n,`settings.json`),description:`User settings (JSON with comments); enabledPlugins maps plugin specs to a boolean`,research:`E-COPILOT-P4`}]}},opencode:e=>{let t=C(xdgConfig(e),`opencode`);return{harness:`opencode`,configDir:t,locations:[{kind:`local-plugins`,path:C(t,`plugins`),description:`JS/TS plugin modules loaded at startup; npm plugins are named in the plugin config array`,research:`E-OC-P2`}]}},kilo:e=>{let t=C(xdgConfig(e),`kilo`);return{harness:`kilo`,configDir:t,locations:[{kind:`local-plugins`,path:C(t,`plugin`),description:`JS/TS plugin modules loaded at startup; npm plugins are named in the plugin config array`,research:`E-KILO-P2`}]}},"gemini-cli":({env:e,homedir:t})=>{let n=C(e.GEMINI_CLI_HOME||t,`.gemini`),r=C(n,`extensions`);return{harness:`gemini-cli`,configDir:n,locations:[{kind:`installed-plugins`,path:r,description:`Installed extensions, one folder each with a gemini-extension.json manifest`,research:`E-GEM-P1`},{kind:`enabled-record`,path:C(r,`extension-enablement.json`),description:`Per-extension path-glob overrides that enable or disable it by folder, not a boolean`,research:`E-GEM-P3`}]}},"qwen-code":({env:e,homedir:t})=>{let n=e.QWEN_HOME||C(t,`.qwen`),r=C(n,`extensions`);return{harness:`qwen-code`,configDir:n,locations:[{kind:`installed-plugins`,path:r,description:`Installed extensions, one folder each with a qwen-extension.json manifest`,research:`E-QWEN-P1`},{kind:`enabled-record`,path:C(r,`extension-enablement.json`),description:`Extension enable/disable state, inherited from Gemini CLI's format`,research:`E-QWEN-P2`}]}},"vscode-copilot":e=>{let{configDir:t,path:n}=vscodeAgentPlugins(e);return{harness:`vscode-copilot`,configDir:t,locations:[{kind:`installed-plugins`,path:n,description:`Installed agent plugins as <host>/<org>/<repo>/`,research:`E-VSC-P3`}]}},cline:({homedir:e})=>{let t=C(e,`.cline`);return{harness:`cline`,configDir:t,locations:[{kind:`installed-plugins`,path:C(t,`plugins`,`_installed`),description:`Installed plugins, grouped by source: npm, git, remote, or local`,research:`E-CLINE-P3`}]}},crush:({env:e,homedir:t})=>({harness:`crush`,configDir:e.CRUSH_GLOBAL_CONFIG||C(e.XDG_CONFIG_HOME||C(t,`.config`),`crush`),locations:[]}),openhands:({env:e,homedir:t})=>{let n=e.OH_PERSISTENCE_DIR||e.OPENHANDS_PERSISTENCE_DIR||C(t,`.openhands`),r=C(n,`plugins`,`installed`);return{harness:`openhands`,configDir:n,locations:[{kind:`installed-plugins`,path:r,description:`Installed plugins, one folder each`,research:`E-OH-P3`},{kind:`enabled-record`,path:C(r,`.installed.json`),description:`Install metadata keyed by plugin name, each with enabled: <bool>`,research:`E-OH-P4`}]}},augment:({homedir:e})=>{let t=C(e,`.augment`);return{harness:`augment`,configDir:t,locations:[{kind:`marketplaces`,path:C(t,`plugins`,`marketplaces`),description:`Marketplace checkouts`,research:`E-AUG-P2`},{kind:`enabled-record`,path:C(t,`settings.json`),description:`User settings; enabledPlugins maps plugin@marketplace to a boolean`,research:`E-AUG-P4`}]}}};async function enabledPlugins(e,t={}){let n=un[e](resolveHarnessEnvironment(t),t.managedSettingsPath),r=new Map,i=[];for(let e of n.sources){let t;try{let n=await readText(e.path);if(n===void 0){i.push({scope:e.scope,path:e.path,found:!1});continue}t=e.parse(n)}catch(t){i.push({scope:e.scope,path:e.path,found:!0,error:String(t)});continue}i.push({scope:e.scope,path:e.path,found:!0});for(let[n,i]of Object.entries(t))r.has(n)||r.set(n,{id:n,enabled:i,scope:e.scope,source:e.path})}return{harness:e,supported:n.supported,plugins:[...r.values()],sources:i,unread:n.unread,research:n.research}}function jsonEnabledPlugins(e){let t=JSON.parse(e),n=isRecord$1(t)?t.enabledPlugins:void 0;return isRecord$1(n)?Object.fromEntries(Object.entries(n).filter(e=>typeof e[1]==`boolean`)):{}}const sn=/^\[\s*plugins\s*\.\s*(?:"([^"]*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*\]\s*(?:#.*)?$/,cn=/^enabled\s*=\s*(true|false)\s*(?:#.*)?$/;function tomlEnabledPlugins(e){let t={},n;for(let r of e.split(/\r?\n/)){let e=r.trim();if(e.startsWith(`[`)){let t=sn.exec(e);n=t?t[1]??t[2]??t[3]:void 0;continue}let i=n===void 0?null:cn.exec(e);n!==void 0&&i&&(t[n]=i[1]===`true`)}return t}const ln={server:`server-managed settings`,"macos-managed-preferences":`MDM managed preferences`,"windows-registry":`Windows registry policy`,directory:`drop-in managed settings`,file:`managed file`};function unreadPolicy(e,t,n=[]){return e.filter(e=>e.location!==t&&!n.some(t=>e.location.endsWith(t))).map(e=>`${ln[e.kind]} (${e.location})`)}function managedFile(e,t){return e.find(e=>e.kind===`file`&&e.location.endsWith(t))?.location}function jsoncEnabledPlugins(e){return jsonEnabledPlugins(stripJsonComments$1(e))}const unsupported$1=(...e)=>({supported:!1,sources:[],unread:[],research:e}),un={"claude-code":(e,t)=>{let{configDir:n}=pluginStorage(`claude-code`,e),r=managedPolicyLocations(`claude-code`,e),i=managedFile(r,`managed-settings.json`),a=t??i,o=C(e.cwd,`.claude`);return{supported:!0,sources:[...a===void 0?[]:[{scope:`managed`,path:a,parse:jsonEnabledPlugins}],{scope:`local`,path:C(o,`settings.local.json`),parse:jsonEnabledPlugins},{scope:`project`,path:C(o,`settings.json`),parse:jsonEnabledPlugins},{scope:`user`,path:C(n,`settings.json`),parse:jsonEnabledPlugins}],unread:unreadPolicy(r,i,[`managed-mcp.json`]),research:[`E-CC-P3`,`E-CC-P7`,`E-CC-M1`,`E-CC-M6`]}},cursor:()=>unsupported$1(),opencode:()=>unsupported$1(`E-OC-P3`),kilo:()=>unsupported$1(`E-KILO-P3`),"gemini-cli":()=>unsupported$1(`E-GEM-P3`),"qwen-code":()=>unsupported$1(`E-QWEN-P2`),"vscode-copilot":()=>unsupported$1(`E-VSC-P4`),cline:()=>unsupported$1(`E-CLINE-P4`),crush:()=>unsupported$1(`E-CRUSH-P2`),openhands:()=>unsupported$1(`E-OH-P4`),augment:()=>unsupported$1(`E-AUG-P4`),codex:e=>{let t=pluginStorage(`codex`,e);return{supported:!0,sources:[{scope:`user`,path:C(t.configDir,`config.toml`),parse:tomlEnabledPlugins}],unread:unreadPolicy(managedPolicyLocations(`codex`,e),void 0),research:[`E-CODEX-P2`,`E-CODEX-M7`]}},"copilot-cli":(e,t)=>{let n=pluginStorage(`copilot-cli`,e),r=managedPolicyLocations(`copilot-cli`,e),i=managedFile(r,`managed-settings.json`),a=t??i,o=C(e.cwd,`.github`,`copilot`),s=C(e.cwd,`.claude`);return{supported:!0,sources:[...a===void 0?[]:[{scope:`managed`,path:a,parse:jsoncEnabledPlugins}],{scope:`local`,path:C(o,`settings.local.json`),parse:jsoncEnabledPlugins},{scope:`project`,path:C(o,`settings.json`),parse:jsoncEnabledPlugins},{scope:`user`,path:C(n.configDir,`settings.json`),parse:jsoncEnabledPlugins}],unread:[...unreadPolicy(r,i),`Claude Code project settings (${C(s,`settings.json`)})`,`Claude Code local settings (${C(s,`settings.local.json`)})`],research:[`E-COPILOT-P4`,`E-COPILOT-M1`,`E-COPILOT-M2`,`E-COPILOT-M4`]}}};async function installedPlugins(e,t={}){let n=vn[e](resolveHarnessEnvironment(t)),r={harness:e,supported:n.supported,unread:n.unread,research:n.research};if(n.source===void 0)return{...r,plugins:[],unresolved:[],sources:[]};let i=n.source;try{let e=await n.read(i);return e===void 0?{...r,plugins:[],unresolved:[],sources:[{path:i,found:!1}]}:{...r,plugins:e.plugins,unresolved:e.unresolved??[],sources:[{path:i,found:!0}]}}catch(e){return{...r,plugins:[],unresolved:[],sources:[{path:i,found:!0,error:String(e)}]}}}const dn=[`managed`,`local`,`project`,`user`],optionalString=e=>typeof e==`string`&&e!==``?e:void 0;async function readClaudeInstalls(e){let t=await readText(e);if(t===void 0)return;let n=JSON.parse(t),r=isRecord$1(n)?n.plugins:void 0;if(!isRecord$1(r))return{plugins:[]};let i=[];for(let[e,t]of Object.entries(r))if(Array.isArray(t))for(let n of t){let t=isRecord$1(n)?optionalString(n.installPath):void 0;if(!isRecord$1(n)||t===void 0)continue;let r=optionalString(n.version),a=typeof n.scope==`string`&&dn.includes(n.scope)?n.scope:void 0,o=optionalString(n.projectPath);i.push({id:e,path:t,...r===void 0?{}:{version:r},...a===void 0?{}:{scope:a},...o===void 0?{}:{projectPath:o},research:[`E-CC-P2`]})}return{plugins:i}}async function readCopilotInstalls(e){let t=await readText(e);if(t===void 0)return;let n=JSON.parse(stripJsonComments$1(t)),r=isRecord$1(n)?n.installedPlugins:void 0;if(!Array.isArray(r))return{plugins:[]};let i=[];for(let e of r){if(!isRecord$1(e))continue;let t=optionalString(e.name),n=optionalString(e.cache_path);if(t===void 0||n===void 0)continue;let r=optionalString(e.marketplace),a=optionalString(e.version);i.push({id:r===void 0?t:`${t}@${r}`,path:n,...a===void 0?{}:{version:a},research:r===void 0?[`E-COPILOT-P10`,`E-COPILOT-P11`]:[`E-COPILOT-P10`]})}return{plugins:i}}const fn=`local`,pn=/^[A-Za-z0-9_-]+$/,mn=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*$/,hn=/^[A-Za-z0-9._+-]+$/;async function readCodexInstalls(e){let t=await directories$1(e);if(t===void 0)return;let n=[],r=[];for(let i of t.filter(e=>pn.test(e)))for(let t of await directories$1(C(e,i))??[]){if(!mn.test(t))continue;let a=`${t}@${i}`,o=(await directories$1(C(e,i,t))??[]).filter(e=>hn.test(e)&&e!==`.`&&e!==`..`);if(o.length===0)continue;let s=activeCodexVersion(o);if(s===void 0){r.push(a);continue}n.push({id:a,path:C(e,i,t,s),version:s,research:[`E-CODEX-P3`,`E-CODEX-P8`]})}return{plugins:n,unresolved:r}}function activeCodexVersion(e){if(e.includes(fn))return fn;let t=e.filter(e=>parseSemver(e)!==void 0).length;if(!(e.length>2&&t!==0&&t!==e.length))return[...e].sort(compareCodexVersions).at(-1)}async function directories$1(e){try{return(await ee(e,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){if(e.code===`ENOENT`)return;throw e}}__name(directories$1,`directories`);const gn=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function parseSemver(e){let t=gn.exec(e);if(t)return{core:[t[1],t[2],t[3]],pre:t[4]===void 0?[]:t[4].split(`.`),build:t[5]===void 0?[]:t[5].split(`.`)}}function compareCodexVersions(e,t){let n=parseSemver(e),r=parseSemver(t);if(n===void 0||r===void 0)return compareStrings(e,t);for(let e=0;e<3;e++){let t=compareNumeric(n.core[e],r.core[e]);if(t!==0)return t}let i=n.pre.length===0||r.pre.length===0?r.pre.length-n.pre.length:compareIdentifiers(n.pre,r.pre);return i===0?compareIdentifiers(n.build,r.build):Math.sign(i)}const _n=/^\d+$/;function compareIdentifiers(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=_n.test(r),o=_n.test(i),s=a&&o?compareNumeric(r,i):a===o?compareStrings(r,i):a?-1:1;if(s!==0)return s}return e.length-t.length}function compareNumeric(e,t){let n=e.replace(/^0+(?=\d)/,``),r=t.replace(/^0+(?=\d)/,``);return n.length-r.length||compareStrings(n,r)||e.length-t.length}const compareStrings=(e,t)=>e<t?-1:+(e>t),B={supported:!1,read:async()=>void 0,unread:[],research:[]},vn={"claude-code":e=>({supported:!0,source:C(pluginStorage(`claude-code`,e).configDir,`plugins`,`installed_plugins.json`),read:readClaudeInstalls,unread:[],research:[`E-CC-P2`]}),codex:e=>({supported:!0,source:C(pluginStorage(`codex`,e).configDir,`plugins`,`cache`),read:readCodexInstalls,unread:[],research:[`E-CODEX-P3`,`E-CODEX-P8`]}),"copilot-cli":e=>{let{configDir:t}=pluginStorage(`copilot-cli`,e);return{supported:!0,source:C(t,`config.json`),read:readCopilotInstalls,unread:[`plugins from marketplaces added by local path (extraKnownMarketplaces in ${C(t,`settings.json`)})`],research:[`E-COPILOT-P10`,`E-COPILOT-P11`,`E-COPILOT-P12`,`E-COPILOT-P13`]}},cursor:()=>B,opencode:()=>B,kilo:()=>B,"gemini-cli":()=>B,"qwen-code":()=>B,"vscode-copilot":()=>B,cline:()=>B,crush:()=>B,openhands:()=>B,augment:()=>B};function skillsDirectories(e){switch(e){case`claude-code`:return{project:[`.claude/skills`],user:[`.claude/skills`],research:[`E-CC-L1`]};case`cursor`:return{project:[`.cursor/skills`,`.claude/skills`,`.codex/skills`,`.grok/skills`,`.agents/skills`],user:[`.cursor/skills`,`.claude/skills`,`.codex/skills`,`.grok/skills`,`.agents/skills`],research:[`E-CUR-L1`,`E-SR-CUR-10`]};case`codex`:return{project:[`.agents/skills`],user:[`.agents/skills`],research:[`E-CODEX-L1`]};case`copilot-cli`:return{project:[`.github/skills`,`.agents/skills`,`.claude/skills`],user:[`.copilot/skills`,`.agents/skills`],research:[`E-COPILOT-S5`,`E-SR-COPILOT-9`],relocatedBy:{variable:`COPILOT_HOME`,skills:`skills`}};case`vscode-copilot`:return{project:[`.github/skills`,`.claude/skills`,`.agents/skills`],user:[`.copilot/skills`,`.claude/skills`,`.agents/skills`],research:[`E-VSC-P1`]};case`opencode`:return{project:[`.opencode/skills`,`.claude/skills`,`.agents/skills`],user:[`.config/opencode/skills`,`.claude/skills`,`.agents/skills`],research:[`E-OC-S1`]};case`gemini-cli`:return{project:[`.agents/skills`,`.gemini/skills`],user:[`.agents/skills`,`.gemini/skills`],research:[`E-GEM-L1`]};case`cline`:return{project:[`.cline/skills`,`.clinerules/skills`,`.claude/skills`,`.agents/skills`],user:[`.cline/skills`,`.agents/skills`],research:[`E-CLINE-S1`,`E-CLINE-S3`]};case`augment`:return{project:[`.augment/skills`,`.claude/skills`,`.agents/skills`],user:[`.augment/skills`,`.claude/skills`,`.agents/skills`],research:[`E-AUG-S4`]};case`kilo`:return{project:[`.kilo/skills`,`.agents/skills`,`.claude/skills`],user:[`.kilo/skills`,`.agents/skills`,`.claude/skills`],research:[`E-KILO-L2`]};case`qwen-code`:case`crush`:case`openhands`:return}}const yn=[`claude-code`,`cursor`,`codex`,`copilot-cli`,`opencode`,`gemini-cli`];function adminSkillFolders(e,t,n={}){let r=n.ProgramData||`C:\\ProgramData`;switch(e){case`claude-code`:return t===`darwin`?[`/Library/Application Support/ClaudeCode/.claude/skills`]:t===`win32`?[O.join(`C:\\Program Files\\ClaudeCode`,`.claude`,`skills`)]:[`/etc/claude-code/.claude/skills`];case`codex`:return t===`win32`?[]:[`/etc/codex/skills`];case`opencode`:{let e=t===`darwin`?`/Library/Application Support/opencode`:t===`win32`?O.join(r,`opencode`):`/etc/opencode`,n=t===`win32`?O:{join:C};return[n.join(e,`skill`),n.join(e,`skills`)]}default:return[]}}function harnessSkillFolders(e,{chain:t,home:n,platform:r,env:i={}}){if(!yn.includes(e))return;let a=skillsDirectories(e);if(!a)return;let o=t.flatMap(e=>a.project.map(t=>C(e,t))),s=a.relocatedBy&&i[a.relocatedBy.variable],c=s&&E(s)!==C(n,`.copilot`)?[C(s,a.relocatedBy.skills)]:a.user.map(e=>C(n,e));return[...o,...c,...adminSkillFolders(e,r,i)]}function manifestSkills(e){for(let t of Ve){let n;try{n=JSON.parse(a(C(e,t),`utf8`))}catch{continue}if(!isRecord$1(n))return;let r=n.skills;return typeof r==`string`?[r]:Array.isArray(r)&&r.every(e=>typeof e==`string`)?r:void 0}}function pluginSkillFolders(e,t){if(e===`opencode`)return[];let n=e===`gemini-cli`?void 0:manifestSkills(t),r=C(t,`skills`);if(!n)return[r];let i=n.map(e=>C(t,e));return e===`claude-code`?[r,...i]:i}function detectedHarnesses(e){return detectHarness({env:e}).candidates}const bn={"macos-managed-preferences":`a macOS managed-preferences domain delivered by MDM`,"windows-registry":`a Windows registry key delivered by MDM or Group Policy`,server:`server-side settings`};function skippedLayer(e,t,n,r){let i={tier:e,dir:t,skipped:n};return e===`plugin`&&(i.origin=`enabled`),r!==void 0&&(i.plugin=r),i}function managedFolders(e,t,n){let r=t===`win32`?O:w,i=managedPolicyLocations(e,{platform:t,env:n}),a=[...new Set(i.flatMap(({kind:e,location:t})=>e===`file`?[r.dirname(t)]:e===`directory`?[t]:[]))];return{read:a.filter(e=>!a.some(t=>e.startsWith(t+r.sep))).map(e=>r.join(e,`references`)),unread:i.flatMap(({kind:t,location:n})=>{let r=bn[t];return r?[{location:n,reason:`${e} keeps this policy in ${r}, which cannot be read locally`}]:[]})}}function harnessManagedLayers(e,t,n){let[r]=e;if(r===void 0)return[skippedLayer(`managed`,`(no harness detected)`,`no harness detected, so no managed folder is read`)];if(e.length>1)return[skippedLayer(`managed`,`(several harnesses detected)`,`detection names several harnesses (${e.join(`, `)}), so no managed folder is read`)];let{read:i,unread:a}=managedFolders(r,t,n);return[...i.map(e=>({tier:`managed`,dir:e})),...a.map(({location:e,reason:t})=>skippedLayer(`managed`,e,t))]}function activeInstall(e,t){for(let n of t){let t=e.find(({projectPath:e})=>e===n);if(t)return t}return e.find(({projectPath:e})=>e===void 0)}async function enabledPluginLayers(e,t,n){let r=[];for(let i of e){let[e,a]=await Promise.all([enabledPlugins(i,n),installedPlugins(i,n)]);if(!e.supported){r.push(skippedLayer(`plugin`,`(${i} enabled plugins)`,`${i} keeps no readable record of enabled plugins`));continue}e.unread.length&&r.push(skippedLayer(`plugin`,`(${i} plugin policy)`,`${e.unread.join(`; `)} may also enable or disable ${i} plugins`));for(let{id:n,enabled:o}of e.plugins){if(!o)continue;let e=n.split(`@`)[0],s=activeInstall(a.plugins.filter(e=>e.id===n),t);if(s){let t=pluginManifestName(s.path)??e;r.push({tier:`plugin`,dir:C(s.path,`references`),plugin:t,origin:`enabled`,version:pluginVersion(s.path,s.version)});continue}r.push(skippedLayer(`plugin`,`(${n})`,`enabled in ${i}, but no install folder for this project is recorded`,e))}}return r}const xn={"reference-missing":{kind:`status`,when:`no tier holds the name, or the plugin a qualified name asks for is not installed (UC1.1)`},"reference-removed":{kind:`status`,when:"a `missing` name a `remove` turned off (UC1.1, R49)"},"reference-ambiguous":{kind:`status`,when:`contributions that cannot be put in one order, or a name two names list as an alias (UC1.2, R98)`},"reference-invalid":{kind:`status`,when:`not a name (UC1.3, R1)`},"frontmatter-invalid":{kind:`warning`,when:`malformed frontmatter (R105)`},"merge-unknown":{kind:`warning`,when:"an unknown `merge` value (R7)"},"marker-unknown":{kind:`warning`,when:`an unknown merge marker (R7)`},"marker-unmatched":{kind:`warning`,when:`an explicit marker that matches nothing below (R7)`},"heading-repeated":{kind:`warning`,when:`a document repeating a heading (R7)`},"remove-body-ignored":{kind:`warning`,when:"a `remove` with a body (R49)"},"extends-invalid":{kind:`warning`,when:"a malformed `extends` (R106)"},"extends-self":{kind:`warning`,when:`a plugin listing itself (R54)`},"extends-step-missing":{kind:`warning`,when:`a step that cannot be used (R55)`},"extends-all-missing":{kind:`warning`,when:`every step cannot be used (R55)`},"extends-not-used":{kind:`warning`,when:"a lower `extends` that builds a different stack (R53); picks written under a managed `extends` that builds it (R109)"},"section-not-held":{kind:`warning`,when:"a `sections` entry the plugin does not hold (R52)"},"default-not-selected":{kind:`warning`,when:"a plugin answering over the default with no `extends` naming either, and no own `extends` of the plugin naming `default` (R56)"},"plugin-not-selected":{kind:`warning`,when:"a plugin holding the name that the `repo` or `user` `extends` building the stack neither places nor declines (R113)"},"default-folder-missing":{kind:`warning`,when:"a `--default` folder that does not exist (R41)"},"default-in-tier":{kind:`warning`,when:"a `<name>.default.md` in a tier folder (R51)"},"file-ignored":{kind:`warning`,when:`a second file for a name in one folder, one under an older name beside the new name's included (R67, R97)`},"format-mismatch":{kind:`warning`,when:`a Markdown contribution above a non-Markdown one (R68)`},"metadata-ignored":{kind:`warning`,when:"a misplaced metadata file, or a body, `merge`, or `implements` in one (R94)"},"project-section-key-ignored":{kind:`warning`,when:"`merge`, `extends`, `implements`, or `aliases` in a project section, or dropped from one `create --in --template` writes (R27, R110)"},"interface-not-composed":{kind:`warning`,when:"`extends`, `merge`, or a higher copy on an interface document (R14)"},"interface-check":{kind:`warning`,when:`a loaded document failing its interface check (R37)`},"base-moved":{kind:`warning`,when:"`check` on a plugin or default file whose extended base has a newer version (R86)"},"reference-stale":{kind:`warning`,when:`a generated document or project section with a changed or missing source (R101)`},"reference-renamed":{kind:`warning`,when:`a name or file under an older name, an interface's older id, or a name a plugin's rename table renames (R96, R97, R120)`},"rename-invalid":{kind:`warning`,when:`a plugin's rename table, or an entry of it, that is not a pair of bare reference names (R120)`},"reference-legacy-format":{kind:`warning`,when:"a contribution in a form version 1 wrote and 2.0 retired, which `reference migrate` rewrites (R119)"},"alias-not-used":{kind:`warning`,when:`an alias a name holds as its own (R98)`},"alias-invalid":{kind:`warning`,when:`an invalid or misplaced alias (R96)`},"project-section-not-markdown":{kind:`warning`,when:`a Markdown project section for a name whose main document is not Markdown, or a non-Markdown file in a project folder (R99)`},"reference-hidden":{kind:`warning`,when:"a file hidden by a `replace` or `remove` above it: one `create` or `customize` wrote (R26), or one `check` finds (R112)"},"repo-hides-user":{kind:`warning`,when:"a `user` file this repository's `repo` contribution hides (R26, R112)"},"root-missing":{kind:`refused`,when:"a `--root` that does not exist (R12)"},"file-unreadable":{kind:`refused`,when:"a `--request` or `--body` file that cannot be read (R81, R82)"},"folder-invalid":{kind:`refused`,when:"a `--plugin` or `--default` folder that does not qualify (R24)"},"file-exists":{kind:`refused`,when:"`create` on a file with a body, or where the target folder holds a file answering the name in another form (R60)"},"extends-replace":{kind:`refused`,when:"a `--plugin` or `--default` file extending a plugin with `replace` (R103)"},"interface-invalid":{kind:`refused`,when:"`--implements` with an unknown interface (R28, R111)"},"interface-unknown":{kind:`refused`,when:"`implementations` of an unknown interface (R35), or of a family matching none; `customize` of a family matching none (R135)"},"template-title":{kind:`refused`,when:`a title template (R32)`},"template-invalid":{kind:`refused`,when:`an unreadable template, or one whose frontmatter is not a mapping (R32)`},"extends-file-invalid":{kind:`refused`,when:"an `--extends-file` that is unreadable or not a YAML `extends` list (R79)"},"step-invalid":{kind:`refused`,when:"a step neither `default` nor a plugin holding the name (R79)"},"no-selection":{kind:`notice`,when:"`--extends none` with no `extends` there: a no-op (R80)"},"body-not-generated":{kind:`refused`,when:"`--request` on a body that records no request (R82)"},"pick-required":{kind:`refused`,when:"`--request` without `--extends` on an `ambiguous` name (R82)"},"name-outside-interface":{kind:`refused`,when:"`customize --implements` on a name outside the interface's namespace (R111)"},"implements-required":{kind:`refused`,when:"`--request` without `--implements` on a `missing` name under a found interface's namespace (R111)"},"in-not-markdown":{kind:`refused`,when:"`create --in` or `customize --in` for a name whose main document is not Markdown, which has no project sections (R82)"},"in-folder-missing":{kind:`refused`,when:"`--in` on `create`, `customize`, or `delete` naming a folder that does not exist (J8)"},"in-folder-ignored":{kind:`refused`,when:"`--in` on `create`, `customize`, or `delete` naming a folder git ignores (J8)"},"no-file":{kind:`notice`,when:"`delete` with no file there: a no-op (R30)"},"name-missing":{kind:`usage`,when:`a command that needs a name, given none (UC1.7)`},"name-invalid":{kind:`usage`,when:"a write given a string that is not a name, such as `../x` (J1, R1); `*` anywhere but the last segment of a family (R136)"},"reference-qualified":{kind:`usage`,when:`a qualified name given to a write (R25)`},"query-missing":{kind:`usage`,when:"`search` with an empty query (UC3.2)"},"change-missing":{kind:`usage`,when:"`customize` with neither `--extends` nor `--request` (R82)"},"options-conflict":{kind:`usage`,when:"flags that exclude each other, such as two of `--scope`, `--in`, `--plugin`, `--default` on `create` and `delete`, `--scope` with `--in` on `customize`, or `--merge` or `--extends` with `--in` (R24, R27, R82)"},"options-missing":{kind:`usage`,when:"a flag given without the one it needs: `--request` without `--body`, or the reverse (R82)"},"option-invalid":{kind:`usage`,when:"a flag given a value it does not accept, such as an unknown `--merge` operation (R27)"},"in-not-below-root":{kind:`usage`,when:"`--in` naming the root or a folder outside it (R24)"},"remove-with-template":{kind:`usage`,when:"`--merge remove` with `--template` (R27)"},"template-with-implements":{kind:`usage`,when:"`--template` with `--implements` (R28)"}};var ReferenceFailure=class extends Error{name=`ReferenceError`;code;usage;details;help;constructor(e,t,{details:n={},help:r}={}){super(t),this.code=e,this.usage=xn[e].kind===`usage`,this.details=n,this.help=r===void 0?[]:typeof r==`string`?[r]:[...r]}};function repoReferencesDir(e){return C(e,`.agents`,`references`)}function userReferencesDir(e){return C(e,`.agents`,`references`)}function readJson$1$1(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$1$1,`readJson$1`);function isDirectory$3(e){try{return f(e).isDirectory()}catch{return!1}}__name(isDirectory$3,`isDirectory`);function findRoot(e){let t=E(e);for(let e=t;;){if(n(C(e,`.git`)))return e;let r=b(e);if(r===e)return t;e=r}}function referenceRoot(e,t=process.cwd()){if(e===void 0)return findRoot(t);let n=E(t,e);if(!isDirectory$3(n))throw new ReferenceFailure(`root-missing`,`the root ${n} does not exist or is not a folder.`,{details:{root:n}});return n}function workingChain(e,t){let n=E(t),r=[];for(let t=E(e);;){if(r.push(t),t===n)return r;let e=b(t);if(e===t)return[n];t=e}}function canonical(e){try{return c(e)}catch{return e}}function dependencyPackages(e){let t=C(e,`package.json`),n=readJson$1$1(t);return n===void 0?[]:declaredDependencies(n).flatMap(e=>{let n=packageDir(e,t);return n?[n]:[]})}function dependencyLayers(e,t){let n=[];for(let r of e){if(t.has(canonical(r)))continue;let e=C(r,`references`);if(!isDirectory$3(e))continue;let i=pluginManifestName(r);n.push(i?{tier:`plugin`,dir:e,plugin:i,origin:`dependency`,version:pluginVersion(r)}:{tier:`plugin`,dir:e,origin:`dependency`,skipped:`not a plugin`})}return n}function holdsDefault(e){try{return o(C(e,`references`)).some(e=>e.endsWith(`.default.md`))}catch{return!1}}function skillDefaults(e,t,n){if(!e.length)return{skills:[],unverified:`no harness detected, so no skill folder is read and no skill's default is listed`};let r=[],i=[];for(let a of e){let e=harnessSkillFolders(a,t);if(!e){i.push(a);continue}r.push(...e,...n.flatMap(e=>pluginSkillFolders(a,e)))}let a=n.filter(e=>skillName(e)!==void 0),o=r.length?skillsIn([...r,...a]).filter(({folder:e})=>holdsDefault(e)):[];return i.length?{skills:o,unverified:`the skill folders ${i.join(`, `)} ${i.length===1?`reads are`:`read are`} not verified, so ${i.length===1?`its`:`their`} skills' defaults are not listed`}:{skills:o}}function defaultLayer(e){let t=C(e,`references`);return isDirectory$3(e)?{tier:`default`,dir:t,skill:skillName(e)??y(e)}:{tier:`default`,dir:t,skill:y(e),skipped:`no skill folder`,warning:{code:`default-folder-missing`,message:`the skill folder ${e} does not exist; the name resolves without its default`}}}async function referenceLayers$1({root:e,cwd:t=process.cwd(),home:n,platform:r,plugin:i,defaultSkill:a,env:o=process.env}){let s=referenceRoot(e,t),c=detectedHarnesses(o),l=workingChain(t,s),u=i&&canonical(i.root),d=await enabledPluginLayers(c,l,{env:o,homedir:n,cwd:s,platform:r}),f=dependencyPackages(s),p=[...i?[i.root]:[],...d.flatMap(({dir:e,skipped:t})=>t?[]:[b(e)]),...f.filter(e=>pluginManifestName(e))],m=skillDefaults(c,{chain:l,home:n,platform:r,env:o},p),h=i?[{tier:`plugin`,dir:C(i.root,`references`),plugin:i.name,origin:`host`,version:pluginVersion(i.root)}]:[],g=[...harnessManagedLayers(c,r,o),{tier:`repo`,dir:repoReferencesDir(s)},{tier:`user`,dir:userReferencesDir(n)},...h,...d.filter(e=>e.skipped||isDirectory$3(e.dir)&&canonical(b(e.dir))!==u),...dependencyLayers(f,new Set(u?[u]:[])),...a===void 0?[]:[defaultLayer(E(t,a))]],_=new Set,v=g.filter(({dir:e})=>!_.has(e)&&_.add(e)),y=[...h,...d.filter(({skipped:e})=>!e),...f.flatMap(e=>{let t=pluginManifestName(e);return t?[{tier:`plugin`,dir:e,plugin:t,origin:`dependency`,version:pluginVersion(e)}]:[]})].flatMap(({plugin:e,version:t,origin:n})=>e===void 0?[]:[{plugin:e,version:t,origin:n}]);return{layers:v,root:s,projects:new Map,harnesses:c,skills:m,plugins:y}}__name(referenceLayers$1,`referenceLayers`);const V=[{extension:`.json`,format:`json`},{extension:`.yaml`,format:`yaml`},{extension:`.yml`,format:`yaml`},{extension:`.toml`,format:`toml`},{extension:`.txt`,format:`txt`}];function formatOfFile(e){return V.find(({extension:t})=>e.endsWith(t))?.format??`markdown`}const H=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/i,U=`.default`,Sn=`.meta`;function isFamilyName(e){return e.endsWith(`.*`)}function parseFamily(e){let t=e.slice(0,-2);return!isFamilyName(e)||!t||t.includes(`*`)||!H.test(t)?{invalid:`"${e}" is not a family. A family is \`<prefix>.*\`, with \`*\` only as the last segment and a prefix of letters, digits, hyphens, and dots.`}:{prefix:t}}function requireName(e){if(!e.trim())throw new ReferenceFailure(`name-missing`,`name a reference.`,{help:"Run `reference list` for every name."})}function parseReferenceName(e){let invalid=t=>({raw:e,name:e,invalid:t});if(e.endsWith(`.md`))return invalid(`"${e}" names a file. Ask for the reference by name, without the .md extension.`);let t=V.find(t=>e.endsWith(t.extension));if(t)return invalid(`"${e}" names a file. Ask for the reference by name, without the ${t.extension} extension.`);if(e.includes(`*`))return invalid(`"${e}" is not a reference name: \`*\` makes a family, \`<prefix>.*\`, which only customize and implementations take.`);let n=e.split(`/`);if(n.length>2||e.includes(`\\`))return invalid(`"${e}" is a path. A name is letters, digits, hyphens, and dots, optionally after "<plugin>/".`);let[r,i]=n,a=i??r,o=i===void 0?void 0:r;return a.endsWith(`.default`)?invalid(`"${e}" names a skill's default file. Ask for "${a.slice(0,-8)}"; the default joins when its skill loads it.`):a.endsWith(`.meta`)?invalid(`"${e}" names a metadata file, which never answers a name. Ask for "${a.slice(0,-5)}".`):!H.test(a)||o!==void 0&&!H.test(o)?invalid(`"${e}" is not a reference name. A name is letters, digits, hyphens, and dots, optionally after "<plugin>/", where <plugin> is a plugin's manifest name.`):o===void 0?{raw:e,name:a}:{raw:e,name:a,plugin:o}}const Cn=[`replace`,`patch`,`combine`,`remove`];function isMergeOperation(e){return Cn.includes(e)}const wn=/^---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;function parseDocument(e,t){let n=wn.exec(e);if(!n)return{metadata:{},body:e};let r=e.slice(n[0].length);try{let e=(0,en.parse)(n[1]);if(e==null)return{metadata:{},body:r};if(isRecord$1(e))return{metadata:e,body:r}}catch{}return t(`frontmatter-invalid`,`frontmatter is not a YAML mapping; it is ignored`),{metadata:{},body:r}}function readMergeOperation(e,t){let n=e.merge;if(n!==void 0)return isMergeOperation(n)?n:(n===`merge-sections`||n===`first-wins`||t(`merge-unknown`,`unknown merge "${String(n)}"; read as patch`),`patch`)}function hasBody(e){return stripMergeMarkers(e).trim().length>0}const Tn=/^\s*<!--\s*merge:\s*([\w-]*)\s*-->\s*$/,En=/^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/,Dn=/^ {0,3}(`{3,}|~{3,})/;function fenceTracker(){let e;return t=>{if(e)return RegExp(`^ {0,3}${e[0]==="`"?"`":`~`}{${e.length},}\\s*$`).test(t)&&(e=void 0),!0;let n=Dn.exec(t);return n?(e=n[1],!0):!1}}function stripMergeMarkers(e){let t=fenceTracker();return e.split(`
153
+ `).filter(e=>t(e)||!Tn.test(e)).join(`
149
154
  `)}function sectionKey$1(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function topLevel(e){let t=fenceTracker(),n;for(let r of e.split(`
150
- `)){if(t(r))continue;let e=wn.exec(r);e&&(n=Math.min(n??6,e[1].length))}return n}function parseSections(e,t){let n=topLevel(e),r={top:n,preamble:[],children:[]},i=[],a=fenceTracker(),o;for(let s of e.split(`
151
- `)){let e=a(s),c=e?null:wn.exec(s);if(c){let e=c[1].length,t={depth:e-(n??e),level:e,title:(c[2]??``).trim(),heading:s.trimEnd(),marker:void 0,text:[],children:[]};for(;(i.at(-1)?.level??0)>=e;)i.pop();(i.at(-1)?.children??r.children).push(t),i.push(t),o=t;continue}if(o&&!e){if(!s.trim())continue;let e=Cn.exec(s);if(e){let n=e[1];isMergeOperation(n)?o.marker=n:(t(`marker-unknown`,`unknown merge "${n}" on "${o.title}"; read as patch`),o.marker=`patch`),o=void 0;continue}}o=void 0,(i.at(-1)?.text??r.preamble).push(s)}return r}function trimBlank(e){let t=0,n=e.length;for(;t<n&&!e[t].trim();)t++;for(;n>t&&!e[n-1].trim();)n--;return e.slice(t,n)}function emptyComposed(){return{top:void 0,preamble:[],preambleSources:[],children:[],removed:[],joined:!1,preambleJoined:!1}}function pathOf(e,t){return e?`${e} > ${t}`:t}function warnRepeats(e,t,{warn:n}){let r=new Set;for(let i of e){let e=sectionKey$1(i.title);r.has(e)&&n(`heading-repeated`,`heading path "${pathOf(t,i.title)}" appears more than once; the first is matched`),r.add(e),warnRepeats(i.children,pathOf(t,i.title),{warn:n})}}function warnUnmatched(e,t,{warn:n}){n(`marker-unmatched`,`"<!-- merge: ${e.marker} -->" on "${pathOf(t,e.title)}" matches no section below`)}function place(e,t,n,r){let i=pathOf(n,e.title),a=e.children.flatMap(e=>(e.marker&&warnUnmatched(e,i,r),e.marker===`remove`?[]:[place(e,e.marker??t,i,r)])),o=trimBlank(e.text);return{depth:e.depth,title:e.title,heading:e.heading,level:e.level,text:o,sources:o.length?[{contribution:r.label,operation:t}]:[],children:a}}function join$1(e,t){return e.length&&t.length?[...e,``,...t]:[...e,...t]}function applyChildren(e,t,n,r,i){let a=[...e],o=[],s=new Set;for(let c of t){let t=c.marker??n,l=sectionKey$1(c.title),u=s.has(l)?-1:e.findIndex(e=>sectionKey$1(e.title)===l);if(s.add(l),u===-1){if(i.matchedOnly)continue;c.marker&&warnUnmatched(c,r,i),t!==`remove`&&o.push(place(c,t,r,i));continue}let d=e[u],f=pathOf(r,d.title);if(t===`remove`){a[u]=void 0,i.composed.removed.push({path:f,by:i.label});continue}if(t===`replace`){a[u]={...place(c,`replace`,r,i),depth:d.depth};continue}let p=trimBlank(c.text),m=p.length?[{contribution:i.label,operation:t}]:[];if(t===`combine`){let e=!!(p.length&&d.text.length);e&&(i.composed.joined=!0),a[u]={...d,...e?{joined:!0}:{},text:join$1(d.text,p),sources:[...d.sources,...m],children:applyChildren(d.children,c.children,`combine`,f,i)};continue}let{joined:h,...g}=d;a[u]={...p.length?g:d,text:p.length?p:d.text,sources:p.length?m:d.sources,children:applyChildren(d.children,c.children,`replace`,f,i)}}return[...a.filter(e=>e!==void 0),...o]}function applyContribution(e,t,n,r,i,{matchedOnly:a=!1}={}){let o=parseSections(t,i),s=n===`replace`?emptyComposed():e,c={...s,removed:[...s.removed]},l={label:r,warn:i,composed:c,matchedOnly:a};warnRepeats(o.children,``,l);let u=a&&!s.preamble.length?[]:trimBlank(o.preamble);return n===`combine`?(u.length&&s.preamble.length&&(c.joined=!0,c.preambleJoined=!0),c.preamble=join$1(s.preamble,u),u.length&&(c.preambleSources=[...s.preambleSources,{contribution:r,operation:n}])):u.length&&(c.preamble=u,c.preambleSources=[{contribution:r,operation:n}],c.preambleJoined=!1),c.top=s.top??o.top,c.children=applyChildren(s.children,o.children,n,``,l),c}function renderComposed(e){let t=[],n=!1,notice=e=>{e&&!n&&(t.push(`Where these sections conflict, the later text wins.`),n=!0)};e.preamble.length&&(notice(e.preambleJoined),t.push(e.preamble.join(`
155
+ `)){if(t(r))continue;let e=En.exec(r);e&&(n=Math.min(n??6,e[1].length))}return n}function parseSections(e,t){let n=topLevel(e),r={top:n,preamble:[],children:[]},i=[],a=fenceTracker(),o;for(let s of e.split(`
156
+ `)){let e=a(s),c=e?null:En.exec(s);if(c){let e=c[1].length,t={depth:e-(n??e),level:e,title:(c[2]??``).trim(),heading:s.trimEnd(),marker:void 0,text:[],children:[]};for(;(i.at(-1)?.level??0)>=e;)i.pop();(i.at(-1)?.children??r.children).push(t),i.push(t),o=t;continue}if(o&&!e){if(!s.trim())continue;let e=Tn.exec(s);if(e){let n=e[1];isMergeOperation(n)?o.marker=n:(t(`marker-unknown`,`unknown merge "${n}" on "${o.title}"; read as patch`),o.marker=`patch`),o=void 0;continue}}o=void 0,(i.at(-1)?.text??r.preamble).push(s)}return r}function trimBlank(e){let t=0,n=e.length;for(;t<n&&!e[t].trim();)t++;for(;n>t&&!e[n-1].trim();)n--;return e.slice(t,n)}function emptyComposed(){return{top:void 0,preamble:[],preambleSources:[],children:[],removed:[],joined:!1,preambleJoined:!1}}function pathOf(e,t){return e?`${e} > ${t}`:t}function warnRepeats(e,t,{warn:n}){let r=new Set;for(let i of e){let e=sectionKey$1(i.title);r.has(e)&&n(`heading-repeated`,`heading path "${pathOf(t,i.title)}" appears more than once; the first is matched`),r.add(e),warnRepeats(i.children,pathOf(t,i.title),{warn:n})}}function warnUnmatched(e,t,{warn:n}){n(`marker-unmatched`,`"<!-- merge: ${e.marker} -->" on "${pathOf(t,e.title)}" matches no section below`)}function place(e,t,n,r){let i=pathOf(n,e.title),a=e.children.flatMap(e=>(e.marker&&warnUnmatched(e,i,r),e.marker===`remove`?[]:[place(e,e.marker??t,i,r)])),o=trimBlank(e.text);return{depth:e.depth,title:e.title,heading:e.heading,level:e.level,text:o,sources:o.length?[{contribution:r.label,operation:t}]:[],children:a}}function join$1(e,t){return e.length&&t.length?[...e,``,...t]:[...e,...t]}function applyChildren(e,t,n,r,i){let a=[...e],o=[],s=new Set;for(let c of t){let t=c.marker??n,l=sectionKey$1(c.title),u=s.has(l)?-1:e.findIndex(e=>sectionKey$1(e.title)===l);if(s.add(l),u===-1){if(i.matchedOnly)continue;c.marker&&warnUnmatched(c,r,i),t!==`remove`&&o.push(place(c,t,r,i));continue}let d=e[u],f=pathOf(r,d.title);if(t===`remove`){a[u]=void 0,i.composed.removed.push({path:f,by:i.label});continue}if(t===`replace`){a[u]={...place(c,`replace`,r,i),depth:d.depth};continue}let p=trimBlank(c.text),m=p.length?[{contribution:i.label,operation:t}]:[];if(t===`combine`){let e=!!(p.length&&d.text.length);e&&(i.composed.joined=!0),a[u]={...d,...e?{joined:!0}:{},text:join$1(d.text,p),sources:[...d.sources,...m],children:applyChildren(d.children,c.children,`combine`,f,i)};continue}let{joined:h,...g}=d;a[u]={...p.length?g:d,text:p.length?p:d.text,sources:p.length?m:d.sources,children:applyChildren(d.children,c.children,`replace`,f,i)}}return[...a.filter(e=>e!==void 0),...o]}function applyContribution(e,t,n,r,i,{matchedOnly:a=!1}={}){let o=parseSections(t,i),s=n===`replace`?emptyComposed():e,c={...s,removed:[...s.removed]},l={label:r,warn:i,composed:c,matchedOnly:a};warnRepeats(o.children,``,l);let u=a&&!s.preamble.length?[]:trimBlank(o.preamble);return n===`combine`?(u.length&&s.preamble.length&&(c.joined=!0,c.preambleJoined=!0),c.preamble=join$1(s.preamble,u),u.length&&(c.preambleSources=[...s.preambleSources,{contribution:r,operation:n}])):u.length&&(c.preamble=u,c.preambleSources=[{contribution:r,operation:n}],c.preambleJoined=!1),c.top=s.top??o.top,c.children=applyChildren(s.children,o.children,n,``,l),c}function renderComposed(e){let t=[],n=!1,notice=e=>{e&&!n&&(t.push(`Where these sections conflict, the later text wins.`),n=!0)};e.preamble.length&&(notice(e.preambleJoined),t.push(e.preamble.join(`
152
157
  `)));let r=e.top??1,visit=e=>{let n=Math.min(6,r+e.depth),i=n===e.level?e.heading:`${`#`.repeat(n)} ${e.title}`.trimEnd();notice(e.joined),t.push(e.text.length?`${i}\n\n${e.text.join(`
153
158
  `)}`:i);for(let t of e.children)visit(t)};for(let t of e.children)visit(t);return t.length?`${t.join(`
154
159
 
155
160
  `)}\n`:``}function composedSections(e){let t=[];e.preambleSources.length&&t.push({path:`(before the first heading)`,sources:e.preambleSources});let visit=(e,n)=>{let r=pathOf(n,e.title);t.push({path:r,sources:e.sources});for(let t of e.children)visit(t,r)};for(let t of e.children)visit(t,``);return t}function headingPaths(e){let t=[],visit=(e,n)=>{let r=pathOf(n,e.title);t.push(r);for(let t of e.children)visit(t,r)};for(let t of parseSections(e,()=>{}).children)visit(t,``);return t}function pickSections(e,t){let n=topLevel(e),r=fenceTracker(),i=[];for(let t of e.split(`
156
- `)){let e=r(t)?null:wn.exec(t);if(e&&e[1].length===n){i.push({key:sectionKey$1(e[2]??``),lines:[t]});continue}i.at(-1)?.lines.push(t)}let a=new Map(t.map(e=>[sectionKey$1(e.heading),e])),o=new Set,s=[];for(let e of i){let t=a.get(e.key);if(!t||o.has(e.key))continue;o.add(e.key);let[n,...r]=e.lines;if(t.merge===void 0){s.push(n,...r);continue}let i=r.findIndex(e=>e.trim()),c=i!==-1&&Cn.test(r[i])?r.filter((e,t)=>t!==i):r;s.push(n,`<!-- merge: ${t.merge} -->`,...c)}let c=t.filter(e=>!o.has(sectionKey$1(e.heading))).map(({heading:e})=>e);return{body:s.join(`
157
- `),missing:c}}const En=[`merge`,`implements`];function sidecarFile(e,t){return`${t}${e.tier==="default"?bn:``}.meta.md`}function readSidecar(e,t,n,{without:r,display:i,warnAt:a,read:o}){let s=sidecarFile(e,t),c=S(e.dir,s),l=c===r?void 0:o(c);if(l===void 0)return;let u=a(i(c));if(n===`markdown`){u(`metadata-ignored`,`it is ignored: a metadata file goes beside a non-Markdown file, and a Markdown contribution carries its keys in its own frontmatter`);return}let{metadata:d,body:f}=parseDocument(l,u),p=d.extends!==void 0;if(n===void 0&&!p){u(`metadata-ignored`,`it is ignored: no non-Markdown file for "${t}" is beside it, and it writes no extends to select one`);return}hasBody(f)&&u(`metadata-ignored`,`its body is ignored: a metadata file holds frontmatter only`);let m={...d};for(let e of En)e in m&&(delete m[e],u(`metadata-ignored`,e===`merge`?"`merge` in it is ignored: a non-Markdown contribution always replaces what is below it":"`implements` in it is ignored: an interface's sections are Markdown"));return{path:c,file:s,frontmatter:d,metadata:m,selects:p}}function readExtends(e,t){if(e===void 0)return;let malformed=e=>{t(`extends-invalid`,`\`extends\` ${e}; it is read as not written`)},n=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!n)return malformed(`is not a list of plugins`);let r=[];for(let e of n){let n=readStep(e,t);if(typeof n==`string`)return malformed(n);r.push(n)}return r}const Dn=[`merge`,`extends`,`sections`];function readStep(e,t){if(typeof e==`string`)return H.test(e)?{target:e}:`names "${e}", which is not a plugin name or default`;if(!isRecord$1(e)||Object.keys(e).length!==1)return`holds ${JSON.stringify(e)}, which is not a step`;let[n,r]=Object.entries(e)[0];if(!H.test(n))return`names "${n}", which is not a plugin name or default`;if(r==null)return{target:n};let i={target:n};if(typeof r==`string`)return i.merge=readStepMerge(r,n,t),i;if(!isRecord$1(r)||Object.keys(r).some(e=>!Dn.includes(e)))return`gives "${n}" keys other than merge, extends, and sections`;if(r.merge!==void 0&&(i.merge=readStepMerge(r.merge,n,t)),r.extends!==void 0){let e=readExtends(r.extends,t);if(!e)return`gives "${n}" a malformed extends`;i.extends=e}if(r.sections!==void 0){let e=readStepSections(r.sections,n,t);if(!e)return`gives "${n}" sections that are not a list of headings`;i.sections=e}return i}function readStepSections(e,t,n){let r=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!r)return;let i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push({heading:e.trim()});continue}if(!isRecord$1(e)||Object.keys(e).length!==1)return;let[r,a]=Object.entries(e)[0];if(!r.trim())return;let o={heading:r.trim()};a!=null&&(o.merge=readStepMerge(a,`${t} > ${r}`,n)),i.push(o)}return i}function readStepMerge(e,t,n){return isMergeOperation(e)?e:(n(`merge-unknown`,`unknown merge "${String(e)}" on the step ${t}; read as patch`),`patch`)}function expand(e,t,n,r,i){let a={entries:[],missing:[],allMissing:!1,replaced:[]},o=new Set,s=new Set,normalize=(e,t,n)=>{let r=[];for(let o of e){if(o.target===n){i(`extends-self`,`${t} lists itself in its extends; that entry is ignored`);continue}r.at(-1)?.target!==o.target&&(r.some(({target:e})=>e===o.target)&&!a.ambiguous&&(a.ambiguous={cause:`repeat`,message:`${t}'s extends lists ${o.target} at two places`}),r.push(o))}return r},c=normalize(e,t),l=new Set(c.map(({target:e})=>e)),visit=(e,c,u)=>{if(a.ambiguous||o.has(e.target))return;if(s.has(e.target)){n===`plugins`&&(a.ambiguous={cause:`cycle`,message:`the plugins' own extends form a cycle: ${[...u,e.target].join(` → `)}`});return}if(!c&&l.has(e.target))return;let d=r(e.target);if(`reason`in d){a.missing.push({target:e.target,reason:d.reason}),e.target!=="default"&&i(`extends-step-missing`,`the step ${e.target} in ${u.at(-1)??t}'s extends ${d.reason}; it is skipped`);return}s.add(e.target);let f=d.steps??[];if(e.extends){let t=new Set(e.extends.map(({target:e})=>e));for(let{target:n}of f)t.has(n)||a.replaced.push({target:n,step:e.target})}for(let t of normalize(e.extends??f,`plugin ${e.target}`,e.target))visit(t,!1,[...u,e.target]);s.delete(e.target);let p=e.merge??d.merge??`patch`,m=e.merge?`step`:d.merge?`contribution`:`default`,h={target:e.target,contribution:d,operation:p,from:m};e.sections&&(h.sections=e.sections),a.entries.push(h),o.add(e.target)};for(let e of c)visit(e,!0,[]);return a.allMissing=c.length>0&&c.every(({target:e})=>!o.has(e))&&c.some(({target:e})=>e!=="default"),a}const noWarn=()=>{};function plan(e,t,n,r,i,a){let o;for(let n of t){if(!n.steps)continue;if(e.plugin!==void 0){n.entry.extendsOutcome=`not used (qualified name)`;continue}if(o){expand(n.steps,n.label,`written`,r,noWarn).entries.map(({target:e})=>e).join(` `)!==o.targets&&(n.entry.extendsOutcome=`not used (${o.builder.label}'s extends builds the stack)`,a(`extends-not-used`,`${n.label} builds a different stack from ${o.builder.label}, whose extends is used`));continue}let t=expand(n.steps,n.label,`written`,r,a);if(t.ambiguous)return{status:`ambiguous`,...t.ambiguous};if(t.allMissing){n.entry.extendsOutcome=`not used (every step is missing)`,a(`extends-all-missing`,`every step in ${n.label}'s extends is missing; it is read as not written`);continue}o={entries:t.entries,builtBy:n.label,replaced:t.replaced,replacedBy:n.label,builder:n,targets:t.entries.map(({target:e})=>e).join(` `)}}if(o)return o;if(e.plugin!==void 0){let t=r(e.plugin);if(`reason`in t)return{status:`missing`,message:`the plugin ${e.plugin} ${t.reason}`};let n=expand([{target:e.plugin}],`plugin ${e.plugin}`,`plugins`,r,a);return n.ambiguous?{status:`ambiguous`,...n.ambiguous}:{entries:n.entries,builtBy:`qualified name`,replaced:[],replacedBy:``}}return planFromPlugins(n,r,i,e.name,a)}function planFromPlugins(e,t,n,r,i){let defaultEntry=()=>n?[{target:`default`,contribution:n,operation:n.merge??`patch`,from:n.merge?`contribution`:`default`}]:[],a=[...e.keys()];if(!a.length)return{entries:defaultEntry(),builtBy:`none`,replaced:[],replacedBy:``};let o=new Map;for(let e of a){let n=expand([{target:e}],`plugin ${e}`,`plugins`,t,noWarn);if(n.ambiguous)return{status:`ambiguous`,...n.ambiguous};o.set(e,new Set(n.entries.map(({target:e})=>e).filter(t=>t!==e)))}let s=a.filter(e=>!a.some(t=>t!==e&&o.get(t)?.has(e))),unordered=()=>({status:`ambiguous`,cause:`unordered`,message:`the plugins ${a.join(`, `)} hold it, and no extends orders them`});if(s.length!==1)return unordered();let c=s[0],l=expand([{target:c}],`plugin ${c}`,`plugins`,t,i);if(l.ambiguous)return{status:`ambiguous`,...l.ambiguous};let u=new Set(l.entries.map(({target:e})=>e));if(a.some(e=>!u.has(e)))return unordered();let d=l.entries;if(n&&!u.has(`default`)){d.unshift(...defaultEntry());let e=a.join(`, `);i(`default-not-selected`,`${a.length>1?`the plugins`:`the plugin`} ${e} ${a.length>1?`answer`:`answers`} over the default of ${n.layer.skill}, and no extends names either; run "reference customize ${r} --extends <option>..." to choose (options: ${[...a,`default`].join(`, `)})`)}return{entries:d,builtBy:c&&(e.get(c)?.steps?.length??0)>0?`plugin ${c}'s extends`:`none`,replaced:[],replacedBy:``}}function readDeclined(e,t){if(e==null)return[];if(!Array.isArray(e))return t(`frontmatter-invalid`,"`declined` is not a list; it is read as declining nothing"),[];let n=e.filter(e=>typeof e==`string`&&H.test(e));return n.length!==e.length&&t(`frontmatter-invalid`,"an entry in `declined` is not a plugin name; it is left out"),n}function pickValues(e){if(!e.some(e=>e.extends!==void 0||e.sections!==void 0))return e.map(({target:e,merge:t})=>t?`${e}:${t}`:e)}function namesDefault(e){return(e??[]).some(e=>e.target==="default"||namesDefault(e.extends))}function tryRead$2(e){try{return a(e,`utf8`)}catch{return}}function candidateFiles(e,t){return e.tier==="default"?[`${t}${bn}.md`,...V.map(({extension:e})=>`${t}${bn}${e}`)]:[`${t}.md`,`${t}/README.md`,...V.map(({extension:e})=>`${t}${e}`)]}function contributionLabel(e,t,n){return e.tier===`plugin`?`plugin ${e.plugin}`:e.tier==="default"?`default of ${e.skill}`:`${e.tier} ${n(t)}`}function readContribution(e,t,n,{display:r,without:i,warnAt:a,older:o=[]}){if(e.tier!=="default"){let n=S(e.dir,`${t}${bn}.md`);n!==i&&tryRead$2(n)!==void 0&&a(r(n))(`default-in-tier`,`it is ignored: a default goes in a skill's references/ folder`)}let s=e.tier===`plugin`||e.tier==="default",[c,...l]=[t,...s?[]:o].flatMap(t=>candidateFiles(e,t).flatMap(n=>{let r=S(e.dir,n),a=r===i?void 0:tryRead$2(r);return a===void 0?[]:[{file:n,path:r,raw:a,as:t}]}));for(let e of l)a(r(e.path))(`file-ignored`,`it is ignored: ${c?.file} answers first in that folder`);let u=c?formatOfFile(c.file):void 0,d={without:i,display:r,warnAt:a,read:tryRead$2},f=readSidecar(e,c?.as??t,u,d);if(!c&&!f&&!s){for(let i of o)if(f=readSidecar(e,i,void 0,d),f){renamed(n,i,t,f.path,r,a);break}}if(c&&c.as!==t&&renamed(n,c.as,t,c.path,r,a),!c)return f?sidecarSelection(e,n,f,r,a):void 0;let p=contributionLabel(e,c.path,r),m=a(p);if(u!==`markdown`){Object.assign(n,{path:c.path,file:c.file,outcome:``});let t=c.raw.trim().length>0;t||(n.empty=!0);let i=f?.metadata??{};return f&&(n.frontmatter=f.frontmatter),typeof i.description==`string`&&(n.description=i.description),{layer:e,entry:n,label:p,path:c.path,metadata:i,body:c.raw,hasBody:t,whole:!0,format:u,merge:`replace`,steps:f?readExtends(f.metadata.extends,a(r(f.path))):void 0}}let{metadata:h,body:g}=parseDocument(c.raw,m),_=readMergeOperation(h,m),v=readExtends(h.extends,m);Object.assign(n,{path:c.path,file:c.file,frontmatter:h,outcome:``}),typeof h.description==`string`&&(n.description=h.description);let y=hasBody(g);return y||(n.empty=!0),v&&!y&&_!==`remove`&&(n.selection=!0),{layer:e,entry:n,label:p,path:c.path,metadata:h,body:g,hasBody:y,format:u,whole:!1,merge:_,steps:v}}function renamed(e,t,n,r,i,a){e.alias=t,a(i(r))(`reference-renamed`,`it is filed under the older name "${t}" and applies as "${n}"; rename it to the new name`)}function sidecarSelection(e,t,n,r,i){let a=contributionLabel(e,n.path,r),o=readExtends(n.metadata.extends,i(a));return Object.assign(t,{path:n.path,file:n.file,frontmatter:n.frontmatter,outcome:``}),typeof n.metadata.description==`string`&&(t.description=n.metadata.description),t.empty=!0,o&&(t.selection=!0),{layer:e,entry:t,label:a,path:n.path,metadata:n.metadata,body:``,hasBody:!1,format:`markdown`,whole:!1,merge:void 0,steps:o}}function layerNames(e){if(e.skipped)return[];let t;try{t=o(e.dir,{withFileTypes:!0})}catch{return[]}let n=new Set,r=e.tier==="default";for(let i of t){let t;if(r){let e=[`${bn}.md`,...V.map(e=>`${bn}${e.extension}`)].find(e=>i.name.endsWith(e));e&&(t=i.name.slice(0,-e.length))}else!i.isDirectory()&&[`.md`,...V.map(e=>e.extension)].some(e=>i.name.endsWith(e))?t=i.name.slice(0,i.name.lastIndexOf(`.`)):!i.isFile()&&tryRead$2(S(e.dir,i.name,`README.md`))!==void 0&&(t=i.name);t===void 0||parseReferenceName(t).invalid||n.add(t)}return[...n]}const On=`.interface`,kn=/^([a-z0-9]+(?:[-.][a-z0-9]+)*)@(\d+)$/i;function interfaceIdOf(e){return e.endsWith(`.interface`)&&e.length>10?e.slice(0,-10):void 0}function isVersion(e){return typeof e==`number`&&Number.isInteger(e)&&e>0}function describe(e){return JSON.stringify(e)??String(e)}function newForm(e,t){return t===`required`||t===!0?`{heading: ${e}, required: true}`:`{heading: ${e}}`}function readSection(e){if(typeof e==`string`&&e.trim())return{heading:e.trim(),required:!1};if(!isRecord$1(e))return{problems:[`section ${describe(e)} is not a heading`]};let t=e.heading;if(t===void 0){let t=Object.keys(e),[n]=t;return t.length===1&&n?.trim()?{problems:[`section ${describe(e)} is in the old form; write it as ${newForm(n.trim(),e[n])}`]}:{problems:[`section ${describe(e)} has no heading`]}}if(typeof t!=`string`||!t.trim())return{problems:[`section ${describe(e)}: heading is not text`]};let n=t.trim(),r=[],i=e.required;i!==void 0&&typeof i!=`boolean`&&r.push(`section "${n}": required is ${describe(i)}; it is true or false`);let a=e.holds;if(a!==void 0&&(typeof a!=`string`||!a.trim()||a.trim().includes(`
158
- `))&&r.push(`section "${n}": holds is ${describe(a)}; it is one line of text`),r.length)return{problems:r};let o={heading:n,required:i===!0};return typeof a==`string`&&(o.holds=a.trim()),o}function sectionKey(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function readInterface(e,t){let n=t.interface;if(!isRecord$1(n))return{problems:[n===void 0?"has no `interface:` block in its frontmatter":"`interface:` is not a mapping"]};let r=[],i=n.cardinality;i!==`one`&&i!==`many`&&r.push(`cardinality is ${JSON.stringify(i)}; it is one or many`);let a=n.version;isVersion(a)||r.push(`version is ${JSON.stringify(a)}; it is a positive integer`);let o=n.versions,s=isVersion(a)?[a]:[];o!==void 0&&(Array.isArray(o)&&o.length&&o.every(isVersion)?s=o:r.push(`versions is not a list of positive integers`));let c=n.sections,l=[];if(!Array.isArray(c)||!c.length)r.push(`sections is not a list of headings`);else{let e=new Set;for(let t of c){let n=readSection(t);if(`problems`in n){r.push(...n.problems);continue}let i=sectionKey(n.heading);e.has(i)&&r.push(`section "${n.heading}" is listed more than once`),e.add(i),l.push(n)}}return r.length?{problems:r}:{value:{id:e,cardinality:i,version:a,versions:s,sections:l},problems:r}}function readImplements(e){let t=e.implements;if(t===void 0)return{problems:[]};let n=Array.isArray(t)?t:[t];if(n.length!==1)return{problems:[n.length?`implements lists ${n.length} interfaces; an implementation implements one`:`implements is an empty list`]};let[r]=n,i=typeof r==`string`?kn.exec(r.trim()):null;return i?{entry:{id:i[1],version:Number(i[2])},problems:[]}:{problems:[`implements ${JSON.stringify(r)} is not <id>@<version>`]}}function fitsName(e,t){return e.cardinality===`one`?t===e.id:t.startsWith(`${e.id}.`)&&t.length>e.id.length+1&&!t.endsWith(`.interface`)}function documentSections(e){let t=[],visit=e=>{if(e.depth===0){let n=e.text.find(e=>e.trim());t.push({title:e.title,unsupported:n?.trim().startsWith(`**Unsupported.**`)??!1})}for(let t of e.children)visit(t)};for(let t of parseSections(e,()=>{}).children)visit(t);return t}function checkImplementation(e,{name:t,version:n,content:r,accept:i=e.versions,declaredId:a=e.id}){let o=[],fail=(t,n)=>o.push({check:t,interface:e.id,message:n});i.includes(n)||fail(`version`,`unknown version ${n}`),fitsName({id:a,cardinality:e.cardinality},t)||fail(`name`,`name ${t} is not ${e.cardinality===`one`?a:`${a}.<key>`}`);let s=documentSections(r),c=e.sections.map(({heading:e})=>sectionKey(e)),l=e.sections.filter(({heading:e})=>{let t=s.find(t=>sectionKey(t.title)===sectionKey(e));return!t||t.unsupported}),u=l.filter(({required:e})=>!e).map(({heading:e})=>e),d=-1,f=``,p=new Set;for(let e of s){let t=sectionKey(e.title),n=c.indexOf(t);n!==-1&&(p.has(t)?fail(`order`,`section ${e.title} appears more than once`):n<d&&fail(`order`,`section ${e.title} comes after ${f}`),p.add(t),n>d&&(d=n,f=e.title))}let m=l.filter(({required:e})=>e).map(({heading:e})=>e);return m.length&&fail(`required`,`required ${m.length===1?`section`:`sections`} ${m.join(`, `)} ${m.length===1?`is`:`are`} left out or marked **Unsupported.**`),{failures:o,unsupported:u}}const An=new WeakMap,quiet=()=>()=>{};function ownerLabel(e){return e.tier===`plugin`?`plugin ${e.plugin}`:`default of ${e.skill}`}function push(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function listed(e){return e==null?[]:Array.isArray(e)?e:[e]}function aliasIndex(e){let t=Array.isArray(e)?void 0:e,n=t&&An.get(t);if(n)return n;let r=Array.isArray(e)?e:e.layers,i=new Map,a=new Map,o=new Map,s=new Map,c=new Map;for(let e of r)if(!(e.tier!==`plugin`&&e.tier!=="default"||e.skipped))for(let t of layerNames(e)){let n=readContribution(e,t,{tier:e.tier,path:e.dir,outcome:``},{display:e=>e,without:void 0,warnAt:quiet});if(!n)continue;let r={name:t,tier:e.tier,path:aliasFile(n)};e.plugin!==void 0&&(r.plugin=e.plugin),e.skill!==void 0&&(r.skill=e.skill),push(o,t,ownerLabel(r));let l=interfaceIdOf(t);for(let e of listed(n.metadata.aliases)){let n=typeof e==`string`?e.trim():void 0,o=n===void 0?void 0:parseReferenceName(n);if(n===void 0||!o||o.invalid||o.plugin!==void 0||n===(l??t)){push(s,t,{code:`alias-invalid`,message:`${ownerLabel(r)}: the alias ${JSON.stringify(e)} is not a reference name of its own; it is ignored`});continue}if(l!==void 0){push(c,l,{alias:n,owner:r});continue}push(i,n,r);let u=a.get(t)??[];u.includes(n)||a.set(t,[...u,n])}}let l={byAlias:i,byName:a,owned:o,warnings:s,interfaces:c};return t&&An.set(t,l),l}function aliasFile(e){return e.entry.frontmatter&&e.whole?e.path.replace(/\.[^./]+$/,`.meta.md`):e.path}function resolveAlias(e,t,n){if(e.invalid)return{kind:`own`};let r=(t.byAlias.get(e.name)??[]).filter(t=>e.plugin===void 0||t.plugin===e.plugin);if(!r.length)return{kind:`own`};let i=t.owned.get(e.name);if(i)return n(`alias-not-used`,notUsedMessage(e.name,i,r)),{kind:`own`};let a=[...new Set(r.map(({name:e})=>e))].sort((e,t)=>e.localeCompare(t));if(a.length>1)return{kind:`ambiguous`,names:e.plugin===void 0?a:a.map(t=>`${e.plugin}/${t}`),message:`"${e.name}" is an older name of ${a.join(` and `)}; load one of them by its own name`};let o=a[0];n(`reference-renamed`,`"${e.raw}" is renamed "${o}"; load "${o}" instead`);let s={raw:e.raw,name:o};return e.plugin!==void 0&&(s.plugin=e.plugin),{kind:`renamed`,ref:s,alias:e.name}}function notUsedMessage(e,t,n){return`the alias "${e}" that ${[...new Set(n.map(e=>`${ownerLabel(e)}'s "${e.name}"`))].join(` and `)} lists is not used: ${t.join(` and `)} ${t.length>1?`hold`:`holds`} "${e}" as its own name`}function olderNames(e,t,n){for(let r of t.warnings.get(e)??[])n(r.code,r.message);let r=[];for(let i of t.byName.get(e)??[]){let e=t.byAlias.get(i)??[],a=t.owned.get(i);if(a){n(`alias-not-used`,notUsedMessage(i,a,e));continue}new Set(e.map(e=>e.name)).size>1||r.push(i)}return r}function shownName(e,t){if(t.owned.has(e))return e;let n=new Set((t.byAlias.get(e)??[]).map(e=>e.name));return n.size===1?[...n][0]:e}function warnMisplacedAliases(e,t){for(let n of e){let{tier:e}=n.layer;e!==`plugin`&&e!=="default"&&`aliases`in n.metadata&&t(n.label)(`alias-invalid`,"`aliases` is ignored: only the owner's contribution, a plugin's or a skill's default, renames a name")}}function picked(e,t){let{contribution:n,sections:r}=e;if(!r||n.whole)return n;let i=pickSections(n.body,r);for(let e of i.missing)t(n.label)(`section-not-held`,`the step's sections list "${e}", which it does not hold; that entry is skipped`);return{...n,body:i.body,hasBody:hasBody(i.body)}}function composeOrder(e,t){let n=emptyComposed(),r=[],i,a=[],o;for(let s of e){let{operation:e,from:c}=s,l=picked(s,t),{entry:u}=l;if(l.whole&&l.hasBody){u.operation=`replace`,u.operationFrom=`default`;for(let e of r)e.entry.outcome=`shadowed by ${l.label} (replace)`;r=[l],n={...emptyComposed(),removed:n.removed},o=l,i=void 0,u.outcome=`used`,a.push(l);continue}if(o&&e!==`remove`&&l.hasBody){u.operation=e,u.operationFrom=c,u.outcome=`not used (format differs from ${o.format})`,t(l.label)(`format-mismatch`,`it is ignored: ${o.label} is ${o.format}, which a Markdown contribution cannot compose with`);continue}e===`remove`&&(o=void 0),u.operation=e,u.operationFrom=c;let d=t(l.label);if(e===`remove`){l.hasBody&&d(`remove-body-ignored`,`a merge: remove contribution has a body; it is ignored`);for(let e of r)e.entry.outcome=`shadowed by ${l.label} (remove)`;for(let e of composedSections(n))e.path!==`(before the first heading)`&&n.removed.push({path:e.path,by:l.label});let e=n.removed;r=[],n={...emptyComposed(),removed:e},i=l,u.outcome=`used`,a.push(l);continue}if(!l.hasBody){u.outcome=u.extendsOutcome??`used`,u.extendsOutcome||a.push(l);continue}if(e===`replace`){for(let e of r)e.entry.outcome=`shadowed by ${l.label} (replace)`;r=[]}n=applyContribution(n,l.body,e,l.label,d),r.push(l),i=void 0,u.outcome=`used`,a.push(l)}return{composed:n,applied:r,removedBy:i,used:a,whole:o}}const jn=[`merge`,`extends`,`sources`,`request`];function composedMetadata(e){let t=Object.assign({},...e.map(({metadata:e})=>e));for(let e of jn)delete t[e];return t}function withNewline(e){return e.endsWith(`
159
- `)?e:`${e}\n`}function trimLeadingBlank(e){return e.replace(/^(?:[ \t]*\r?\n)+/,``)}const U=[`.agents`,`references`];function lsFiles(e,...t){return k(`git`,[`ls-files`,`-z`,...t,`--exclude-standard`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],maxBuffer:268435456}).split(`\0`).filter(Boolean)}function gitListing(e){try{let t=lsFiles(e,`-coi`,`--directory`),n=new Set(t);return{files:lsFiles(e,`-co`).filter(e=>!n.has(e)),ignored:t}}catch{return}}function folderOf(e){let t=e.split(`/`);for(let e=1;e+U.length<t.length;e++)if(t[e]===U[0]&&t[e+1]===U[1])return t.slice(0,e).join(`/`)}function ignoredFolderOf(e,t){if(!t.endsWith(`/`))return folderOf(t);let n=t.slice(0,-1).split(`/`);n.at(-1)===U[1]&&n.at(-2)===U[0]?n.splice(-2):n.at(-1)===U[0]&&n.splice(-1);let r=n.join(`/`);return r&&isDirectory$3(S(e,...n,...U))?r:void 0}function entries(e){try{return o(e,{withFileTypes:!0})}catch{return[]}}function walk(e){let t=[],n=[],visit=r=>{let i=entries(S(e,r));r&&!r.split(`/`).includes(`node_modules`)&&i.some(e=>e.isFile()&&e.name===`package.json`)&&n.push(r);for(let n of i){if(!n.isDirectory())continue;let i=r?`${r}/${n.name}`:n.name;if(n.name!==U[0]){visit(i);continue}r&&entries(S(e,i,U[1])).length&&t.push(r);for(let t of entries(S(e,i)))t.isDirectory()&&t.name!==U[1]&&visit(`${i}/${t.name}`)}};return visit(``),{folders:t,packages:n}}function comparePaths(e,t){let n=e.split(`/`),r=t.split(`/`);for(let e=0;e<Math.min(n.length,r.length);e++){let t=n[e],i=r[e];if(t!==i)return t<i?-1:1}return n.length-r.length}function located(e,t){return[...t].sort(comparePaths).map(t=>({folder:t,dir:S(e,...t.split(`/`),...U)})).filter(({dir:e})=>isDirectory$3(e))}function discover(e){let t=gitListing(e);if(t===void 0){let t=walk(e);return{folders:located(e,t.folders),ignored:[],packages:t.packages.sort(comparePaths)}}let n=new Set(t.files.flatMap(e=>folderOf(e)??[])),r=new Set(t.ignored.flatMap(t=>{let r=ignoredFolderOf(e,t);return r===void 0||n.has(r)?[]:[r]})),i=t.files.flatMap(e=>e.endsWith(`/package.json`)?[e.slice(0,-13)]:[]);return{folders:located(e,n),ignored:located(e,r),listed:new Set(t.files),packages:i.sort(comparePaths)}}function projectFolders(e,t=new Map){let n=T(e),r=t.get(n);if(r)return r;let i=discover(n);return t.set(n,i),i}function gitIgnores(e,t){try{return k(`git`,[`check-ignore`,`-q`,`--`,t],{cwd:e,stdio:`ignore`}),!0}catch{return!1}}const Mn=new WeakMap;function readJson$2(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$2,`readJson`);function declared(e,t){let n=[];for(let r of t){let t=S(e,...r.split(`/`),`package.json`),i=readJson$2(t);for(let e of declaredDependencies(i)){let i=packageDir(e,t),a=i&&pluginManifestName(i);i&&a&&(n.some(e=>e.plugin===a&&r.startsWith(`${e.folder}/`))||n.some(e=>e.plugin===a&&e.folder===r)||n.push({folder:r,plugin:a,root:i,version:pluginVersion(i)}))}}return n}function packagePlugins(e,t,n){let r=projectFolders(e,t),i=Mn.get(r);return i||(i=declared(e,r.packages),Mn.set(r,i)),i.filter(({plugin:e})=>!n.has(e))}function packagePluginReferences(e){return S(e.root,`references`)}function heldPlugins({layers:e,plugins:t=[]}){return new Set([...e.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[]),...t.flatMap(({plugin:e,origin:t})=>t===`package`?[]:[e])])}function isRecord$2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}__name(isRecord$2,`isRecord`);function text$1(e){if(typeof e==`string`)return e.trim()?e.trim():void 0;if(typeof e==`number`)return String(e)}__name(text$1,`text`);function readSource(e){if(!isRecord$2(e))return;let t=text$1(e.plugin),n=text$1(e.version),r=text$1(e.default);if(r!==void 0)return{default:r,...t===void 0?{}:{plugin:t},...t!==void 0&&n!==void 0?{version:n}:{}};if(t!==void 0)return n===void 0?{plugin:t}:{plugin:t,version:n}}function readGeneratedRecord(e,t){let n={},r=e.request;typeof r==`string`&&r.trim()&&(n.request=r);let i=e.sources;if(i==null)return n;if(!Array.isArray(i))return t?.(`frontmatter-invalid`,"`sources` is not a list; it is read as recording no sources"),n;let a=i.flatMap(e=>{let n=readSource(e);return n||t?.(`frontmatter-invalid`,"a source in `sources` is not {plugin, version} or {default, plugin, version}; it is left out"),n?[n]:[]});return a.length&&(n.sources=a),n}function isGenerated(e){return e!==void 0&&readGeneratedRecord(e).request!==void 0}function sourceCatalog(e,{tier:t}){let n=Array.isArray(e)?e:e.layers,r=Array.isArray(e)?n.flatMap(({tier:e,plugin:t,version:n,origin:r,skipped:i})=>e===`plugin`&&t!==void 0&&!i?[{plugin:t,version:n,origin:r}]:[]):e.plugins??n.flatMap(({tier:e,plugin:t,version:n,origin:r,skipped:i})=>e===`plugin`&&t!==void 0&&!i?[{plugin:t,version:n,origin:r}]:[]),i=new Map;for(let e of r)(t!==`user`||e.origin!==`dependency`)&&(i.has(e.plugin)||i.set(e.plugin,e));let a=n.flatMap(({tier:e,skill:t,skipped:n})=>e==="default"&&t!==void 0&&!n?[t]:[]),o=Array.isArray(e)?void 0:e.skills;return{plugins:i,skills:o&&!o.unverified?new Set([...a,...o.skills.map(({name:e})=>e)]):void 0}}function compareSources(e,{plugins:t,skills:n}){return e.map(e=>{let r={status:`current`};if(`default`in e&&(r.default=e.default),e.plugin!==void 0&&(r.plugin=e.plugin),e.version!==void 0&&(r.recorded=e.version),e.plugin===void 0)return`default`in e&&n&&!n.has(e.default)&&(r.status=`missing`),r;let i=t.get(e.plugin);return i?(i.version!==void 0&&(r.installed=i.version),e.version!==void 0&&e.version!==i.version&&(r.status=`changed`),r):(r.status=`missing`,r)})}function describeSource(e){let t=e.default===void 0?`plugin ${e.plugin}`:`the default of ${e.default}`;return e.status===`missing`?e.plugin!==void 0&&e.default!==void 0?`${t} (plugin ${e.plugin}) is not installed`:`${t} is not installed`:`${t}${e.default===void 0?``:` (plugin ${e.plugin})`} is ${e.installed??`installed with no version`}, recorded ${e.recorded}`}function staleMessage(e,t){return`it is stale: ${t.filter(({status:e})=>e!==`current`).map(describeSource).join(`; `)}. Customize mode revises "${e}" from its recorded request`}function checkGenerated(e,t,n){let r=readGeneratedRecord(e,n);if(r.sources===void 0&&r.request===void 0)return;let i=compareSources(r.sources??[],t),a={sources:i,stale:i.some(({status:e})=>e!==`current`)};return r.request!==void 0&&(a.request=r.request),a}function recordedSources(e,t,n){return e.flatMap(e=>{if(e==="default"){if(!n)return[];let e=n.plugin===void 0?void 0:t.plugins.get(n.plugin);return e?[e.version===void 0?{default:n.skill,plugin:e.plugin}:{default:n.skill,plugin:e.plugin,version:e.version}]:[{default:n.skill}]}let r=t.plugins.get(e);return r?[r.version===void 0?{plugin:e}:{plugin:e,version:r.version}]:[]})}function generatedFrontmatter(e){let t={};return e.sources?.length&&(t.sources=e.sources.map(e=>({...e}))),e.request!==void 0&&(t.request=e.request.endsWith(`
160
- `)?e.request:`${e.request}\n`),t}const Nn=[`merge`,`extends`,`implements`,`aliases`],Pn=[`sources`,`request`];function names(e){try{return new Set(o(e))}catch{return new Set}}function filesFor(e,t,n){let r=names(e.dir),at=n=>({folder:e,file:n,as:t,path:S(e.dir,...n.split(`/`)),relative:`${e.folder}/.agents/references/${n}`});return{markdown:[`${t}.md`,`${t}/README.md`].filter(e=>r.has(e.split(`/`)[0])).map(at).filter(({path:e})=>e!==n&&tryRead$2(e)!==void 0),data:V.map(({extension:e})=>`${t}${e}`).filter(e=>r.has(e)).map(at).filter(({path:e})=>e!==n)}}function folderEntries(e,t){let n=new Map,at=e=>{let t=n.get(e);return t||(t={folder:e,ignored:!1,plugins:[]},n.set(e,t)),t};for(let t of e.folders)at(t.folder).own=t;for(let t of e.ignored)Object.assign(at(t.folder),{own:t,ignored:!0});for(let e of t)at(e.folder).plugins.push(e);return[...n.values()].sort((e,t)=>comparePaths(e.folder,t.folder))}function readProjectSections(e,t){let{root:n,cache:r,catalog:i,held:a=new Set}=t,o=projectFolders(n,r),s=packagePlugins(n,r,a),c={...t,older:t.older??[],catalog:i&&withPackagePlugins(i,s),dropping:droppingOperation(t.managed),listed:e=>!o.listed||o.listed.has(e.relative)},l={sections:[],trace:[]};for(let t of folderEntries(o,s)){for(let n of pluginHits(e,t,c))readPluginSection(e,n,c,l);t.own&&readOwnSection(e,t.own,t.ignored,c,l)}return l}function withPackagePlugins(e,t){if(!t.length)return e;let n=new Map(e.plugins);for(let{plugin:e,version:r}of t)n.has(e)||n.set(e,{plugin:e,version:r,origin:`package`});return{...e,plugins:n}}function pluginHits(e,t,n){let r=[];for(let i of[...t.plugins].sort((e,t)=>e.plugin.localeCompare(t.plugin))){let a={folder:t.folder,dir:packagePluginReferences(i)},[o]=[e,...n.older].flatMap(e=>filesFor(a,e,n.without).markdown);if(!o)continue;let{metadata:s,body:c}=parseDocument(tryRead$2(o.path)??``,n.warnAt(`plugin ${n.display(o.path)}`)),l=readExtends(s.extends,()=>{})??[];r.push({plugin:i,hit:o,metadata:s,body:c,after:l.map(({target:e})=>e)})}let i=[],a=new Set(r.map(({plugin:e})=>e.plugin));for(;r.length;){let e=new Set(i.map(({plugin:e})=>e.plugin)),t=r.findIndex(({after:t})=>t.every(t=>!a.has(t)||e.has(t)));i.push(...r.splice(t===-1?0:t,1))}return i}function readPluginSection(e,t,n,r){let{plugin:i,hit:a,metadata:o,body:s}=t,c={folder:i.folder,path:a.path,file:a.file,frontmatter:o,outcome:`used`,plugin:i.plugin};i.version!==void 0&&(c.version=i.version),a.as!==e&&(c.alias=a.as),r.trace.push(c);let l=`plugin ${n.display(a.path)}`;if(n.format!==void 0&&n.format!==`markdown`){c.outcome=`not used (format differs from ${n.format})`,n.warnAt(l)(`project-section-not-markdown`,`it is not delivered: the main document of "${e}" is ${n.format}, which has no project sections`);return}if(n.dropping){c.outcome=`shadowed by ${n.dropping.label} (${n.dropping.operation})`;return}if(!hasBody(s)){c.outcome=`not used (no body)`;return}let u={...o};for(let e of[...Nn,...Pn,`declined`])delete u[e];let d=applyManaged(s,l,n.managed,n.warnAt);d.sections&&(c.sections=d.sections),r.sections.push({folder:i.folder,path:a.path,content:d.content,metadata:u,plugin:i.plugin})}function readOwnSection(e,t,n,r,i){let{trace:a,sections:o}=i,{format:s,display:c,without:l,warnAt:u,catalog:d,older:f,listed:p,dropping:m,managed:h}=r,g=[e,...f].map(e=>filesFor(t,e,l)),_=g.flatMap(e=>e.markdown),v=g.flatMap(e=>e.data);if(n||![..._,...v].some(p)){(_.length||v.length)&&a.push({folder:t.folder,path:t.dir,outcome:`not read (ignored)`});return}for(let t of v.filter(p))u(c(t.path))(`project-section-not-markdown`,`it is not delivered: a project section is Markdown, written as ${e}.md`);let[y,...b]=_.filter(p);if(!y)return;for(let e of b)u(c(e.path))(`file-ignored`,`it is ignored: ${y.file} answers first in that folder`);let x={folder:t.folder,path:y.path,file:y.file,outcome:`used`};a.push(x);let S=`project ${c(y.path)}`;if(y.as!==e&&(x.alias=y.as,u(c(y.path))(`reference-renamed`,`it is filed under the older name "${y.as}" and applies as "${e}"; rename it to the new name`)),s!==void 0&&s!==`markdown`){x.outcome=`not used (format differs from ${s})`,u(S)(`project-section-not-markdown`,`it is not delivered: the main document of "${e}" is ${s}, which has no project sections`);return}let{metadata:C,body:w}=parseDocument(tryRead$2(y.path)??``,u(S));x.frontmatter=C;let T={...C};for(let e of Nn)e in T&&(delete T[e],u(S)(`project-section-key-ignored`,`\`${e}\` is ignored in the project section for ${t.folder}: a project section states only what differs in its folder`));if(m){x.outcome=`shadowed by ${m.label} (${m.operation})`;return}if(!hasBody(w)){x.outcome=`not used (no body)`;return}for(let e of Pn)delete T[e];let E=applyManaged(w,S,h,u);E.sections&&(x.sections=E.sections);let D=d&&checkGenerated(C,d,u(S));D&&(D.sources.length&&(x.sources=D.sources),D.request!==void 0&&(x.request=D.request),D.stale&&(x.outcome=`stale`,u(S)(`reference-stale`,staleMessage(e,D.sources)))),o.push({folder:t.folder,path:y.path,content:E.content,metadata:T})}function droppingOperation(e){if(e?.entry.outcome!==`used`)return;let t=e.merge??`patch`;if(t===`remove`||t===`replace`&&e.hasBody)return{label:e.label,operation:t}}function applyManaged(e,t,n,r){let i=withNewline(trimLeadingBlank(stripMergeMarkers(e)));if(n?.entry.outcome!==`used`||!n.hasBody||n.whole)return{content:i};let a=n.merge??`patch`;if(a===`remove`||a===`replace`)return{content:i};let o=applyContribution(emptyComposed(),e,`patch`,t,r(t)),s=applyContribution(o,n.body,a,n.label,r(n.label),{matchedOnly:!0}),c=renderComposed(s);return c===renderComposed(o)?{content:i}:{content:c,sections:composedSections(s).map(({path:e,sources:t})=>({path:e,contributions:t}))}}function projectSectionNames(e,t,n=new Set){let r=projectFolders(e,t),i=new Set;for(let e of r.folders)for(let t of layerNames({tier:`project`,dir:e.dir})){let{markdown:n}=filesFor(e,t,void 0);n.some(e=>!r.listed||r.listed.has(e.relative))&&i.add(t)}for(let r of packagePlugins(e,t,n)){let e=packagePluginReferences(r);for(let t of layerNames({tier:`plugin`,dir:e}))filesFor({folder:r.folder,dir:e},t,void 0).markdown.length&&i.add(t)}return[...i]}function layersOf(e){return Array.isArray(e)?{layers:[...e],harnesses:[]}:e}function emptyTrace(e){return{stack:[],builtBy:`none`,contributions:[],sections:[],layers:[],harnesses:[...e],projectSections:[]}}function stackOrder(e,t){let rank=e=>{if(e.tier!==`plugin`&&e.tier!=="default")return-1;let n=t.indexOf(e.tier==="default"?`default`:e.plugin??``);return n===-1?t.length:t.length-1-n};return e.map((e,t)=>({layer:e,index:t,rank:rank(e)})).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(({layer:e})=>e)}function resolveReference(e,t,n={}){return resolveAdjusted(e,t,n,void 0)}function resolveAdjusted(e,t,{display:n=e=>e,without:r,below:i,projectSections:a=!0},o){let s=typeof e==`string`?parseReferenceName(e):e,{layers:c,harnesses:l,root:u,projects:d}=layersOf(t),f=emptyTrace(l),p=[],m={name:s.raw,status:`missing`,projectSections:[],warnings:p,trace:f};if(s.invalid)return{...m,status:`invalid`,code:`reference-invalid`,message:s.invalid};let h=new Set,warnAt=e=>(t,n)=>{let r=e?`${e}: ${n}`:n;h.has(`${t} ${r}`)||(h.add(`${t} ${r}`),p.push({code:t,message:r}))},g=warnAt(``),_=aliasIndex(t),v=resolveAlias(s,_,g);if(v.kind===`ambiguous`)return{...m,status:`ambiguous`,code:`reference-ambiguous`,message:v.message,cause:`alias`,options:v.names};let y=v.kind===`renamed`?v.ref:s;v.kind===`renamed`&&(f.alias={name:v.alias,resolvedAs:y.name});let b=olderNames(y.name,_,g),x=i===void 0?-1:c.findIndex(e=>e.dir===i),S=x===-1?c:c.slice(x+1),C=[];for(let e of S){e.warning&&g(e.warning.code,e.warning.message);let t={tier:e.tier,path:e.dir,outcome:`missing`};if(e.plugin!==void 0&&(t.plugin=e.plugin),e.skill!==void 0&&(t.skill=e.skill),f.layers.push(t),e.skipped){t.outcome=`not read (${e.skipped})`;continue}let i=readContribution(e,y.name,t,{display:n,without:r,warnAt,older:b}),a=o?o(e,i,t):i;a?C.push(a):e.tier==="default"&&(t.outcome=`not read (no default)`)}warnMisplacedAliases(C,warnAt);let w=new Map;for(let e of C.filter(({layer:e})=>e.tier===`plugin`)){let t=e.layer.plugin,r=w.get(t);r?e.entry.outcome=`not read (plugin ${t} answers from ${n(r.path)})`:w.set(t,e)}let T=C.find(({layer:e})=>e.tier==="default"),E=C.filter(({layer:e})=>e.tier!==`plugin`&&e.tier!=="default"),D=new Set(S.flatMap(({plugin:e,skipped:t})=>e&&!t?[e]:[])),lookup=e=>e==="default"?T??{reason:`has no default`}:w.get(e)??{reason:D.has(e)?`holds no ${y.name}`:`is not installed`},options=()=>[...[...w.keys()].map(e=>`${e}/${y.name}`),...T?[`default`]:[]];if(interfaceIdOf(y.name)!==void 0)return resolveInterface(y,C,w,T,m,g,options);let sectionsOver=e=>{if(u===void 0||i!==void 0||!a)return{sections:[],trace:[]};let o=E.find(({layer:e})=>e.tier===`managed`),s=sourceCatalog(t,{tier:`project`}),c=readProjectSections(y.name,{root:u,cache:d,managed:o,format:e,display:n,without:r,warnAt,catalog:s,older:b,held:heldPlugins(layersOf(t))});return f.projectSections=c.trace,c},O=plan(y,E,w,lookup,T,g);if(`status`in O){if(O.status===`ambiguous`){for(let{entry:e}of C)e.outcome===``&&(e.outcome=`ambiguous`);return{...m,status:`ambiguous`,code:`reference-ambiguous`,message:O.message,cause:O.cause,options:options()}}for(let{entry:e}of C)e.outcome===``&&(e.outcome=`not used (qualified name)`);return{...m,status:`missing`,code:`reference-missing`,message:O.message}}!S.some(({tier:e})=>e==="default")&&C.some(({steps:e})=>namesDefault(e))&&f.layers.push({tier:`default`,path:`(no skill folder given)`,outcome:`not read (no default)`}),f.stack=O.entries.map(({target:e})=>e),f.builtBy=O.builtBy,f.layers=stackOrder(f.layers,f.stack);let ee=new Set(f.stack);for(let[e,t]of[...w.entries(),...T?[[`default`,T]]:[]]){if(ee.has(e))continue;let n=O.replaced.find(t=>t.target===e);t.entry.outcome=y.plugin===void 0?n?`not used (${n.step}'s extends replaced by ${O.replacedBy})`:`not used (not in extends)`:`not used (qualified name)`}y.plugin===void 0&&warnUndecided(y.name,O,w,ee,warnAt);let{composed:k,applied:te,removedBy:ne,used:re,whole:A}=composeOrder([...O.entries,...[...E].reverse().map(e=>({contribution:e,operation:e.merge??`patch`,from:e.merge?`contribution`:`default`}))],warnAt);if(markStale(y.name,re,t,warnAt),f.sections=k.removed.map(({path:e,by:t})=>({path:e,contributions:[],removedBy:t})),!te.length){let e=sectionsOver(void 0).sections;if(e.length)return{...m,status:`found`,content:``,format:`markdown`,metadata:{},projectSections:e};if(ne)return f.removedBy=ne.label,{...m,status:`missing`,code:`reference-removed`,message:`"${y.name}" is turned off by ${ne.label} (remove)`};let t=y.plugin===void 0?`no tier holds a document for "${y.name}"`:`the plugin ${y.plugin} holds no document for "${y.name}"`;return{...m,status:`missing`,code:`reference-missing`,message:t}}let ie=re.filter(({entry:e})=>e.outcome===`used`||e.outcome===`stale`);if(f.contributions=te.map(({layer:e,entry:t})=>{let n={tier:e.tier,path:t.path,operation:t.operation};return t.plugin!==void 0&&(n.plugin=t.plugin),t.skill!==void 0&&(n.skill=t.skill),n}),f.sections=[...composedSections(k).map(({path:e,sources:t})=>({path:e,contributions:t})),...f.sections],A)return sectionsOver(A.format),{...m,status:`found`,content:A.body,format:A.format,metadata:composedMetadata(ie)};let j=te.length===1&&!k.removed.length?te[0].body:void 0,ae=j!==void 0&&stripMergeMarkers(j)===j?withNewline(trimLeadingBlank(j)):renderComposed(k);return{...m,status:`found`,content:ae,format:`markdown`,metadata:composedMetadata(ie),projectSections:sectionsOver(`markdown`).sections}}function markStale(e,t,n,r){for(let i of t){let{layer:t,entry:a}=i;if(a.outcome!==`used`||t.tier!==`repo`&&t.tier!==`user`)continue;let o=r(i.label),s=checkGenerated(i.metadata,sourceCatalog(n,{tier:t.tier}),o);s&&(s.sources.length&&(a.sources=s.sources),s.request!==void 0&&(a.request=s.request),s.stale&&(a.outcome=`stale`,o(`reference-stale`,staleMessage(e,s.sources))))}}function warnUndecided(e,t,n,r,i){let a=t.builder;if(!a||a.layer.tier!==`repo`&&a.layer.tier!==`user`)return;let o=new Set(readDeclined(a.metadata.declined,i(a.label))),s=[];for(let[e,t]of n)r.has(e)||(a.layer.tier!==`user`||t.layer.origin!==`dependency`)&&(o.has(e)?t.entry.outcome=`not used (declined by ${a.label})`:s.push(e));if(!s.length)return;let c=a.layer.tier===`user`?` --scope user`:``,l=pickValues(a.steps??[]),u=l?`run "reference customize ${e}${c} --extends ${[...l,...s].join(` `)}" to add ${s.length>1?`them`:`it`}, or "reference customize ${e}${c} --extends ${l.join(` `)}" to leave ${s.length>1?`them`:`it`} out`:`add ${s.length>1?`them`:`it`} to the extends with "reference customize ${e}${c} --extends-file <file>", or write the same extends again to leave ${s.length>1?`them`:`it`} out`,d=s.join(`, `);i(a.label)(`plugin-not-selected`,`${s.length>1?`the plugins`:`the plugin`} ${d} ${s.length>1?`hold`:`holds`} "${e}" but ${s.length>1?`are`:`is`} neither in its extends nor declined, so ${s.length>1?`they are`:`it is`} not used; ${u}`)}function resolveInterface(e,t,n,r,i,a,o){for(let e of t)(e.merge!==void 0||e.steps!==void 0)&&a(`interface-not-composed`,`${e.label}: merge and extends on an interface document are ignored; an interface is never composed`);if(e.plugin===void 0&&n.size>1){for(let{entry:e}of t)e.outcome===``&&(e.outcome=`ambiguous`);return{...i,status:`ambiguous`,code:`reference-ambiguous`,message:`the plugins ${[...n.keys()].join(`, `)} each hold the interface document`,cause:`unordered`,options:o()}}let s=e.plugin===void 0?[...n.values()]:n.has(e.plugin)?[n.get(e.plugin)]:[];if(e.plugin!==void 0){for(let[t,r]of n)t!==e.plugin&&(r.entry.outcome=`not used (qualified name)`);if(!s.length)return{...i,status:`missing`,code:`reference-missing`,message:`the plugin ${e.plugin} holds no "${e.name}"`}}let c=t.filter(({layer:e})=>e.tier!==`plugin`&&e.tier!=="default"),[l,...u]=[...e.plugin===void 0&&r?[r]:[],...s,...[...c].reverse()];if(!l)return{...i,status:`missing`,code:`reference-missing`,message:`no tier holds a document for "${e.name}"`};for(let e of u)e.entry.outcome=`not used (an interface document is never composed)`,a(`interface-not-composed`,`${e.label} is ignored: an interface document is never composed; define a new interface id instead`);r&&r!==l&&(r.entry.outcome=`not used (qualified name)`),l.entry.outcome=`used`,l.entry.operation=`replace`,l.entry.operationFrom=`default`;let{trace:d}=i;return l.layer.tier===`plugin`&&(d.stack=[l.layer.plugin]),l.layer.tier==="default"&&(d.stack=[`default`]),d.contributions=[{tier:l.layer.tier,...l.entry.plugin?{plugin:l.entry.plugin}:{},...l.entry.skill?{skill:l.entry.skill}:{},path:l.path,operation:`replace`}],{...i,status:`found`,content:withNewline(trimLeadingBlank(stripMergeMarkers(l.body))),metadata:composedMetadata([l])}}function referenceNames(e){return[...new Set(layersOf(e).layers.flatMap(layerNames))].sort((e,t)=>e.localeCompare(t))}function skillHoldings(e){return(Array.isArray(e)?[]:e.skills?.skills??[]).flatMap(e=>layerNames(defaultLayer(e.folder)).map(t=>({name:t,skill:e}))).sort((e,t)=>e.name.localeCompare(t.name)||e.skill.name.localeCompare(t.skill.name))}function defaultsUnverified(e){return Array.isArray(e)?void 0:e.skills?.unverified}function withDefault(e,t){let n=Array.isArray(e)?{layers:[...e],harnesses:[]}:e;return{...n,layers:[...n.layers.filter(({tier:e})=>e!=="default"),defaultLayer(t)]}}function patternMatcher(e){let t=e.split(`*`).map(e=>e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`));return RegExp(`^${t.join(`.*`)}$`,`s`)}function firstLine$1(e){return typeof e==`string`&&e.split(`
161
- `)[0]?.trim()||``}function collect(e,t,n){for(let r of n){let n=`${r.code} ${r.message}`;t.has(n)||e.push(r),t.add(n)}}function layerRow(e,t){let n={name:e,tier:t.tier,path:t.path,description:firstLine$1(t.description),outcome:t.outcome};return t.plugin!==void 0&&(n.plugin=t.plugin),t.skill!==void 0&&(n.skill=t.skill),t.selection?n.kind=`selection`:isGenerated(t.frontmatter)&&(n.kind=`generated`),n}function projectRow(e,t){return{name:e,tier:`project`,path:t.path,description:firstLine$1(t.frontmatter?.description),outcome:t.outcome,kind:`project-section`,folder:t.folder,...t.plugin===void 0?{}:{plugin:t.plugin}}}function catalogNames(e){let t=Array.isArray(e)?void 0:e,n=t?.root===void 0?[]:projectSectionNames(t.root,t.projects,heldPlugins(t)),r=aliasIndex(e);return[...new Set([...referenceNames(e),...n].map(e=>shownName(e,r)))]}function listReferences(e,t={}){let{pattern:n,...r}=t,i=n===void 0?void 0:patternMatcher(n),a={references:[],layers:[],warnings:[]},o=defaultsUnverified(e);o&&(a.defaults=o);let s=new Set,c=skillHoldings(e),l=[...new Set([...catalogNames(e),...c.map(({name:e})=>e)])].sort((e,t)=>e.localeCompare(t));for(let t of l){if(i&&!i.test(t))continue;let n=c.filter(e=>e.name===t),o=resolveReference(t,e,r);!(o.trace.layers.some(({file:e,tier:t})=>e&&t!=="default")||o.trace.projectSections.some(({file:e})=>e))&&n[0]&&(o=resolveReference(t,withDefault(e,n[0].skill.folder),r)),collect(a.warnings,s,o.warnings);let l={name:t,description:o.status===`found`?firstLine$1(o.metadata?.description):``,status:o.status};if(o.code&&(l.code=o.code),o.format&&o.format!==`markdown`&&(l.format=o.format),o.options){let e=n.map(({skill:e})=>`default of ${e.name}`);l.options=[...new Set([...o.options.filter(e=>e!=="default"),...e])]}a.references.push(l);for(let e of o.trace.layers)e.file!==void 0&&e.tier!=="default"&&a.layers.push(layerRow(t,e));for(let e of o.trace.projectSections)e.file!==void 0&&a.layers.push(projectRow(t,e));for(let{skill:i}of n)a.layers.push(defaultRow(t,i.name,i.folder,e,r))}return a}function defaultRow(e,t,n,r,i){return{...layerRow(e,resolveReference(e,withDefault(r,n),i).trace.layers.find(({tier:e,file:t})=>e==="default"&&t)),reachedBy:`the default step, when ${t} loads ${e}`}}const Fn=[`name`,`prefix`,`close name`,`description`,`heading`,`body`];function distance(e,t){let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r++){let i=[r];for(let a=1;a<=t.length;a++){let o=n[a-1]+(e[r-1]===t[a-1]?0:1);i.push(Math.min(n[a]+1,i[a-1]+1,o))}n=i}return n[t.length]}function headings(e){let t=!1,n=[];for(let r of e.split(`
161
+ `)){let e=r(t)?null:En.exec(t);if(e&&e[1].length===n){i.push({key:sectionKey$1(e[2]??``),lines:[t]});continue}i.at(-1)?.lines.push(t)}let a=new Map(t.map(e=>[sectionKey$1(e.heading),e])),o=new Set,s=[];for(let e of i){let t=a.get(e.key);if(!t||o.has(e.key))continue;o.add(e.key);let[n,...r]=e.lines;if(t.merge===void 0){s.push(n,...r);continue}let i=r.findIndex(e=>e.trim()),c=i!==-1&&Tn.test(r[i])?r.filter((e,t)=>t!==i):r;s.push(n,`<!-- merge: ${t.merge} -->`,...c)}let c=t.filter(e=>!o.has(sectionKey$1(e.heading))).map(({heading:e})=>e);return{body:s.join(`
162
+ `),missing:c}}const On={"merge-sections":void 0,"first-wins":`replace`};function isLegacyMerge(e){return e===`merge-sections`||e===`first-wins`}function overriddenPlugins(e){let t=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(t?.length&&t.every(e=>typeof e==`string`&&e.trim()))return[...new Set(t.map(e=>e.split(`/`)[0].trim()))]}function stepTargets(e){let t=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!t)return;let n=[];for(let e of t)if(typeof e==`string`)n.push(e);else if(isRecord$1(e)&&Object.keys(e).length===1)n.push(Object.keys(e)[0]);else return;return n}const flow=e=>`[${e.join(`, `)}]`;function legacyRewrite(e,t,n,r){let i=[],a={},o=e.merge;if(isLegacyMerge(o)){let e=On[o];a.merge=n===`project`?void 0:e,i.push({form:o,from:`merge: ${o}`,to:n===`project`?`no merge: a project section carries none`:e===void 0?`no merge: patch is the default`:`merge: ${e}`,reads:`it reads as patch`})}if(`overrides`in e&&i.push(overridesFinding(e,n,a)),n===`project`&&e.extends!==void 0&&!hasBody(t)){let t=stepTargets(e.extends);i.push({form:`project-selection`,from:`extends: ${t?flow(t):JSON.stringify(e.extends)}`,manual:`a pick now applies to the whole repository: run \`reference customize ${r} --extends ${t?.join(` `)??`<step>...`}\` at the root, then delete this file`,reads:`its extends is ignored`})}return{findings:i,keys:a}}function overridesFinding(e,t,n){let r=e.overrides,i=overriddenPlugins(r),a=`overrides: ${i?flow(Array.isArray(r)?r:[String(r)]):JSON.stringify(r)}`,o=`it is ignored`;if(t===`project`)return n.overrides=void 0,{form:`overrides`,from:a,to:`removed: a project section carries no extends`,reads:o};if(!i)return{form:`overrides`,from:a,manual:"`overrides` is not a list of plugin names",reads:o};let s=e.extends;if(s===void 0)return n.overrides=void 0,n.extends=i,{form:`overrides`,from:a,to:`extends: ${flow(i)}`,reads:o};let c=stepTargets(s),l=i.filter(e=>!c?.includes(e));return c&&!l.length?(n.overrides=void 0,{form:`overrides`,from:a,to:`removed: extends already names each plugin`,reads:o}):{form:`overrides`,from:a,manual:`\`extends\` is also written and does not name ${l.join(`, `)}; add ${l.length>1?`them`:`it`} to \`extends\` where it belongs, then remove \`overrides\``,reads:o}}function defaultLayoutFinding(e){return{form:`default-layout`,from:`references/${e}.md`,to:`references/${e}.default.md`,reads:`it is not read as the default`}}function warnLegacy(e,t,n){let r=e.note===void 0?``:`, and ${e.note}`,i=e.to===void 0?``:`; its 2.0 form is ${e.to}${r}`,a=e.manual===void 0?t:`To fix it, ${e.manual}${e.note===void 0?``:`; ${e.note}`}.`;n(`reference-legacy-format`,`\`${e.from}\` is a version 1 form, and ${e.reads}${i}. ${a}`)}function directoryEntries(e){try{return o(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}function qualifiedOverrides(e,t){let n=[];for(let r of directoryEntries(e)){let i=r.name;if(!r.isDirectory()||!H.test(i))continue;let a=directoryEntries(C(e,i));if(!a.some(e=>e.name===`README.md`))for(let r of a){if(!r.isFile()||!r.name.endsWith(`.md`))continue;let a=r.name.slice(0,-3);!H.test(a)||a.endsWith(`.default`)||a.endsWith(`.meta`)||(t===void 0||a===t)&&n.push({plugin:i,name:a,path:C(e,i,r.name),file:`${i}/${r.name}`})}}return n}function qualifiedOverrideFinding(e,t){let{plugin:n,name:r,file:i}=e,a={form:`qualified-override`,from:i,reads:`no released version read it, so the override never applied`,note:`applying the plan turns it on`};return t===`project`?{...a,manual:`pick plugin ${n} for the whole repository with \`reference customize ${r} --extends ${n}\` at the root, since a project section carries no extends; then move this file's body into ${r}.md in this folder and delete this file`}:{...a,to:`${r}.md with extends: [${n}]`}}const kn=[`merge`,`implements`];function sidecarFile(e,t){return`${t}${e.tier==="default"?U:``}${Sn}.md`}function readSidecar(e,t,n,{without:r,display:i,warnAt:a,read:o}){let s=sidecarFile(e,t),c=C(e.dir,s),l=c===r?void 0:o(c);if(l===void 0)return;let u=a(i(c));if(n===`markdown`){u(`metadata-ignored`,`it is ignored: a metadata file goes beside a non-Markdown file, and a Markdown contribution carries its keys in its own frontmatter`);return}let{metadata:d,body:f}=parseDocument(l,u),p=d.extends!==void 0;if(n===void 0&&!p){u(`metadata-ignored`,`it is ignored: no non-Markdown file for "${t}" is beside it, and it writes no extends to select one`);return}hasBody(f)&&u(`metadata-ignored`,`its body is ignored: a metadata file holds frontmatter only`);let m={...d};for(let e of kn)e in m&&(delete m[e],u(`metadata-ignored`,e===`merge`?"`merge` in it is ignored: a non-Markdown contribution always replaces what is below it":"`implements` in it is ignored: an interface's sections are Markdown"));return{path:c,file:s,frontmatter:d,metadata:m,selects:p}}function readExtends(e,t){if(e===void 0)return;let malformed=e=>{t(`extends-invalid`,`\`extends\` ${e}; it is read as not written`)},n=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!n)return malformed(`is not a list of plugins`);let r=[];for(let e of n){let n=readStep(e,t);if(typeof n==`string`)return malformed(n);r.push(n)}return r}const An=[`merge`,`extends`,`sections`];function readStep(e,t){if(typeof e==`string`)return H.test(e)?{target:e}:`names "${e}", which is not a plugin name or default`;if(!isRecord$1(e)||Object.keys(e).length!==1)return`holds ${JSON.stringify(e)}, which is not a step`;let[n,r]=Object.entries(e)[0];if(!H.test(n))return`names "${n}", which is not a plugin name or default`;if(r==null)return{target:n};let i={target:n};if(typeof r==`string`)return i.merge=readStepMerge(r,n,t),i;if(!isRecord$1(r)||Object.keys(r).some(e=>!An.includes(e)))return`gives "${n}" keys other than merge, extends, and sections`;if(r.merge!==void 0&&(i.merge=readStepMerge(r.merge,n,t)),r.extends!==void 0){let e=readExtends(r.extends,t);if(!e)return`gives "${n}" a malformed extends`;i.extends=e}if(r.sections!==void 0){let e=readStepSections(r.sections,n,t);if(!e)return`gives "${n}" sections that are not a list of headings`;i.sections=e}return i}function readStepSections(e,t,n){let r=typeof e==`string`?[e]:Array.isArray(e)?e:void 0;if(!r)return;let i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push({heading:e.trim()});continue}if(!isRecord$1(e)||Object.keys(e).length!==1)return;let[r,a]=Object.entries(e)[0];if(!r.trim())return;let o={heading:r.trim()};a!=null&&(o.merge=readStepMerge(a,`${t} > ${r}`,n)),i.push(o)}return i}function readStepMerge(e,t,n){return isMergeOperation(e)?e:(n(`merge-unknown`,`unknown merge "${String(e)}" on the step ${t}; read as patch`),`patch`)}function expand(e,t,n,r,i){let a={entries:[],missing:[],allMissing:!1,replaced:[]},o=new Set,s=new Set,normalize=(e,t,n)=>{let r=[];for(let o of e){if(o.target===n){i(`extends-self`,`${t} lists itself in its extends; that entry is ignored`);continue}r.at(-1)?.target!==o.target&&(r.some(({target:e})=>e===o.target)&&!a.ambiguous&&(a.ambiguous={cause:`repeat`,message:`${t}'s extends lists ${o.target} at two places`}),r.push(o))}return r},c=normalize(e,t),l=new Set(c.map(({target:e})=>e)),visit=(e,c,u)=>{if(a.ambiguous||o.has(e.target))return;if(s.has(e.target)){n===`plugins`&&(a.ambiguous={cause:`cycle`,message:`the plugins' own extends form a cycle: ${[...u,e.target].join(` → `)}`});return}if(!c&&l.has(e.target))return;let d=r(e.target);if(`reason`in d){a.missing.push({target:e.target,reason:d.reason}),e.target!=="default"&&i(`extends-step-missing`,`the step ${e.target} in ${u.at(-1)??t}'s extends ${d.reason}; it is skipped`);return}s.add(e.target);let f=d.steps??[];if(e.extends){let t=new Set(e.extends.map(({target:e})=>e));for(let{target:n}of f)t.has(n)||a.replaced.push({target:n,step:e.target})}for(let t of normalize(e.extends??f,`plugin ${e.target}`,e.target))visit(t,!1,[...u,e.target]);s.delete(e.target);let p=e.merge??d.merge??`patch`,m=e.merge?`step`:d.merge?`contribution`:`default`,h={target:e.target,contribution:d,operation:p,from:m};e.sections&&(h.sections=e.sections),a.entries.push(h),o.add(e.target)};for(let e of c)visit(e,!0,[]);return a.allMissing=c.length>0&&c.every(({target:e})=>!o.has(e))&&c.some(({target:e})=>e!=="default"),a}const noWarn=()=>{};function plan(e,t,n,r,i,a){let o;for(let n of t){if(!n.steps)continue;if(e.plugin!==void 0){n.entry.extendsOutcome=`not used (qualified name)`;continue}if(o){expand(n.steps,n.label,`written`,r,noWarn).entries.map(({target:e})=>e).join(` `)!==o.targets&&(n.entry.extendsOutcome=`not used (${o.builder.label}'s extends builds the stack)`,a(`extends-not-used`,`${n.label} builds a different stack from ${o.builder.label}, whose extends is used`));continue}let t=expand(n.steps,n.label,`written`,r,a);if(t.ambiguous)return{status:`ambiguous`,...t.ambiguous};if(t.allMissing){n.entry.extendsOutcome=`not used (every step is missing)`,a(`extends-all-missing`,`every step in ${n.label}'s extends is missing; it is read as not written`);continue}o={entries:t.entries,builtBy:n.label,replaced:t.replaced,replacedBy:n.label,builder:n,targets:t.entries.map(({target:e})=>e).join(` `)}}if(o)return o;if(e.plugin!==void 0){let t=r(e.plugin);if(`reason`in t)return{status:`missing`,message:`the plugin ${e.plugin} ${t.reason}`};let n=expand([{target:e.plugin}],`plugin ${e.plugin}`,`plugins`,r,a);return n.ambiguous?{status:`ambiguous`,...n.ambiguous}:{entries:n.entries,builtBy:`qualified name`,replaced:[],replacedBy:``}}return planFromPlugins(n,r,i,e.name,a)}function planFromPlugins(e,t,n,r,i){let defaultEntry=()=>n?[{target:`default`,contribution:n,operation:n.merge??`patch`,from:n.merge?`contribution`:`default`}]:[],a=[...e.keys()];if(!a.length)return{entries:defaultEntry(),builtBy:`none`,replaced:[],replacedBy:``};let o=new Map;for(let e of a){let n=expand([{target:e}],`plugin ${e}`,`plugins`,t,noWarn);if(n.ambiguous)return{status:`ambiguous`,...n.ambiguous};o.set(e,new Set(n.entries.map(({target:e})=>e).filter(t=>t!==e)))}let s=a.filter(e=>!a.some(t=>t!==e&&o.get(t)?.has(e))),unordered=()=>({status:`ambiguous`,cause:`unordered`,message:`the plugins ${a.join(`, `)} hold it, and no extends orders them`});if(s.length!==1)return unordered();let c=s[0],l=expand([{target:c}],`plugin ${c}`,`plugins`,t,i);if(l.ambiguous)return{status:`ambiguous`,...l.ambiguous};let u=new Set(l.entries.map(({target:e})=>e));if(a.some(e=>!u.has(e)))return unordered();let d=l.entries;if(n&&!u.has(`default`)){d.unshift(...defaultEntry());let e=a.join(`, `);i(`default-not-selected`,`${a.length>1?`the plugins`:`the plugin`} ${e} ${a.length>1?`answer`:`answers`} over the default of ${n.layer.skill}, and no extends names either; run "reference customize ${r} --extends <option>..." to choose (options: ${[...a,`default`].join(`, `)})`)}return{entries:d,builtBy:c&&(e.get(c)?.steps?.length??0)>0?`plugin ${c}'s extends`:`none`,replaced:[],replacedBy:``}}function readDeclined(e,t){if(e==null)return[];if(!Array.isArray(e))return t(`frontmatter-invalid`,"`declined` is not a list; it is read as declining nothing"),[];let n=e.filter(e=>typeof e==`string`&&H.test(e));return n.length!==e.length&&t(`frontmatter-invalid`,"an entry in `declined` is not a plugin name; it is left out"),n}function pickValues(e){if(!e.some(e=>e.extends!==void 0||e.sections!==void 0))return e.map(({target:e,merge:t})=>t?`${e}:${t}`:e)}function namesDefault(e){return(e??[]).some(e=>e.target==="default"||namesDefault(e.extends))}function tryRead$2(e){try{return a(e,`utf8`)}catch{return}}function candidateFiles(e,t){return e.tier==="default"?[`${t}${U}.md`,...V.map(({extension:e})=>`${t}${U}${e}`)]:[`${t}.md`,`${t}/README.md`,...V.map(({extension:e})=>`${t}${e}`)]}function contributionLabel(e,t,n){return e.tier===`plugin`?`plugin ${e.plugin}`:e.tier==="default"?`default of ${e.skill}`:`${e.tier} ${n(t)}`}function readContribution(e,t,n,{display:r,without:i,warnAt:a,older:o=[]}){if(e.tier!=="default"){let n=C(e.dir,`${t}${U}.md`);n!==i&&tryRead$2(n)!==void 0&&a(r(n))(`default-in-tier`,`it is ignored: a default goes in a skill's references/ folder`)}(e.tier===`repo`||e.tier===`user`)&&warnQualifiedOverrides$1(e,t,{display:r,without:i,warnAt:a});let s=e.tier===`plugin`||e.tier==="default",[c,...l]=[t,...s?[]:o].flatMap(t=>candidateFiles(e,t).flatMap(n=>{let r=C(e.dir,n),a=r===i?void 0:tryRead$2(r);return a===void 0?[]:[{file:n,path:r,raw:a,as:t}]}));for(let e of l)a(r(e.path))(`file-ignored`,`it is ignored: ${c?.file} answers first in that folder`);let u=c?formatOfFile(c.file):void 0,d={without:i,display:r,warnAt:a,read:tryRead$2},f=readSidecar(e,c?.as??t,u,d);if(!c&&!f&&!s){for(let i of o)if(f=readSidecar(e,i,void 0,d),f){renamed(n,i,t,f.path,r,a);break}}if(c&&c.as!==t&&renamed(n,c.as,t,c.path,r,a),!c&&!f&&e.tier==="default"&&warnDefaultLayout(e,t,{display:r,without:i,warnAt:a}),!c)return f?sidecarSelection(e,n,f,r,a):void 0;let p=contributionLabel(e,c.path,r),m=a(p);if(u!==`markdown`){Object.assign(n,{path:c.path,file:c.file,outcome:``});let t=c.raw.trim().length>0;t||(n.empty=!0);let i=f?.metadata??{};return f&&(n.frontmatter=f.frontmatter),typeof i.description==`string`&&(n.description=i.description),{layer:e,entry:n,label:p,path:c.path,metadata:i,body:c.raw,hasBody:t,whole:!0,format:u,merge:`replace`,steps:f?readExtends(f.metadata.extends,a(r(f.path))):void 0}}let{metadata:h,body:g}=parseDocument(c.raw,m),_=legacyFix(e,t,r);for(let e of legacyRewrite(h,g,`contribution`,t).findings)warnLegacy(e,_,m);let v=readMergeOperation(h,m),y=readExtends(h.extends,m);Object.assign(n,{path:c.path,file:c.file,frontmatter:h,outcome:``}),typeof h.description==`string`&&(n.description=h.description);let b=hasBody(g);return b||(n.empty=!0),y&&!b&&v!==`remove`&&(n.selection=!0),{layer:e,entry:n,label:p,path:c.path,metadata:h,body:g,hasBody:b,format:u,whole:!1,merge:v,steps:y}}function legacyFix(e,t,n){return e.tier===`plugin`?`Plugin ${e.plugin}'s author rewrites it with \`reference migrate --plugin <its source folder>\`; until then, customize the name.`:e.tier==="default"?`Its skill's author rewrites it with \`reference migrate ${t} --default ${n(b(e.dir))}\`.`:e.tier===`managed`?"An admin rewrites it; `reference migrate` never changes a managed file.":"Run `reference migrate` to rewrite it."}function warnQualifiedOverrides$1(e,t,{display:n,without:r,warnAt:i}){for(let a of qualifiedOverrides(e.dir,t))a.path!==r&&warnLegacy(qualifiedOverrideFinding(a,`contribution`),legacyFix(e,t,n),i(contributionLabel(e,a.path,n)))}function warnDefaultLayout(e,t,{display:n,without:r,warnAt:i}){let a=C(e.dir,`${t}.md`);a!==r&&tryRead$2(a)!==void 0&&warnLegacy(defaultLayoutFinding(t),legacyFix(e,t,n),i(n(a)))}function renamed(e,t,n,r,i,a){e.alias=t,a(i(r))(`reference-renamed`,`it is filed under the older name "${t}" and applies as "${n}"; rename it to the new name`)}function sidecarSelection(e,t,n,r,i){let a=contributionLabel(e,n.path,r),o=readExtends(n.metadata.extends,i(a));return Object.assign(t,{path:n.path,file:n.file,frontmatter:n.frontmatter,outcome:``}),typeof n.metadata.description==`string`&&(t.description=n.metadata.description),t.empty=!0,o&&(t.selection=!0),{layer:e,entry:t,label:a,path:n.path,metadata:n.metadata,body:``,hasBody:!1,format:`markdown`,whole:!1,merge:void 0,steps:o}}function layerNames(e){if(e.skipped)return[];let t;try{t=o(e.dir,{withFileTypes:!0})}catch{return[]}let n=new Set,r=e.tier==="default";for(let i of t){let t;if(r){let e=[`${U}.md`,...V.map(e=>`${U}${e.extension}`)].find(e=>i.name.endsWith(e));e&&(t=i.name.slice(0,-e.length))}else!i.isDirectory()&&[`.md`,...V.map(e=>e.extension)].some(e=>i.name.endsWith(e))?t=i.name.slice(0,i.name.lastIndexOf(`.`)):!i.isFile()&&tryRead$2(C(e.dir,i.name,`README.md`))!==void 0&&(t=i.name);t===void 0||parseReferenceName(t).invalid||n.add(t)}return[...n]}const W=`.interface`,jn=/^([a-z0-9]+(?:[-.][a-z0-9]+)*)@(\d+)$/i;function interfaceIdOf(e){return e.endsWith(`.interface`)&&e.length>10?e.slice(0,-10):void 0}function isVersion(e){return typeof e==`number`&&Number.isInteger(e)&&e>0}function describe(e){return JSON.stringify(e)??String(e)}function newForm(e,t){return t===`required`||t===!0?`{heading: ${e}, required: true}`:`{heading: ${e}}`}function readSection(e){if(typeof e==`string`&&e.trim())return{heading:e.trim(),required:!1};if(!isRecord$1(e))return{problems:[`section ${describe(e)} is not a heading`]};let t=e.heading;if(t===void 0){let t=Object.keys(e),[n]=t;return t.length===1&&n?.trim()?{problems:[`section ${describe(e)} is in the old form; write it as ${newForm(n.trim(),e[n])}`]}:{problems:[`section ${describe(e)} has no heading`]}}if(typeof t!=`string`||!t.trim())return{problems:[`section ${describe(e)}: heading is not text`]};let n=t.trim(),r=[],i=e.required;i!==void 0&&typeof i!=`boolean`&&r.push(`section "${n}": required is ${describe(i)}; it is true or false`);let a=e.holds;if(a!==void 0&&(typeof a!=`string`||!a.trim()||a.trim().includes(`
163
+ `))&&r.push(`section "${n}": holds is ${describe(a)}; it is one line of text`),r.length)return{problems:r};let o={heading:n,required:i===!0};return typeof a==`string`&&(o.holds=a.trim()),o}function sectionKey(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function readInterface(e,t){let n=t.interface;if(!isRecord$1(n))return{problems:[n===void 0?"has no `interface:` block in its frontmatter":"`interface:` is not a mapping"]};let r=[],i=n.cardinality;i!==`one`&&i!==`many`&&r.push(`cardinality is ${JSON.stringify(i)}; it is one or many`);let a=n.version;isVersion(a)||r.push(`version is ${JSON.stringify(a)}; it is a positive integer`);let o=n.versions,s=isVersion(a)?[a]:[];o!==void 0&&(Array.isArray(o)&&o.length&&o.every(isVersion)?s=o:r.push(`versions is not a list of positive integers`));let c=n.sections,l=[];if(!Array.isArray(c)||!c.length)r.push(`sections is not a list of headings`);else{let e=new Set;for(let t of c){let n=readSection(t);if(`problems`in n){r.push(...n.problems);continue}let i=sectionKey(n.heading);e.has(i)&&r.push(`section "${n.heading}" is listed more than once`),e.add(i),l.push(n)}}return r.length?{problems:r}:{value:{id:e,cardinality:i,version:a,versions:s,sections:l},problems:r}}function readImplements(e){let t=e.implements;if(t===void 0)return{problems:[]};let n=Array.isArray(t)?t:[t];if(n.length!==1)return{problems:[n.length?`implements lists ${n.length} interfaces; an implementation implements one`:`implements is an empty list`]};let[r]=n,i=typeof r==`string`?jn.exec(r.trim()):null;return i?{entry:{id:i[1],version:Number(i[2])},problems:[]}:{problems:[`implements ${JSON.stringify(r)} is not <id>@<version>`]}}function fitsName(e,t){return e.cardinality===`one`?t===e.id:t.startsWith(`${e.id}.`)&&t.length>e.id.length+1&&!t.endsWith(`.interface`)}function documentSections(e){let t=[],visit=e=>{if(e.depth===0){let n=e.text.find(e=>e.trim());t.push({title:e.title,unsupported:n?.trim().startsWith(`**Unsupported.**`)??!1})}for(let t of e.children)visit(t)};for(let t of parseSections(e,()=>{}).children)visit(t);return t}function checkImplementation(e,{name:t,version:n,content:r,accept:i=e.versions,declaredId:a=e.id}){let o=[],fail=(t,n)=>o.push({check:t,interface:e.id,message:n});i.includes(n)||fail(`version`,`unknown version ${n}`),fitsName({id:a,cardinality:e.cardinality},t)||fail(`name`,`name ${t} is not ${e.cardinality===`one`?a:`${a}.<key>`}`);let s=documentSections(r),c=e.sections.map(({heading:e})=>sectionKey(e)),l=e.sections.filter(({heading:e})=>{let t=s.find(t=>sectionKey(t.title)===sectionKey(e));return!t||t.unsupported}),u=l.filter(({required:e})=>!e).map(({heading:e})=>e),d=-1,f=``,p=new Set;for(let e of s){let t=sectionKey(e.title),n=c.indexOf(t);n!==-1&&(p.has(t)?fail(`order`,`section ${e.title} appears more than once`):n<d&&fail(`order`,`section ${e.title} comes after ${f}`),p.add(t),n>d&&(d=n,f=e.title))}let m=l.filter(({required:e})=>e).map(({heading:e})=>e);return m.length&&fail(`required`,`required ${m.length===1?`section`:`sections`} ${m.join(`, `)} ${m.length===1?`is`:`are`} left out or marked **Unsupported.**`),{failures:o,unsupported:u}}const Mn=new WeakMap,quiet=()=>()=>{};function ownerLabel(e){return e.tier===`plugin`?`plugin ${e.plugin}`:`default of ${e.skill}`}function push(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function listed(e){return e==null?[]:Array.isArray(e)?e:[e]}function aliasIndex(e){let t=Array.isArray(e)?void 0:e,n=t&&Mn.get(t);if(n)return n;let r=Array.isArray(e)?e:e.layers,i=new Map,a=new Map,o=new Map,s=new Map,c=new Map;for(let e of r)if(!(e.tier!==`plugin`&&e.tier!=="default"||e.skipped))for(let t of layerNames(e)){let n=readContribution(e,t,{tier:e.tier,path:e.dir,outcome:``},{display:e=>e,without:void 0,warnAt:quiet});if(!n)continue;let r={name:t,tier:e.tier,path:aliasFile(n)};e.plugin!==void 0&&(r.plugin=e.plugin),e.skill!==void 0&&(r.skill=e.skill),push(o,t,ownerLabel(r));let l=interfaceIdOf(t);for(let e of listed(n.metadata.aliases)){let o=typeof e==`string`?e.trim():void 0,u=o===void 0?void 0:parseReferenceName(o);if(o===void 0||!u||u.invalid||u.plugin!==void 0||o===(l??t)){push(s,t,{code:`alias-invalid`,message:`${ownerLabel(r)}: the alias ${JSON.stringify(e)} is not a reference name of its own; it is ignored`});continue}l!==void 0&&push(c,l,{alias:o,owner:r});for(let e of l===void 0?[o]:documentNames$1(o,n.metadata)){push(i,e,r);let n=a.get(t)??[];n.includes(e)||a.set(t,[...n,e])}}}let l={byAlias:i,byName:a,owned:o,warnings:s,interfaces:c};return t&&Mn.set(t,l),l}function documentNames$1(e,t){let n=t.interface;return isRecord$1(n)&&n.cardinality===`many`?[e,`${e}${W}`]:[`${e}${W}`]}__name(documentNames$1,`documentNames`);function aliasFile(e){return e.entry.frontmatter&&e.whole?e.path.replace(/\.[^./]+$/,`.meta.md`):e.path}function resolveAlias(e,t,n){if(e.invalid)return{kind:`own`};let r=(t.byAlias.get(e.name)??[]).filter(t=>e.plugin===void 0||t.plugin===e.plugin);if(!r.length)return{kind:`own`};let i=t.owned.get(e.name);if(i)return n(`alias-not-used`,notUsedMessage(e.name,i,r)),{kind:`own`};let a=[...new Set(r.map(({name:e})=>e))].sort((e,t)=>e.localeCompare(t));if(a.length>1)return{kind:`ambiguous`,names:e.plugin===void 0?a:a.map(t=>`${e.plugin}/${t}`),message:`"${e.name}" is an older name of ${a.join(` and `)}; load one of them by its own name`};let o=a[0];n(`reference-renamed`,`"${e.raw}" is renamed "${o}"; load "${o}" instead`);let s={raw:e.raw,name:o};return e.plugin!==void 0&&(s.plugin=e.plugin),{kind:`renamed`,ref:s,alias:e.name}}function notUsedMessage(e,t,n){return`the alias "${e}" that ${[...new Set(n.map(e=>`${ownerLabel(e)}'s "${e.name}"`))].join(` and `)} lists is not used: ${t.join(` and `)} ${t.length>1?`hold`:`holds`} "${e}" as its own name`}function olderNames(e,t,n){for(let r of t.warnings.get(e)??[])n(r.code,r.message);let r=[];for(let i of t.byName.get(e)??[]){let e=t.byAlias.get(i)??[],a=t.owned.get(i);if(a){n(`alias-not-used`,notUsedMessage(i,a,e));continue}new Set(e.map(e=>e.name)).size>1||r.push(i)}return r}function shownName(e,t){if(t.owned.has(e))return e;let n=new Set((t.byAlias.get(e)??[]).map(e=>e.name));return n.size===1?[...n][0]:e}function warnMisplacedAliases(e,t){for(let n of e){let{tier:e}=n.layer;e!==`plugin`&&e!=="default"&&`aliases`in n.metadata&&t(n.label)(`alias-invalid`,"`aliases` is ignored: only the owner's contribution, a plugin's or a skill's default, renames a name")}}function picked(e,t){let{contribution:n,sections:r}=e;if(!r||n.whole)return n;let i=pickSections(n.body,r);for(let e of i.missing)t(n.label)(`section-not-held`,`the step's sections list "${e}", which it does not hold; that entry is skipped`);return{...n,body:i.body,hasBody:hasBody(i.body)}}function composeOrder(e,t){let n=emptyComposed(),r=[],i,a=[],o;for(let s of e){let{operation:e,from:c}=s,l=picked(s,t),{entry:u}=l;if(l.whole&&l.hasBody){u.operation=`replace`,u.operationFrom=`default`;for(let e of r)e.entry.outcome=`shadowed by ${l.label} (replace)`;r=[l],n={...emptyComposed(),removed:n.removed},o=l,i=void 0,u.outcome=`used`,a.push(l);continue}if(o&&e!==`remove`&&l.hasBody){u.operation=e,u.operationFrom=c,u.outcome=`not used (format differs from ${o.format})`,t(l.label)(`format-mismatch`,`it is ignored: ${o.label} is ${o.format}, which a Markdown contribution cannot compose with`);continue}e===`remove`&&(o=void 0),u.operation=e,u.operationFrom=c;let d=t(l.label);if(e===`remove`){l.hasBody&&d(`remove-body-ignored`,`a merge: remove contribution has a body; it is ignored`);for(let e of r)e.entry.outcome=`shadowed by ${l.label} (remove)`;for(let e of composedSections(n))e.path!==`(before the first heading)`&&n.removed.push({path:e.path,by:l.label});let e=n.removed;r=[],n={...emptyComposed(),removed:e},i=l,u.outcome=`used`,a.push(l);continue}if(!l.hasBody){u.outcome=u.extendsOutcome??`used`,u.extendsOutcome||a.push(l);continue}if(e===`replace`){for(let e of r)e.entry.outcome=`shadowed by ${l.label} (replace)`;r=[]}n=applyContribution(n,l.body,e,l.label,d),r.push(l),i=void 0,u.outcome=`used`,a.push(l)}return{composed:n,applied:r,removedBy:i,used:a,whole:o}}const Nn=[`merge`,`extends`,`sources`,`request`];function composedMetadata(e){let t=Object.assign({},...e.map(({metadata:e})=>e));for(let e of Nn)delete t[e];return t}function withNewline(e){return e.endsWith(`
164
+ `)?e:`${e}\n`}function trimLeadingBlank(e){return e.replace(/^(?:[ \t]*\r?\n)+/,``)}const G=[`.agents`,`references`];function lsFiles(e,...t){return A(`git`,[`ls-files`,`-z`,...t,`--exclude-standard`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],maxBuffer:268435456}).split(`\0`).filter(Boolean)}function gitListing(e){try{let t=lsFiles(e,`-coi`,`--directory`),n=new Set(t);return{files:lsFiles(e,`-co`).filter(e=>!n.has(e)),ignored:t}}catch{return}}function folderOf(e){let t=e.split(`/`);for(let e=1;e+G.length<t.length;e++)if(t[e]===G[0]&&t[e+1]===G[1])return t.slice(0,e).join(`/`)}function ignoredFolderOf(e,t){if(!t.endsWith(`/`))return folderOf(t);let n=t.slice(0,-1).split(`/`);n.at(-1)===G[1]&&n.at(-2)===G[0]?n.splice(-2):n.at(-1)===G[0]&&n.splice(-1);let r=n.join(`/`);return r&&isDirectory$3(C(e,...n,...G))?r:void 0}function entries$1(e){try{return o(e,{withFileTypes:!0})}catch{return[]}}function walk(e){let t=[],n=[],visit=r=>{let i=entries$1(C(e,r));r&&!r.split(`/`).includes(`node_modules`)&&i.some(e=>e.isFile()&&e.name===`package.json`)&&n.push(r);for(let n of i){if(!n.isDirectory())continue;let i=r?`${r}/${n.name}`:n.name;if(n.name!==G[0]){visit(i);continue}r&&entries$1(C(e,i,G[1])).length&&t.push(r);for(let t of entries$1(C(e,i)))t.isDirectory()&&t.name!==G[1]&&visit(`${i}/${t.name}`)}};return visit(``),{folders:t,packages:n}}function comparePaths(e,t){let n=e.split(`/`),r=t.split(`/`);for(let e=0;e<Math.min(n.length,r.length);e++){let t=n[e],i=r[e];if(t!==i)return t<i?-1:1}return n.length-r.length}function located(e,t){return[...t].sort(comparePaths).map(t=>({folder:t,dir:C(e,...t.split(`/`),...G)})).filter(({dir:e})=>isDirectory$3(e))}function discover(e){let t=gitListing(e);if(t===void 0){let t=walk(e);return{folders:located(e,t.folders),ignored:[],packages:t.packages.sort(comparePaths)}}let n=new Set(t.files.flatMap(e=>folderOf(e)??[])),r=new Set(t.ignored.flatMap(t=>{let r=ignoredFolderOf(e,t);return r===void 0||n.has(r)?[]:[r]})),i=t.files.flatMap(e=>e.endsWith(`/package.json`)?[e.slice(0,-13)]:[]);return{folders:located(e,n),ignored:located(e,r),listed:new Set(t.files),packages:i.sort(comparePaths)}}function projectFolders(e,t=new Map){let n=E(e),r=t.get(n);if(r)return r;let i=discover(n);return t.set(n,i),i}function gitIgnores(e,t){try{return A(`git`,[`check-ignore`,`-q`,`--`,t],{cwd:e,stdio:`ignore`}),!0}catch{return!1}}const Pn=new WeakMap;function readJson$3(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$3,`readJson`);function declared(e,t){let n=[];for(let r of t){let t=C(e,...r.split(`/`),`package.json`),i=readJson$3(t);for(let e of declaredDependencies(i)){let i=packageDir(e,t),a=i&&pluginManifestName(i);i&&a&&(n.some(e=>e.plugin===a&&r.startsWith(`${e.folder}/`))||n.some(e=>e.plugin===a&&e.folder===r)||n.push({folder:r,plugin:a,root:i,version:pluginVersion(i)}))}}return n}function packagePlugins(e,t,n){let r=projectFolders(e,t),i=Pn.get(r);return i||(i=declared(e,r.packages),Pn.set(r,i)),i.filter(({plugin:e})=>!n.has(e))}function packagePluginReferences(e){return C(e.root,`references`)}function heldPlugins({layers:e,plugins:t=[]}){return new Set([...e.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[]),...t.flatMap(({plugin:e,origin:t})=>t===`package`?[]:[e])])}function isRecord$2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}__name(isRecord$2,`isRecord`);function text$1(e){if(typeof e==`string`)return e.trim()?e.trim():void 0;if(typeof e==`number`)return String(e)}__name(text$1,`text`);function readSource(e){if(!isRecord$2(e))return;let t=text$1(e.plugin),n=text$1(e.version),r=text$1(e.default);if(r!==void 0)return{default:r,...t===void 0?{}:{plugin:t},...t!==void 0&&n!==void 0?{version:n}:{}};if(t!==void 0)return n===void 0?{plugin:t}:{plugin:t,version:n}}function readGeneratedRecord(e,t){let n={},r=e.request;typeof r==`string`&&r.trim()&&(n.request=r);let i=e.sources;if(i==null)return n;if(!Array.isArray(i))return t?.(`frontmatter-invalid`,"`sources` is not a list; it is read as recording no sources"),n;let a=i.flatMap(e=>{let n=readSource(e);return n||t?.(`frontmatter-invalid`,"a source in `sources` is not {plugin, version} or {default, plugin, version}; it is left out"),n?[n]:[]});return a.length&&(n.sources=a),n}function isGenerated(e){return e!==void 0&&readGeneratedRecord(e).request!==void 0}function sourceCatalog(e,{tier:t}){let n=Array.isArray(e)?e:e.layers,r=Array.isArray(e)?n.flatMap(({tier:e,plugin:t,version:n,origin:r,skipped:i})=>e===`plugin`&&t!==void 0&&!i?[{plugin:t,version:n,origin:r}]:[]):e.plugins??n.flatMap(({tier:e,plugin:t,version:n,origin:r,skipped:i})=>e===`plugin`&&t!==void 0&&!i?[{plugin:t,version:n,origin:r}]:[]),i=new Map;for(let e of r)(t!==`user`||e.origin!==`dependency`)&&(i.has(e.plugin)||i.set(e.plugin,e));let a=n.flatMap(({tier:e,skill:t,skipped:n})=>e==="default"&&t!==void 0&&!n?[t]:[]),o=Array.isArray(e)?void 0:e.skills;return{plugins:i,skills:o&&!o.unverified?new Set([...a,...o.skills.map(({name:e})=>e)]):void 0}}function compareSources(e,{plugins:t,skills:n}){return e.map(e=>{let r={status:`current`};if(`default`in e&&(r.default=e.default),e.plugin!==void 0&&(r.plugin=e.plugin),e.version!==void 0&&(r.recorded=e.version),e.plugin===void 0)return`default`in e&&n&&!n.has(e.default)&&(r.status=`missing`),r;let i=t.get(e.plugin);return i?(i.version!==void 0&&(r.installed=i.version),e.version!==void 0&&e.version!==i.version&&(r.status=`changed`),r):(r.status=`missing`,r)})}function describeSource(e){let t=e.default===void 0?`plugin ${e.plugin}`:`the default of ${e.default}`;return e.status===`missing`?e.plugin!==void 0&&e.default!==void 0?`${t} (plugin ${e.plugin}) is not installed`:`${t} is not installed`:`${t}${e.default===void 0?``:` (plugin ${e.plugin})`} is ${e.installed??`installed with no version`}, recorded ${e.recorded}`}function staleMessage(e,t){return`it is stale: ${t.filter(({status:e})=>e!==`current`).map(describeSource).join(`; `)}. Customize mode revises "${e}" from its recorded request`}function checkGenerated(e,t,n){let r=readGeneratedRecord(e,n);if(r.sources===void 0&&r.request===void 0)return;let i=compareSources(r.sources??[],t),a={sources:i,stale:i.some(({status:e})=>e!==`current`)};return r.request!==void 0&&(a.request=r.request),a}function recordedSources(e,t,n){return e.flatMap(e=>{if(e==="default"){if(!n)return[];let e=n.plugin===void 0?void 0:t.plugins.get(n.plugin);return e?[e.version===void 0?{default:n.skill,plugin:e.plugin}:{default:n.skill,plugin:e.plugin,version:e.version}]:[{default:n.skill}]}let r=t.plugins.get(e);return r?[r.version===void 0?{plugin:e}:{plugin:e,version:r.version}]:[]})}function generatedFrontmatter(e){let t={};return e.sources?.length&&(t.sources=e.sources.map(e=>({...e}))),e.request!==void 0&&(t.request=e.request.endsWith(`
165
+ `)?e.request:`${e.request}\n`),t}const Fn=[`merge`,`extends`,`implements`,`aliases`],In=[`sources`,`request`];function names(e){try{return new Set(o(e))}catch{return new Set}}function filesFor(e,t,n){let r=names(e.dir),at=n=>({folder:e,file:n,as:t,path:C(e.dir,...n.split(`/`)),relative:`${e.folder}/.agents/references/${n}`});return{markdown:[`${t}.md`,`${t}/README.md`].filter(e=>r.has(e.split(`/`)[0])).map(at).filter(({path:e})=>e!==n&&tryRead$2(e)!==void 0),data:V.map(({extension:e})=>`${t}${e}`).filter(e=>r.has(e)).map(at).filter(({path:e})=>e!==n)}}function folderEntries(e,t){let n=new Map,at=e=>{let t=n.get(e);return t||(t={folder:e,ignored:!1,plugins:[]},n.set(e,t)),t};for(let t of e.folders)at(t.folder).own=t;for(let t of e.ignored)Object.assign(at(t.folder),{own:t,ignored:!0});for(let e of t)at(e.folder).plugins.push(e);return[...n.values()].sort((e,t)=>comparePaths(e.folder,t.folder))}function readProjectSections(e,t){let{root:n,cache:r,catalog:i,held:a=new Set}=t,o=projectFolders(n,r),s=packagePlugins(n,r,a),c={...t,older:t.older??[],catalog:i&&withPackagePlugins(i,s),dropping:droppingOperation(t.managed),listed:e=>!o.listed||o.listed.has(e.relative)},l={sections:[],trace:[]};for(let t of folderEntries(o,s)){for(let n of pluginHits(e,t,c))readPluginSection(e,n,c,l);t.own&&readOwnSection(e,t.own,t.ignored,c,l)}return l}function withPackagePlugins(e,t){if(!t.length)return e;let n=new Map(e.plugins);for(let{plugin:e,version:r}of t)n.has(e)||n.set(e,{plugin:e,version:r,origin:`package`});return{...e,plugins:n}}function pluginHits(e,t,n){let r=[];for(let i of[...t.plugins].sort((e,t)=>e.plugin.localeCompare(t.plugin))){let a={folder:t.folder,dir:packagePluginReferences(i)},[o]=[e,...n.older].flatMap(e=>filesFor(a,e,n.without).markdown);if(!o)continue;let{metadata:s,body:c}=parseDocument(tryRead$2(o.path)??``,n.warnAt(`plugin ${n.display(o.path)}`)),l=readExtends(s.extends,()=>{})??[];r.push({plugin:i,hit:o,metadata:s,body:c,after:l.map(({target:e})=>e)})}let i=[],a=new Set(r.map(({plugin:e})=>e.plugin));for(;r.length;){let e=new Set(i.map(({plugin:e})=>e.plugin)),t=r.findIndex(({after:t})=>t.every(t=>!a.has(t)||e.has(t)));i.push(...r.splice(t===-1?0:t,1))}return i}function readPluginSection(e,t,n,r){let{plugin:i,hit:a,metadata:o,body:s}=t,c={folder:i.folder,path:a.path,file:a.file,frontmatter:o,outcome:`used`,plugin:i.plugin};i.version!==void 0&&(c.version=i.version),a.as!==e&&(c.alias=a.as),r.trace.push(c);let l=`plugin ${n.display(a.path)}`;if(n.format!==void 0&&n.format!==`markdown`){c.outcome=`not used (format differs from ${n.format})`,n.warnAt(l)(`project-section-not-markdown`,`it is not delivered: the main document of "${e}" is ${n.format}, which has no project sections`);return}if(n.dropping){c.outcome=`shadowed by ${n.dropping.label} (${n.dropping.operation})`;return}if(!hasBody(s)){c.outcome=`not used (no body)`;return}let u={...o};for(let e of[...Fn,...In,`declined`])delete u[e];let d=applyManaged(s,l,n.managed,n.warnAt);d.sections&&(c.sections=d.sections),r.sections.push({folder:i.folder,path:a.path,content:d.content,metadata:u,plugin:i.plugin})}function warnQualifiedOverrides(e,t,n){let{display:r,without:i,warnAt:a,listed:o}=n;for(let n of qualifiedOverrides(t.dir,e)){let s={folder:t,file:n.file,as:e,path:n.path,relative:`${t.folder}/.agents/references/${n.file}`};n.path!==i&&o(s)&&warnLegacy(qualifiedOverrideFinding(n,`project`),``,a(`project ${r(n.path)}`))}}function readOwnSection(e,t,n,r,i){let{trace:a,sections:o}=i,{format:s,display:c,without:l,warnAt:u,catalog:d,older:f,listed:p,dropping:m,managed:h}=r;n||warnQualifiedOverrides(e,t,r);let g=[e,...f].map(e=>filesFor(t,e,l)),_=g.flatMap(e=>e.markdown),v=g.flatMap(e=>e.data);if(n||![..._,...v].some(p)){(_.length||v.length)&&a.push({folder:t.folder,path:t.dir,outcome:`not read (ignored)`});return}for(let t of v.filter(p))u(c(t.path))(`project-section-not-markdown`,`it is not delivered: a project section is Markdown, written as ${e}.md`);let[y,...b]=_.filter(p);if(!y)return;for(let e of b)u(c(e.path))(`file-ignored`,`it is ignored: ${y.file} answers first in that folder`);let x={folder:t.folder,path:y.path,file:y.file,outcome:`used`};a.push(x);let S=`project ${c(y.path)}`;if(y.as!==e&&(x.alias=y.as,u(c(y.path))(`reference-renamed`,`it is filed under the older name "${y.as}" and applies as "${e}"; rename it to the new name`)),s!==void 0&&s!==`markdown`){x.outcome=`not used (format differs from ${s})`,u(S)(`project-section-not-markdown`,`it is not delivered: the main document of "${e}" is ${s}, which has no project sections`);return}let{metadata:C,body:w}=parseDocument(tryRead$2(y.path)??``,u(S));x.frontmatter=C;let T={...C},E=legacyRewrite(C,w,`project`,e).findings;for(let e of E)warnLegacy(e,"Run `reference migrate` to rewrite it.",u(S));let D=new Set(E.flatMap(({form:e})=>e===`project-selection`?[`extends`]:e===`overrides`?[`overrides`]:[`merge`]));delete T.overrides;for(let e of Fn)e in T&&(delete T[e],!D.has(e)&&u(S)(`project-section-key-ignored`,`\`${e}\` is ignored in the project section for ${t.folder}: a project section states only what differs in its folder`));if(m){x.outcome=`shadowed by ${m.label} (${m.operation})`;return}if(!hasBody(w)){x.outcome=`not used (no body)`;return}for(let e of In)delete T[e];let O=applyManaged(w,S,h,u);O.sections&&(x.sections=O.sections);let k=d&&checkGenerated(C,d,u(S));k&&(k.sources.length&&(x.sources=k.sources),k.request!==void 0&&(x.request=k.request),k.stale&&(x.outcome=`stale`,u(S)(`reference-stale`,staleMessage(e,k.sources)))),o.push({folder:t.folder,path:y.path,content:O.content,metadata:T})}function droppingOperation(e){if(e?.entry.outcome!==`used`)return;let t=e.merge??`patch`;if(t===`remove`||t===`replace`&&e.hasBody)return{label:e.label,operation:t}}function applyManaged(e,t,n,r){let i=withNewline(trimLeadingBlank(stripMergeMarkers(e)));if(n?.entry.outcome!==`used`||!n.hasBody||n.whole)return{content:i};let a=n.merge??`patch`;if(a===`remove`||a===`replace`)return{content:i};let o=applyContribution(emptyComposed(),e,`patch`,t,r(t)),s=applyContribution(o,n.body,a,n.label,r(n.label),{matchedOnly:!0}),c=renderComposed(s);return c===renderComposed(o)?{content:i}:{content:c,sections:composedSections(s).map(({path:e,sources:t})=>({path:e,contributions:t}))}}function projectSectionNames(e,t,n=new Set){let r=projectFolders(e,t),i=new Set;for(let e of r.folders)for(let t of layerNames({tier:`project`,dir:e.dir})){let{markdown:n}=filesFor(e,t,void 0);n.some(e=>!r.listed||r.listed.has(e.relative))&&i.add(t)}for(let r of packagePlugins(e,t,n)){let e=packagePluginReferences(r);for(let t of layerNames({tier:`plugin`,dir:e}))filesFor({folder:r.folder,dir:e},t,void 0).markdown.length&&i.add(t)}return[...i]}function projectQualifiedNames(e,t){let n=projectFolders(e,t);return n.folders.flatMap(e=>qualifiedOverrides(e.dir).filter(({file:t})=>!n.listed||n.listed.has(`${e.folder}/.agents/references/${t}`)).map(({name:e})=>e))}const Ln=`_renames.yaml`,Rn=new WeakMap;function bare(e){if(typeof e!=`string`)return;let t=parseReferenceName(e.trim());return t.invalid||t.plugin!==void 0?void 0:t.name}function renameTable(e){let t=Array.isArray(e)?void 0:e,n=t&&Rn.get(t);if(n)return n;let r=Array.isArray(e)?e:e.layers,i=new Map,a=[],o=new Set;for(let e of r){if(e.tier!==`plugin`||e.skipped||e.plugin===void 0)continue;let t=C(e.dir,Ln);if(o.has(t))continue;o.add(t);let n=tryRead$2(t);if(n===void 0)continue;let r=e.plugin,s;try{s=(0,en.parse)(n)}catch{s=void 0}if(s==null){n.trim()&&a.push({code:`rename-invalid`,message:`plugin ${r}: ${t} is not YAML; it is ignored`});continue}if(!isRecord$1(s)){a.push({code:`rename-invalid`,message:`plugin ${r}: ${t} is not a mapping of older names to new names; it is ignored`});continue}for(let[e,t]of Object.entries(s)){let n=bare(e),o=bare(t);if(n===void 0||o===void 0||n===o){a.push({code:`rename-invalid`,message:`plugin ${r}: the rename ${JSON.stringify(e)}: ${JSON.stringify(t)} in ${Ln} is not a pair of bare reference names; it is ignored`});continue}let s=i.get(n)??[];s.some(e=>e.to===o&&e.plugin===r)||s.push({from:n,to:o,plugin:r}),i.set(n,s)}}let s={byOld:i,warnings:a};return t&&Rn.set(t,s),s}function layersOf(e){return Array.isArray(e)?{layers:[...e],harnesses:[]}:e}function emptyTrace(e){return{stack:[],builtBy:`none`,contributions:[],sections:[],layers:[],harnesses:[...e],projectSections:[]}}function stackOrder(e,t){let rank=e=>{if(e.tier!==`plugin`&&e.tier!=="default")return-1;let n=t.indexOf(e.tier==="default"?`default`:e.plugin??``);return n===-1?t.length:t.length-1-n};return e.map((e,t)=>({layer:e,index:t,rank:rank(e)})).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(({layer:e})=>e)}function resolveReference(e,t,n={}){return resolveAdjusted(e,t,n,void 0)}function resolveAdjusted(e,t,{display:n=e=>e,without:r,below:i,projectSections:a=!0},o){let s=typeof e==`string`?parseReferenceName(e):e,{layers:c,harnesses:l,root:u,projects:d}=layersOf(t),f=emptyTrace(l),p=[],m={name:s.raw,status:`missing`,projectSections:[],warnings:p,trace:f};if(s.invalid)return{...m,status:`invalid`,code:`reference-invalid`,message:s.invalid};let h=new Set,warnAt=e=>(t,n)=>{let r=e?`${e}: ${n}`:n;h.has(`${t} ${r}`)||(h.add(`${t} ${r}`),p.push({code:t,message:r}))},g=warnAt(``),_=aliasIndex(t),v=resolveAlias(s,_,g);if(v.kind===`ambiguous`)return{...m,status:`ambiguous`,code:`reference-ambiguous`,message:v.message,cause:`alias`,options:v.names};let y=v.kind===`renamed`?v.ref:s;v.kind===`renamed`&&(f.alias={name:v.alias,resolvedAs:y.name});let b=olderNames(y.name,_,g);v.kind===`own`&&warnTableRename(y,t,_,g);let x=i===void 0?-1:c.findIndex(e=>e.dir===i),S=x===-1?c:c.slice(x+1),C=[];for(let e of S){e.warning&&g(e.warning.code,e.warning.message);let t={tier:e.tier,path:e.dir,outcome:`missing`};if(e.plugin!==void 0&&(t.plugin=e.plugin),e.skill!==void 0&&(t.skill=e.skill),f.layers.push(t),e.skipped){t.outcome=`not read (${e.skipped})`;continue}let i=readContribution(e,y.name,t,{display:n,without:r,warnAt,older:b}),a=o?o(e,i,t):i;a?C.push(a):e.tier==="default"&&(t.outcome=`not read (no default)`)}warnMisplacedAliases(C,warnAt);let w=new Map;for(let e of C.filter(({layer:e})=>e.tier===`plugin`)){let t=e.layer.plugin,r=w.get(t);r?e.entry.outcome=`not read (plugin ${t} answers from ${n(r.path)})`:w.set(t,e)}let T=C.find(({layer:e})=>e.tier==="default"),E=C.filter(({layer:e})=>e.tier!==`plugin`&&e.tier!=="default"),D=new Set(S.flatMap(({plugin:e,skipped:t})=>e&&!t?[e]:[])),lookup=e=>e==="default"?T??{reason:`has no default`}:w.get(e)??{reason:D.has(e)?`holds no ${y.name}`:`is not installed`},options=()=>[...[...w.keys()].map(e=>`${e}/${y.name}`),...T?[`default`]:[]];if(interfaceIdOf(y.name)!==void 0)return resolveInterface(y,C,w,T,m,g,options);let sectionsOver=e=>{if(u===void 0||i!==void 0||!a)return{sections:[],trace:[]};let o=E.find(({layer:e})=>e.tier===`managed`),s=sourceCatalog(t,{tier:`project`}),c=readProjectSections(y.name,{root:u,cache:d,managed:o,format:e,display:n,without:r,warnAt,catalog:s,older:b,held:heldPlugins(layersOf(t))});return f.projectSections=c.trace,c},O=plan(y,E,w,lookup,T,g);if(`status`in O){if(O.status===`ambiguous`){for(let{entry:e}of C)e.outcome===``&&(e.outcome=`ambiguous`);return{...m,status:`ambiguous`,code:`reference-ambiguous`,message:O.message,cause:O.cause,options:options()}}for(let{entry:e}of C)e.outcome===``&&(e.outcome=`not used (qualified name)`);return{...m,status:`missing`,code:`reference-missing`,message:O.message}}!S.some(({tier:e})=>e==="default")&&C.some(({steps:e})=>namesDefault(e))&&f.layers.push({tier:`default`,path:`(no skill folder given)`,outcome:`not read (no default)`}),f.stack=O.entries.map(({target:e})=>e),f.builtBy=O.builtBy,f.layers=stackOrder(f.layers,f.stack);let k=new Set(f.stack);for(let[e,t]of[...w.entries(),...T?[[`default`,T]]:[]]){if(k.has(e))continue;let n=O.replaced.find(t=>t.target===e);t.entry.outcome=y.plugin===void 0?n?`not used (${n.step}'s extends replaced by ${O.replacedBy})`:`not used (not in extends)`:`not used (qualified name)`}y.plugin===void 0&&warnUndecided(y.name,O,w,k,warnAt);let{composed:ee,applied:A,removedBy:te,used:ne,whole:re}=composeOrder([...O.entries,...[...E].reverse().map(e=>({contribution:e,operation:e.merge??`patch`,from:e.merge?`contribution`:`default`}))],warnAt);if(markStale(y.name,ne,t,warnAt),f.sections=ee.removed.map(({path:e,by:t})=>({path:e,contributions:[],removedBy:t})),!A.length){let e=sectionsOver(void 0).sections;if(e.length)return{...m,status:`found`,content:``,format:`markdown`,metadata:{},projectSections:e};if(te)return f.removedBy=te.label,{...m,status:`missing`,code:`reference-removed`,message:`"${y.name}" is turned off by ${te.label} (remove)`};let t=y.plugin===void 0?`no tier holds a document for "${y.name}"`:`the plugin ${y.plugin} holds no document for "${y.name}"`;return{...m,status:`missing`,code:`reference-missing`,message:t}}let ie=ne.filter(({entry:e})=>e.outcome===`used`||e.outcome===`stale`);if(f.contributions=A.map(({layer:e,entry:t})=>{let n={tier:e.tier,path:t.path,operation:t.operation};return t.plugin!==void 0&&(n.plugin=t.plugin),t.skill!==void 0&&(n.skill=t.skill),n}),f.sections=[...composedSections(ee).map(({path:e,sources:t})=>({path:e,contributions:t})),...f.sections],re)return sectionsOver(re.format),{...m,status:`found`,content:re.body,format:re.format,metadata:composedMetadata(ie)};let ae=A.length===1&&!ee.removed.length?A[0].body:void 0,j=ae!==void 0&&stripMergeMarkers(ae)===ae?withNewline(trimLeadingBlank(ae)):renderComposed(ee);return{...m,status:`found`,content:j,format:`markdown`,metadata:composedMetadata(ie),projectSections:sectionsOver(`markdown`).sections}}function markStale(e,t,n,r){for(let i of t){let{layer:t,entry:a}=i;if(a.outcome!==`used`||t.tier!==`repo`&&t.tier!==`user`)continue;let o=r(i.label),s=checkGenerated(i.metadata,sourceCatalog(n,{tier:t.tier}),o);s&&(s.sources.length&&(a.sources=s.sources),s.request!==void 0&&(a.request=s.request),s.stale&&(a.outcome=`stale`,o(`reference-stale`,staleMessage(e,s.sources))))}}function warnUndecided(e,t,n,r,i){let a=t.builder;if(!a||a.layer.tier!==`repo`&&a.layer.tier!==`user`)return;let o=new Set(readDeclined(a.metadata.declined,i(a.label))),s=[];for(let[e,t]of n)r.has(e)||(a.layer.tier!==`user`||t.layer.origin!==`dependency`)&&(o.has(e)?t.entry.outcome=`not used (declined by ${a.label})`:s.push(e));if(!s.length)return;let c=a.layer.tier===`user`?` --scope user`:``,l=pickValues(a.steps??[]),u=l?`run "reference customize ${e}${c} --extends ${[...l,...s].join(` `)}" to add ${s.length>1?`them`:`it`}, or "reference customize ${e}${c} --extends ${l.join(` `)}" to leave ${s.length>1?`them`:`it`} out`:`add ${s.length>1?`them`:`it`} to the extends with "reference customize ${e}${c} --extends-file <file>", or write the same extends again to leave ${s.length>1?`them`:`it`} out`,d=s.join(`, `);i(a.label)(`plugin-not-selected`,`${s.length>1?`the plugins`:`the plugin`} ${d} ${s.length>1?`hold`:`holds`} "${e}" but ${s.length>1?`are`:`is`} neither in its extends nor declined, so ${s.length>1?`they are`:`it is`} not used; ${u}`)}function resolveInterface(e,t,n,r,i,a,o){for(let e of t)(e.merge!==void 0||e.steps!==void 0)&&a(`interface-not-composed`,`${e.label}: merge and extends on an interface document are ignored; an interface is never composed`);if(e.plugin===void 0&&n.size>1){for(let{entry:e}of t)e.outcome===``&&(e.outcome=`ambiguous`);return{...i,status:`ambiguous`,code:`reference-ambiguous`,message:`the plugins ${[...n.keys()].join(`, `)} each hold the interface document`,cause:`unordered`,options:o()}}let s=e.plugin===void 0?[...n.values()]:n.has(e.plugin)?[n.get(e.plugin)]:[];if(e.plugin!==void 0){for(let[t,r]of n)t!==e.plugin&&(r.entry.outcome=`not used (qualified name)`);if(!s.length)return{...i,status:`missing`,code:`reference-missing`,message:`the plugin ${e.plugin} holds no "${e.name}"`}}let c=t.filter(({layer:e})=>e.tier!==`plugin`&&e.tier!=="default"),[l,...u]=[...e.plugin===void 0&&r?[r]:[],...s,...[...c].reverse()];if(!l)return{...i,status:`missing`,code:`reference-missing`,message:`no tier holds a document for "${e.name}"`};for(let e of u)e.entry.outcome=`not used (an interface document is never composed)`,a(`interface-not-composed`,`${e.label} is ignored: an interface document is never composed; define a new interface id instead`);r&&r!==l&&(r.entry.outcome=`not used (qualified name)`),l.entry.outcome=`used`,l.entry.operation=`replace`,l.entry.operationFrom=`default`;let{trace:d}=i;return l.layer.tier===`plugin`&&(d.stack=[l.layer.plugin]),l.layer.tier==="default"&&(d.stack=[`default`]),d.contributions=[{tier:l.layer.tier,...l.entry.plugin?{plugin:l.entry.plugin}:{},...l.entry.skill?{skill:l.entry.skill}:{},path:l.path,operation:`replace`}],{...i,status:`found`,content:withNewline(trimLeadingBlank(stripMergeMarkers(l.body))),metadata:composedMetadata([l])}}function referenceNames(e){return[...new Set(layersOf(e).layers.flatMap(layerNames))].sort((e,t)=>e.localeCompare(t))}function warnTableRename(e,t,n,r){if(n.owned.has(e.name))return;let i=(renameTable(t).byOld.get(e.name)??[]).filter(t=>e.plugin===void 0||t.plugin===e.plugin);if(!i.length)return;let a=[...new Set(i.map(({plugin:e})=>`plugin ${e}`))].join(` and `),o=[...new Set(i.map(({to:e})=>`"${e}"`))].join(` or `);r(`reference-renamed`,`${a} renamed "${e.name}" to ${o}: load ${o} instead, and run \`reference migrate\` to rename the files filed under "${e.name}"`)}function skillHoldings(e){return(Array.isArray(e)?[]:e.skills?.skills??[]).flatMap(e=>layerNames(defaultLayer(e.folder)).map(t=>({name:t,skill:e}))).sort((e,t)=>e.name.localeCompare(t.name)||e.skill.name.localeCompare(t.skill.name))}function defaultsUnverified(e){return Array.isArray(e)?void 0:e.skills?.unverified}function withDefault(e,t){let n=Array.isArray(e)?{layers:[...e],harnesses:[]}:e;return{...n,layers:[...n.layers.filter(({tier:e})=>e!=="default"),defaultLayer(t)]}}function patternMatcher(e){let t=e.split(`*`).map(e=>e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`));return RegExp(`^${t.join(`.*`)}$`,`s`)}function firstLine$1(e){return typeof e==`string`&&e.split(`
166
+ `)[0]?.trim()||``}function collect(e,t,n){for(let r of n){let n=`${r.code} ${r.message}`;t.has(n)||e.push(r),t.add(n)}}function layerRow(e,t){let n={name:e,tier:t.tier,path:t.path,description:firstLine$1(t.description),outcome:t.outcome};return t.plugin!==void 0&&(n.plugin=t.plugin),t.skill!==void 0&&(n.skill=t.skill),t.selection?n.kind=`selection`:isGenerated(t.frontmatter)&&(n.kind=`generated`),n}function projectRow(e,t){return{name:e,tier:`project`,path:t.path,description:firstLine$1(t.frontmatter?.description),outcome:t.outcome,kind:`project-section`,folder:t.folder,...t.plugin===void 0?{}:{plugin:t.plugin}}}function catalogNames(e){let t=Array.isArray(e)?void 0:e,n=t?.root===void 0?[]:projectSectionNames(t.root,t.projects,heldPlugins(t)),r=aliasIndex(e);return[...new Set([...referenceNames(e),...n].map(e=>shownName(e,r)))]}function listReferences(e,t={}){let{pattern:n,...r}=t,i=n===void 0?void 0:patternMatcher(n),a={references:[],layers:[],warnings:[]},o=defaultsUnverified(e);o&&(a.defaults=o);let s=new Set,c=skillHoldings(e),l=[...new Set([...catalogNames(e),...c.map(({name:e})=>e)])].sort((e,t)=>e.localeCompare(t));for(let t of l){if(i&&!i.test(t))continue;let n=c.filter(e=>e.name===t),o=resolveReference(t,e,r);!(o.trace.layers.some(({file:e,tier:t})=>e&&t!=="default")||o.trace.projectSections.some(({file:e})=>e))&&n[0]&&(o=resolveReference(t,withDefault(e,n[0].skill.folder),r)),collect(a.warnings,s,o.warnings);let l={name:t,description:o.status===`found`?firstLine$1(o.metadata?.description):``,status:o.status};if(o.code&&(l.code=o.code),o.format&&o.format!==`markdown`&&(l.format=o.format),o.options){let e=n.map(({skill:e})=>`default of ${e.name}`);l.options=[...new Set([...o.options.filter(e=>e!=="default"),...e])]}a.references.push(l);for(let e of o.trace.layers)e.file!==void 0&&e.tier!=="default"&&a.layers.push(layerRow(t,e));for(let e of o.trace.projectSections)e.file!==void 0&&a.layers.push(projectRow(t,e));for(let{skill:i}of n)a.layers.push(defaultRow(t,i.name,i.folder,e,r))}return a}function defaultRow(e,t,n,r,i){return{...layerRow(e,resolveReference(e,withDefault(r,n),i).trace.layers.find(({tier:e,file:t})=>e==="default"&&t)),reachedBy:`the default step, when ${t} loads ${e}`}}const zn=[`name`,`prefix`,`close name`,`description`,`heading`,`body`];function distance(e,t){let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r++){let i=[r];for(let a=1;a<=t.length;a++){let o=n[a-1]+(e[r-1]===t[a-1]?0:1);i.push(Math.min(n[a]+1,i[a-1]+1,o))}n=i}return n[t.length]}function headings(e){let t=!1,n=[];for(let r of e.split(`
162
167
  `))/^ {0,3}(`{3,}|~{3,})/.test(r)?t=!t:!t&&/^ {0,3}#{1,6}\s/.test(r)&&n.push(r);return n.join(`
163
- `)}function tagText(e){return Array.isArray(e)?e.map(String).join(` `):typeof e==`string`?e:``}function matchKind(e,t,n){let r=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(r===n||e.toLowerCase()===n)return`name`;if(r.startsWith(n))return`prefix`;if(r.includes(n)||distance(r,n)<=Math.max(1,Math.floor(n.length/4)))return`close name`;let i=n.split(/\s+/),holds=e=>{let t=e.toLowerCase();return i.every(e=>t.includes(e))},a=t.metadata??{};return holds(`${typeof a.description==`string`?a.description:``} ${tagText(a.tags)}`)?`description`:textMatch(t.content??``,holds)}function textMatch(e,t){if(t(headings(e)))return`heading`;if(t(e))return`body`}function sectionMatchKind(e,t){let n=t.split(/\s+/),holds=e=>{let t=e.toLowerCase();return n.every(e=>t.includes(e))},{metadata:r}=e;return holds(`${typeof r.description==`string`?r.description:``} ${tagText(r.tags)}`)?`description`:textMatch(e.content,holds)}function searchReferences(e,t,n={}){let r=e.trim().toLowerCase();if(!r)throw new ReferenceFailure(`query-missing`,`search needs a query: what the reference is about.`,{help:"Run `reference list` for every name."});let i=[],a=new Set,considerSections=e=>{let t=parseReferenceName(e.name).name;for(let n of e.projectSections){let o=`${t}\0${n.folder}\0${n.plugin??``}`;if(a.has(o))continue;a.add(o);let s=sectionMatchKind(n,r);s&&i.push({name:e.name,description:firstLine$1(n.metadata.description),match:s,tier:`project`,folder:n.folder,...n.plugin===void 0?{}:{plugin:n.plugin}})}},consider=(e,t)=>{if(e.status!==`found`)return;considerSections(e);let n=matchKind(e.name,e,r);if(!n)return;let a=e.trace.contributions.at(-1),o={name:e.name,description:firstLine$1(e.metadata?.description),match:n,tier:a?.tier??`plugin`};a?.plugin!==void 0&&(o.plugin=a.plugin),a?.skill!==void 0&&(o.skill=a.skill),t!==void 0&&(o.loadedBy=t),i.push(o)},o=new Map;for(let e of catalogNames(t)){let r=resolveReference(e,t,n);if(o.set(e,r.content),r.status!==`ambiguous`)consider(r);else for(let e of r.options??[])e!=="default"&&consider(resolveReference(e,t,n))}for(let{name:e,skill:r}of skillHoldings(t)){let i=resolveReference(e,withDefault(t,r.folder),n);i.trace.layers.some(({tier:e,outcome:t})=>e==="default"&&t===`used`)&&i.content!==o.get(e)&&consider(i,r.name)}i.sort((e,t)=>Fn.indexOf(e.match)-Fn.indexOf(t.match)||e.name.localeCompare(t.name)||comparePaths(e.folder??``,t.folder??``));let s=defaultsUnverified(t);return s?{matches:i,defaults:s}:{matches:i}}function isTiered(e){return e===`managed`||e===`repo`||e===`project`||e===`user`}function hides(e){return!e.file||e.outcome!==`used`&&e.outcome!==`stale`?!1:e.operation===`remove`||e.operation===`replace`&&!e.empty}function stackTarget(e){return e.tier==="default"?`default`:e.plugin??``}function above(e,t,n){let r=e.trace.layers,i=r.findIndex(e=>e.path===t||e.path===n),a=r[i];if(!a)return[];let tiersAbove=e=>r.slice(0,e).filter(({tier:e})=>isTiered(e)).reverse();if(isTiered(a.tier))return tiersAbove(i);let{stack:o}=e.trace,s=o.indexOf(stackTarget(a));return[...s===-1?[]:r.filter(e=>!isTiered(e.tier)&&o.indexOf(stackTarget(e))>s).sort((e,t)=>o.indexOf(stackTarget(e))-o.indexOf(stackTarget(t))),...tiersAbove(r.length)]}function hiderLabel(e,t=e=>e){return`${e.tier}${e.plugin?` ${e.plugin}`:``} ${t(e.path)} (${e.operation})`}function hidingLayer(e,t,n){return above(e,t,n).find(hides)}function projectHidingLayer(e){return e.trace.layers.find(e=>e.tier===`managed`&&hides(e))}const In={"frontmatter-invalid":`defect`,"merge-unknown":`defect`,"marker-unknown":`defect`,"marker-unmatched":`defect`,"heading-repeated":`defect`,"remove-body-ignored":`defect`,"extends-invalid":`defect`,"extends-self":`defect`,"extends-step-missing":`environment`,"extends-all-missing":`environment`,"extends-not-used":`environment`,"section-not-held":`environment`,"default-not-selected":`environment`,"plugin-not-selected":`environment`,"default-folder-missing":`environment`,"default-in-tier":`defect`,"file-ignored":`defect`,"format-mismatch":`defect`,"metadata-ignored":`defect`,"project-section-key-ignored":`project-section`,"interface-not-composed":`defect`,"interface-check":`environment`,"base-moved":`environment`,"reference-stale":`environment`,"reference-renamed":`environment`,"alias-not-used":`environment`,"alias-invalid":`defect`,"project-section-not-markdown":`project-section`,"reference-hidden":`environment`,"repo-hides-user":`environment`};function splitComposeWarnings(e){let t=[],n=[];for(let r of e){let e=In[r.code];e===`defect`?t.push(r):e===`environment`&&n.push(r)}return{defects:t,passed:n}}function hiddenWarnings(e,t){let n=[],message=(e,n)=>`${t(e)} is hidden: ${n} applies above it, so load does not read it until that contribution changes`;for(let r of e.trace.layers){if(r.tier!==`repo`&&r.tier!==`user`||!r.file)continue;let i=hidingLayer(e,r.path,r.path);i&&n.push({code:r.tier===`user`&&i.tier===`repo`?`repo-hides-user`:`reference-hidden`,message:message(r.path,hiderLabel(i,t))})}let r=projectHidingLayer(e);if(r)for(let i of e.trace.projectSections)i.file&&i.plugin===void 0&&i.outcome.startsWith(`shadowed by`)&&n.push({code:`reference-hidden`,message:message(i.path,hiderLabel(r,t))});return n}function baseMovedWarnings(e,t){let n=[],r;for(let i of e.trace.layers){if(i.tier!==`plugin`&&i.tier!=="default"||!i.file||!i.frontmatter||i.outcome!==`used`&&i.outcome!==`stale`)continue;let{sources:e}=readGeneratedRecord(i.frontmatter);if(!e)continue;r??=sourceCatalog(t,{tier:`plugin`});let a=i.tier===`plugin`?`plugin ${i.plugin}`:`default of ${i.skill}`;for(let t of compareSources(e,r)){if(t.status!==`changed`)continue;let e=t.default===void 0?`plugin ${t.plugin}`:`the default of ${t.default} (plugin ${t.plugin})`;n.push({code:`base-moved`,message:`${a}: it records ${e} at ${t.recorded}, and ${t.installed??`a version with no number`} is installed; review it against the installed base and record the new version`})}}return n}function interfaceLookup(e,t={}){let n=new Map;return r=>{let i=n.get(r);if(i)return i;let a=lookUp(r,e,t);return n.set(r,a),a}}function lookUp(e,t,n){let r=resolveReference(`${e}${On}`,t,n);if(r.status===`missing`){let r=[...aliasIndex(t).interfaces].filter(([,t])=>t.some(({alias:t})=>t===e)).map(([e])=>e);if(r.length>1)return lookupFailure(e,`${e} is an older id of ${r.join(` and `)}; implement one of them by its own id`);if(r.length===1){let e=r[0],i=readFound(e,resolveReference(`${e}${On}`,t,n));return i.value?{...i,renamed:e}:i}}return readFound(e,r)}function lookupFailure(e,t){return{failure:{check:`interface-found`,interface:e,message:t}}}function readFound(e,t){let n=`${e}${On}`;if(t.status===`invalid`)return lookupFailure(e,`${e} is not an interface id`);if(t.status===`missing`)return lookupFailure(e,`no interface document ${n}`);if(t.status===`ambiguous`)return lookupFailure(e,`${n} is ambiguous between ${(t.options??[]).join(` and `)}`);let{value:r,problems:i}=readInterface(e,t.metadata??{});return r?{value:r}:lookupFailure(e,`${n} is malformed: ${i.join(`; `)}`)}function bareName$1(e){return e.slice(e.lastIndexOf(`/`)+1)}function kindOf(e){let t=e.metadata??{};return interfaceIdOf(bareName$1(e.name))!==void 0||t.interface!==void 0?`interface`:t.implements===void 0?`none`:`implementation`}function composeFailure(e){let{defects:t}=splitComposeWarnings(e);if(t.length)return{check:`compose`,message:`composing it raised ${t.length===1?`a warning`:`${t.length} warnings`}: ${t.map(({code:e,message:t})=>`${e}: ${t}`).join(`; `)}`}}function checkResolved(e,t,n){let r={failures:[],unsupported:[],warnings:[]};if(e.status!==`found`)return r;let{failures:i,warnings:a}=r,o=bareName$1(e.name),s=e.metadata??{};if(kindOf(e)===`interface`){let e=interfaceIdOf(o);if(e===void 0)i.push({check:`interface`,message:`${o} has an \`interface:\` block; an interface document is named <id>${On}`});else for(let t of readInterface(e,s).problems)i.push({check:`interface`,interface:e,message:t})}else{let{entry:c,problems:l}=readImplements(s);for(let e of l)i.push({check:`interface-found`,message:e});if(c){let s=t(c.id);if(s.value){let t=s.value.id;s.renamed!==void 0&&a.push({code:`reference-renamed`,message:`implements names ${c.id}@${c.version}, an older id of ${t}; declare implements: ${t}@${c.version}`});let l=checkImplementation(s.value,{name:o,version:c.version,content:e.content??``,accept:n?.id===t?n.versions:void 0,declaredId:c.id});i.push(...l.failures),r.unsupported=l.unsupported}else i.push(s.failure)}}let c=composeFailure(e.warnings);return c&&i.push(c),r}function dedupe(e){let t=new Set;return e.filter(({code:e,message:n})=>{let r=`${e} ${n}`;return!t.has(r)&&(t.add(r),!0)})}const warningKey=({code:e,message:t})=>`${e} ${t}`;function sectionWarnings({main:e,full:t}){if(t===e)return[];let n=new Set(e.warnings.map(warningKey));return t.warnings.filter(e=>!n.has(warningKey(e)))}function entryOf(e,t,n=[]){let{main:r,full:i}=e,a=r.status===`found`||i.status===`found`,o=r.status===`found`?checkResolved(r,t):{failures:[],unsupported:[],warnings:[]},s=[...o.failures];if(r.status!==`found`){!a&&r.code!==`reference-removed`&&s.push({check:r.code,message:r.message??r.status});let e=composeFailure(r.warnings);e&&s.push(e)}return{name:r.name,kind:r.status===`found`?kindOf(r):`none`,status:a?s.length?`failed`:`passed`:r.status,failures:s,unsupported:o.unsupported,warnings:dedupe([...o.warnings,...splitComposeWarnings(r.warnings).passed,...sectionWarnings(e),...n])}}function pluginCopies(e,t){let n=[...new Set(t.trace.layers.flatMap(({plugin:e,file:t})=>e!==void 0&&t?[e]:[]))];return n.length>1?n.map(t=>`${t}/${e}`):[]}function checkReferences(e,t={}){let{names:n,...r}=t,i=r.display??(e=>e),a={...r,projectSections:!1},o=interfaceLookup(e,r),s=Array.isArray(e)?void 0:e,c=new Set(s?.root===void 0?[]:projectSectionNames(s.root,s.projects,heldPlugins(s))),resolve=t=>{let n=parseReferenceName(t),i=resolveReference(n,e,a);return{main:i,full:n.plugin===void 0&&c.has(n.name)?resolveReference(n,e,r):i}},fileWarnings=({main:t,full:n})=>[...hiddenWarnings(n,i),...baseMovedWarnings(t,e)];if(n?.length)return n.map(e=>{let t=resolve(e);return entryOf(t,o,fileWarnings(t))});let l=[],u=new Map;for(let t of catalogNames(e)){let n=resolve(t);u.set(t,n.main.content),l.push(entryOf(n,o,fileWarnings(n)));for(let r of pluginCopies(t,n.main).map(resolve))l.push(entryOf(r,o,baseMovedWarnings(r.main,e)))}for(let{name:t,skill:n}of skillHoldings(e)){let r=withDefault(e,n.folder),i=resolveReference(t,r,a),s=i.trace.layers.some(({tier:e,outcome:t})=>e==="default"&&t===`used`);if(i.status!==`found`||!s)continue;let c=baseMovedWarnings(i,r);(i.content!==u.get(t)||c.length)&&l.push({...entryOf({main:i,full:i},o,c),loadedBy:n.name})}return l}function implementationTemplate(e){let t=e.sections.map(({heading:e,holds:t})=>`## ${e}\n\n**Unsupported.** ${t??`Replace this line with the section, or say in one sentence why it is not supported.`}\n`);return parseTemplate(`---\ndescription: What this ${e.id} implementation covers, and when an agent should read it.\nimplements: ${e.id}@${e.version}\n---\n\n${t.join(`
168
+ `)}function tagText(e){return Array.isArray(e)?e.map(String).join(` `):typeof e==`string`?e:``}function matchKind(e,t,n){let r=e.slice(e.lastIndexOf(`/`)+1).toLowerCase();if(r===n||e.toLowerCase()===n)return`name`;if(r.startsWith(n))return`prefix`;if(r.includes(n)||distance(r,n)<=Math.max(1,Math.floor(n.length/4)))return`close name`;let i=n.split(/\s+/),holds=e=>{let t=e.toLowerCase();return i.every(e=>t.includes(e))},a=t.metadata??{};return holds(`${typeof a.description==`string`?a.description:``} ${tagText(a.tags)}`)?`description`:textMatch(t.content??``,holds)}function textMatch(e,t){if(t(headings(e)))return`heading`;if(t(e))return`body`}function sectionMatchKind(e,t){let n=t.split(/\s+/),holds=e=>{let t=e.toLowerCase();return n.every(e=>t.includes(e))},{metadata:r}=e;return holds(`${typeof r.description==`string`?r.description:``} ${tagText(r.tags)}`)?`description`:textMatch(e.content,holds)}function searchReferences(e,t,n={}){let r=e.trim().toLowerCase();if(!r)throw new ReferenceFailure(`query-missing`,`search needs a query: what the reference is about.`,{help:"Run `reference list` for every name."});let i=[],a=new Set,considerSections=e=>{let t=parseReferenceName(e.name).name;for(let n of e.projectSections){let o=`${t}\0${n.folder}\0${n.plugin??``}`;if(a.has(o))continue;a.add(o);let s=sectionMatchKind(n,r);s&&i.push({name:e.name,description:firstLine$1(n.metadata.description),match:s,tier:`project`,folder:n.folder,...n.plugin===void 0?{}:{plugin:n.plugin}})}},consider=(e,t)=>{if(e.status!==`found`)return;considerSections(e);let n=matchKind(e.name,e,r);if(!n)return;let a=e.trace.contributions.at(-1),o={name:e.name,description:firstLine$1(e.metadata?.description),match:n,tier:a?.tier??`plugin`};a?.plugin!==void 0&&(o.plugin=a.plugin),a?.skill!==void 0&&(o.skill=a.skill),t!==void 0&&(o.loadedBy=t),i.push(o)},o=new Map;for(let e of catalogNames(t)){let r=resolveReference(e,t,n);if(o.set(e,r.content),r.status!==`ambiguous`)consider(r);else for(let e of r.options??[])e!=="default"&&consider(resolveReference(e,t,n))}for(let{name:e,skill:r}of skillHoldings(t)){let i=resolveReference(e,withDefault(t,r.folder),n);i.trace.layers.some(({tier:e,outcome:t})=>e==="default"&&t===`used`)&&i.content!==o.get(e)&&consider(i,r.name)}i.sort((e,t)=>zn.indexOf(e.match)-zn.indexOf(t.match)||e.name.localeCompare(t.name)||comparePaths(e.folder??``,t.folder??``));let s=defaultsUnverified(t);return s?{matches:i,defaults:s}:{matches:i}}function isTiered(e){return e===`managed`||e===`repo`||e===`project`||e===`user`}function hides(e){return!e.file||e.outcome!==`used`&&e.outcome!==`stale`?!1:e.operation===`remove`||e.operation===`replace`&&!e.empty}function stackTarget(e){return e.tier==="default"?`default`:e.plugin??``}function above(e,t,n){let r=e.trace.layers,i=r.findIndex(e=>e.path===t||e.path===n),a=r[i];if(!a)return[];let tiersAbove=e=>r.slice(0,e).filter(({tier:e})=>isTiered(e)).reverse();if(isTiered(a.tier))return tiersAbove(i);let{stack:o}=e.trace,s=o.indexOf(stackTarget(a));return[...s===-1?[]:r.filter(e=>!isTiered(e.tier)&&o.indexOf(stackTarget(e))>s).sort((e,t)=>o.indexOf(stackTarget(e))-o.indexOf(stackTarget(t))),...tiersAbove(r.length)]}function hiderLabel(e,t=e=>e){return`${e.tier}${e.plugin?` ${e.plugin}`:``} ${t(e.path)} (${e.operation})`}function hidingLayer(e,t,n){return above(e,t,n).find(hides)}function projectHidingLayer(e){return e.trace.layers.find(e=>e.tier===`managed`&&hides(e))}const Bn={"frontmatter-invalid":`defect`,"merge-unknown":`defect`,"marker-unknown":`defect`,"marker-unmatched":`defect`,"heading-repeated":`defect`,"remove-body-ignored":`defect`,"extends-invalid":`defect`,"extends-self":`defect`,"extends-step-missing":`environment`,"extends-all-missing":`environment`,"extends-not-used":`environment`,"section-not-held":`environment`,"default-not-selected":`environment`,"plugin-not-selected":`environment`,"default-folder-missing":`environment`,"default-in-tier":`defect`,"file-ignored":`defect`,"format-mismatch":`defect`,"metadata-ignored":`defect`,"project-section-key-ignored":`project-section`,"interface-not-composed":`defect`,"interface-check":`environment`,"base-moved":`environment`,"reference-stale":`environment`,"reference-renamed":`environment`,"alias-not-used":`environment`,"rename-invalid":`environment`,"reference-legacy-format":`defect`,"alias-invalid":`defect`,"project-section-not-markdown":`project-section`,"reference-hidden":`environment`,"repo-hides-user":`environment`};function splitComposeWarnings(e){let t=[],n=[];for(let r of e){let e=Bn[r.code];e===`defect`?t.push(r):e===`environment`&&n.push(r)}return{defects:t,passed:n}}function hiddenWarnings(e,t){let n=[],message=(e,n)=>`${t(e)} is hidden: ${n} applies above it, so load does not read it until that contribution changes`;for(let r of e.trace.layers){if(r.tier!==`repo`&&r.tier!==`user`||!r.file)continue;let i=hidingLayer(e,r.path,r.path);i&&n.push({code:r.tier===`user`&&i.tier===`repo`?`repo-hides-user`:`reference-hidden`,message:message(r.path,hiderLabel(i,t))})}let r=projectHidingLayer(e);if(r)for(let i of e.trace.projectSections)i.file&&i.plugin===void 0&&i.outcome.startsWith(`shadowed by`)&&n.push({code:`reference-hidden`,message:message(i.path,hiderLabel(r,t))});return n}function baseMovedWarnings(e,t){let n=[],r;for(let i of e.trace.layers){if(i.tier!==`plugin`&&i.tier!=="default"||!i.file||!i.frontmatter||i.outcome!==`used`&&i.outcome!==`stale`)continue;let{sources:e}=readGeneratedRecord(i.frontmatter);if(!e)continue;r??=sourceCatalog(t,{tier:`plugin`});let a=i.tier===`plugin`?`plugin ${i.plugin}`:`default of ${i.skill}`;for(let t of compareSources(e,r)){if(t.status!==`changed`)continue;let e=t.default===void 0?`plugin ${t.plugin}`:`the default of ${t.default} (plugin ${t.plugin})`;n.push({code:`base-moved`,message:`${a}: it records ${e} at ${t.recorded}, and ${t.installed??`a version with no number`} is installed; review it against the installed base and record the new version`})}}return n}function interfaceLookup(e,t={}){let n=new Map;return r=>{let i=n.get(r);if(i)return i;let a=lookUp(r,e,t);return n.set(r,a),a}}function lookUp(e,t,n){let r=resolveReference(`${e}${W}`,t,n),i=interfaceIdOf(r.trace.alias?.resolvedAs??``);if(i!==void 0){let e=readFound(i,r);return e.value?{...e,renamed:i}:e}if(r.status===`missing`){let r=[...aliasIndex(t).interfaces].filter(([,t])=>t.some(({alias:t})=>t===e)).map(([e])=>e);if(r.length>1)return lookupFailure(e,`${e} is an older id of ${r.join(` and `)}; implement one of them by its own id`);if(r.length===1){let e=r[0],i=readFound(e,resolveReference(`${e}${W}`,t,n));return i.value?{...i,renamed:e}:i}}return readFound(e,r)}function lookupFailure(e,t){return{failure:{check:`interface-found`,interface:e,message:t}}}function readFound(e,t){let n=`${e}${W}`;if(t.status===`invalid`)return lookupFailure(e,`${e} is not an interface id`);if(t.status===`missing`)return lookupFailure(e,`no interface document ${n}`);if(t.status===`ambiguous`)return lookupFailure(e,`${n} is ambiguous between ${(t.options??[]).join(` and `)}`);let{value:r,problems:i}=readInterface(e,t.metadata??{});return r?{value:r}:lookupFailure(e,`${n} is malformed: ${i.join(`; `)}`)}function bareName$1(e){let t=e.trace.alias?.resolvedAs??e.name;return t.slice(t.lastIndexOf(`/`)+1)}function kindOf(e){let t=e.metadata??{};return interfaceIdOf(bareName$1(e))!==void 0||t.interface!==void 0?`interface`:t.implements===void 0?`none`:`implementation`}function composeFailure(e){let{defects:t}=splitComposeWarnings(e);if(t.length)return{check:`compose`,message:`composing it raised ${t.length===1?`a warning`:`${t.length} warnings`}: ${t.map(({code:e,message:t})=>`${e}: ${t}`).join(`; `)}`}}function checkResolved(e,t,n){let r={failures:[],unsupported:[],warnings:[]};if(e.status!==`found`)return r;let{failures:i,warnings:a}=r,o=bareName$1(e),s=e.metadata??{};if(kindOf(e)===`interface`){let e=interfaceIdOf(o);if(e===void 0)i.push({check:`interface`,message:`${o} has an \`interface:\` block; an interface document is named <id>${W}`});else for(let t of readInterface(e,s).problems)i.push({check:`interface`,interface:e,message:t})}else{let{entry:c,problems:l}=readImplements(s);for(let e of l)i.push({check:`interface-found`,message:e});if(c){let s=t(c.id);if(s.value){let t=s.value.id;s.renamed!==void 0&&a.push({code:`reference-renamed`,message:`implements names ${c.id}@${c.version}, an older id of ${t}; declare implements: ${t}@${c.version}`});let l=checkImplementation(s.value,{name:o,version:c.version,content:e.content??``,accept:n?.id===t?n.versions:void 0,declaredId:c.id});i.push(...l.failures),r.unsupported=l.unsupported}else i.push(s.failure)}}let c=composeFailure(e.warnings);return c&&i.push(c),r}function dedupe(e){let t=new Set;return e.filter(({code:e,message:n})=>{let r=`${e} ${n}`;return!t.has(r)&&(t.add(r),!0)})}const warningKey=({code:e,message:t})=>`${e} ${t}`;function sectionWarnings({main:e,full:t}){if(t===e)return[];let n=new Set(e.warnings.map(warningKey));return t.warnings.filter(e=>!n.has(warningKey(e)))}function entryOf(e,t,n=[]){let{main:r,full:i}=e,a=r.status===`found`||i.status===`found`,o=r.status===`found`?checkResolved(r,t):{failures:[],unsupported:[],warnings:[]},s=[...o.failures];if(r.status!==`found`){!a&&r.code!==`reference-removed`&&s.push({check:r.code,message:r.message??r.status});let e=composeFailure(r.warnings);e&&s.push(e)}return{name:r.name,kind:r.status===`found`?kindOf(r):`none`,status:a?s.length?`failed`:`passed`:r.status,failures:s,unsupported:o.unsupported,warnings:dedupe([...o.warnings,...splitComposeWarnings(r.warnings).passed,...sectionWarnings(e),...n])}}function pluginCopies(e,t){let n=[...new Set(t.trace.layers.flatMap(({plugin:e,file:t})=>e!==void 0&&t?[e]:[]))];return n.length>1?n.map(t=>`${t}/${e}`):[]}function checkReferences(e,t={}){let{names:n,...r}=t,i=r.display??(e=>e),a={...r,projectSections:!1},o=interfaceLookup(e,r),s=Array.isArray(e)?void 0:e,c=new Set(s?.root===void 0?[]:[...projectSectionNames(s.root,s.projects,heldPlugins(s)),...projectQualifiedNames(s.root,s.projects)]),resolve=t=>{let n=parseReferenceName(t),i=resolveReference(n,e,a);return{main:i,full:n.plugin===void 0&&c.has(n.name)?resolveReference(n,e,r):i}},fileWarnings=({main:t,full:n})=>[...hiddenWarnings(n,i),...baseMovedWarnings(t,e)];if(n?.length)return n.map(e=>{let t=resolve(e);return entryOf(t,o,fileWarnings(t))});let l=[],u=new Map;for(let t of catalogNames(e)){let n=resolve(t);u.set(t,n.main.content),l.push(entryOf(n,o,fileWarnings(n)));for(let r of pluginCopies(t,n.main).map(resolve))l.push(entryOf(r,o,baseMovedWarnings(r.main,e)))}for(let{name:t,skill:n}of skillHoldings(e)){let r=withDefault(e,n.folder),i=resolveReference(t,r,a),s=i.trace.layers.some(({tier:e,outcome:t})=>e==="default"&&t===`used`);if(i.status!==`found`||!s)continue;let c=baseMovedWarnings(i,r);(i.content!==u.get(t)||c.length)&&l.push({...entryOf({main:i,full:i},o,c),loadedBy:n.name})}return l}function implementationTemplate(e){let t=e.sections.map(({heading:e,holds:t})=>`## ${e}\n\n**Unsupported.** ${t??`Replace this line with the section, or say in one sentence why it is not supported.`}\n`);return parseTemplate(`---\ndescription: What this ${e.id} implementation covers, and when an agent should read it.\nimplements: ${e.id}@${e.version}\n---\n\n${t.join(`
164
169
  `)}`,`the ${e.id} interface`)}function readTemplate(e){if(e===void 0)return parseTemplate(`---
165
170
  description: What this reference covers, and when an agent should read it.
166
171
  tags: [topic]
@@ -169,12 +174,12 @@ tags: [topic]
169
174
  ## Overview
170
175
 
171
176
  Write the guidance here. Give each topic its own top-level \`##\` section.
172
- `,`the default template`);let t;try{t=a(e,`utf8`)}catch(t){throw new ReferenceFailure(`template-invalid`,`cannot read the template ${e}: ${t.message}`,{details:{path:e}})}return parseTemplate(t,`the template ${e}`)}function parseTemplate(e,t){let n=!0,{metadata:r,body:i}=parseDocument(e,()=>{n=!1});if(!n)throw new ReferenceFailure(`template-invalid`,`${t} has frontmatter that is not a YAML mapping.`);return{content:e,metadata:r,body:i}}function titleOf({body:e}){let t=parseSections(e,()=>{}),[n]=t.children;return t.children.length===1&&n?.children.length?n.heading.trim():void 0}function hasDescription({metadata:e}){return typeof e.description==`string`&&e.description.trim().length>0}function editFrontmatter(e,t){let n=Sn.exec(e),r=n?e.slice(n[0].length):e,i=(0,Qt.parseDocument)(n?n[1]:``);for(let[e,n]of Object.entries(t))if(n===void 0)(0,Qt.isMap)(i.contents)&&i.delete(e);else{let t=Array.isArray(n)&&n.every(e=>typeof e!=`object`||!e),r=i.createNode(n,{flow:t});i.set(e,r)}if(!i.contents?.items?.length)return r.replace(/^(?:[ \t]*\r?\n)+/,``);let a=!n&&r.trim()?`
177
+ `,`the default template`);let t;try{t=a(e,`utf8`)}catch(t){throw new ReferenceFailure(`template-invalid`,`cannot read the template ${e}: ${t.message}`,{details:{path:e}})}return parseTemplate(t,`the template ${e}`)}function parseTemplate(e,t){let n=!0,{metadata:r,body:i}=parseDocument(e,()=>{n=!1});if(!n)throw new ReferenceFailure(`template-invalid`,`${t} has frontmatter that is not a YAML mapping.`);return{content:e,metadata:r,body:i}}function titleOf({body:e}){let t=parseSections(e,()=>{}),[n]=t.children;return t.children.length===1&&n?.children.length?n.heading.trim():void 0}function hasDescription({metadata:e}){return typeof e.description==`string`&&e.description.trim().length>0}function editFrontmatter(e,t){let n=wn.exec(e),r=n?e.slice(n[0].length):e,i=(0,en.parseDocument)(n?n[1]:``);for(let[e,n]of Object.entries(t))if(n===void 0)(0,en.isMap)(i.contents)&&i.delete(e);else{let t=Array.isArray(n)&&n.every(e=>typeof e!=`object`||!e),r=i.createNode(n,{flow:t});i.set(e,r)}if(!i.contents?.items?.length)return r.replace(/^(?:[ \t]*\r?\n)+/,``);let a=!n&&r.trim()?`
173
178
  `:``;return`---\n${i.toString({lineWidth:0,flowCollectionPadding:!1})}---\n${a}${r}`}function baseLayers(e,t){let n=t.scope===`user`,r=e.layers.filter(e=>n?e.tier!==`repo`&&(e.tier!==`plugin`||e.origin!==`dependency`):e.tier!==`user`),i=n?e.plugins?.filter(({origin:e})=>e!==`dependency`):e.plugins;return{...e,layers:r,...i?{plugins:i}:{}}}function structureOnly(e,t){return e.entry.empty=!0,{...e,body:``,hasBody:!1,merge:void 0,steps:t}}function resolveBase(e,t,n,r,i={}){let a=i.display??(e=>e),adjust=(t,i,o)=>{if(t.tier===`managed`){if(!i)return;if(i.whole){o.outcome=`not read (managed text is left out)`;return}return structureOnly(i,i.steps)}if(n.scope===`project`||t.dir!==n.dir)return i;let s=r===void 0?i?.steps:r??void 0;if(!s){i&&(o.outcome=`not read (the target is left out)`);return}return i&&!i.whole?structureOnly(i,s):(Object.assign(o,{path:n.path,file:`${e.name}.md`,outcome:``,selection:!0}),{layer:t,entry:o,label:contributionLabel(t,n.path,a),path:n.path,metadata:{},body:``,hasBody:!1,format:`markdown`,whole:!1,merge:void 0,steps:s})},o=resolveAdjusted(e,baseLayers(t,n),i,adjust),s=n.folder,c=s===void 0?[]:o.projectSections.filter(e=>s.startsWith(`${e.folder}/`)||e.folder===s&&e.plugin!==void 0);return{...o,projectSections:c}}function generatorBase(e,t){let n=t?implementationTemplate(t).body.trim():void 0,r=[n,e.status===`found`?(e.content??``).trim():``].filter(e=>!!e),i={content:r.length?`${r.join(`
174
179
 
175
- `)}\n`:``,projectSections:e.status===`found`?e.projectSections:[],resolved:e};return n!==void 0&&(i.stub=`${n}\n`),i}function bareName(e){requireName(e);let t=parseReferenceName(e);if(t.invalid)throw new ReferenceFailure(`name-invalid`,t.invalid);if(t.plugin!==void 0)throw new ReferenceFailure(`reference-qualified`,`a contribution is written under the bare name, which every tier resolves; ask for "${t.name}".`);return t}function insideRepository(e,t){let n=canonical(T(t)),r=canonical(e);return r!==n&&!r.startsWith(n+E)?!1:!r.slice(n.length).split(E).includes(`node_modules`)}function below(e,t){let n=w(e,t);return n&&!n.startsWith(`..`)&&!x(n)?n:void 0}function inFolder(e,t){let n=T(e),r=below(T(t),n)??below(canonical(T(t)),canonical(n));if(r===void 0)throw new ReferenceFailure(`in-not-below-root`,`--in names ${n}, which is ${n===T(t)?`the root itself`:`outside the root`}; a project section is written for a folder strictly below the root ${T(t)}.`);return{folder:r.split(E).join(`/`),path:n}}function checkPlaces(e,t){if([e.scope,e.in,e.plugin,e.default].filter(e=>e!==void 0).length>1)throw new ReferenceFailure(`options-conflict`,`pass one of ${t}.`)}function checkScope(e){if(e!==void 0&&e!==`repo`&&e!==`user`)throw new ReferenceFailure(`option-invalid`,`--scope is repo or user; got "${e}".`)}function sourceFolder(e,t,n){let r=T(e);if(!(n===`plugin`?pluginManifestName(r):skillName(r)!==void 0))throw new ReferenceFailure(`folder-invalid`,n===`plugin`?`${r} holds no plugin manifest, so it is not a plugin folder.`:`${r} holds no SKILL.md, so it is not a skill folder.`);if(!insideRepository(r,t))throw new ReferenceFailure(`folder-invalid`,`${r} is outside the repository, such as an installed copy; write to the ${n}'s source instead.`);return r}function writeTarget$1(e,t){let{root:n,home:r,scope:i,plugin:a,default:o}=t;if(a!==void 0){let t=S(sourceFolder(a,n,`plugin`),`references`);return{scope:`plugin`,dir:t,path:S(t,`${e.name}.md`)}}if(o!==void 0){let t=S(sourceFolder(o,n,`skill`),`references`);return{scope:`default`,dir:t,path:S(t,`${e.name}.default.md`)}}if(t.in!==void 0){let{folder:r,path:i}=inFolder(t.in,n),a=S(i,`.agents`,`references`);return{scope:`project`,dir:a,path:S(a,`${e.name}.md`),folder:r,folderPath:i}}let s=i===`user`?userReferencesDir(r):repoReferencesDir(T(n));return{scope:i===`user`?`user`:`repo`,dir:s,path:S(s,`${e.name}.md`)}}__name(writeTarget$1,`writeTarget`);function targetFiles(e,t){return candidateFiles({tier:e.scope==="default"?`default`:`repo`},t).map(t=>S(e.dir,...t.split(`/`)))}function answeringFile(e,t,r){return targetFiles(e,t).find(e=>e!==r&&n(e))}function metadataFile(e,t){return S(e.dir,`${t}${e.scope==="default"?`.default`:``}.meta.md`)}function reachOf(e){return e.scope===`user`?`only you, in every repository`:e.scope===`project`?`everyone working in ${e.folder}`:`everyone working in this repository`}const Ln=`a project section carries no merge (K24); drop --merge or --in.`;function readPicks(e,t){if(e.includes(`none`)){if(e.length>1)throw new ReferenceFailure(`option-invalid`,`--extends none removes the picks, so it takes no other step; got ${e.join(` `)}.`);return`none`}if(!e.length)throw new ReferenceFailure(`option-invalid`,`--extends names one or more steps, or none.`);return{values:e.map(e=>{let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?void 0:e.slice(n+1),a=r.endsWith(`/${t}`)?r.slice(0,-t.length-1):r;if(!H.test(a))throw new ReferenceFailure(`option-invalid`,`--extends takes a plugin, \`<plugin>/${t}\`, or default, each optionally \`:<merge>\`; got "${e}".`);if(i===void 0)return a;if(!isMergeOperation(i))throw new ReferenceFailure(`option-invalid`,`the merge in "${e}" is replace, patch, combine, or remove; got "${i}".`);return{[a]:i}})}}function customizeUsage(e,t){let n=e.extends!==void 0||e.extendsFile!==void 0,r=e.request!==void 0||e.body!==void 0;if(!e.base&&!n&&!r)throw new ReferenceFailure(`change-missing`,`say what to change: --extends or --extends-file picks what the name builds on, and --request with --body writes a generated body.`,{help:`Run \`reference customize ${t.name} --base\` for what the generator reads.`});let conflict=e=>new ReferenceFailure(`options-conflict`,e);if(e.plugin!==void 0)throw conflict("customize never writes a file a plugin ships; an author writes one with `create --plugin`.");if(e.scope!==void 0&&e.in!==void 0)throw conflict(`pass --scope or --in, not both: a customization goes to one place.`);if(e.in!==void 0&&e.merge!==void 0)throw conflict(Ln);if(e.in!==void 0&&n)throw conflict(`a project section has no stack, so it takes no picks; pick for the main document with --scope.`);if(e.extends!==void 0&&e.extendsFile!==void 0)throw conflict(`pass --extends or --extends-file, not both.`);if(e.implements!==void 0&&n)throw conflict(`an implementation is a whole document that replaces the stack, so it takes no picks.`);if(e.base&&(r||e.merge!==void 0||e.dryRun))throw conflict(`--base writes nothing; it takes only --extends or --extends-file, --scope or --in, --default, and --implements.`);if(r&&e.extends?.includes(`none`))throw conflict(`--extends none removes the picks and writes no body; pass it without --request and --body.`);if(r&&(e.request===void 0||e.body===void 0))throw new ReferenceFailure(`options-missing`,e.request===void 0?`--body needs --request: a generated body records the request it was written from.`:`--request needs --body: the command writes the body the generator wrote, and runs no model.`);checkScope(e.scope),checkMerge(e.merge);let i=e.extends===void 0?void 0:readPicks(e.extends,t.name);return e.in!==void 0&&inFolder(e.in,e.root),i?{picks:i}:{}}function checkMerge(e){if(e!==void 0&&!isMergeOperation(e))throw new ReferenceFailure(`option-invalid`,`--merge is replace, patch, combine, or remove; got "${e}".`)}function checkUsage(e){let t=bareName(e.name);if(e.command===`customize`)return{name:t,merge:e.merge,...customizeUsage(e,t)};if(checkPlaces(e,`--scope, --in, --plugin, and --default`),e.command===`create`&&e.in!==void 0&&e.merge!==void 0)throw new ReferenceFailure(`options-conflict`,Ln);checkScope(e.scope),checkMerge(e.merge);let n=e.merge;if(e.in!==void 0&&inFolder(e.in,e.root),e.command===`create`){if(n===`remove`&&e.template!==void 0)throw new ReferenceFailure(`remove-with-template`,`--merge remove writes no body, so it takes no --template.`);if(e.template!==void 0&&e.implements!==void 0)throw new ReferenceFailure(`template-with-implements`,`pass --template or --implements, not both.`)}return{name:t,merge:n}}function lookUpInterface(e,t,n){let r=parseReferenceName(e);if(r.invalid||r.plugin!==void 0)throw new ReferenceFailure(`interface-invalid`,`"${e}" is not an interface id.`);let i=interfaceLookup(t,n)(e);if(!i.value)throw new ReferenceFailure(`interface-invalid`,i.failure?.message??`no interface ${e}`);return i.value}function tryRead$1(e){try{return a(e,`utf8`)}catch{return}}function operationOf(e,t,n,r){if(t.scope===`project`)return;if(e.implements!==void 0)return`replace`;if(t.scope===`plugin`||t.scope==="default")return n;let i=r.metadata.merge;return n??(isMergeOperation(i)?i:void 0)??`patch`}function validateWrite(e,t,n={}){let r=checkUsage(e);if(!t)return r;let{name:i,merge:a}=r,o=n.display??(e=>e);if(!isDirectory$3(e.root))throw new ReferenceFailure(`root-missing`,`the root ${e.root} does not exist or is not a folder.`,{details:{root:e.root}});if(e.command===`customize`)return planCustomize(e,r,t,n);let s=writeTarget$1(i,e);if(e.command===`delete`)return checkFolder(s,i.name),{name:i,merge:a,target:s,before:resolveReference(i,t,n),extended:[]};let c=e.implements!==void 0||a===`remove`?{content:``,metadata:{},body:``}:readTemplate(e.template),l=titleOf(c);if(l)throw new ReferenceFailure(`template-title`,`the template's top level is the single heading "${l}" holding the others; patch matches by heading path, so make its sections top-level.`);let u=e.implements===void 0?void 0:lookUpInterface(e.implements,t,n);checkNamespace(u,s,i);let d=u?implementationTemplate(u):c;checkFolder(s,i.name);let f=resolveReference(i,t,n);checkMarkdown(f,s,i);let p={name:i,merge:a,target:s,template:d,before:f,extended:[]};u&&(p.iface=u);let m=tryRead$1(s.path),h=m===void 0?void 0:parseDocument(m,()=>{});if(p.operation=operationOf(e,s,a,d),p.extended=(readExtends(h?.metadata.extends,()=>{})??readExtends(d.metadata.extends,()=>{})??[]).map(({target:e})=>e).filter(e=>e!=="default"),(s.scope===`plugin`||s.scope==="default")&&p.operation===`replace`&&p.extended.length)throw new ReferenceFailure(`extends-replace`,`a ${s.scope===`plugin`?`plugin's file`:`skill's default`} that extends ${p.extended.join(`, `)} states only the sections it changes, so it takes no merge: replace; to replace the base entirely, write a snapshot of your own with no extends on it.`);if(h&&hasBody(h.body))throw new ReferenceFailure(`file-exists`,`${o(s.path)} already holds "${i.name}"; change it with the reference skill's Update mode.`,{details:{path:o(s.path)}});let g=answeringFile(s,i.name,s.path)??selectingSidecar(s,i.name);if(g)throw new ReferenceFailure(`file-exists`,`${o(g)} already answers "${i.name}" in that folder; change it there, or delete it first.`,{details:{path:o(g)}});return m!==void 0&&(p.existing=m),p}function selectingSidecar(e,t){if(e.scope===`project`)return;let n=metadataFile(e,t),r=tryParse(tryRead$1(n));return r&&r.metadata.extends!==void 0?n:void 0}function checkFolder(e,t){if(e.scope===`project`&&e.folderPath!==void 0&&e.folder!==void 0){if(!isDirectory$3(e.folderPath))throw new ReferenceFailure(`in-folder-missing`,`--in names ${e.folderPath}, which does not exist.`,{details:{folder:e.folder}});if(gitIgnores(e.folderPath,e.path))throw new ReferenceFailure(`in-folder-ignored`,`git ignores ${e.folder}/.agents/references/${t}.md, so load would never read a project section there.`,{details:{folder:e.folder}})}}function checkNamespace(e,t,n){if(!e||t.scope===`project`||fitsName(e,n.name))return;let r=e.cardinality===`one`?e.id:`${e.id}.<key>`;throw new ReferenceFailure(`name-outside-interface`,`an implementation of ${e.id} is named ${r}, not "${n.name}".`,{help:`Name it ${r}, or write it for one folder with --in.`})}function checkMarkdown(e,t,n){if(t.scope===`project`&&e.status===`found`&&e.format!==`markdown`)throw new ReferenceFailure(`in-not-markdown`,`the main document of "${n.name}" is ${e.format}, which has no project sections; customize the main document instead.`)}function readGiven(e,t){try{return a(e,`utf8`)}catch(n){throw new ReferenceFailure(`file-unreadable`,`cannot read the ${t} file ${e}: ${n.message}`,{details:{path:e}})}}function isStep(e){if(typeof e==`string`)return H.test(e);if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);if(t.length!==1)return!1;let[n,r]=t[0];if(!H.test(n))return!1;if(r==null)return!0;if(typeof r==`string`)return isMergeOperation(r);if(typeof r!=`object`||Array.isArray(r))return!1;let i=r;return Object.keys(i).some(e=>e!==`merge`&&e!==`extends`&&e!==`sections`)||i.merge!==void 0&&!isMergeOperation(i.merge)||i.sections!==void 0&&!Array.isArray(i.sections)?!1:i.extends===void 0||Array.isArray(i.extends)&&i.extends.every(isStep)}function readExtendsFile(e){let invalid=t=>new ReferenceFailure(`extends-file-invalid`,`the --extends-file ${e} ${t}.`,{details:{path:e}}),t;try{t=a(e,`utf8`)}catch(e){throw invalid(`cannot be read: ${e.message}`)}let n;try{n=(0,Qt.parse)(t)}catch(e){throw invalid(`is not YAML: ${e.message}`)}let r=n&&typeof n==`object`&&!Array.isArray(n)?n.extends:n;if(!Array.isArray(r)||!r.length||!r.every(isStep))throw invalid("is not a YAML `extends` list: each step a plugin or default, with only merge, extends, and sections");return{values:r}}function stepsOf(e){if(e===void 0)return;if(e===`none`)return null;let strip=e=>{if(typeof e!=`object`||!e)return e;let[t,n]=Object.entries(e)[0];if(typeof n!=`object`||!n)return e;let{sections:r,extends:i,...a}=n;return{[t]:Array.isArray(i)?{...a,extends:i.map(strip)}:a}};return readExtends(e.values.map(strip),()=>{})??[]}function checkSteps(e,t,n,r){let i=new Set(r.layers.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[])),a=new Set(n.trace.layers.flatMap(({tier:e,plugin:t,file:n})=>e===`plugin`&&t!==void 0&&n&&i.has(t)?[t]:[])),o=e.map(({target:e})=>e).filter(e=>e!=="default"&&!a.has(e));if(o.length)throw new ReferenceFailure(`step-invalid`,`${o.join(`, `)} ${o.length===1?`is`:`are`} neither default nor a plugin holding "${t}"${a.size?`; the plugins holding it are ${[...a].join(`, `)}`:``}.`,{details:{steps:o}})}function coveringInterface(e,t,n){let r=interfaceLookup(t,n),i=e.split(`.`);for(let t=i.length;t>=1;t--){let n=r(i.slice(0,t).join(`.`)).value;if(n&&fitsName(n,e))return n}}function tryParse(e){return e===void 0?void 0:parseDocument(e,()=>{})}function customizeFiles(e,t,n){let r=e.scope===`project`?[e.path,S(e.dir,t,`README.md`)]:[e.path,S(e.dir,t,`README.md`),...V.map(({extension:n})=>S(e.dir,`${t}${n}`))],i=answeringFile(e,t),a=i!==void 0&&r.includes(i)?i:void 0,o=S(e.dir,t,`README.md`),s=e.path,c=`markdown`;if(a!==void 0&&a!==o)s=a,c=formatOfFile(a);else if(a===void 0&&e.scope!==`project`&&n.status===`found`&&n.format!==void 0&&n.format!==`markdown`){c=n.format;let r=[...n.trace.contributions].reverse().find(({path:e})=>formatOfFile(e)===c),i=r?b(r.path):V.find(e=>e.format===c)?.extension;s=S(e.dir,`${t}${i}`)}return{file:s,format:c,holder:c===`markdown`?s:metadataFile(e,t),other:a===o?o:void 0}}function quietInterface(e,t,n){let r=Array.isArray(e)?e[0]:e,i=typeof r==`string`?/^(.+)@\d+$/.exec(r.trim())?.[1]:void 0;return i===void 0?void 0:interfaceLookup(t,n)(i).value}function planCustomize(e,t,n,r){let{name:i}=t,a=r.display??(e=>e),o=writeTarget$1(i,{root:e.root,home:e.home,scope:e.scope,in:e.in}),s=e.request===void 0?void 0:readGiven(e.request,`--request`),c=e.body===void 0?void 0:readGiven(e.body,`--body`),l=e.extendsFile===void 0?t.picks:readExtendsFile(e.extendsFile),u=e.implements===void 0?void 0:lookUpInterface(e.implements,n,r);checkNamespace(u,o,i),checkFolder(o,i.name);let d=resolveReference(i,n,r);checkMarkdown(d,o,i);let f=stepsOf(l);f&&checkSteps(f,i.name,d,baseLayers(n,o));let p=customizeFiles(o,i.name,d),m=tryRead$1(p.file),h=p.holder===p.file?m:tryRead$1(p.holder),g=tryParse(h),_=u||o.scope===`project`?void 0:g?.metadata.implements,v=u??(_===void 0?void 0:quietInterface(_,n,r)),y=resolveBase(i,n,o,f,r),b=s!==void 0||!!e.base;if(b&&l===void 0&&y.status===`ambiguous`)throw new ReferenceFailure(`pick-required`,`"${i.name}" is ambiguous: ${y.message}; pick what it builds on before the request is applied.`,{details:{options:y.options??[]},help:`Pass --extends with the picks, bottom first, from: ${(y.options??[]).join(`, `)}.`});if(b&&!v&&_===void 0&&y.status===`missing`){let e=coveringInterface(i.name,n,r);if(e)throw new ReferenceFailure(`implements-required`,`"${i.name}" is in the namespace of the interface ${e.id}, and nothing implements it; name the interface.`,{details:{interface:e.id},help:`Run \`reference customize ${i.name} --implements ${e.id} --request <file> --body <file>\`.`})}let x=p.format===`markdown`?hasBody(g?.body??``):!!m?.trim();if(s!==void 0&&x&&!isGenerated(g?.metadata))throw new ReferenceFailure(`body-not-generated`,`${a(p.file)} holds a body that records no request, written with create or by hand; customizing would replace it.`,{details:{path:a(p.file)},help:`Change it with the reference skill's Update mode, or delete it first.`});if(p.other&&!e.base)throw new ReferenceFailure(`file-exists`,`${a(p.other)} already answers "${i.name}" in that folder; change it there, or delete it first.`,{details:{path:a(p.other)}});let S={...t,picks:l,target:o,before:d,base:y,file:p.file,format:p.format,holder:p.holder};return f!==void 0&&(S.steps=f),s!==void 0&&(S.request=s),c!==void 0&&(S.body=c),v&&(S.iface=v),u?S.implementsValue=`${u.id}@${u.version}`:typeof _==`string`&&(S.implementsValue=_),m!==void 0&&(S.existing=m),h!==void 0&&(S.held=h),S}function tryRead(e){try{return a(e,`utf8`)}catch{return}}function describeAnswer(e,t=e=>e){if(e.status===`found`){let n=e.trace.contributions.at(-1),r=n?n.tier===`plugin`?`plugin ${n.plugin}`:n.tier==="default"?`the default of ${n.skill}`:`the ${n.tier} file ${t(n.path)}`:void 0,i=e.trace.stack.length?`, on the stack ${e.trace.stack.join(` → `)}`:``,a=[...new Set(e.projectSections.map(({folder:e})=>e))];if(!r)return`"${e.name}" is answered only by the project sections of ${a.join(`, `)}.`;let o=a.length?`, with the project sections of ${a.join(`, `)}`:``;return`"${e.name}" is answered by ${r}${i}${o}.`}return e.status===`ambiguous`?`"${e.name}" is ambiguous: ${e.message}; the options are ${(e.options??[]).join(`, `)}.`:`"${e.name}" is ${e.status}: ${e.message}.`}const Rn=[`merge`,`extends`,`implements`,`aliases`];function selectionKeys(e,t){let n=parseDocument(e,()=>{}).metadata,r={};for(let[e,i]of Object.entries(t.metadata))e!==`merge`&&!(e in n)&&(r[e]=i);return r}function withBody(e,t){let n=t.replace(/^(?:[ \t]*\r?\n)+/,``);return n?`${e.replace(/\s*$/,``)}\n\n${n}`:e}function hiddenWarning(e,t,n,r){let i=t.scope===`project`?projectHidingLayer(e):hidingLayer(e,t.dir,t.path);if(i)return{code:t.scope===`user`&&i.tier===`repo`?`repo-hides-user`:`reference-hidden`,message:`${r(n)} is written, but ${hiderLabel(i,r)} applies above it, so load does not read it until that contribution changes.`}}function createContribution(e,t,n={}){let r=validateWrite({command:`create`,...t},e,n),{name:a,target:o,existing:s,operation:c}=r,l=r.template,u=n.display??(e=>e),d=[],f={merge:c};if(o.scope===`project`)for(let e of Rn)f[e]=void 0,!r.iface&&e in l.metadata&&d.push({code:`project-section-key-ignored`,message:`\`${e}\` is dropped from the project section for ${o.folder}: a project section states only what differs in its folder.`});if((o.scope===`plugin`||o.scope==="default")&&r.extended.length){let t=recordedSources(r.extended,sourceCatalog(e,{tier:o.scope}));Object.assign(f,generatedFrontmatter({sources:t}))}let m=s===void 0?editFrontmatter(l.content,f):withBody(editFrontmatter(s,{...selectionKeys(s,l),...f}),l.body),h=hiddenWarning(r.before,o,o.path,u);h&&d.push(h);let g=hasDescription(parseDocument(m,()=>{}))?[]:["it has no `description` in its frontmatter, so `list` and `search` show it blank"],_={name:a.name,scope:o.scope,path:o.path,content:m,dryRun:!!t.dryRun,hints:g,warnings:d};return o.folder!==void 0&&(_.folder=o.folder),_.dryRun?_:(i(o.dir,{recursive:!0}),p(o.path,m,s===void 0?{flag:`wx`}:{}),(o.scope===`project`||r.before.trace.layers.some(e=>e.path===o.dir||e.path===o.path))&&(_.after=resolveReference(a,{...e,projects:new Map},n)),_)}function placeOf(e){return e.scope===`project`?`project section for ${e.folder}`:e.scope==="default"?`default`:`${e.scope} contribution`}function deleteContribution(e,t,r={}){let{name:i,target:a,before:o}=validateWrite({command:`delete`,...t},e,r),s=r.display??(e=>e),c=!!t.dryRun,d=answeringFile(a,i.name,r.without),f=metadataFile(a,i.name),p=f!==r.without&&n(f),m=d??(p?f:void 0),h={name:i.name,scope:a.scope};if(a.folder!==void 0&&(h.folder=a.folder),!m)return{...h,path:a.path,dryRun:c,code:`no-file`,message:`${s(a.path)} does not exist, so there is no ${placeOf(a)} of "${i.name}" to delete; nothing was deleted. ${describeAnswer(o,r.display)} An installed plugin's, a managed, or an installed skill's contribution is never deleted.`,after:o};let g=d&&formatOfFile(d)!==`markdown`&&p?f:void 0,_=formatOfFile(m)===`markdown`?m:g,v=_===void 0?void 0:readExtends(parseDocument(tryRead(_)??``,()=>{}).metadata.extends,()=>{});if(!c&&(l(m),g&&l(g),y(m)!==a.dir))try{u(y(m))}catch{}let b={...h,path:m,dryRun:c,after:resolveReference(i,{...e,projects:new Map},{...r,without:c?m:void 0})};return g&&(b.metadataFile=g),v&&(b.selection=v.map(({target:e})=>e)),b}function defaultSkill(e){let t=e.layers.find(({tier:e,skipped:t})=>e==="default"&&!t);if(t?.skill===void 0)return;let n=y(t.dir),r=e.layers.find(({tier:e,plugin:t,dir:r})=>e===`plugin`&&t!==void 0&&n.startsWith(y(r)+E));return r?.plugin===void 0?{skill:t.skill}:{skill:t.skill,plugin:r.plugin}}function bodyOf(e){let t=e.held===void 0?void 0:parseDocument(e.held,()=>{}),n=e.format===`markdown`?hasBody(t?.body??``):!!e.existing?.trim();return{metadata:t?.metadata??{},held:n}}function write(e,t){i(y(e),{recursive:!0}),p(e,t)}function writePicks(e,t,n,r){let i=r.display??(e=>e),{name:a,holder:o,picks:s,before:c}=e;n.path=o;let{metadata:u,held:d}=bodyOf(e);if(s===`none`){if(e.held===void 0||!(`extends`in u))return{...n,action:`cleared`,code:`no-selection`,message:`${i(o)} holds no selection of "${a.name}", so nothing was removed. ${describeAnswer(c,r.display)}`,after:c};let s=editFrontmatter(e.held,{extends:void 0,declined:void 0}),d=!s.trim();return n.action=`cleared`,d?n.deleted=!0:n.content=s,n.dryRun?n:(d?l(o):write(o,s),after(n,e,t,r))}let f=s?s.values:[],p=editFrontmatter(e.held??``,{extends:f,declined:declinedBy(e,f)});Object.assign(n,{action:`selection`,content:p,extends:f});let m=hiddenWarning(c,e.target,o,i);return m&&n.warnings.push(m),e.base.trace.builtBy.startsWith(`managed `)&&n.warnings.push({code:`extends-not-used`,message:`the picks are written to ${i(o)}, but ${e.base.trace.builtBy}'s extends builds the stack, so they are not used while it does.`}),d&&isGenerated(u)&&n.hints.push(`its body was generated from a request against the old stack; customize "${a.name}" again with that request (\`reference customize ${a.name} --request <file> --body <file>\`) to regenerate it on the new picks.`),n.dryRun?n:(write(o,p),after(n,e,t,r))}function packageSources(e){let t=new Set(e.trace.stack),n=new Set(e.projectSections.flatMap(({plugin:e})=>e===void 0?[]:[e])),r=new Map;for(let{plugin:i,version:a}of e.trace.projectSections)i===void 0||!n.has(i)||t.has(i)||r.has(i)||r.set(i,a===void 0?{plugin:i}:{plugin:i,version:a});return[...r.values()]}function writeGenerated(e,t,n,r){let i=r.display??(e=>e),{target:a,base:o,picks:s}=e,c=a.scope===`project`,l=!c&&e.implementsValue!==void 0,{metadata:u}=bodyOf(e),d=s&&s!==`none`?s.values:u.extends,f=l||o.status!==`found`?[]:[...recordedSources(o.trace.stack,sourceCatalog(baseLayers(t,a),{tier:a.scope===`user`?`user`:`repo`}),defaultSkill(t)),...c?packageSources(o):[]],p=!c&&!l&&d!==void 0,m={extends:p?d:void 0,declined:p?declinedBy(e,d):void 0,sources:void 0,request:void 0,...generatedFrontmatter({sources:f,request:e.request})},h=e.body;n.action=`generated`,n.path=e.file,e.format===`markdown`?n.content=editFrontmatter(h,{merge:c?void 0:l?`replace`:e.merge??`patch`,implements:l?e.implementsValue:void 0,...m}):(n.content=h,n.metadataFile=e.holder,n.metadataContent=editFrontmatter(e.held??``,{merge:void 0,implements:void 0,...m}));let g=hiddenWarning(e.before,a,e.file,i);return g&&n.warnings.push(g),n.dryRun?n:(write(e.file,n.content),n.metadataContent!==void 0&&write(e.holder,n.metadataContent),after(n,e,t,r))}function declinedBy(e,t){let n=readExtends(t,()=>{});if(!n)return;let r=new Map;for(let{tier:t,plugin:n,file:i,outcome:a,frontmatter:o}of e.base.trace.layers)t!==`plugin`||n===void 0||i===void 0||a.startsWith(`not read`)||r.has(n)||r.set(n,o?.extends);let i=new Set,place=e=>{for(let t of e)i.has(t.target)||(i.add(t.target),place(t.extends??readExtends(r.get(t.target),()=>{})??[]))};place(n);let a=[...r.keys()].filter(e=>!i.has(e));return a.length?a:void 0}function after(e,t,n,r){return{...e,after:resolveReference(t.name,{...n,projects:new Map},r)}}function customizeContribution(e,t,n={}){let r=validateWrite({command:`customize`,...t},e,n),i={name:r.name.name,scope:r.target.scope,action:`base`,path:r.file,dryRun:!!t.dryRun,hints:[],warnings:[]};return r.target.folder!==void 0&&(i.folder=r.target.folder),t.base?{...i,base:generatorBase(r.base,r.iface)}:r.request===void 0?writePicks(r,e,i,n):writeGenerated(r,e,i,n)}function firstLine(e){return typeof e==`string`&&e.split(`
176
- `)[0]?.trim()||``}function belongsElsewhere(e,t,n){return t!==void 0&&t!==n&&(e===t||e.startsWith(`${t}.`))}function ownTier(e){return e.trace.layers.find(e=>(e.tier===`repo`||e.tier===`user`)&&e.file&&(e.outcome===`used`||e.outcome===`stale`)&&!e.selection&&!e.empty)?.tier}function holders(e){return[...new Set(e.trace.layers.flatMap(({tier:e,plugin:t,file:n})=>e===`plugin`&&t!==void 0&&n?[t]:[]))]}function referenceImplementations(e,t,n={}){let{accept:r,...i}=n,a={...i,projectSections:!1},o=parseReferenceName(`${e}${On}`);if(o.invalid||o.plugin!==void 0)throw new ReferenceFailure(`interface-unknown`,`"${e}" is not an interface id.`);let s=interfaceLookup(t,i),c=s(e),l=c.value;if(!l)throw new ReferenceFailure(`interface-unknown`,c.failure?.message??`no interface ${e}`);let u=aliasIndex(t),d=[l.id,...(u.interfaces.get(l.id)??[]).map(({alias:e})=>e)],f=[...r?.length?r:l.versions],p={interface:l.id,cardinality:l.cardinality,accept:f,implementations:[],excluded:[],warnings:[]},m=new Set,warn=e=>{for(let t of e){let e=`${t.code} ${t.message}`;m.has(e)||p.warnings.push(t),m.add(e)}};c.renamed!==void 0&&warn([{code:`reference-renamed`,message:`${e} is an older id of ${l.id}; ask for ${l.id} instead`}]);let inNamespace=e=>d.some(t=>e===t||e.startsWith(`${t}.`)),relevant=(e,t)=>{let n=readImplements(t.metadata??{}).entry?.id;return n!==void 0&&d.includes(n)?!0:inNamespace(e)&&!d.some(t=>belongsElsewhere(e,n,t))},consider=({pin:e,name:t,resolved:n,tier:r})=>{warn(n.warnings);let i=readImplements(n.metadata??{}).entry;if(!i||!d.includes(i.id)){let n=fitsNamespace(l.cardinality,d,t)?``:` and is not named ${l.cardinality===`one`?l.id:`${l.id}.<key>`}`;p.excluded.push({name:e,reasons:[`declares no implements ${l.id}@<version>${n}`]});return}let a=checkResolved(n,s,{id:l.id,versions:f});if(warn(a.warnings),a.failures.length){p.excluded.push({name:e,reasons:a.failures.map(({check:e,message:t})=>`${e}: ${t}`)});return}p.implementations.push({pin:e,description:firstLine(n.metadata?.description),unsupported:a.unsupported,name:t,tier:r,version:i.version})},qualified=(e,n)=>resolveReference(parseReferenceName(`${e}/${n}`),t,a),h=[...new Set(referenceNames(t).map(e=>shownName(e,u)))];for(let e of h){if(interfaceIdOf(e)!==void 0)continue;let n=resolveReference(e,t,a);if(n.status===`ambiguous`){for(let r of n.options??[]){if(r==="default")continue;let i=resolveReference(parseReferenceName(r),t,a);i.status===`found`&&relevant(e,i)&&(warn(i.warnings),p.excluded.push({name:r,reasons:[`ambiguous: ${n.message}; each is left out until a customizer picks one`]}))}continue}if(n.status!==`found`||!relevant(e,n))continue;let r=holders(n),i=l.cardinality===`many`?ownTier(n):void 0;if(i!==void 0){consider({pin:e,name:e,resolved:n,tier:i});for(let t of r)p.excluded.push({name:`${t}/${e}`,reasons:[`the ${i} implementation answers ${e}; a consumer loads it by that name`]});continue}let o=n.trace.stack.filter(e=>e!=="default").at(-1);if(o!==void 0){consider({pin:`${o}/${e}`,name:e,resolved:qualified(o,e),tier:`plugin`});for(let t of r)t!==o&&p.excluded.push({name:`${t}/${e}`,reasons:[`${e} loads the stack of ${o}, the pick; load ${o}/${e}`]})}}return p}function fitsNamespace(e,t,n){return t.some(t=>e===`one`?n===t:n.startsWith(`${t}.`)&&n.length>t.length+1)}function whereReference(e,t,{root:n,display:r=e=>e,in:i}){typeof e==`string`&&requireName(e);let a=i===void 0?void 0:inFolder(i,n),o=typeof e==`string`?parseReferenceName(e):e,s=resolveReference(o,t,{display:r}),c={name:o.raw,status:s.status,files:[],headings:s.status===`found`&&s.format===`markdown`?headingPaths(s.content??``):[],used:s.trace.stack,layers:s.trace.layers,warnings:s.warnings};if(s.options&&(c.options=s.options),o.invalid)return c;let l=(Array.isArray(t)?t:t.layers).find(({tier:e})=>e===`user`)?.dir,u=[{scope:`repo`,dir:repoReferencesDir(n),path:``},...l?[{scope:`user`,dir:l,path:``}]:[],...a?[{scope:`project`,dir:S(a.path,`.agents`,`references`),path:``,folder:a.folder}]:[]];for(let e of u){let t=answeringFile(e,o.name)??S(e.dir,`${o.name}.md`),i=e.scope===`project`?projectHidingLayer(s):hidingLayer(s,e.dir,t),a={scope:e.folder??e.scope,path:e.scope===`user`?r(t):w(n,t),reaches:reachOf(e)};i&&(a.hiddenBy=hiderLabel(i,r)),c.files.push(a)}return c}const zn=new Set([`deps`,`dependencies`,`local`,`plugins`,`marketplace`,`plugin`,`default`]);function isGenericName(e){return zn.has(e.toLowerCase())}function marketplaceName(e){return e.replace(/^@/,``).replace(/\//g,`-`).replace(/[^a-zA-Z0-9-_.]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`agent-plugins`}function buildCatalog({name:e,owner:t,plugins:n}){let r=[...n].sort((e,t)=>e.plugin.localeCompare(t.plugin)).map(({plugin:e,package:t,version:n,description:r})=>{let i={source:`npm`,package:t,version:n};return r?{name:e,source:i,description:r}:{name:e,source:i}});return{name:e,owner:{name:t},description:`Plugins provided by this repository’s dependencies. Generated — do not edit.`,plugins:r}}function serializeCatalog(e){return`${JSON.stringify(e,null,` `)}\n`}function readJson$1(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$1,`readJson`);function readDepPlugin(e,t){let n=packageDir(e,t);if(!n)return{ok:!1,package:e,reason:`unresolved`};let r=readJson$1(S(n,`plugin.json`));if(!r||typeof r!=`object`)return{ok:!1,package:e,reason:`no-manifest`};let i=r,a=typeof i.name==`string`?i.name:void 0;if(!a)return{ok:!1,package:e,reason:`unnamed`};let o=readJson$1(S(n,`package.json`)),s=typeof o?.version==`string`?o.version:void 0;if(!s)return{ok:!1,package:e,reason:`no-manifest`};let c=typeof i.description==`string`?i.description:void 0;return{ok:!0,plugin:c?{package:e,plugin:a,version:s,description:c}:{package:e,plugin:a,version:s}}}function isPnp(){return!!process.versions.pnp}const Bn=S(`.agents`,`buddy-agent-harness`),Vn=S(Bn,`.claude-plugin`,`marketplace.json`);function readManifest(e){return JSON.parse(a(e,`utf8`))}function deriveCatalog(e){let t=S(e,`package.json`),n=readManifest(t),r=[],i=[];for(let e of declaredDependencies(n)){let n=readDepPlugin(e,t);n.ok?r.push(n.plugin):n.reason===`unresolved`&&i.push({package:e,reason:n.reason})}let a=typeof n.name==`string`?n.name:`unknown`,o=marketplaceName(a);return{catalog:buildCatalog({name:o,owner:a,plugins:r}),plugins:r,unresolved:i,genericName:isGenericName(o),pnp:isPnp()}}function catalogStatus(e,t){let n;try{n=a(S(e,Vn),`utf8`)}catch{n=void 0}return n===serializeCatalog(t)?`unchanged`:n===void 0?`created`:`updated`}function writeCatalog(e,t){let n=catalogStatus(e,t);if(n===`unchanged`)return n;let r=S(e,Vn);return i(y(r),{recursive:!0}),p(r,serializeCatalog(t)),n}function readJson(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}function directories(e){try{return o(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}function claudeConfigDir(e,t=process.env){return t.CLAUDE_CONFIG_DIR||S(e,`.claude`)}function readClaudeState(e){let t=readJson(S(e,`plugins`,`installed_plugins.json`)),n=[];for(let[e,r]of Object.entries(t?.plugins??{}))if(Array.isArray(r))for(let t of r){if(!t||typeof t!=`object`)continue;let r=t,i=typeof r.version==`string`?r.version:void 0,a=typeof r.scope==`string`?r.scope:void 0;if(!i||!a)continue;let o=typeof r.projectPath==`string`?r.projectPath:void 0;n.push(o?{id:e,version:i,scope:a,projectPath:o}:{id:e,version:i,scope:a})}let r=readJson(S(e,`plugins`,`known_marketplaces.json`)),i=[];for(let[e,t]of Object.entries(r??{}))i.push({name:e,path:typeof t?.source?.path==`string`?t.source.path:``});return{installed:n,marketplaces:i}}const Hn={name:`claude-code`,scoped:!0,installedOnMachine:(e,t=process.env)=>n(claudeConfigDir(e,t)),state:(e,t=process.env)=>readClaudeState(claudeConfigDir(e,t)),register:e=>`claude plugin marketplace add ./${e} --scope project`,install:e=>`claude plugin install ${e} --scope project`,update:e=>`claude plugin update ${e} --scope project`,uninstall:e=>`claude plugin uninstall ${e} --scope project`,refreshMarketplace:e=>`claude plugin marketplace update ${e}`};function codexHome(e,t=process.env){return t.CODEX_HOME||S(e,`.codex`)}function readCodexState(e){let t=S(e,`plugins`,`cache`),n=[];for(let e of directories(t))for(let r of directories(S(t,e)))for(let i of directories(S(t,e,r)))n.push({id:`${r}@${e}`,version:i,scope:`user`});let r=[],i=``;try{i=a(S(e,`config.toml`),`utf8`)}catch{i=``}let o;for(let e of i.split(`
177
- `)){let t=/^\s*\[marketplaces\.(?:"([^"]+)"|([^\]]+))\]\s*$/.exec(e);if(t){o={name:t[1]??t[2],path:``},r.push(o);continue}if(/^\s*\[/.test(e)){o=void 0;continue}let n=o?/^\s*source\s*=\s*"([^"]*)"\s*$/.exec(e):void 0;n?.[1]&&o&&(o.path=n[1])}return{installed:n,marketplaces:r}}const Un=[Hn,{name:`codex`,scoped:!1,installedOnMachine:(e,t=process.env)=>n(codexHome(e,t)),state:(e,t=process.env)=>readCodexState(codexHome(e,t)),register:e=>`codex plugin marketplace add ./${e}`,install:e=>`codex plugin add ${e}`,update:e=>`codex plugin add ${e}`,uninstall:e=>`codex plugin remove ${e}`,refreshMarketplace:()=>``}];function ours(e,t,n,r){let i=`@${t}`;return e.filter(e=>e.id.endsWith(i)&&(!r||e.projectPath===n))}function reconcile({catalog:e,catalogDir:t,root:n,installed:r,marketplaces:i,scoped:a=!0}){let o=i.find(t=>t.name===e.name),s=[],c=t.split(/[\\/]/).filter(Boolean),l=o?c.every(e=>o.path.includes(e)):!1,u=o&&!l?o.path:void 0;o||s.push({kind:`register`,subject:e.name,detail:`marketplace is not registered with this harness`});let d=ours(r,e.name,n,a),f=new Map(d.map(e=>[e.id,e]));for(let t of e.plugins){let n=`${t.name}@${e.name}`,r=f.get(n);if(!r){s.push({kind:`install`,subject:n,detail:`not installed; catalog pins ${t.source.version}`});continue}r.version!==t.source.version&&s.push({kind:`update`,subject:n,detail:`installed ${r.version}, catalog pins ${t.source.version}`})}let p=new Set(e.plugins.map(t=>`${t.name}@${e.name}`));for(let e of d)p.has(e.id)||s.push({kind:`uninstall`,subject:e.id,detail:`installed but no longer in the catalog; it will report a load failure until removed`});return{actions:s,...u?{collision:u}:{},unregistered:!o}}function commandFor(e,t,n){switch(t.kind){case`register`:return e.register(Bn);case`install`:return e.install(t.subject);case`update`:{let r=e.refreshMarketplace(n),i=e.update(t.subject);return r?`${r} && ${i}`:i}case`uninstall`:return e.uninstall(t.subject)}}function notesFor(e){let t=[];e.pnp&&t.push(`Yarn Plug’n’Play is active: dependencies live inside zip archives, so no harness can install from them. Set nodeLinker: node-modules, or unplug the plugin dependencies.`),e.genericName&&t.push(`Marketplace name "${e.catalog.name}" is generic. Registering a second marketplace under a name already in use replaces the first silently, and the install that follows reports "already installed" — the repository then runs the other one's versions.`);for(let{package:n}of e.unresolved)t.push(`Declared dependency "${n}" is not installed; install dependencies before generating.`);return t}const Wn=command({name:`dep-plugins`,description:`Derive the marketplace catalog for plugins shipped by this repository’s dependencies, so a harness can install them. Writes the catalog; installing is the harness’s own job.`,options:{root:{description:`Repository directory. Defaults to the current directory.`,type:N.string().optional()},check:{description:`Report whether the catalog is current without writing it. For CI and postinstall.`,type:N.boolean().optional()}},run(e){try{let t=e.root??process.cwd(),n=deriveCatalog(t),r=e.check?catalogStatus(t,n.catalog)===`unchanged`?`current`:`would-change`:writeCatalog(t,n.catalog),i=g(),a=notesFor(n),o=Un.filter(e=>e.installedOnMachine(i)),s=[],c=[];for(let e of o){let r=e.state(i),o=reconcile({catalog:n.catalog,catalogDir:Bn,root:T(t),installed:r.installed,marketplaces:r.marketplaces,scoped:e.scoped});o.collision&&a.push(`${e.name}: marketplace "${n.catalog.name}" is already registered against ${o.collision}. Registering over it replaces the other repository's silently, and the install that follows reports "already installed" — rename this repository's marketplace instead.`),s.push({runtime:e.name,status:o.actions.length?`${o.actions.length} to apply`:`in sync`});for(let t of o.actions)c.push({runtime:e.name,do:commandFor(e,t,n.catalog.name),subject:t.subject,why:t.detail})}n.plugins.length&&a.push(`Copilot CLI rejects an npm marketplace source, so it cannot install from this catalog. It needs a path-sourced catalog, which cannot reach node_modules from a subdirectory.`);let l=result({catalog:Vn,marketplace:n.catalog.name,outcome:r,plugins:n.plugins.length?n.plugins.map(({plugin:e,package:t,version:n})=>({name:e,package:t,version:n})):`0 dependencies ship a plugin — nothing to install`,harness:s.length?s:`no supported harness detected on this machine`,actions:c.length?c:`0 actions — every detected harness matches the catalog`,...a.length?{notes:a}:{}});return r===`would-change`?answerThenFail(l,this.format):l}catch(e){return fail(e,`Catalog generation failed.`)}}});function filesUnder(e){try{return o(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(t=>w(e,S(t.parentPath,t.name)).split(E).join(C.sep)).sort()}catch{return[]}}function skillsProjection(e,t,n=skillsDirectories(e)?.[t]){let r=n??[],[i]=r;if(i===void 0)throw Error(`cyber-agentkit records no ${t} skills directories for ${e}.`);return r.includes(`.agents/skills`)?{}:{skillsDirectory:i}}const Gn=`.agents/AGENTS.md`,Kn=[{name:`claude-code`,project:{detect:`.claude`,...skillsProjection(`claude-code`,`project`),shadowedBy:[`CLAUDE.md`,`.claude/CLAUDE.md`,`CLAUDE.local.md`],mcpConfig:{path:`.mcp.json`,key:`mcpServers`,format:`json`,dialect:`claude-code`},nonstandard:[{path:`.claude/commands`,shape:`directory`,kind:`command`},{path:`.claude/rules`,shape:`directory`,kind:`rule`},{path:`.claude/agents`,shape:`directory`,kind:`subagent`}]},user:{detect:`.claude`,...skillsProjection(`claude-code`,`user`),relocatedBy:`CLAUDE_CONFIG_DIR`,emptyRelocatesToStart:!0,instructionBridge:{kind:`import`,path:`.claude/CLAUDE.md`,line:`@~/${Gn}`}}},{name:`cursor`,project:{detect:`.cursor`,...skillsProjection(`cursor`,`project`),mcpConfig:{path:`.cursor/mcp.json`,key:`mcpServers`,format:`json`,dialect:`cursor`},nonstandard:[{path:`.cursorrules`,shape:`file`,kind:`instructions`},{path:`.cursor/rules`,shape:`directory`,kind:`rule`},{path:`.cursor/commands`,shape:`directory`,kind:`command`},{path:`.cursor/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.cursor`,...skillsProjection(`cursor`,`user`)}},{name:`codex`,project:{detect:`.codex`,...skillsProjection(`codex`,`project`),mcpConfig:{path:`.codex/config.toml`,key:`mcp_servers`,format:`toml`,dialect:`codex`,shared:!0},nonstandard:[{path:`.codex/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.codex`,...skillsProjection(`codex`,`user`),instructionBridge:{kind:`symlink`,path:`.codex/AGENTS.md`},shadowedBy:[`.codex/AGENTS.override.md`],relocatedBy:`CODEX_HOME`}},{name:`copilot-cli`,project:{detect:`.github/skills`,...skillsProjection(`copilot-cli`,`project`),nonstandard:[{path:`.github/copilot-instructions.md`,shape:`file`,kind:`instructions`},{path:`.github/instructions`,shape:`directory`,kind:`instructions`},{path:`.github/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.copilot`,...skillsProjection(`copilot-cli`,`user`),relocatedBy:`COPILOT_HOME`,instructionBridge:{kind:`symlink`,path:`.copilot/copilot-instructions.md`}}},{name:`gemini-cli`,project:{detect:`.gemini`,...skillsProjection(`gemini-cli`,`project`),instructionBridge:{kind:`settings-entry`,path:`.gemini/settings.json`,key:`context.fileName`},mcpConfig:{path:`.gemini/settings.json`,key:`mcpServers`,format:`json`,dialect:`gemini-cli`,shared:!0},nonstandard:[{path:`GEMINI.md`,shape:`file`,kind:`instructions`},{path:`.gemini/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.gemini`,...skillsProjection(`gemini-cli`,`user`),instructionBridge:{kind:`symlink`,path:`.gemini/GEMINI.md`}}},{name:`devin-desktop`,project:{detect:`.devin`}},{name:`windsurf`,project:{detect:`.windsurf`,skillsDirectory:`.windsurf/skills`,nonstandard:[{path:`.windsurfrules`,shape:`file`,kind:`instructions`},{path:`.windsurf/rules`,shape:`directory`,kind:`rule`}]},deprecated:`devin-desktop`}],qn=new Set(Kn.map(e=>e.name));function isHarnessName(e){return qn.has(e)}function parseHarnesses(e){let t=(e??``).split(`,`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>!isHarnessName(e));if(n.length)throw Error(`Unsupported harness: ${n.join(`, `)}. Supported: ${Kn.map(e=>e.name).join(`, `)}.`);return t.filter(isHarnessName)}const Jn=[`claude-code`,`cursor`];function directoryExists(e){try{return r(e).isDirectory()}catch{return!1}}function selectHarnesses(e,t){let n=new Set([...Jn,...t]);return Kn.filter(t=>n.has(t.name)||directoryExists(S(e,t.project.detect)))}function locatorText({file:e,server:t,field:n,position:r}){return r?`${e}#L${r.line}:${r.column}`:t===void 0?e:`${e}#servers.${t}${n===void 0?``:`.${n}`}`}function repairsOf(e){return Object.entries(e).map(([e,t])=>({problem:e,...t}))}const Yn=`buddy-agent-harness`,Xn=`/buddy-agent-harness:init-buddy-agent-harness`,pnpmSkillRef=e=>`\`${e}\` (pnpm install: \`pnpm-${Yn}-${e.slice(e.indexOf(`:`)+1)}\`)`,W=pnpmSkillRef(Xn),G=pnpmSkillRef(`/buddy-agent-harness:repair`),K=`.agents/buddy-agent-harness/mcp.toml`,Zn={"no-canonical":{detail:`the canonical skill directory does not exist, so no bridge can resolve`,repair:(e,t)=>({command:`${t} init`,instruction:`run \`${t} init\` to create .agents/skills and the bridges into it`}),skillRepair:()=>`run ${W}, which creates \`.agents/skills\` and the bridges`},missing:{detail:`no bridge at this path — the harness sees zero project skills`,repair:({file:e},t)=>({command:`${t} init`,instruction:`run \`${t} init\` to create the bridge at ${e}`}),skillRepair:()=>`run ${W}`},degraded:{detail:`expected a directory but found a regular file — checkout without core.symlinks`,repair:({file:e},t)=>({command:`${t} init --copy --force ${e}`,instruction:`run \`${t} init --copy --force ${e}\` to rebuild ${e} as a real directory`}),skillRepair:({file:e})=>`run \`${Xn} --copy --force ${e}\``},stale:{detail:`symlink does not resolve to .agents/skills`,repair:({file:e},t)=>({command:`${t} init --force ${e}`,instruction:`run \`${t} init --force ${e}\` to repoint ${e} at .agents/skills`}),skillRepair:({file:e})=>`run \`${Xn} --force ${e}\``},"diverged-bridge":{detail:`only the bridge changed since the two last agreed — an agent wrote through the copy`,repair:({file:e},t)=>({command:``,instruction:`replace .agents/skills with ${e} to keep the newer edit, then run \`${t} init --force ${e}\``}),skillRepair:({file:e})=>`replace .agents/skills with ${e} to keep the newer edit, then run \`${Xn} --force ${e}\``},"diverged-canonical":{detail:`only .agents/skills changed since the two last agreed — the copy is stale`,repair:({file:e},t)=>({command:`${t} init --copy --force ${e}`,instruction:`run \`${t} init --copy --force ${e}\` to rebuild ${e} from the newer .agents/skills`}),skillRepair:({file:e})=>`run \`${Xn} --copy --force ${e}\``},"diverged-both":{detail:`both sides changed since they last agreed — rebuilding would discard one of them`,repair:({file:e})=>({command:``,instruction:`reconcile .agents/skills with ${e} by hand — rebuilding would discard one of them; \`git diff --no-index .agents/skills ${e}\` shows what differs`}),skillRepair:({file:e})=>`run \`git diff --no-index .agents/skills ${e}\` and reconcile by hand`},"diverged-unknown":{detail:`contents differ and no commit where they agreed was found — which side moved is unknown`,repair:({file:e})=>({command:``,instruction:`reconcile .agents/skills with ${e} by hand — which side moved is unknown; \`git diff --no-index .agents/skills ${e}\` shows what differs`}),skillRepair:({file:e})=>`run \`git diff --no-index .agents/skills ${e}\` and reconcile by hand`},"unpinned-copy":{detail:`tracked copy without the skip-worktree bit — the tree is dirty with content that must not be committed`,repair:({file:e})=>({command:`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree`,instruction:`run \`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree\` to restore the skip-worktree bit`}),skillRepair:({file:e})=>`run \`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree\``}};repairsOf(Zn);const Qn={"no-instructions":{detail:`no AGENTS.md at the repository root, so the instructions this repository has reach one harness at most`,repair:()=>({command:``,instruction:`hand this to ${W}, which consolidates what the repository has into AGENTS.md, or derives it`}),skillRepair:()=>`run ${W}, which consolidates or derives AGENTS.md`},"instructions-missing":{detail:`no instruction bridge at this path — the harness reads none of AGENTS.md`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${W}, which writes the bridge into it`}),skillRepair:()=>`run ${W}`},"instructions-unbridged":{detail:`the file is present but names AGENTS.md nowhere — the harness reads none of it`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${W}, which adds the bridge without discarding what the file already says`}),skillRepair:()=>`run ${W}, which adds the bridge without discarding what the file already says`},"instructions-shadowing":{detail:`this file suppresses the AGENTS.md beside it — the harness reads this instead, and none of AGENTS.md`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${W}, which consolidates what it says into AGENTS.md, or adds an @AGENTS.md import above it where the file has to stay`}),skillRepair:()=>`run ${W}, which consolidates the file into AGENTS.md or imports AGENTS.md from it`},"instructions-superseded":{detail:`a bridge from before the harness read AGENTS.md itself — it still works, and nothing needs it`,repair:({file:e})=>({command:``,instruction:`remove ${e}, or keep it for sessions that cannot read AGENTS.md directly — ${W} offers the choice`}),skillRepair:()=>`run ${W}, which offers to remove it`},"instructions-unreadable":{detail:`the settings file does not parse, so the harness reads none of it`,repair:({file:e})=>({command:``,instruction:`fix the JSON in ${e} by hand, then hand it to ${W}`}),skillRepair:()=>`fix the JSON by hand, then run ${W}`}};repairsOf(Qn);const $n=`~/${Gn}`;function globalBridgeStep(e,t=`~/${e.path}`){return e.kind===`import`?`add the line \`${e.line}\` to ${t}`:`run \`ln -s ${$n} ${t}\``}function userSpellings(e,t){let n=`${e.detect}/`;return e.relocatedBy!==void 0&&t.startsWith(n)?[`~/${t}`,`$${e.relocatedBy}/${t.slice(n.length)}`]:[`~/${t}`]}function userBridgeAt(e){for(let{user:t}of Kn){let n=t?.instructionBridge;if(t&&n&&userSpellings(t,n.path).includes(e))return n}}function stepAt(e,t){let n=userBridgeAt(e);return n===void 0?`add the bridge the harness page names for ${e}`:`${t&&n.kind!==`import`?`move what ${e} says into ${$n} and remove it, then `:``}${globalBridgeStep(n,e)}`}const er=`hand the user this step, since nothing here writes outside the repository:`,tr={"global-instructions-missing":{detail:`no user-scope instruction file at this path — the harness loads none of ${$n}`,repair:({file:e})=>({command:``,instruction:`${er} ${stepAt(e,!1)}`}),skillRepair:()=>`hand the user the step the harness page names for that file; write nothing yourself`},"global-instructions-unbridged":{detail:`the file holds its own content and does not load ${$n} — text placed there reaches no session of this harness`,repair:({file:e})=>({command:``,instruction:`${er} ${stepAt(e,!0)}`}),skillRepair:()=>`hand the user the step the harness page names for that file, keeping what the file says; write nothing yourself`},"global-instructions-overridden":{detail:`the harness reads this file in place of its own user-scope file, so whatever that file loads goes unread, and this one does not load ${$n}`,repair:({file:e})=>({command:``,instruction:`${er} move what ${e} says into ${$n} and remove it`}),skillRepair:()=>`hand the user the move of what that file says into the global file, and its removal; write nothing yourself`},"global-instructions-emptied":{detail:`the variable is set but empty, which this harness reads as the directory it starts in rather than as unset — its user-scope file is whichever one sits there, not the one in its own folder`,repair:({file:e})=>({command:``,instruction:`${er} unset ${e.slice(1)} where your shell sets it, or set it to the folder you meant`}),skillRepair:()=>`hand the user the step of unsetting that variable; write nothing yourself`}};repairsOf(tr);const nr={"deprecated-harness":{detail:`a projection under a harness name that has been superseded — the replacement reads .agents/skills natively and needs no projection at all`,repair:({file:e})=>({command:``,instruction:`remove ${e} and enable the harness that replaced it — ${G} offers the correction`}),skillRepair:()=>`run ${G}`},"ignored-bridge":{detail:`a .gitignore rule matches this bridge — an untracked bridge swallows a real edit silently`,repair:({file:e})=>({command:``,instruction:`narrow or remove the .gitignore rule matching ${e} — ${G} offers the correction`}),skillRepair:()=>`run ${G}`},"unread-local-override":{detail:`no harness reads this filename, so everything in it is invisible to every agent`,repair:({file:e})=>({command:``,instruction:`move ${e} to CLAUDE.local.md, or consolidate it into AGENTS.md — ${G} offers the correction`}),skillRepair:()=>`run ${G}`},"unloadable-skill":{detail:`frontmatter that does not parse, or no description — either one makes a harness skip the skill outright`,repair:({file:e})=>({command:``,instruction:`quote the description in ${e}, or add one — ${G} offers the correction`}),skillRepair:()=>`run ${G}`}};repairsOf(nr);const rr={"mcp-golden-unreadable":{detail:`the golden MCP set does not parse — the locator gives the line and column, and nothing else can be said about it`,repair:e=>({command:``,instruction:`fix the TOML at ${locatorText(e)}`}),skillRepair:e=>`fix the TOML at ${locatorText(e)} by hand — the reported line and column are all that can be quoted, because the parser's own message repeats the offending line and that line is the one holding the credential`},"mcp-target-unreadable":{detail:`this harness config does not parse, so the harness starts none of its servers and nothing in it can be compared`,repair:e=>({command:``,instruction:`fix the syntax of ${locatorText(e)}`}),skillRepair:e=>`fix the syntax of ${locatorText(e)} by hand`},"mcp-unprojected":{detail:`the golden set declares this server and the harness config does not carry it`,repair:({file:e,server:t})=>({command:``,instruction:`add the server ${t} to ${e}, or drop it from the golden set — ${G} offers the correction`}),skillRepair:e=>`hand ${locatorText(e)} to ${G}, which projects it from its golden entry with \`mcp project\` — or drop it from the golden set`},"mcp-undeclared":{detail:`the harness config carries this server and the golden set does not declare it`,repair:({file:e,server:t})=>({command:``,instruction:`add the server ${t} to ${K}, or drop it from ${e} — ${G} offers the import`}),skillRepair:e=>`hand ${locatorText(e)} to ${G}, which imports it field by field with \`mcp reconcile\`, refusing any literal credential — or drop it from ${e.file}`},"mcp-diverged-target":{detail:`only the harness config changed since the two last agreed — the edit was made through the copy`,repair:e=>({command:``,instruction:`reconcile the value at ${locatorText(e)} back into ${K} — ${G} offers the import`}),skillRepair:e=>`hand ${locatorText(e)} to ${G}, which imports the field into ${K} with \`mcp reconcile\` once approved`},"mcp-diverged-golden":{detail:`only the golden set changed since the two last agreed — the harness copy is stale`,repair:e=>({command:``,instruction:`update ${locatorText(e)} from the golden entry — ${G} offers the correction`}),skillRepair:e=>`hand ${locatorText(e)} to ${G}, which updates it from the golden entry with \`mcp project\``},"mcp-diverged-both":{detail:`both sides changed since they last agreed — merging either way would discard the other`,repair:e=>({command:``,instruction:`reconcile ${locatorText(e)} against ${K} by hand`}),skillRepair:e=>`reconcile ${locatorText(e)} against ${K} by hand — never merge a three-way conflict automatically`},"mcp-diverged-unknown":{detail:`the two disagree and no baseline says which side moved — neither history nor a last-projected record covers this server`,repair:e=>({command:``,instruction:`compare ${locatorText(e)} against ${K} by hand`}),skillRepair:e=>`compare ${locatorText(e)} against ${K} by hand`},"mcp-literal-secret":{detail:`a credential-bearing field holds a literal rather than a reference to an environment variable`,repair:e=>({command:``,instruction:`move the value at ${locatorText(e)} into an environment variable and reference it`}),skillRepair:e=>`move the value at ${locatorText(e)} into an environment variable and reference it — read the value from the file, never from this report, and never repeat it back`},"mcp-committed-secret":{detail:`a credential-bearing field holds a literal in a git-tracked file — the credential is committed, and moving it does not un-commit it`,repair:e=>({command:``,instruction:`rotate the credential behind ${locatorText(e)}, then reference it from an environment variable`}),skillRepair:e=>`rotate the credential behind ${locatorText(e)} at its issuer, then reference it from an environment variable — it is in the repository's history, so moving it is not enough`}};repairsOf(rr);const ir={"nonstandard-instructions":{detail:`instruction content only one harness reads — AGENTS.md carries the same prose to all of them`,repair:({file:e})=>({command:``,instruction:`consolidate ${e} into AGENTS.md — ${W} offers the consolidation, and keeps the content reachable where this harness needs it`}),skillRepair:({file:e})=>`hand ${e} to ${W}, which consolidates it into AGENTS.md`},"nonstandard-rule":{detail:`a path-scoped rule only one harness reads — a skill reaches every harness where the scoping is incidental`,repair:({file:e})=>({command:``,instruction:`convert ${e} into a skill under .agents/skills where its guidance is not tied to the paths it names — ${W} offers the conversion; keep it where the path scoping is the point`}),skillRepair:({file:e})=>`hand ${e} to ${W} to convert into a skill, unless the path scoping is load-bearing`},"nonstandard-command":{detail:`a harness command file — a skill is the portable form, and this harness reads skills too`,repair:({file:e})=>({command:``,instruction:`move ${e} to .agents/skills/<name>/SKILL.md — ${W} offers the move`}),skillRepair:({file:e})=>`hand ${e} to ${W}, which moves it to .agents/skills`},"nonstandard-skill":{detail:`a skill under a harness directory rather than the canonical one, where only that harness finds it`,repair:({file:e})=>({command:``,instruction:`move ${e} to .agents/skills and project it back where the harness needs one — ${W} offers the move`}),skillRepair:({file:e})=>`hand ${e} to ${W}, which moves it to .agents/skills`},"nonstandard-subagent":{detail:`a subagent definition with no cross-harness form — nothing outside this harness can read it, and no canonical form exists yet`,repair:({file:e})=>({command:``,instruction:`leave ${e} where it is and record that it reaches one harness only — no portable form exists to convert it to`}),skillRepair:({file:e})=>`leave ${e} in place — no portable form exists yet, so this is work for a person rather than a skill`}};repairsOf(ir);const ar={...Zn,...Qn,...tr,...nr,...rr,...ir};repairsOf(ar);function repairFor(e){return{problem:e,...ar[e]}}const or=`.agents/skills`,sr=`AGENTS.local.md`;function frontmatterFault(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);if(!t)return`unparseable`;let n=/^description:[ \t]*(.*)$/m.exec(t[1])?.[1]?.trim();if(!n)return`no-description`;if(!/^(['"]).*\1$/.test(n)&&/:\s/.test(n))return`unparseable`}function diagnoseConfiguration({root:e,git:t,cli:r}){let i=[],add=(e,t)=>{let{detail:n,repair:a}=repairFor(t);i.push({path:e,problem:t,detail:n,repair:a({file:e},r)})},o=selectHarnesses(e,[]);for(let t of o){let r=t.project.skillsDirectory;t.deprecated&&r&&n(S(e,r))&&add(r,`deprecated-harness`)}for(let r of o){let i=r.project.skillsDirectory;i&&n(S(e,i))&&t.isIgnored(i)&&add(i,`ignored-bridge`)}n(S(e,sr))&&add(sr,`unread-local-override`);for(let t of filesUnder(S(e,or)).filter(e=>e.endsWith(`SKILL.md`)))frontmatterFault(a(S(e,or,t),`utf8`))&&add(`${or}/${t}`,`unloadable-skill`);return i}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const cr=[`transport`,`command`,`args`,`env`,`url`,`headers`,`description`,`enabled`,`timeout`,`source`],lr=new Set([`env`,`headers`]);function sameValue(e,t,n){if(lr.has(e)&&isRecord(t)&&isRecord(n)){let e=Object.keys(t);return e.length===Object.keys(n).length&&e.every(e=>t[e]===n[e])}return JSON.stringify(t)===JSON.stringify(n)}function divergingFields(e,t,n=new Set(cr)){return cr.filter(r=>{if(!n.has(r))return!1;let i=e[r];if(i===void 0)return!1;if(lr.has(r)&&isRecord(i)&&isRecord(t[r])){let e=t[r];return Object.keys(i).some(t=>i[t]!==e[t])}return!sameValue(r,i,t[r])})}function sameField(e,t,n){return sameValue(e,t?.[e],n?.[e])}function stringMap(e){if(!isRecord(e))return;let t=Object.entries(e).filter(([,e])=>typeof e==`string`);return t.length?Object.fromEntries(t):void 0}const ur=new Set([`stdio`,`http`,`sse`]);function transportOf(e){let t=e.type??e.transport;if(typeof t==`string`&&ur.has(t))return t;if(typeof e.url==`string`)return`http`;if(typeof e.command==`string`)return`stdio`}function serverFrom(e){let t=Array.isArray(e.args)&&e.args.every(e=>typeof e==`string`),n=transportOf(e),r=stringMap(e.env),i=stringMap(e.headers);return{...n?{transport:n}:{},...typeof e.command==`string`?{command:e.command}:{},...t?{args:e.args}:{},...r?{env:r}:{},...typeof e.url==`string`?{url:e.url}:{},...i?{headers:i}:{},...typeof e.description==`string`?{description:e.description}:{},...typeof e.enabled==`boolean`?{enabled:e.enabled}:{},...typeof e.timeout==`number`?{timeout:e.timeout}:{},...typeof e.source==`string`?{source:e.source}:{}}}const dr=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/,fr=/\$\{[^}]*\}|\$[A-Za-z_]/;var Refusal=class extends Error{field;reason;constructor(e,t){super(t),this.field=e,this.reason=t}};function refuse(e,t){throw new Refusal(e,t)}function rendering(e){try{return{kind:`entry`,entry:e()}}catch(e){if(!(e instanceof Refusal))throw e;return{kind:`refused`,field:e.field,reason:e.reason}}}function assertRunnable(e){(e.transport===`stdio`?!e.command:!e.url)&&refuse(e.transport===`stdio`?`command`:`url`,`the golden set leaves it unset and the target requires it`)}function defined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function mapValues(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t(n)]))}function noReferenceIn(e,t,n){for(let r of t){let t=e[r];(Array.isArray(t)?t:[t]).some(e=>typeof e==`string`&&fr.test(e))&&refuse(r,`${n} documents no reference expansion here`)}}const pr={fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`description`,`timeout`]),read:serverFrom,write:e=>rendering(()=>(assertRunnable(e),defined({type:e.transport,command:e.command,args:e.args,env:e.env,url:e.url,headers:e.headers,description:e.description,timeout:e.timeout})))};function toCursor(e,t){return e.replace(/\$\{([^}]*)\}|\$[A-Za-z_]/g,(e,n)=>((n===void 0||!dr.test(e))&&refuse(t,`Cursor expands only a plain variable reference, with no default`),`\${env:${n}}`))}function fromCursor(e){return e.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,t)=>`\${${t}}`)}function fromCursorEntry(e){let strings=e=>typeof e==`string`?fromCursor(e):e,map=e=>isRecord(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,strings(t)])):e;return{...e,command:strings(e.command),args:Array.isArray(e.args)?e.args.map(strings):e.args,env:map(e.env),url:strings(e.url),headers:map(e.headers)}}const mr={fields:new Set([`command`,`args`,`env`,`url`,`headers`]),read:e=>serverFrom(fromCursorEntry(e)),write:e=>rendering(()=>(assertRunnable(e),defined({type:e.transport===`stdio`?`stdio`:void 0,command:e.command&&toCursor(e.command,`command`),args:e.args?.map(e=>toCursor(e,`args`)),env:mapValues(e.env,e=>toCursor(e,`env`)),url:e.url&&toCursor(e.url,`url`),headers:mapValues(e.headers,e=>toCursor(e,`headers`))})))},hr=/^Bearer \$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;function codexEnv(e){let t={},n=[];for(let[r,i]of Object.entries(e??{}))dr.exec(i)?.[1]===r?n.push(r):fr.test(i)?refuse(`env`,`Codex passes a variable through only under its own name`):t[r]=i;return defined({env:Object.keys(t).length?t:void 0,env_vars:n.length?n:void 0})}function codexHeaders(e){let t={},n={},r;for(let[i,a]of Object.entries(e??{})){let e=dr.exec(a)?.[1],o=hr.exec(a)?.[1];o&&i===`Authorization`?r=o:e?n[i]=e:fr.test(a)?refuse(`headers`,`Codex fills a header only from a whole variable reference, or Bearer and one`):t[i]=a}return defined({http_headers:Object.keys(t).length?t:void 0,env_http_headers:Object.keys(n).length?n:void 0,bearer_token_env_var:r})}function stringRecord(e){return isRecord(e)?Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`string`)):{}}function fromCodex(e){let t=Array.isArray(e.env_vars)?e.env_vars.filter(e=>typeof e==`string`):[],n={...stringRecord(e.env),...Object.fromEntries(t.map(e=>[e,`\${${e}}`]))},r=e.bearer_token_env_var,i={...stringRecord(e.http_headers),...Object.fromEntries(Object.entries(stringRecord(e.env_http_headers)).map(([e,t])=>[e,`\${${t}}`])),...typeof r==`string`?{Authorization:`Bearer \${${r}}`}:{}},a=e.tool_timeout_sec;return{command:e.command,args:e.args,env:n,url:e.url,headers:i,enabled:e.enabled,timeout:typeof a==`number`?Math.round(a*1e3):void 0}}const gr={fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`enabled`,`timeout`]),defaults:{timeout:6e4},read:e=>serverFrom(fromCodex(e)),write:e=>rendering(()=>(e.transport===`sse`&&refuse(`transport`,`Codex supports no SSE transport`),assertRunnable(e),noReferenceIn(e,[`command`,`args`,`url`],`Codex`),defined({command:e.command,args:e.args,...codexEnv(e.env),url:e.url,...codexHeaders(e.headers),enabled:e.enabled,tool_timeout_sec:e.timeout===void 0?void 0:e.timeout/1e3})))};function fromGemini(e){let{httpUrl:t,url:n,...r}=e;return typeof t==`string`?{...r,type:`http`,url:t}:typeof n==`string`?{...r,type:`sse`,url:n}:r}const q={"claude-code":pr,cursor:mr,codex:gr,"gemini-cli":{fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`timeout`]),defaults:{timeout:6e5},read:e=>serverFrom(fromGemini(e)),write:e=>rendering(()=>(assertRunnable(e),defined({command:e.command,args:e.args,env:e.env,url:e.transport===`sse`?e.url:void 0,httpUrl:e.transport===`http`?e.url:void 0,headers:e.headers,timeout:e.timeout})))}};function stripJsonComments(e){let t=``,n=0,r=!1,i=!1;for(;n<e.length;){let a=e[n];if(r){t+=a,i?i=!1:a===`\\`?i=!0:a===`"`&&(r=!1),n+=1;continue}if(a===`"`){r=!0,t+=a,n+=1;continue}if(a===`/`&&e[n+1]===`/`){for(;n<e.length&&e[n]!==`
180
+ `)}\n`:``,projectSections:e.status===`found`?e.projectSections:[],resolved:e};return n!==void 0&&(i.stub=`${n}\n`),i}function firstLine(e){return typeof e==`string`&&e.split(`
181
+ `)[0]?.trim()||``}function belongsElsewhere(e,t,n){return t!==void 0&&t!==n&&(e===t||e.startsWith(`${t}.`))}function ownTier(e){return e.trace.layers.find(e=>(e.tier===`repo`||e.tier===`user`)&&e.file&&(e.outcome===`used`||e.outcome===`stale`)&&!e.selection&&!e.empty)?.tier}function holders(e){return[...new Set(e.trace.layers.flatMap(({tier:e,plugin:t,file:n})=>e===`plugin`&&t!==void 0&&n?[t]:[]))]}function referenceImplementations(e,t,n={}){return isFamilyName(e)||e.includes(`*`)?familyImplementations(e,t,n):interfaceImplementations(e,t,n)}function familyInterfaces(e,t,n={}){let r=parseFamily(e);if(r.invalid!==void 0)throw new ReferenceFailure(`name-invalid`,r.invalid);let i=interfaceLookup(t,n),a=aliasIndex(t),o=new Set;for(let e of referenceNames(t)){let t=interfaceIdOf(shownName(e,a));if(t===void 0||!t.startsWith(`${r.prefix}.`))continue;let n=i(t).value;n&&o.add(n.id)}if(!o.size)throw new ReferenceFailure(`interface-unknown`,`no interface document matches ${e}.`,{help:"Run `reference list` for the names found."});return[...o].sort((e,t)=>e.localeCompare(t))}function familyImplementations(e,t,n={}){return{family:e,interfaces:familyInterfaces(e,t,n).map(e=>interfaceImplementations(e,t,n))}}function interfaceImplementations(e,t,n){let{accept:r,...i}=n,a={...i,projectSections:!1},o=parseReferenceName(`${e}${W}`);if(o.invalid||o.plugin!==void 0)throw new ReferenceFailure(`interface-unknown`,`"${e}" is not an interface id.`);let s=interfaceLookup(t,i),c=s(e),l=c.value;if(!l)throw new ReferenceFailure(`interface-unknown`,c.failure?.message??`no interface ${e}`);let u=aliasIndex(t),d=[l.id,...(u.interfaces.get(l.id)??[]).map(({alias:e})=>e)],f=[...r?.length?r:l.versions],p={interface:l.id,cardinality:l.cardinality,accept:f,implementations:[],excluded:[],warnings:[]},m=new Set,warn=e=>{for(let t of e){let e=`${t.code} ${t.message}`;m.has(e)||p.warnings.push(t),m.add(e)}};c.renamed!==void 0&&warn([{code:`reference-renamed`,message:`${e} is an older id of ${l.id}; ask for ${l.id} instead`}]);let inNamespace=e=>d.some(t=>e===t||e.startsWith(`${t}.`)),relevant=(e,t)=>{let n=readImplements(t.metadata??{}).entry?.id;return n!==void 0&&d.includes(n)?!0:inNamespace(e)&&!d.some(t=>belongsElsewhere(e,n,t))},consider=({pin:e,name:t,resolved:n,tier:r})=>{warn(n.warnings);let i=readImplements(n.metadata??{}).entry;if(!i||!d.includes(i.id)){let n=fitsNamespace(l.cardinality,d,t)?``:` and is not named ${l.cardinality===`one`?l.id:`${l.id}.<key>`}`;p.excluded.push({name:e,reasons:[`declares no implements ${l.id}@<version>${n}`]});return}let a=checkResolved(n,s,{id:l.id,versions:f});if(warn(a.warnings),a.failures.length){p.excluded.push({name:e,reasons:a.failures.map(({check:e,message:t})=>`${e}: ${t}`)});return}p.implementations.push({pin:e,description:firstLine(n.metadata?.description),unsupported:a.unsupported,name:t,tier:r,version:i.version})},qualified=(e,n)=>resolveReference(parseReferenceName(`${e}/${n}`),t,a),h=[...new Set(referenceNames(t).map(e=>shownName(e,u)))];for(let e of h){if(interfaceIdOf(e)!==void 0)continue;let n=resolveReference(e,t,a);if(n.status===`ambiguous`){for(let r of n.options??[]){if(r==="default")continue;let i=resolveReference(parseReferenceName(r),t,a);i.status===`found`&&relevant(e,i)&&(warn(i.warnings),p.excluded.push({name:r,reasons:[`ambiguous: ${n.message}; each is left out until a customizer picks one`]}))}continue}if(n.status!==`found`||!relevant(e,n))continue;let r=holders(n),i=l.cardinality===`many`?ownTier(n):void 0;if(i!==void 0){consider({pin:e,name:e,resolved:n,tier:i});for(let t of r)p.excluded.push({name:`${t}/${e}`,reasons:[`the ${i} implementation answers ${e}; a consumer loads it by that name`]});continue}let o=n.trace.stack.filter(e=>e!=="default").at(-1);if(o!==void 0){consider({pin:`${o}/${e}`,name:e,resolved:qualified(o,e),tier:`plugin`});for(let t of r)t!==o&&p.excluded.push({name:`${t}/${e}`,reasons:[`${e} loads the stack of ${o}, the pick; load ${o}/${e}`]})}}if(l.cardinality===`one`){let e=implementationInUse(l.id,t,a,p.implementations);e!==void 0&&(p.inUse=e)}return p}function implementationInUse(e,t,n,r){let i=resolveReference(parseReferenceName(e),t,n);if(i.status!==`found`)return;let a=i.trace.stack.filter(e=>e!=="default").at(-1);return a===void 0?i.trace.stack.includes(`default`)?`default`:void 0:r.find(({pin:t})=>t===`${a}/${e}`)?.pin}function fitsNamespace(e,t,n){return t.some(t=>e===`one`?n===t:n.startsWith(`${t}.`)&&n.length>t.length+1)}function bareName(e){requireName(e);let t=parseReferenceName(e);if(t.invalid)throw new ReferenceFailure(`name-invalid`,t.invalid);if(t.plugin!==void 0)throw new ReferenceFailure(`reference-qualified`,`a contribution is written under the bare name, which every tier resolves; ask for "${t.name}".`);return t}function insideRepository(e,t){let n=canonical(E(t)),r=canonical(e);return r!==n&&!r.startsWith(n+D)?!1:!r.slice(n.length).split(D).includes(`node_modules`)}function below(e,t){let n=T(e,t);return n&&!n.startsWith(`..`)&&!S(n)?n:void 0}function inFolder(e,t){let n=E(e),r=below(E(t),n)??below(canonical(E(t)),canonical(n));if(r===void 0)throw new ReferenceFailure(`in-not-below-root`,`--in names ${n}, which is ${n===E(t)?`the root itself`:`outside the root`}; a project section is written for a folder strictly below the root ${E(t)}.`);return{folder:r.split(D).join(`/`),path:n}}function checkPlaces(e,t){if([e.scope,e.in,e.plugin,e.default].filter(e=>e!==void 0).length>1)throw new ReferenceFailure(`options-conflict`,`pass one of ${t}.`)}function checkScope(e){if(e!==void 0&&e!==`repo`&&e!==`user`)throw new ReferenceFailure(`option-invalid`,`--scope is repo or user; got "${e}".`)}function sourceFolder(e,t,n){let r=E(e);if(!(n===`plugin`?pluginManifestName(r):skillName(r)!==void 0))throw new ReferenceFailure(`folder-invalid`,n===`plugin`?`${r} holds no plugin manifest, so it is not a plugin folder.`:`${r} holds no SKILL.md, so it is not a skill folder.`);if(!insideRepository(r,t))throw new ReferenceFailure(`folder-invalid`,`${r} is outside the repository, such as an installed copy; write to the ${n}'s source instead.`);return r}function writeTarget$1(e,t){let{root:n,home:r,scope:i,plugin:a,default:o}=t;if(a!==void 0){let t=C(sourceFolder(a,n,`plugin`),`references`);return{scope:`plugin`,dir:t,path:C(t,`${e.name}.md`)}}if(o!==void 0){let t=C(sourceFolder(o,n,`skill`),`references`);return{scope:`default`,dir:t,path:C(t,`${e.name}.default.md`)}}if(t.in!==void 0){let{folder:r,path:i}=inFolder(t.in,n),a=C(i,`.agents`,`references`);return{scope:`project`,dir:a,path:C(a,`${e.name}.md`),folder:r,folderPath:i}}let s=i===`user`?userReferencesDir(r):repoReferencesDir(E(n));return{scope:i===`user`?`user`:`repo`,dir:s,path:C(s,`${e.name}.md`)}}__name(writeTarget$1,`writeTarget`);function targetFiles(e,t){return candidateFiles({tier:e.scope==="default"?`default`:`repo`},t).map(t=>C(e.dir,...t.split(`/`)))}function answeringFile(e,t,r){return targetFiles(e,t).find(e=>e!==r&&n(e))}function metadataFile(e,t){return C(e.dir,`${t}${e.scope==="default"?`.default`:``}.meta.md`)}function reachOf(e){return e.scope===`user`?`only you, in every repository`:e.scope===`project`?`everyone working in ${e.folder}`:`everyone working in this repository`}const Vn=`a project section carries no merge (K24); drop --merge or --in.`;function readPicks(e,t){if(e.includes(`none`)){if(e.length>1)throw new ReferenceFailure(`option-invalid`,`--extends none removes the picks, so it takes no other step; got ${e.join(` `)}.`);return`none`}if(!e.length)throw new ReferenceFailure(`option-invalid`,`--extends names one or more steps, or none.`);return{values:e.map(e=>{let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?void 0:e.slice(n+1),a=r.endsWith(`/${t}`)?r.slice(0,-t.length-1):r;if(!H.test(a))throw new ReferenceFailure(`option-invalid`,`--extends takes a plugin, \`<plugin>/${t}\`, or default, each optionally \`:<merge>\`; got "${e}".`);if(i===void 0)return a;if(!isMergeOperation(i))throw new ReferenceFailure(`option-invalid`,`the merge in "${e}" is replace, patch, combine, or remove; got "${i}".`);return{[a]:i}})}}function customizeUsage(e,t){let n=e.extends!==void 0||e.extendsFile!==void 0,r=e.request!==void 0||e.body!==void 0;if(!e.base&&!n&&!r)throw new ReferenceFailure(`change-missing`,`say what to change: --extends or --extends-file picks what the name builds on, and --request with --body writes a generated body.`,{help:`Run \`reference customize ${t.name} --base\` for what the generator reads.`});let conflict=e=>new ReferenceFailure(`options-conflict`,e);if(e.plugin!==void 0)throw conflict("customize never writes a file a plugin ships; an author writes one with `create --plugin`.");if(e.scope!==void 0&&e.in!==void 0)throw conflict(`pass --scope or --in, not both: a customization goes to one place.`);if(e.in!==void 0&&e.merge!==void 0)throw conflict(Vn);if(e.in!==void 0&&n)throw conflict(`a project section has no stack, so it takes no picks; pick for the main document with --scope.`);if(e.extends!==void 0&&e.extendsFile!==void 0)throw conflict(`pass --extends or --extends-file, not both.`);if(e.implements!==void 0&&n)throw conflict(`an implementation is a whole document that replaces the stack, so it takes no picks.`);if(e.base&&(r||e.merge!==void 0||e.dryRun))throw conflict(`--base writes nothing; it takes only --extends or --extends-file, --scope or --in, --default, and --implements.`);if(r&&e.extends?.includes(`none`))throw conflict(`--extends none removes the picks and writes no body; pass it without --request and --body.`);if(r&&(e.request===void 0||e.body===void 0))throw new ReferenceFailure(`options-missing`,e.request===void 0?`--body needs --request: a generated body records the request it was written from.`:`--request needs --body: the command writes the body the generator wrote, and runs no model.`);checkScope(e.scope),checkMerge(e.merge);let i=e.extends===void 0?void 0:readPicks(e.extends,t.name);return e.in!==void 0&&inFolder(e.in,e.root),i?{picks:i}:{}}function checkMerge(e){if(e!==void 0&&!isMergeOperation(e))throw new ReferenceFailure(`option-invalid`,`--merge is replace, patch, combine, or remove; got "${e}".`)}function checkUsage(e){let t=bareName(e.name);if(e.command===`customize`)return{name:t,merge:e.merge,...customizeUsage(e,t)};if(checkPlaces(e,`--scope, --in, --plugin, and --default`),e.command===`create`&&e.in!==void 0&&e.merge!==void 0)throw new ReferenceFailure(`options-conflict`,Vn);checkScope(e.scope),checkMerge(e.merge);let n=e.merge;if(e.in!==void 0&&inFolder(e.in,e.root),e.command===`create`){if(n===`remove`&&e.template!==void 0)throw new ReferenceFailure(`remove-with-template`,`--merge remove writes no body, so it takes no --template.`);if(e.template!==void 0&&e.implements!==void 0)throw new ReferenceFailure(`template-with-implements`,`pass --template or --implements, not both.`)}return{name:t,merge:n}}function lookUpInterface(e,t,n){let r=parseReferenceName(e);if(r.invalid||r.plugin!==void 0)throw new ReferenceFailure(`interface-invalid`,`"${e}" is not an interface id.`);let i=interfaceLookup(t,n)(e);if(!i.value)throw new ReferenceFailure(`interface-invalid`,i.failure?.message??`no interface ${e}`);return i.value}function tryRead$1(e){try{return a(e,`utf8`)}catch{return}}function operationOf(e,t,n,r){if(t.scope===`project`)return;if(e.implements!==void 0)return`replace`;if(t.scope===`plugin`||t.scope==="default")return n;let i=r.metadata.merge;return n??(isMergeOperation(i)?i:void 0)??`patch`}function validateWrite(e,t,n={}){let r=checkUsage(e);if(!t)return r;let{name:i,merge:a}=r,o=n.display??(e=>e);if(!isDirectory$3(e.root))throw new ReferenceFailure(`root-missing`,`the root ${e.root} does not exist or is not a folder.`,{details:{root:e.root}});if(e.command===`customize`)return planCustomize(e,r,t,n);let s=writeTarget$1(i,e);if(e.command===`delete`)return checkFolder(s,i.name),{name:i,merge:a,target:s,before:resolveReference(i,t,n),extended:[]};let c=e.implements!==void 0||a===`remove`?{content:``,metadata:{},body:``}:readTemplate(e.template),l=titleOf(c);if(l)throw new ReferenceFailure(`template-title`,`the template's top level is the single heading "${l}" holding the others; patch matches by heading path, so make its sections top-level.`);let u=e.implements===void 0?void 0:lookUpInterface(e.implements,t,n);checkNamespace(u,s,i);let d=u?implementationTemplate(u):c;checkFolder(s,i.name);let f=resolveReference(i,t,n);checkMarkdown(f,s,i);let p={name:i,merge:a,target:s,template:d,before:f,extended:[]};u&&(p.iface=u);let m=tryRead$1(s.path),h=m===void 0?void 0:parseDocument(m,()=>{});if(p.operation=operationOf(e,s,a,d),p.extended=(readExtends(h?.metadata.extends,()=>{})??readExtends(d.metadata.extends,()=>{})??[]).map(({target:e})=>e).filter(e=>e!=="default"),(s.scope===`plugin`||s.scope==="default")&&p.operation===`replace`&&p.extended.length)throw new ReferenceFailure(`extends-replace`,`a ${s.scope===`plugin`?`plugin's file`:`skill's default`} that extends ${p.extended.join(`, `)} states only the sections it changes, so it takes no merge: replace; to replace the base entirely, write a snapshot of your own with no extends on it.`);if(h&&hasBody(h.body))throw new ReferenceFailure(`file-exists`,`${o(s.path)} already holds "${i.name}"; change it with the reference skill's Update mode.`,{details:{path:o(s.path)}});let g=answeringFile(s,i.name,s.path)??selectingSidecar(s,i.name);if(g)throw new ReferenceFailure(`file-exists`,`${o(g)} already answers "${i.name}" in that folder; change it there, or delete it first.`,{details:{path:o(g)}});return m!==void 0&&(p.existing=m),p}function selectingSidecar(e,t){if(e.scope===`project`)return;let n=metadataFile(e,t),r=tryParse(tryRead$1(n));return r&&r.metadata.extends!==void 0?n:void 0}function checkFolder(e,t){if(e.scope===`project`&&e.folderPath!==void 0&&e.folder!==void 0){if(!isDirectory$3(e.folderPath))throw new ReferenceFailure(`in-folder-missing`,`--in names ${e.folderPath}, which does not exist.`,{details:{folder:e.folder}});if(gitIgnores(e.folderPath,e.path))throw new ReferenceFailure(`in-folder-ignored`,`git ignores ${e.folder}/.agents/references/${t}.md, so load would never read a project section there.`,{details:{folder:e.folder}})}}function checkNamespace(e,t,n){if(!e||t.scope===`project`||fitsName(e,n.name))return;let r=e.cardinality===`one`?e.id:`${e.id}.<key>`;throw new ReferenceFailure(`name-outside-interface`,`an implementation of ${e.id} is named ${r}, not "${n.name}".`,{help:`Name it ${r}, or write it for one folder with --in.`})}function checkMarkdown(e,t,n){if(t.scope===`project`&&e.status===`found`&&e.format!==`markdown`)throw new ReferenceFailure(`in-not-markdown`,`the main document of "${n.name}" is ${e.format}, which has no project sections; customize the main document instead.`)}function readGiven(e,t){try{return a(e,`utf8`)}catch(n){throw new ReferenceFailure(`file-unreadable`,`cannot read the ${t} file ${e}: ${n.message}`,{details:{path:e}})}}function isStep(e){if(typeof e==`string`)return H.test(e);if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);if(t.length!==1)return!1;let[n,r]=t[0];if(!H.test(n))return!1;if(r==null)return!0;if(typeof r==`string`)return isMergeOperation(r);if(typeof r!=`object`||Array.isArray(r))return!1;let i=r;return Object.keys(i).some(e=>e!==`merge`&&e!==`extends`&&e!==`sections`)||i.merge!==void 0&&!isMergeOperation(i.merge)||i.sections!==void 0&&!Array.isArray(i.sections)?!1:i.extends===void 0||Array.isArray(i.extends)&&i.extends.every(isStep)}function readExtendsFile(e){let invalid=t=>new ReferenceFailure(`extends-file-invalid`,`the --extends-file ${e} ${t}.`,{details:{path:e}}),t;try{t=a(e,`utf8`)}catch(e){throw invalid(`cannot be read: ${e.message}`)}let n;try{n=(0,en.parse)(t)}catch(e){throw invalid(`is not YAML: ${e.message}`)}let r=n&&typeof n==`object`&&!Array.isArray(n)?n.extends:n;if(!Array.isArray(r)||!r.length||!r.every(isStep))throw invalid("is not a YAML `extends` list: each step a plugin or default, with only merge, extends, and sections");return{values:r}}function stepsOf(e){if(e===void 0)return;if(e===`none`)return null;let strip=e=>{if(typeof e!=`object`||!e)return e;let[t,n]=Object.entries(e)[0];if(typeof n!=`object`||!n)return e;let{sections:r,extends:i,...a}=n;return{[t]:Array.isArray(i)?{...a,extends:i.map(strip)}:a}};return readExtends(e.values.map(strip),()=>{})??[]}function checkSteps(e,t,n,r){let i=new Set(r.layers.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[])),a=new Set(n.trace.layers.flatMap(({tier:e,plugin:t,file:n})=>e===`plugin`&&t!==void 0&&n&&i.has(t)?[t]:[])),o=e.map(({target:e})=>e).filter(e=>e!=="default"&&!a.has(e));if(o.length)throw new ReferenceFailure(`step-invalid`,`${o.join(`, `)} ${o.length===1?`is`:`are`} neither default nor a plugin holding "${t}"${a.size?`; the plugins holding it are ${[...a].join(`, `)}`:``}.`,{details:{steps:o}})}function coveringInterface(e,t,n){let r=interfaceLookup(t,n),i=e.split(`.`);for(let t=i.length;t>=1;t--){let n=r(i.slice(0,t).join(`.`)).value;if(n&&fitsName(n,e))return n}}function tryParse(e){return e===void 0?void 0:parseDocument(e,()=>{})}function customizeFiles(e,t,n){let r=e.scope===`project`?[e.path,C(e.dir,t,`README.md`)]:[e.path,C(e.dir,t,`README.md`),...V.map(({extension:n})=>C(e.dir,`${t}${n}`))],i=answeringFile(e,t),a=i!==void 0&&r.includes(i)?i:void 0,o=C(e.dir,t,`README.md`),s=e.path,c=`markdown`;if(a!==void 0&&a!==o)s=a,c=formatOfFile(a);else if(a===void 0&&e.scope!==`project`&&n.status===`found`&&n.format!==void 0&&n.format!==`markdown`){c=n.format;let r=[...n.trace.contributions].reverse().find(({path:e})=>formatOfFile(e)===c),i=r?x(r.path):V.find(e=>e.format===c)?.extension;s=C(e.dir,`${t}${i}`)}return{file:s,format:c,holder:c===`markdown`?s:metadataFile(e,t),other:a===o?o:void 0}}function quietInterface(e,t,n){let r=Array.isArray(e)?e[0]:e,i=typeof r==`string`?/^(.+)@\d+$/.exec(r.trim())?.[1]:void 0;return i===void 0?void 0:interfaceLookup(t,n)(i).value}function planCustomize(e,t,n,r){let{name:i}=t,a=r.display??(e=>e),o=writeTarget$1(i,{root:e.root,home:e.home,scope:e.scope,in:e.in}),s=e.request===void 0?void 0:readGiven(e.request,`--request`),c=e.body===void 0?void 0:readGiven(e.body,`--body`),l=e.extendsFile===void 0?t.picks:readExtendsFile(e.extendsFile),u=e.implements===void 0?void 0:lookUpInterface(e.implements,n,r);checkNamespace(u,o,i),checkFolder(o,i.name);let d=resolveReference(i,n,r);checkMarkdown(d,o,i);let f=stepsOf(l);f&&checkSteps(f,i.name,d,baseLayers(n,o));let p=customizeFiles(o,i.name,d),m=tryRead$1(p.file),h=p.holder===p.file?m:tryRead$1(p.holder),g=tryParse(h),_=u||o.scope===`project`?void 0:g?.metadata.implements,v=u??(_===void 0?void 0:quietInterface(_,n,r)),y=resolveBase(i,n,o,f,r),b=s!==void 0||!!e.base;if(b&&l===void 0&&y.status===`ambiguous`)throw new ReferenceFailure(`pick-required`,`"${i.name}" is ambiguous: ${y.message}; pick what it builds on before the request is applied.`,{details:{options:y.options??[]},help:`Pass --extends with the picks, bottom first, from: ${(y.options??[]).join(`, `)}.`});if(b&&!v&&_===void 0&&y.status===`missing`){let e=coveringInterface(i.name,n,r);if(e)throw new ReferenceFailure(`implements-required`,`"${i.name}" is in the namespace of the interface ${e.id}, and nothing implements it; name the interface.`,{details:{interface:e.id},help:`Run \`reference customize ${i.name} --implements ${e.id} --request <file> --body <file>\`.`})}let x=p.format===`markdown`?hasBody(g?.body??``):!!m?.trim();if(s!==void 0&&x&&!isGenerated(g?.metadata))throw new ReferenceFailure(`body-not-generated`,`${a(p.file)} holds a body that records no request, written with create or by hand; customizing would replace it.`,{details:{path:a(p.file)},help:`Change it with the reference skill's Update mode, or delete it first.`});if(p.other&&!e.base)throw new ReferenceFailure(`file-exists`,`${a(p.other)} already answers "${i.name}" in that folder; change it there, or delete it first.`,{details:{path:a(p.other)}});let S={...t,picks:l,target:o,before:d,base:y,file:p.file,format:p.format,holder:p.holder};return f!==void 0&&(S.steps=f),s!==void 0&&(S.request=s),c!==void 0&&(S.body=c),v&&(S.iface=v),u?S.implementsValue=`${u.id}@${u.version}`:typeof _==`string`&&(S.implementsValue=_),m!==void 0&&(S.existing=m),h!==void 0&&(S.held=h),S}function tryRead(e){try{return a(e,`utf8`)}catch{return}}function describeAnswer(e,t=e=>e){if(e.status===`found`){let n=e.trace.contributions.at(-1),r=n?n.tier===`plugin`?`plugin ${n.plugin}`:n.tier==="default"?`the default of ${n.skill}`:`the ${n.tier} file ${t(n.path)}`:void 0,i=e.trace.stack.length?`, on the stack ${e.trace.stack.join(` → `)}`:``,a=[...new Set(e.projectSections.map(({folder:e})=>e))];if(!r)return`"${e.name}" is answered only by the project sections of ${a.join(`, `)}.`;let o=a.length?`, with the project sections of ${a.join(`, `)}`:``;return`"${e.name}" is answered by ${r}${i}${o}.`}return e.status===`ambiguous`?`"${e.name}" is ambiguous: ${e.message}; the options are ${(e.options??[]).join(`, `)}.`:`"${e.name}" is ${e.status}: ${e.message}.`}const Hn=[`merge`,`extends`,`implements`,`aliases`];function selectionKeys(e,t){let n=parseDocument(e,()=>{}).metadata,r={};for(let[e,i]of Object.entries(t.metadata))e!==`merge`&&!(e in n)&&(r[e]=i);return r}function withBody(e,t){let n=t.replace(/^(?:[ \t]*\r?\n)+/,``);return n?`${e.replace(/\s*$/,``)}\n\n${n}`:e}function hiddenWarning(e,t,n,r){let i=t.scope===`project`?projectHidingLayer(e):hidingLayer(e,t.dir,t.path);if(i)return{code:t.scope===`user`&&i.tier===`repo`?`repo-hides-user`:`reference-hidden`,message:`${r(n)} is written, but ${hiderLabel(i,r)} applies above it, so load does not read it until that contribution changes.`}}function createContribution(e,t,n={}){let r=validateWrite({command:`create`,...t},e,n),{name:a,target:o,existing:s,operation:c}=r,l=r.template,u=n.display??(e=>e),d=[],f={merge:c};if(o.scope===`project`)for(let e of Hn)f[e]=void 0,!r.iface&&e in l.metadata&&d.push({code:`project-section-key-ignored`,message:`\`${e}\` is dropped from the project section for ${o.folder}: a project section states only what differs in its folder.`});if((o.scope===`plugin`||o.scope==="default")&&r.extended.length){let t=recordedSources(r.extended,sourceCatalog(e,{tier:o.scope}));Object.assign(f,generatedFrontmatter({sources:t}))}let p=s===void 0?editFrontmatter(l.content,f):withBody(editFrontmatter(s,{...selectionKeys(s,l),...f}),l.body),h=hiddenWarning(r.before,o,o.path,u);h&&d.push(h);let g=hasDescription(parseDocument(p,()=>{}))?[]:["it has no `description` in its frontmatter, so `list` and `search` show it blank"],_={name:a.name,scope:o.scope,path:o.path,content:p,dryRun:!!t.dryRun,hints:g,warnings:d};return o.folder!==void 0&&(_.folder=o.folder),_.dryRun?_:(i(o.dir,{recursive:!0}),m(o.path,p,s===void 0?{flag:`wx`}:{}),(o.scope===`project`||r.before.trace.layers.some(e=>e.path===o.dir||e.path===o.path))&&(_.after=resolveReference(a,{...e,projects:new Map},n)),_)}function placeOf(e){return e.scope===`project`?`project section for ${e.folder}`:e.scope==="default"?`default`:`${e.scope} contribution`}function deleteContribution(e,t,r={}){let{name:i,target:a,before:o}=validateWrite({command:`delete`,...t},e,r),s=r.display??(e=>e),c=!!t.dryRun,l=answeringFile(a,i.name,r.without),f=metadataFile(a,i.name),p=f!==r.without&&n(f),m=l??(p?f:void 0),h={name:i.name,scope:a.scope};if(a.folder!==void 0&&(h.folder=a.folder),!m)return{...h,path:a.path,dryRun:c,code:`no-file`,message:`${s(a.path)} does not exist, so there is no ${placeOf(a)} of "${i.name}" to delete; nothing was deleted. ${describeAnswer(o,r.display)} An installed plugin's, a managed, or an installed skill's contribution is never deleted.`,after:o};let g=l&&formatOfFile(l)!==`markdown`&&p?f:void 0,_=formatOfFile(m)===`markdown`?m:g,v=_===void 0?void 0:readExtends(parseDocument(tryRead(_)??``,()=>{}).metadata.extends,()=>{});if(!c&&(u(m),g&&u(g),b(m)!==a.dir))try{d(b(m))}catch{}let y={...h,path:m,dryRun:c,after:resolveReference(i,{...e,projects:new Map},{...r,without:c?m:void 0})};return g&&(y.metadataFile=g),v&&(y.selection=v.map(({target:e})=>e)),y}function defaultSkill(e){let t=e.layers.find(({tier:e,skipped:t})=>e==="default"&&!t);if(t?.skill===void 0)return;let n=b(t.dir),r=e.layers.find(({tier:e,plugin:t,dir:r})=>e===`plugin`&&t!==void 0&&n.startsWith(b(r)+D));return r?.plugin===void 0?{skill:t.skill}:{skill:t.skill,plugin:r.plugin}}function bodyOf(e){let t=e.held===void 0?void 0:parseDocument(e.held,()=>{}),n=e.format===`markdown`?hasBody(t?.body??``):!!e.existing?.trim();return{metadata:t?.metadata??{},held:n}}function write(e,t){i(b(e),{recursive:!0}),m(e,t)}function writePicks(e,t,n,r){let i=r.display??(e=>e),{name:a,holder:o,picks:s,before:c}=e;n.path=o;let{metadata:l,held:d}=bodyOf(e);if(s===`none`){if(e.held===void 0||!(`extends`in l))return{...n,action:`cleared`,code:`no-selection`,message:`${i(o)} holds no selection of "${a.name}", so nothing was removed. ${describeAnswer(c,r.display)}`,after:c};let s=editFrontmatter(e.held,{extends:void 0,declined:void 0}),d=!s.trim();return n.action=`cleared`,d?n.deleted=!0:n.content=s,n.dryRun?n:(d?u(o):write(o,s),after(n,e,t,r))}let f=s?s.values:[],p=editFrontmatter(e.held??``,{extends:f,declined:declinedBy(e,f)});Object.assign(n,{action:`selection`,content:p,extends:f});let m=hiddenWarning(c,e.target,o,i);return m&&n.warnings.push(m),e.base.trace.builtBy.startsWith(`managed `)&&n.warnings.push({code:`extends-not-used`,message:`the picks are written to ${i(o)}, but ${e.base.trace.builtBy}'s extends builds the stack, so they are not used while it does.`}),d&&isGenerated(l)&&n.hints.push(`its body was generated from a request against the old stack; customize "${a.name}" again with that request (\`reference customize ${a.name} --request <file> --body <file>\`) to regenerate it on the new picks.`),n.dryRun?n:(write(o,p),after(n,e,t,r))}function packageSources(e){let t=new Set(e.trace.stack),n=new Set(e.projectSections.flatMap(({plugin:e})=>e===void 0?[]:[e])),r=new Map;for(let{plugin:i,version:a}of e.trace.projectSections)i===void 0||!n.has(i)||t.has(i)||r.has(i)||r.set(i,a===void 0?{plugin:i}:{plugin:i,version:a});return[...r.values()]}function writeGenerated(e,t,n,r){let i=r.display??(e=>e),{target:a,base:o,picks:s}=e,c=a.scope===`project`,l=!c&&e.implementsValue!==void 0,{metadata:u}=bodyOf(e),d=s&&s!==`none`?s.values:u.extends,f=l||o.status!==`found`?[]:[...recordedSources(o.trace.stack,sourceCatalog(baseLayers(t,a),{tier:a.scope===`user`?`user`:`repo`}),defaultSkill(t)),...c?packageSources(o):[]],p=!c&&!l&&d!==void 0,m={extends:p?d:void 0,declined:p?declinedBy(e,d):void 0,sources:void 0,request:void 0,...generatedFrontmatter({sources:f,request:e.request})},h=e.body;n.action=`generated`,n.path=e.file,e.format===`markdown`?n.content=editFrontmatter(h,{merge:c?void 0:l?`replace`:e.merge??`patch`,implements:l?e.implementsValue:void 0,...m}):(n.content=h,n.metadataFile=e.holder,n.metadataContent=editFrontmatter(e.held??``,{merge:void 0,implements:void 0,...m}));let g=hiddenWarning(e.before,a,e.file,i);return g&&n.warnings.push(g),n.dryRun?n:(write(e.file,n.content),n.metadataContent!==void 0&&write(e.holder,n.metadataContent),after(n,e,t,r))}function declinedBy(e,t){let n=readExtends(t,()=>{});if(!n)return;let r=new Map;for(let{tier:t,plugin:n,file:i,outcome:a,frontmatter:o}of e.base.trace.layers)t!==`plugin`||n===void 0||i===void 0||a.startsWith(`not read`)||r.has(n)||r.set(n,o?.extends);let i=new Set,place=e=>{for(let t of e)i.has(t.target)||(i.add(t.target),place(t.extends??readExtends(r.get(t.target),()=>{})??[]))};place(n);let a=[...r.keys()].filter(e=>!i.has(e));return a.length?a:void 0}function after(e,t,n,r){return{...e,after:resolveReference(t.name,{...n,projects:new Map},r)}}function givesSections(e){return Array.isArray(e)?e.some(givesSections):typeof e!=`object`||!e?!1:Object.values(e).some(e=>{if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.sections!==void 0||givesSections(t.extends)})}function customizeFamily(e,t,n={}){let r=parseFamily(t.name);if(r.invalid!==void 0)throw new ReferenceFailure(`name-invalid`,r.invalid);let i=validateWrite({command:`customize`,...t,name:r.prefix});if([t.base,t.request,t.body,t.implements,t.merge].some(e=>e!==void 0))throw new ReferenceFailure(`options-conflict`,`a family takes only picks: --extends or --extends-file, with --scope and --dry-run; a body, a merge, or a base is per name.`);let a=t.extendsFile===void 0?i.picks:readExtendsFile(t.extendsFile);if(a!==void 0&&a!==`none`&&givesSections(a.values))throw new ReferenceFailure(`step-invalid`,`a step of ${t.name} gives sections, which differ per interface; pick for one interface at a time to change sections.`);let o=interfaceLookup(e,n),s=familyInterfaces(t.name,e,n).map(r=>{if(o(r).value?.cardinality===`many`)return{interface:r,outcome:`skipped`,reason:`${r} is a many interface, which has no single pick.`};let i={...t,name:r};try{let t=validateWrite({command:`customize`,...i},e,n);if(a!==`none`&&t.base.status!==`found`)return{interface:r,outcome:`kept`,reason:`no step holds ${r}; it keeps what it had.`}}catch(e){if(e instanceof ReferenceFailure&&e.code===`step-invalid`)return{interface:r,outcome:`kept`,reason:`${e.message} It keeps what it had.`};throw e}return{interface:r,outcome:`written`,answer:i}}).map(({answer:t,...r})=>t===void 0?r:{...r,result:customizeSingle(e,t,n)});return{family:t.name,scope:t.scope??`repo`,dryRun:!!t.dryRun,interfaces:s}}function customizeContribution(e,t,n={}){return isFamilyName(t.name)||t.name.includes(`*`)?customizeFamily(e,t,n):customizeSingle(e,t,n)}function customizeSingle(e,t,n){let r=validateWrite({command:`customize`,...t},e,n),i={name:r.name.name,scope:r.target.scope,action:`base`,path:r.file,dryRun:!!t.dryRun,hints:[],warnings:[]};return r.target.folder!==void 0&&(i.folder=r.target.folder),t.base?{...i,base:generatorBase(r.base,r.iface)}:r.request===void 0?writePicks(r,e,i,n):writeGenerated(r,e,i,n)}const Un=V.map(({extension:e})=>e);function entries(e){try{return o(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))}catch{return[]}}function valid(e){return!parseReferenceName(e).invalid}function heldFiles(e){let t=[],n=e.tier==="default",r=n?U:``;for(let i of entries(e.dir)){let a=i.name,o=C(e.dir,a);if(i.isDirectory()){!n&&valid(a)&&tryRead$2(C(o,`README.md`))!==void 0&&t.push({name:a,path:C(o,`README.md`),suffix:`/README.md`,kind:`markdown`,folderForm:!0});continue}if(a===`_renames.yaml`)continue;let s=`${r}${Sn}.md`;if(a.endsWith(s)){let e=a.slice(0,-s.length);valid(e)&&t.push({name:e,path:o,suffix:s,kind:`metadata`,folderForm:!1});continue}let c=`${r}.md`;if(a.endsWith(c)){let e=a.slice(0,-c.length);valid(e)&&t.push({name:e,path:o,suffix:c,kind:`markdown`,folderForm:!1});continue}let l=Un.find(e=>a.endsWith(`${r}${e}`));if(l){let e=a.slice(0,-`${r}${l}`.length);valid(e)&&t.push({name:e,path:o,suffix:`${r}${l}`,kind:`data`,folderForm:!1})}}return t}function placesOf(e,t,n){if(n.plugin!==void 0&&n.default!==void 0)throw new ReferenceFailure(`options-conflict`,`pass one of --plugin and --default.`);if(n.plugin!==void 0)return[{tier:`plugin`,dir:C(sourceFolder(n.plugin,t,`plugin`),`references`)}];if(n.default!==void 0)return[{tier:`default`,dir:C(sourceFolder(n.default,t,`skill`),`references`)}];let r=[{tier:`repo`,dir:repoReferencesDir(t)},{tier:`user`,dir:userReferencesDir(n.home)},...projectFolders(t,e.projects).folders.map(({folder:e,dir:t})=>({tier:`project`,dir:t,folder:e}))],i=new Set;return r.filter(({dir:e})=>{let t=E(e);return!i.has(t)&&(i.add(t),!0)})}function renameSources(e){let t=renameTable(e),n=aliasIndex(e);return e=>{if(n.owned.has(e))return[];let r=new Map,add=(e,t)=>r.set(e,(r.get(e)??new Set).add(t));for(let n of t.byOld.get(e)??[])add(n.to,`plugin ${n.plugin}'s ${Ln}`);for(let t of n.byAlias.get(e)??[])add(t.name,`the aliases of ${t.tier===`plugin`?`plugin ${t.plugin}`:`the default of ${t.skill}`}`);return[...r].map(([e,t])=>({to:e,by:[...t].join(` and `)}))}}function holdsName(e,t){let r=e.tier==="default"?U:``;return[`${t}${r}.md`,...e.tier==="default"?[]:[C(t,`README.md`)],...Un.map(e=>`${t}${r}${e}`),`${t}${r}${Sn}.md`].some(t=>n(C(e.dir,t)))}function migrateReferences(e,t){let r=E(t.root??e.root??process.cwd()),i=t.names?.length?new Set(t.names.map(e=>bareName(e).name)):void 0,a=placesOf(e,r,t),o=renameSources(e),s=new Set(e.layers.flatMap(({tier:e,plugin:t,skipped:n})=>e===`plugin`&&t&&!n?[t]:[])),c=[],u=[];for(let e of a){let t=e.folder===void 0?{}:{folder:e.folder},r=e.tier===`repo`||e.tier===`user`||e.tier===`project`,a=new Set,l=heldFiles(e);e.tier==="default"&&l.push(...oldDefaults(e,i,l));for(let s of l){let l=r?o(s.name):[];if(i&&!i.has(s.name)&&!l.some(({to:e})=>i.has(e)))continue;let d={path:s.path,tier:e.tier,...t,name:s.name},f={path:s.path};if(s.kind===`markdown`){let t=tryRead$2(s.path)??``,{metadata:n,body:r}=parseDocument(t,()=>{}),{findings:i,keys:a}=legacyRewrite(n,r,e.tier===`project`?`project`:`contribution`,s.name);for(let e of i)c.push(rowOf(d,e));Object.keys(a).length&&(f.content=editFrontmatter(t,a))}if(s.suffix===`.md`&&e.tier==="default"){let t=C(e.dir,`${s.name}${U}.md`),r=defaultLayoutFinding(s.name);if(n(t)){let{to:e,...t}=r;c.push(rowOf(d,{...t,manual:`${s.name}${U}.md is there too and answers the name; the old file is not read, so delete it by hand once nothing in it is needed`}))}else c.push(rowOf(d,r)),Object.assign(f,{moveFrom:s.path,moveTo:t})}l.length&&renameRow(e,s,l,a,d,c,f),(f.content!==void 0||f.moveTo!==void 0)&&u.push(f)}if(r)for(let n of qualifiedOverrides(e.dir)){if(i&&!i.has(n.name))continue;let r=qualifiedRow(e,n,s,a,{path:n.path,tier:e.tier,...t,name:n.name},c);r&&u.push(r)}}let d=!1;if(t.write)for(let e of u)e.content!==void 0&&m(e.path,e.content),e.moveFrom!==void 0&&e.moveTo!==void 0&&l(e.moveFrom,e.moveTo),e.prune!==void 0&&pruneEmpty(e.prune),d=!0;return{rows:c,written:d,warnings:[...renameTable(e).warnings]}}function rowOf(e,t){let n={...e,form:t.form,from:t.from},r=t.note===void 0?``:`; ${t.reads}, and ${t.note}`;return t.to!==void 0&&(n.to=`${t.to}${r}`),t.manual!==void 0&&(n.manual=`${t.manual}${r}`),n}function oldDefaults(e,t,n){return t?[...t].flatMap(t=>{let r=C(e.dir,`${t}.md`);return tryRead$2(r)===void 0||n.some(e=>e.path===r)?[]:[{name:t,path:r,suffix:`.md`,kind:`markdown`,folderForm:!1}]}):[]}function renameRow(e,t,n,r,i,a,o){let s=t.folderForm?`${t.name}/`:`${t.name}${t.suffix}`,c={...i,form:`renamed`,from:s,by:n.map(({by:e})=>e).join(`; `)};if(n.length>1){a.push({...c,manual:`it is renamed differently: ${n.map(({to:e,by:t})=>`"${e}" by ${t}`).join(`, `)}; rename it by hand to the one that applies`});return}let{to:l}=n[0],u=t.kind===`metadata`||t.kind===`data`;if(holdsName(e,l)&&!r.has(l)||r.has(l)&&!u){a.push({...c,manual:`"${l}" already has a file in that folder; merge the two by hand, then delete this one`});return}r.add(l);let d=t.folderForm?`${l}/`:`${l}${t.suffix}`;a.push({...c,to:d});let f=t.folderForm?b(t.path):t.path;Object.assign(o,{moveFrom:f,moveTo:C(e.dir,t.folderForm?l:`${l}${t.suffix}`)})}function pruneEmpty(e){try{o(e).length||d(e)}catch{}}function qualifiedRow(e,t,n,r,i,a){let{plugin:o,name:s}=t,c=qualifiedOverrideFinding(t,e.tier===`project`?`project`:`contribution`),{to:l,...u}=c,manual=e=>{a.push(rowOf(i,{...u,manual:e}))};if(l===void 0)return manual(c.manual);if(!n.has(o))return manual(`plugin ${o} is not installed; it would become ${l}, extending a plugin that is not there: install ${o} and run migrate again, or delete this file`);if(holdsName(e,s)||r.has(s))return manual(`"${s}" already has a file in that folder; move this file's sections into it and add ${o} to its extends, then delete this one`);let d=tryRead$2(t.path)??``,{metadata:f,body:p}=parseDocument(d,()=>{}),m=[`extends`,`overrides`].find(e=>e in f);if(m!==void 0)return manual(`it also writes \`${m}\`; move it to ${s}.md by hand, with an extends that names ${o}`);r.add(s),a.push(rowOf(i,c));let{findings:h,keys:g}=legacyRewrite(f,p,`contribution`,s);for(let e of h)a.push(rowOf(i,e));return{path:t.path,content:editFrontmatter(d,{...g,extends:[o]}),moveFrom:t.path,moveTo:C(e.dir,`${s}.md`),prune:b(t.path)}}function whereReference(e,t,{root:n,display:r=e=>e,in:i}){typeof e==`string`&&requireName(e);let a=i===void 0?void 0:inFolder(i,n),o=typeof e==`string`?parseReferenceName(e):e,s=resolveReference(o,t,{display:r}),c={name:o.raw,status:s.status,files:[],headings:s.status===`found`&&s.format===`markdown`?headingPaths(s.content??``):[],used:s.trace.stack,layers:s.trace.layers,warnings:s.warnings};if(s.options&&(c.options=s.options),o.invalid)return c;let l=(Array.isArray(t)?t:t.layers).find(({tier:e})=>e===`user`)?.dir,u=[{scope:`repo`,dir:repoReferencesDir(n),path:``},...l?[{scope:`user`,dir:l,path:``}]:[],...a?[{scope:`project`,dir:C(a.path,`.agents`,`references`),path:``,folder:a.folder}]:[]];for(let e of u){let t=answeringFile(e,o.name)??C(e.dir,`${o.name}.md`),i=e.scope===`project`?projectHidingLayer(s):hidingLayer(s,e.dir,t),a={scope:e.folder??e.scope,path:e.scope===`user`?r(t):T(n,t),reaches:reachOf(e)};i&&(a.hiddenBy=hiderLabel(i,r)),c.files.push(a)}return c}function skillsProjection(e,t,n=skillsDirectories(e)?.[t]){let r=n??[],[i]=r;if(i===void 0)throw Error(`cyber-agentkit records no ${t} skills directories for ${e}.`);return r.includes(`.agents/skills`)?{}:{skillsDirectory:i}}const Wn=`.agents/AGENTS.md`,Gn=[{name:`claude-code`,project:{detect:`.claude`,...skillsProjection(`claude-code`,`project`),shadowedBy:[`CLAUDE.md`,`.claude/CLAUDE.md`,`CLAUDE.local.md`],mcpConfig:{path:`.mcp.json`,key:`mcpServers`,format:`json`,dialect:`claude-code`},nonstandard:[{path:`.claude/commands`,shape:`directory`,kind:`command`},{path:`.claude/rules`,shape:`directory`,kind:`rule`},{path:`.claude/agents`,shape:`directory`,kind:`subagent`}]},user:{detect:`.claude`,...skillsProjection(`claude-code`,`user`),relocatedBy:`CLAUDE_CONFIG_DIR`,emptyRelocatesToStart:!0,instructionBridge:{kind:`import`,path:`.claude/CLAUDE.md`,line:`@~/${Wn}`}}},{name:`cursor`,project:{detect:`.cursor`,...skillsProjection(`cursor`,`project`),mcpConfig:{path:`.cursor/mcp.json`,key:`mcpServers`,format:`json`,dialect:`cursor`},nonstandard:[{path:`.cursorrules`,shape:`file`,kind:`instructions`},{path:`.cursor/rules`,shape:`directory`,kind:`rule`},{path:`.cursor/commands`,shape:`directory`,kind:`command`},{path:`.cursor/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.cursor`,...skillsProjection(`cursor`,`user`)}},{name:`codex`,project:{detect:`.codex`,...skillsProjection(`codex`,`project`),mcpConfig:{path:`.codex/config.toml`,key:`mcp_servers`,format:`toml`,dialect:`codex`,shared:!0},nonstandard:[{path:`.codex/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.codex`,...skillsProjection(`codex`,`user`),instructionBridge:{kind:`symlink`,path:`.codex/AGENTS.md`},shadowedBy:[`.codex/AGENTS.override.md`],relocatedBy:`CODEX_HOME`}},{name:`copilot-cli`,project:{detect:`.github/skills`,...skillsProjection(`copilot-cli`,`project`),nonstandard:[{path:`.github/copilot-instructions.md`,shape:`file`,kind:`instructions`},{path:`.github/instructions`,shape:`directory`,kind:`instructions`},{path:`.github/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.copilot`,...skillsProjection(`copilot-cli`,`user`),relocatedBy:`COPILOT_HOME`,instructionBridge:{kind:`symlink`,path:`.copilot/copilot-instructions.md`}}},{name:`gemini-cli`,project:{detect:`.gemini`,...skillsProjection(`gemini-cli`,`project`),instructionBridge:{kind:`settings-entry`,path:`.gemini/settings.json`,key:`context.fileName`},mcpConfig:{path:`.gemini/settings.json`,key:`mcpServers`,format:`json`,dialect:`gemini-cli`,shared:!0},nonstandard:[{path:`GEMINI.md`,shape:`file`,kind:`instructions`},{path:`.gemini/skills`,shape:`directory`,kind:`skill`}]},user:{detect:`.gemini`,...skillsProjection(`gemini-cli`,`user`),instructionBridge:{kind:`symlink`,path:`.gemini/GEMINI.md`}}},{name:`devin-desktop`,project:{detect:`.devin`}},{name:`windsurf`,project:{detect:`.windsurf`,skillsDirectory:`.windsurf/skills`,nonstandard:[{path:`.windsurfrules`,shape:`file`,kind:`instructions`},{path:`.windsurf/rules`,shape:`directory`,kind:`rule`}]},deprecated:`devin-desktop`}],Kn=new Set(Gn.map(e=>e.name));function isHarnessName(e){return Kn.has(e)}function parseHarnesses(e){let t=(e??``).split(`,`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>!isHarnessName(e));if(n.length)throw Error(`Unsupported harness: ${n.join(`, `)}. Supported: ${Gn.map(e=>e.name).join(`, `)}.`);return t.filter(isHarnessName)}const qn=[`claude-code`,`cursor`];function directoryExists(e){try{return r(e).isDirectory()}catch{return!1}}function selectHarnesses(e,t){let n=new Set([...qn,...t]);return Gn.filter(t=>n.has(t.name)||directoryExists(C(e,t.project.detect)))}function fail(e,t,n){throw isCliError(e)?e:new M(e instanceof Error?e.message:t,{code:`command-failed`,exitCode:j.error,...n?{help:n}:{},cause:e})}function answerThenFail(e,t){let n=printAnswer(e,t);throw n!==void 0&&process.stdout.write(n),M.reported(j.error)}function collapseHome$1(e,t){return e&&t.startsWith(e+D)?`~${t.slice(e.length)}`:t}__name(collapseHome$1,`collapseHome`);function displayBinPath(e,t){return t?collapseHome$1(e,t):`buddy-agent-harness`}function parseHarnessOption(e){try{return parseHarnesses(e)}catch(e){throw new M(e.message,{code:`unsupported-harness`,exitCode:j.usage,help:`Pass --harness as a comma-separated list of the supported names.`,cause:e})}}const Jn=new Set([`deps`,`dependencies`,`local`,`plugins`,`marketplace`,`plugin`,`default`]);function isGenericName(e){return Jn.has(e.toLowerCase())}function marketplaceName(e){return e.replace(/^@/,``).replace(/\//g,`-`).replace(/[^a-zA-Z0-9-_.]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)||`agent-plugins`}function buildCatalog({name:e,owner:t,plugins:n}){let r=[...n].sort((e,t)=>e.plugin.localeCompare(t.plugin)).map(({plugin:e,package:t,version:n,description:r})=>{let i={source:`npm`,package:t,version:n};return r?{name:e,source:i,description:r}:{name:e,source:i}});return{name:e,owner:{name:t},description:`Plugins provided by this repository’s dependencies. Generated — do not edit.`,plugins:r}}function serializeCatalog(e){return`${JSON.stringify(e,null,` `)}\n`}function readJson$2(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$2,`readJson`);function readDepPlugin(e,t){let n=packageDir(e,t);if(!n)return{ok:!1,package:e,reason:`unresolved`};let r=readJson$2(C(n,`plugin.json`));if(!r||typeof r!=`object`)return{ok:!1,package:e,reason:`no-manifest`};let i=r,a=typeof i.name==`string`?i.name:void 0;if(!a)return{ok:!1,package:e,reason:`unnamed`};let o=readJson$2(C(n,`package.json`)),s=typeof o?.version==`string`?o.version:void 0;if(!s)return{ok:!1,package:e,reason:`no-manifest`};let c=typeof i.description==`string`?i.description:void 0;return{ok:!0,plugin:c?{package:e,plugin:a,version:s,description:c}:{package:e,plugin:a,version:s}}}function isPnp(){return!!process.versions.pnp}const Yn=C(`.agents`,`buddy-agent-harness`),Xn=C(Yn,`.claude-plugin`,`marketplace.json`);function readManifest(e){return JSON.parse(a(e,`utf8`))}function deriveCatalog(e){let t=C(e,`package.json`),n=readManifest(t),r=[],i=[];for(let e of declaredDependencies(n)){let n=readDepPlugin(e,t);n.ok?r.push(n.plugin):n.reason===`unresolved`&&i.push({package:e,reason:n.reason})}let a=typeof n.name==`string`?n.name:`unknown`,o=marketplaceName(a);return{catalog:buildCatalog({name:o,owner:a,plugins:r}),plugins:r,unresolved:i,genericName:isGenericName(o),pnp:isPnp()}}function catalogStatus(e,t){let n;try{n=a(C(e,Xn),`utf8`)}catch{n=void 0}return n===serializeCatalog(t)?`unchanged`:n===void 0?`created`:`updated`}function writeCatalog(e,t){let n=catalogStatus(e,t);if(n===`unchanged`)return n;let r=C(e,Xn);return i(b(r),{recursive:!0}),m(r,serializeCatalog(t)),n}function readJson$1(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}__name(readJson$1,`readJson`);function directories(e){try{return o(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}function claudeConfigDir(e,t=process.env){return t.CLAUDE_CONFIG_DIR||C(e,`.claude`)}function readClaudeState(e){let t=readJson$1(C(e,`plugins`,`installed_plugins.json`)),n=[];for(let[e,r]of Object.entries(t?.plugins??{}))if(Array.isArray(r))for(let t of r){if(!t||typeof t!=`object`)continue;let r=t,i=typeof r.version==`string`?r.version:void 0,a=typeof r.scope==`string`?r.scope:void 0;if(!i||!a)continue;let o=typeof r.projectPath==`string`?r.projectPath:void 0;n.push(o?{id:e,version:i,scope:a,projectPath:o}:{id:e,version:i,scope:a})}let r=readJson$1(C(e,`plugins`,`known_marketplaces.json`)),i=[];for(let[e,t]of Object.entries(r??{}))i.push({name:e,path:typeof t?.source?.path==`string`?t.source.path:``});return{installed:n,marketplaces:i}}const Zn={name:`claude-code`,scoped:!0,installedOnMachine:(e,t=process.env)=>n(claudeConfigDir(e,t)),state:(e,t=process.env)=>readClaudeState(claudeConfigDir(e,t)),register:e=>`claude plugin marketplace add ./${e} --scope project`,install:e=>`claude plugin install ${e} --scope project`,update:e=>`claude plugin update ${e} --scope project`,uninstall:e=>`claude plugin uninstall ${e} --scope project`,refreshMarketplace:e=>`claude plugin marketplace update ${e}`};function codexHome(e,t=process.env){return t.CODEX_HOME||C(e,`.codex`)}function readCodexState(e){let t=C(e,`plugins`,`cache`),n=[];for(let e of directories(t))for(let r of directories(C(t,e)))for(let i of directories(C(t,e,r)))n.push({id:`${r}@${e}`,version:i,scope:`user`});let r=[],i=``;try{i=a(C(e,`config.toml`),`utf8`)}catch{i=``}let o;for(let e of i.split(`
182
+ `)){let t=/^\s*\[marketplaces\.(?:"([^"]+)"|([^\]]+))\]\s*$/.exec(e);if(t){o={name:t[1]??t[2],path:``},r.push(o);continue}if(/^\s*\[/.test(e)){o=void 0;continue}let n=o?/^\s*source\s*=\s*"([^"]*)"\s*$/.exec(e):void 0;n?.[1]&&o&&(o.path=n[1])}return{installed:n,marketplaces:r}}const Qn=[Zn,{name:`codex`,scoped:!1,installedOnMachine:(e,t=process.env)=>n(codexHome(e,t)),state:(e,t=process.env)=>readCodexState(codexHome(e,t)),register:e=>`codex plugin marketplace add ./${e}`,install:e=>`codex plugin add ${e}`,update:e=>`codex plugin add ${e}`,uninstall:e=>`codex plugin remove ${e}`,refreshMarketplace:()=>``}];function ours(e,t,n,r){let i=`@${t}`;return e.filter(e=>e.id.endsWith(i)&&(!r||e.projectPath===n))}function reconcile({catalog:e,catalogDir:t,root:n,installed:r,marketplaces:i,scoped:a=!0}){let o=i.find(t=>t.name===e.name),s=[],c=t.split(/[\\/]/).filter(Boolean),l=o?c.every(e=>o.path.includes(e)):!1,u=o&&!l?o.path:void 0;o||s.push({kind:`register`,subject:e.name,detail:`marketplace is not registered with this harness`});let d=ours(r,e.name,n,a),f=new Map(d.map(e=>[e.id,e]));for(let t of e.plugins){let n=`${t.name}@${e.name}`,r=f.get(n);if(!r){s.push({kind:`install`,subject:n,detail:`not installed; catalog pins ${t.source.version}`});continue}r.version!==t.source.version&&s.push({kind:`update`,subject:n,detail:`installed ${r.version}, catalog pins ${t.source.version}`})}let p=new Set(e.plugins.map(t=>`${t.name}@${e.name}`));for(let e of d)p.has(e.id)||s.push({kind:`uninstall`,subject:e.id,detail:`installed but no longer in the catalog; it will report a load failure until removed`});return{actions:s,...u?{collision:u}:{},unregistered:!o}}function commandFor(e,t,n){switch(t.kind){case`register`:return e.register(Yn);case`install`:return e.install(t.subject);case`update`:{let r=e.refreshMarketplace(n),i=e.update(t.subject);return r?`${r} && ${i}`:i}case`uninstall`:return e.uninstall(t.subject)}}function notesFor(e){let t=[];e.pnp&&t.push(`Yarn Plug’n’Play is active: dependencies live inside zip archives, so no harness can install from them. Set nodeLinker: node-modules, or unplug the plugin dependencies.`),e.genericName&&t.push(`Marketplace name "${e.catalog.name}" is generic. Registering a second marketplace under a name already in use replaces the first silently, and the install that follows reports "already installed" — the repository then runs the other one's versions.`);for(let{package:n}of e.unresolved)t.push(`Declared dependency "${n}" is not installed; install dependencies before generating.`);return t}const $n=command({name:`dep-plugins`,description:`Derive the marketplace catalog for plugins shipped by this repository’s dependencies, so a harness can install them. Writes the catalog; installing is the harness’s own job.`,options:{root:{description:`Repository directory. Defaults to the current directory.`,type:N.string().optional()},check:{description:`Report whether the catalog is current without writing it. For CI and postinstall.`,type:N.boolean().optional()}},examples:[{command:`buddy-agent-harness dep-plugins`,description:`Write the marketplace catalog for dependency plugins`},{command:`buddy-agent-harness dep-plugins --check`,description:`Fail when the catalog is stale (CI)`}],run(e){try{let t=e.root??process.cwd(),n=deriveCatalog(t),r=e.check?catalogStatus(t,n.catalog)===`unchanged`?`current`:`would-change`:writeCatalog(t,n.catalog),i=_(),a=notesFor(n),o=Qn.filter(e=>e.installedOnMachine(i)),s=[],c=[];for(let e of o){let r=e.state(i),o=reconcile({catalog:n.catalog,catalogDir:Yn,root:E(t),installed:r.installed,marketplaces:r.marketplaces,scoped:e.scoped});o.collision&&a.push(`${e.name}: marketplace "${n.catalog.name}" is already registered against ${o.collision}. Registering over it replaces the other repository's silently, and the install that follows reports "already installed" — rename this repository's marketplace instead.`),s.push({runtime:e.name,status:o.actions.length?`${o.actions.length} to apply`:`in sync`});for(let t of o.actions)c.push({runtime:e.name,do:commandFor(e,t,n.catalog.name),subject:t.subject,why:t.detail})}n.plugins.length&&a.push(`Copilot CLI rejects an npm marketplace source, so it cannot install from this catalog. It needs a path-sourced catalog, which cannot reach node_modules from a subdirectory.`);let l=result({catalog:Xn,marketplace:n.catalog.name,outcome:r,plugins:n.plugins.length?n.plugins.map(({plugin:e,package:t,version:n})=>({name:e,package:t,version:n})):`0 dependencies ship a plugin — nothing to install`,harness:s.length?s:`no supported harness detected on this machine`,actions:c.length?c:`0 actions — every detected harness matches the catalog`,...a.length?{notes:a}:{}});return r===`would-change`?answerThenFail(l,this.format):l}catch(e){return fail(e,`Catalog generation failed.`)}}});function filesUnder(e){try{return o(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(t=>T(e,C(t.parentPath,t.name)).split(D).join(w.sep)).sort()}catch{return[]}}function locatorText({file:e,server:t,field:n,position:r}){return r?`${e}#L${r.line}:${r.column}`:t===void 0?e:`${e}#servers.${t}${n===void 0?``:`.${n}`}`}function repairsOf(e){return Object.entries(e).map(([e,t])=>({problem:e,...t}))}const er=`buddy-agent-harness`,tr=`/buddy-agent-harness:init-buddy-agent-harness`,pnpmSkillRef=e=>`\`${e}\` (pnpm install: \`pnpm-${er}-${e.slice(e.indexOf(`:`)+1)}\`)`,K=pnpmSkillRef(tr),nr=pnpmSkillRef(`/buddy-agent-harness:enhance`),q=pnpmSkillRef(`/buddy-agent-harness:repair`),rr=`.agents/buddy-agent-harness/mcp.toml`,ir={"no-canonical":{detail:`the canonical skill directory does not exist, so no bridge can resolve`,repair:(e,t)=>({command:`${t} init`,instruction:`run \`${t} init\` to create .agents/skills and the bridges into it`}),skillRepair:()=>`run ${K}, which creates \`.agents/skills\` and the bridges`},missing:{detail:`no bridge at this path — the harness sees zero project skills`,repair:({file:e},t)=>({command:`${t} init`,instruction:`run \`${t} init\` to create the bridge at ${e}`}),skillRepair:()=>`run ${K}`},degraded:{detail:`expected a directory but found a regular file — checkout without core.symlinks`,repair:({file:e},t)=>({command:`${t} init --copy --force ${e}`,instruction:`run \`${t} init --copy --force ${e}\` to rebuild ${e} as a real directory`}),skillRepair:({file:e})=>`run \`${tr} --copy --force ${e}\``},stale:{detail:`symlink does not resolve to .agents/skills`,repair:({file:e},t)=>({command:`${t} init --force ${e}`,instruction:`run \`${t} init --force ${e}\` to repoint ${e} at .agents/skills`}),skillRepair:({file:e})=>`run \`${tr} --force ${e}\``},"diverged-bridge":{detail:`only the bridge changed since the two last agreed — an agent wrote through the copy`,repair:({file:e},t)=>({command:``,instruction:`replace .agents/skills with ${e} to keep the newer edit, then run \`${t} init --force ${e}\``}),skillRepair:({file:e})=>`replace .agents/skills with ${e} to keep the newer edit, then run \`${tr} --force ${e}\``},"diverged-canonical":{detail:`only .agents/skills changed since the two last agreed — the copy is stale`,repair:({file:e},t)=>({command:`${t} init --copy --force ${e}`,instruction:`run \`${t} init --copy --force ${e}\` to rebuild ${e} from the newer .agents/skills`}),skillRepair:({file:e})=>`run \`${tr} --copy --force ${e}\``},"diverged-both":{detail:`both sides changed since they last agreed — rebuilding would discard one of them`,repair:({file:e})=>({command:``,instruction:`reconcile .agents/skills with ${e} by hand — rebuilding would discard one of them; \`git diff --no-index .agents/skills ${e}\` shows what differs`}),skillRepair:({file:e})=>`run \`git diff --no-index .agents/skills ${e}\` and reconcile by hand`},"diverged-unknown":{detail:`contents differ and no commit where they agreed was found — which side moved is unknown`,repair:({file:e})=>({command:``,instruction:`reconcile .agents/skills with ${e} by hand — which side moved is unknown; \`git diff --no-index .agents/skills ${e}\` shows what differs`}),skillRepair:({file:e})=>`run \`git diff --no-index .agents/skills ${e}\` and reconcile by hand`},"unpinned-copy":{detail:`tracked copy without the skip-worktree bit — the tree is dirty with content that must not be committed`,repair:({file:e})=>({command:`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree`,instruction:`run \`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree\` to restore the skip-worktree bit`}),skillRepair:({file:e})=>`run \`git ls-files -z ${e} | xargs -0 git update-index --skip-worktree\``}};repairsOf(ir);const ar={"no-instructions":{detail:`no AGENTS.md at the repository root, so the instructions this repository has reach one harness at most`,repair:()=>({command:``,instruction:`hand this to ${K}, which consolidates what the repository has into AGENTS.md, or derives it`}),skillRepair:()=>`run ${K}, which consolidates or derives AGENTS.md`},"instructions-missing":{detail:`no instruction bridge at this path — the harness reads none of AGENTS.md`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${K}, which writes the bridge into it`}),skillRepair:()=>`run ${K}`},"instructions-unbridged":{detail:`the file is present but names AGENTS.md nowhere — the harness reads none of it`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${K}, which adds the bridge without discarding what the file already says`}),skillRepair:()=>`run ${K}, which adds the bridge without discarding what the file already says`},"instructions-shadowing":{detail:`this file suppresses the AGENTS.md beside it — the harness reads this instead, and none of AGENTS.md`,repair:({file:e})=>({command:``,instruction:`hand ${e} to ${K}, which consolidates what it says into AGENTS.md, or adds an @AGENTS.md import above it where the file has to stay`}),skillRepair:()=>`run ${K}, which consolidates the file into AGENTS.md or imports AGENTS.md from it`},"instructions-superseded":{detail:`a bridge from before the harness read AGENTS.md itself — it still works, and nothing needs it`,repair:({file:e})=>({command:``,instruction:`remove ${e}, or keep it for sessions that cannot read AGENTS.md directly — ${K} offers the choice`}),skillRepair:()=>`run ${K}, which offers to remove it`},"instructions-unreadable":{detail:`the settings file does not parse, so the harness reads none of it`,repair:({file:e})=>({command:``,instruction:`fix the JSON in ${e} by hand, then hand it to ${K}`}),skillRepair:()=>`fix the JSON by hand, then run ${K}`}};repairsOf(ar);const or=`~/${Wn}`;function globalBridgeStep(e,t=`~/${e.path}`){return e.kind===`import`?`add the line \`${e.line}\` to ${t}`:`run \`ln -s ${or} ${t}\``}function userSpellings(e,t){let n=`${e.detect}/`;return e.relocatedBy!==void 0&&t.startsWith(n)?[`~/${t}`,`$${e.relocatedBy}/${t.slice(n.length)}`]:[`~/${t}`]}function userBridgeAt(e){for(let{user:t}of Gn){let n=t?.instructionBridge;if(t&&n&&userSpellings(t,n.path).includes(e))return n}}function stepAt(e,t){let n=userBridgeAt(e);return n===void 0?`add the bridge the harness page names for ${e}`:`${t&&n.kind!==`import`?`move what ${e} says into ${or} and remove it, then `:``}${globalBridgeStep(n,e)}`}const sr=`hand the user this step, since nothing here writes outside the repository:`,cr={"global-instructions-missing":{detail:`no user-scope instruction file at this path — the harness loads none of ${or}`,repair:({file:e})=>({command:``,instruction:`${sr} ${stepAt(e,!1)}`}),skillRepair:()=>`hand the user the step the harness page names for that file; write nothing yourself`},"global-instructions-unbridged":{detail:`the file holds its own content and does not load ${or} — text placed there reaches no session of this harness`,repair:({file:e})=>({command:``,instruction:`${sr} ${stepAt(e,!0)}`}),skillRepair:()=>`hand the user the step the harness page names for that file, keeping what the file says; write nothing yourself`},"global-instructions-overridden":{detail:`the harness reads this file in place of its own user-scope file, so whatever that file loads goes unread, and this one does not load ${or}`,repair:({file:e})=>({command:``,instruction:`${sr} move what ${e} says into ${or} and remove it`}),skillRepair:()=>`hand the user the move of what that file says into the global file, and its removal; write nothing yourself`},"global-instructions-emptied":{detail:`the variable is set but empty, which this harness reads as the directory it starts in rather than as unset — its user-scope file is whichever one sits there, not the one in its own folder`,repair:({file:e})=>({command:``,instruction:`${sr} unset ${e.slice(1)} where your shell sets it, or set it to the folder you meant`}),skillRepair:()=>`hand the user the step of unsetting that variable; write nothing yourself`}};repairsOf(cr);const lr={"deprecated-harness":{detail:`a projection under a harness name that has been superseded — the replacement reads .agents/skills natively and needs no projection at all`,repair:({file:e})=>({command:``,instruction:`remove ${e} and enable the harness that replaced it — ${q} offers the correction`}),skillRepair:()=>`run ${q}`},"ignored-bridge":{detail:`a .gitignore rule matches this bridge — an untracked bridge swallows a real edit silently`,repair:({file:e})=>({command:``,instruction:`narrow or remove the .gitignore rule matching ${e} — ${q} offers the correction`}),skillRepair:()=>`run ${q}`},"unread-local-override":{detail:`no harness reads this filename, so everything in it is invisible to every agent`,repair:({file:e})=>({command:``,instruction:`move ${e} to CLAUDE.local.md, or consolidate it into AGENTS.md — ${q} offers the correction`}),skillRepair:()=>`run ${q}`},"unloadable-skill":{detail:`frontmatter that does not parse, or no description — either one makes a harness skip the skill outright`,repair:({file:e})=>({command:``,instruction:`quote the description in ${e}, or add one — ${q} offers the correction`}),skillRepair:()=>`run ${q}`}};repairsOf(lr);const ur={"mcp-golden-unreadable":{detail:`the golden MCP set does not parse — the locator gives the line and column, and nothing else can be said about it`,repair:e=>({command:``,instruction:`fix the TOML at ${locatorText(e)}`}),skillRepair:e=>`fix the TOML at ${locatorText(e)} by hand — the reported line and column are all that can be quoted, because the parser's own message repeats the offending line and that line is the one holding the credential`},"mcp-target-unreadable":{detail:`this harness config does not parse, so the harness starts none of its servers and nothing in it can be compared`,repair:e=>({command:``,instruction:`fix the syntax of ${locatorText(e)}`}),skillRepair:e=>`fix the syntax of ${locatorText(e)} by hand`},"mcp-unprojected":{detail:`the golden set declares this server and the harness config does not carry it`,repair:({file:e,server:t})=>({command:``,instruction:`add the server ${t} to ${e}, or drop it from the golden set — ${q} offers the correction`}),skillRepair:e=>`hand ${locatorText(e)} to ${q}, which projects it from its golden entry with \`mcp project\` — or drop it from the golden set`},"mcp-undeclared":{detail:`the harness config carries this server and the golden set does not declare it`,repair:({file:e,server:t})=>({command:``,instruction:`add the server ${t} to ${rr}, or drop it from ${e} — ${q} offers the import`}),skillRepair:e=>`hand ${locatorText(e)} to ${q}, which imports it field by field with \`mcp reconcile\`, refusing any literal credential — or drop it from ${e.file}`},"mcp-diverged-target":{detail:`only the harness config changed since the two last agreed — the edit was made through the copy`,repair:e=>({command:``,instruction:`reconcile the value at ${locatorText(e)} back into ${rr} — ${q} offers the import`}),skillRepair:e=>`hand ${locatorText(e)} to ${q}, which imports the field into ${rr} with \`mcp reconcile\` once approved`},"mcp-diverged-golden":{detail:`only the golden set changed since the two last agreed — the harness copy is stale`,repair:e=>({command:``,instruction:`update ${locatorText(e)} from the golden entry — ${q} offers the correction`}),skillRepair:e=>`hand ${locatorText(e)} to ${q}, which updates it from the golden entry with \`mcp project\``},"mcp-diverged-both":{detail:`both sides changed since they last agreed — merging either way would discard the other`,repair:e=>({command:``,instruction:`reconcile ${locatorText(e)} against ${rr} by hand`}),skillRepair:e=>`reconcile ${locatorText(e)} against ${rr} by hand — never merge a three-way conflict automatically`},"mcp-diverged-unknown":{detail:`the two disagree and no baseline says which side moved — neither history nor a last-projected record covers this server`,repair:e=>({command:``,instruction:`compare ${locatorText(e)} against ${rr} by hand`}),skillRepair:e=>`compare ${locatorText(e)} against ${rr} by hand`},"mcp-literal-secret":{detail:`a credential-bearing field holds a literal rather than a reference to an environment variable`,repair:e=>({command:``,instruction:`move the value at ${locatorText(e)} into an environment variable and reference it`}),skillRepair:e=>`move the value at ${locatorText(e)} into an environment variable and reference it — read the value from the file, never from this report, and never repeat it back`},"mcp-committed-secret":{detail:`a credential-bearing field holds a literal in a git-tracked file — the credential is committed, and moving it does not un-commit it`,repair:e=>({command:``,instruction:`rotate the credential behind ${locatorText(e)}, then reference it from an environment variable`}),skillRepair:e=>`rotate the credential behind ${locatorText(e)} at its issuer, then reference it from an environment variable — it is in the repository's history, so moving it is not enough`}};repairsOf(ur);const dr={"nonstandard-instructions":{detail:`instruction content only one harness reads — AGENTS.md carries the same prose to all of them`,repair:({file:e})=>({command:``,instruction:`consolidate ${e} into AGENTS.md — ${K} offers the consolidation, and keeps the content reachable where this harness needs it`}),skillRepair:({file:e})=>`hand ${e} to ${K}, which consolidates it into AGENTS.md`},"nonstandard-rule":{detail:`a path-scoped rule only one harness reads — a skill reaches every harness where the scoping is incidental`,repair:({file:e})=>({command:``,instruction:`convert ${e} into a skill under .agents/skills where its guidance is not tied to the paths it names — ${K} offers the conversion; keep it where the path scoping is the point`}),skillRepair:({file:e})=>`hand ${e} to ${K} to convert into a skill, unless the path scoping is load-bearing`},"nonstandard-command":{detail:`a harness command file — a skill is the portable form, and this harness reads skills too`,repair:({file:e})=>({command:``,instruction:`move ${e} to .agents/skills/<name>/SKILL.md — ${K} offers the move`}),skillRepair:({file:e})=>`hand ${e} to ${K}, which moves it to .agents/skills`},"nonstandard-skill":{detail:`a skill under a harness directory rather than the canonical one, where only that harness finds it`,repair:({file:e})=>({command:``,instruction:`move ${e} to .agents/skills and project it back where the harness needs one — ${K} offers the move`}),skillRepair:({file:e})=>`hand ${e} to ${K}, which moves it to .agents/skills`},"nonstandard-subagent":{detail:`a subagent definition with no cross-harness form — nothing outside this harness can read it, and no canonical form exists yet`,repair:({file:e})=>({command:``,instruction:`leave ${e} where it is and record that it reaches one harness only — no portable form exists to convert it to`}),skillRepair:({file:e})=>`leave ${e} in place — no portable form exists yet, so this is work for a person rather than a skill`}};repairsOf(dr);const fr=`${K} offers it, or ${nr} where the repository already has an AGENTS.md`,pr={"worktrees-untracked":{detail:`.claude/worktrees/ is not git-ignored, so every agent worktree Claude Code creates there shows up as untracked in git status`,repair:({file:e})=>({command:``,instruction:`add \`.claude/worktrees/\` to ${e} — ${fr}`}),skillRepair:()=>`run ${K} or ${nr}, which offers the .gitignore line`},"worktrees-scanned":{detail:`this config does not exclude .claude/worktrees, so the tool walks into each agent worktree, a whole checkout with its own config, and Biome stops on the nested root configuration`,repair:({file:e})=>({command:``,instruction:`add \`"!**/.claude/worktrees"\` to \`files.includes\` in ${e} — ${fr}`}),skillRepair:()=>`run ${K} or ${nr}, which offers the exclusion`},"worktree-base-unset":{detail:`worktree.baseRef is unset, so agent worktrees branch from the default branch rather than the current HEAD — work on a feature branch starts without its commits`,repair:({file:e})=>({command:``,instruction:`decide whether agent worktrees should branch from HEAD, and if so set \`"worktree": { "baseRef": "head" }\` in ${e} — ${fr}`}),skillRepair:()=>`run ${K} or ${nr}, which explains the trade-off and offers the setting`}};repairsOf(pr);const mr={...ir,...ar,...cr,...lr,...ur,...dr,...pr};repairsOf(mr);function repairFor(e){return{problem:e,...mr[e]}}const hr=`.agents/skills`,gr=`AGENTS.local.md`;function frontmatterFault(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);if(!t)return`unparseable`;let n=/^description:[ \t]*(.*)$/m.exec(t[1])?.[1]?.trim();if(!n)return`no-description`;if(!/^(['"]).*\1$/.test(n)&&/:\s/.test(n))return`unparseable`}function diagnoseConfiguration({root:e,git:t,cli:r}){let i=[],add=(e,t)=>{let{detail:n,repair:a}=repairFor(t);i.push({path:e,problem:t,detail:n,repair:a({file:e},r)})},o=selectHarnesses(e,[]);for(let t of o){let r=t.project.skillsDirectory;t.deprecated&&r&&n(C(e,r))&&add(r,`deprecated-harness`)}for(let r of o){let i=r.project.skillsDirectory;i&&n(C(e,i))&&t.isIgnored(i)&&add(i,`ignored-bridge`)}n(C(e,gr))&&add(gr,`unread-local-override`);for(let t of filesUnder(C(e,hr)).filter(e=>e.endsWith(`SKILL.md`)))frontmatterFault(a(C(e,hr,t),`utf8`))&&add(`${hr}/${t}`,`unloadable-skill`);return i}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const _r=[`transport`,`command`,`args`,`env`,`url`,`headers`,`description`,`enabled`,`timeout`,`source`],vr=new Set([`env`,`headers`]);function sameValue(e,t,n){if(vr.has(e)&&isRecord(t)&&isRecord(n)){let e=Object.keys(t);return e.length===Object.keys(n).length&&e.every(e=>t[e]===n[e])}return JSON.stringify(t)===JSON.stringify(n)}function divergingFields(e,t,n=new Set(_r)){return _r.filter(r=>{if(!n.has(r))return!1;let i=e[r];if(i===void 0)return!1;if(vr.has(r)&&isRecord(i)&&isRecord(t[r])){let e=t[r];return Object.keys(i).some(t=>i[t]!==e[t])}return!sameValue(r,i,t[r])})}function sameField(e,t,n){return sameValue(e,t?.[e],n?.[e])}function stringMap(e){if(!isRecord(e))return;let t=Object.entries(e).filter(([,e])=>typeof e==`string`);return t.length?Object.fromEntries(t):void 0}const yr=new Set([`stdio`,`http`,`sse`]);function transportOf(e){let t=e.type??e.transport;if(typeof t==`string`&&yr.has(t))return t;if(typeof e.url==`string`)return`http`;if(typeof e.command==`string`)return`stdio`}function serverFrom(e){let t=Array.isArray(e.args)&&e.args.every(e=>typeof e==`string`),n=transportOf(e),r=stringMap(e.env),i=stringMap(e.headers);return{...n?{transport:n}:{},...typeof e.command==`string`?{command:e.command}:{},...t?{args:e.args}:{},...r?{env:r}:{},...typeof e.url==`string`?{url:e.url}:{},...i?{headers:i}:{},...typeof e.description==`string`?{description:e.description}:{},...typeof e.enabled==`boolean`?{enabled:e.enabled}:{},...typeof e.timeout==`number`?{timeout:e.timeout}:{},...typeof e.source==`string`?{source:e.source}:{}}}const br=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/,xr=/\$\{[^}]*\}|\$[A-Za-z_]/;var Refusal=class extends Error{field;reason;constructor(e,t){super(t),this.field=e,this.reason=t}};function refuse(e,t){throw new Refusal(e,t)}function rendering(e){try{return{kind:`entry`,entry:e()}}catch(e){if(!(e instanceof Refusal))throw e;return{kind:`refused`,field:e.field,reason:e.reason}}}function assertRunnable(e){(e.transport===`stdio`?!e.command:!e.url)&&refuse(e.transport===`stdio`?`command`:`url`,`the golden set leaves it unset and the target requires it`)}function defined(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function mapValues(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t(n)]))}function noReferenceIn(e,t,n){for(let r of t){let t=e[r];(Array.isArray(t)?t:[t]).some(e=>typeof e==`string`&&xr.test(e))&&refuse(r,`${n} documents no reference expansion here`)}}const Sr={fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`description`,`timeout`]),read:serverFrom,write:e=>rendering(()=>(assertRunnable(e),defined({type:e.transport,command:e.command,args:e.args,env:e.env,url:e.url,headers:e.headers,description:e.description,timeout:e.timeout})))};function toCursor(e,t){return e.replace(/\$\{([^}]*)\}|\$[A-Za-z_]/g,(e,n)=>((n===void 0||!br.test(e))&&refuse(t,`Cursor expands only a plain variable reference, with no default`),`\${env:${n}}`))}function fromCursor(e){return e.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,t)=>`\${${t}}`)}function fromCursorEntry(e){let strings=e=>typeof e==`string`?fromCursor(e):e,map=e=>isRecord(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,strings(t)])):e;return{...e,command:strings(e.command),args:Array.isArray(e.args)?e.args.map(strings):e.args,env:map(e.env),url:strings(e.url),headers:map(e.headers)}}const Cr={fields:new Set([`command`,`args`,`env`,`url`,`headers`]),read:e=>serverFrom(fromCursorEntry(e)),write:e=>rendering(()=>(assertRunnable(e),defined({type:e.transport===`stdio`?`stdio`:void 0,command:e.command&&toCursor(e.command,`command`),args:e.args?.map(e=>toCursor(e,`args`)),env:mapValues(e.env,e=>toCursor(e,`env`)),url:e.url&&toCursor(e.url,`url`),headers:mapValues(e.headers,e=>toCursor(e,`headers`))})))},wr=/^Bearer \$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;function codexEnv(e){let t={},n=[];for(let[r,i]of Object.entries(e??{}))br.exec(i)?.[1]===r?n.push(r):xr.test(i)?refuse(`env`,`Codex passes a variable through only under its own name`):t[r]=i;return defined({env:Object.keys(t).length?t:void 0,env_vars:n.length?n:void 0})}function codexHeaders(e){let t={},n={},r;for(let[i,a]of Object.entries(e??{})){let e=br.exec(a)?.[1],o=wr.exec(a)?.[1];o&&i===`Authorization`?r=o:e?n[i]=e:xr.test(a)?refuse(`headers`,`Codex fills a header only from a whole variable reference, or Bearer and one`):t[i]=a}return defined({http_headers:Object.keys(t).length?t:void 0,env_http_headers:Object.keys(n).length?n:void 0,bearer_token_env_var:r})}function stringRecord(e){return isRecord(e)?Object.fromEntries(Object.entries(e).filter(([,e])=>typeof e==`string`)):{}}function fromCodex(e){let t=Array.isArray(e.env_vars)?e.env_vars.filter(e=>typeof e==`string`):[],n={...stringRecord(e.env),...Object.fromEntries(t.map(e=>[e,`\${${e}}`]))},r=e.bearer_token_env_var,i={...stringRecord(e.http_headers),...Object.fromEntries(Object.entries(stringRecord(e.env_http_headers)).map(([e,t])=>[e,`\${${t}}`])),...typeof r==`string`?{Authorization:`Bearer \${${r}}`}:{}},a=e.tool_timeout_sec;return{command:e.command,args:e.args,env:n,url:e.url,headers:i,enabled:e.enabled,timeout:typeof a==`number`?Math.round(a*1e3):void 0}}const Tr={fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`enabled`,`timeout`]),defaults:{timeout:6e4},read:e=>serverFrom(fromCodex(e)),write:e=>rendering(()=>(e.transport===`sse`&&refuse(`transport`,`Codex supports no SSE transport`),assertRunnable(e),noReferenceIn(e,[`command`,`args`,`url`],`Codex`),defined({command:e.command,args:e.args,...codexEnv(e.env),url:e.url,...codexHeaders(e.headers),enabled:e.enabled,tool_timeout_sec:e.timeout===void 0?void 0:e.timeout/1e3})))};function fromGemini(e){let{httpUrl:t,url:n,...r}=e;return typeof t==`string`?{...r,type:`http`,url:t}:typeof n==`string`?{...r,type:`sse`,url:n}:r}const Er={"claude-code":Sr,cursor:Cr,codex:Tr,"gemini-cli":{fields:new Set([`transport`,`command`,`args`,`env`,`url`,`headers`,`timeout`]),defaults:{timeout:6e5},read:e=>serverFrom(fromGemini(e)),write:e=>rendering(()=>(assertRunnable(e),defined({command:e.command,args:e.args,env:e.env,url:e.transport===`sse`?e.url:void 0,httpUrl:e.transport===`http`?e.url:void 0,headers:e.headers,timeout:e.timeout})))}};function stripJsonComments(e){let t=``,n=0,r=!1,i=!1;for(;n<e.length;){let a=e[n];if(r){t+=a,i?i=!1:a===`\\`?i=!0:a===`"`&&(r=!1),n+=1;continue}if(a===`"`){r=!0,t+=a,n+=1;continue}if(a===`/`&&e[n+1]===`/`){for(;n<e.length&&e[n]!==`
178
183
  `;)n+=1;continue}if(a===`/`&&e[n+1]===`*`){for(n+=2;n<e.length&&(e[n]!==`*`||e[n+1]!==`/`);)n+=1;n+=2;continue}t+=a,n+=1}return t}function parseJsonWithComments(e){try{return JSON.parse(stripJsonComments(e))}catch{return}}
179
184
  /*!
180
185
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -262,7 +267,7 @@ function parseString(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s
262
267
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
263
268
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
264
269
  */
265
- let _r=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var vr=class TomlDate extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`){if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(_r);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(e,t=`Z`){let n=new TomlDate(e);return n.#n=t,n}static wrapAsLocalDateTime(e){let t=new TomlDate(e);return t.#n=null,t}static wrapAsLocalDate(e){let t=new TomlDate(e);return t.#t=!1,t.#n=null,t}static wrapAsLocalTime(e){let t=new TomlDate(e);return t.#e=!1,t.#n=null,t}};
270
+ let Dr=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var Or=class TomlDate extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`){if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(Dr);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(e,t=`Z`){let n=new TomlDate(e);return n.#n=t,n}static wrapAsLocalDateTime(e){let t=new TomlDate(e);return t.#n=null,t}static wrapAsLocalDate(e){let t=new TomlDate(e);return t.#t=!1,t.#n=null,t}static wrapAsLocalTime(e){let t=new TomlDate(e);return t.#e=!1,t.#n=null,t}};
266
271
  /*!
267
272
  * Copyright (c) Squirrel Chat et al., All rights reserved.
268
273
  * SPDX-License-Identifier: BSD-3-Clause
@@ -290,7 +295,7 @@ let _r=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
290
295
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
291
296
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
292
297
  */
293
- function isDigit$2(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}__name(isDigit$2,`isDigit`);function isEndOfValue(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function extractValue(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||J.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?parseArray(e):parseInlineTable(e);return e.d++,t}return r===34||r===39?parseString(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&J.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&J.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?parseNumber(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?parseDate(e,r,t):e.s.charCodeAt(e.p+2)===58?parseTime(e,r,t):parseNumber(e,e.p,r,0,t)}function parseNumber(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&J.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&J.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||isEndOfValue(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return parseIntegerBaseN(e,t,16,i);if(a===98)return parseIntegerBaseN(e,t,2,i);if(a===111)return parseIntegerBaseN(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:J.x(`illegal leading zero`,e,t)}else isDigit$2(a)||J.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!isEndOfValue(a,i));)o||=1,a===95?(o&1||J.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)||(isDigit$2(a)?o>9?o-=11:o&1||o++:J.x(`illegal character in numeric literal`,e));if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||J.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):parseInteger(e,c,10,t)}function parseIntegerBaseN(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!isEndOfValue(i,r));)i===95?(a&1&&J.x(`illegal underscore`,e),a=3):isDigit$2(i,n)?a&1&&a--:J.x(`illegal character in numeric literal`,e);a&1&&J.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),parseInteger(e,o,n,t)}function parseInteger(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;J.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function parseDate(e,t,n){let r=e.p++,i;if(!isDigit$2(t)||!isDigit$2(e.s.charCodeAt(e.p++))||!isDigit$2(e.s.charCodeAt(e.p++))||!isDigit$2(e.s.charCodeAt(e.p++)))return parseNumber(e,e.p=r,t,0,n);if(e.p+=5,isDigit$2(e.s.charCodeAt(e.p++))||J.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!isDigit$2(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return readDate(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&J.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;isDigit$2(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return readDate(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return readDate(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return readDate(e,e.s.slice(r,e.p),2,i,r)}function parseTime(e,t,n){let r=e.p;if(!isDigit$2(t)||!isDigit$2(e.s.charCodeAt(++e.p)))return parseNumber(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;isDigit$2(e.s.charCodeAt(++e.p)););return readDate(e,e.s.slice(r,e.p),4,!1,r)}function readDate(e,t,n,r,i,a){if(e.ld){let a=new vr(t,n,r);return a.isValid()||J.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){J.x(t instanceof Error?t.message:``+t,e,i)}}
298
+ function isDigit$2(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}__name(isDigit$2,`isDigit`);function isEndOfValue(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function extractValue(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||J.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?parseArray(e):parseInlineTable(e);return e.d++,t}return r===34||r===39?parseString(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&J.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&J.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?parseNumber(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?parseDate(e,r,t):e.s.charCodeAt(e.p+2)===58?parseTime(e,r,t):parseNumber(e,e.p,r,0,t)}function parseNumber(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&J.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&J.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||isEndOfValue(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return parseIntegerBaseN(e,t,16,i);if(a===98)return parseIntegerBaseN(e,t,2,i);if(a===111)return parseIntegerBaseN(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:J.x(`illegal leading zero`,e,t)}else isDigit$2(a)||J.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!isEndOfValue(a,i));)o||=1,a===95?(o&1||J.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)||(isDigit$2(a)?o>9?o-=11:o&1||o++:J.x(`illegal character in numeric literal`,e));if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||J.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):parseInteger(e,c,10,t)}function parseIntegerBaseN(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!isEndOfValue(i,r));)i===95?(a&1&&J.x(`illegal underscore`,e),a=3):isDigit$2(i,n)?a&1&&a--:J.x(`illegal character in numeric literal`,e);a&1&&J.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),parseInteger(e,o,n,t)}function parseInteger(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;J.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function parseDate(e,t,n){let r=e.p++,i;if(!isDigit$2(t)||!isDigit$2(e.s.charCodeAt(e.p++))||!isDigit$2(e.s.charCodeAt(e.p++))||!isDigit$2(e.s.charCodeAt(e.p++)))return parseNumber(e,e.p=r,t,0,n);if(e.p+=5,isDigit$2(e.s.charCodeAt(e.p++))||J.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!isDigit$2(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return readDate(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&J.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;isDigit$2(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return readDate(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return readDate(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return readDate(e,e.s.slice(r,e.p),2,i,r)}function parseTime(e,t,n){let r=e.p;if(!isDigit$2(t)||!isDigit$2(e.s.charCodeAt(++e.p)))return parseNumber(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;isDigit$2(e.s.charCodeAt(++e.p)););return readDate(e,e.s.slice(r,e.p),4,!1,r)}function readDate(e,t,n,r,i,a){if(e.ld){let a=new Or(t,n,r);return a.isValid()||J.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){J.x(t instanceof Error?t.message:``+t,e,i)}}
294
299
  /*!
295
300
  * Copyright (c) Squirrel Chat et al., All rights reserved.
296
301
  * SPDX-License-Identifier: BSD-3-Clause
@@ -402,7 +407,7 @@ function peekTable(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){i
402
407
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
403
408
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
404
409
  */
405
- let yr=/^[a-z0-9-_]+$/i,br=!!``.isWellFormed;function extendedTypeOf(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(typeof e.getUTCDate==`function`&&e instanceof Date)return`date`;if(globalThis.Temporal){if(e.until){if(e instanceof Temporal.ZonedDateTime)return`temporal/tz+uc`;if(e instanceof Temporal.PlainDateTime||e instanceof Temporal.PlainDate)return`temporal/uc`;if(e instanceof Temporal.PlainTime||e instanceof Temporal.Instant)return`temporal`;if(e instanceof Temporal.PlainYearMonth)return`temporal/x`}else if(e.toPlainDate&&e instanceof Temporal.PlainMonthDay||e.negated&&e instanceof Temporal.Duration)return`temporal/x`}}return t}function isArrayOfTables(e){for(let t=0;t<e.length;t++)if(extendedTypeOf(e[t])!==`object`)return!1;return e.length!=0}function formatWellFormedStringUnchecked(e){return JSON.stringify(e).replaceAll(``,`\\u007f`)}function formatString(e){return formatWellFormedStringUnchecked(br?e.toWellFormed():e)}function formatKey(e){if(yr.test(e))return e;if(br&&!e.isWellFormed())throw RangeError(`key contains illegal lone surrogates`);return formatWellFormedStringUnchecked(e)}function stringifyValue(e,t,n,r,i){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);switch(t){case`number`:if(isNaN(e))return`nan`;if(e===1/0)return`inf`;if(e===-1/0)return`-inf`;if(Number.isInteger(e)&&(r||!Number.isSafeInteger(e)))return e.toFixed(1);case`bigint`:case`boolean`:case`temporal`:return e.toString();case`string`:return formatString(e);case`date`:if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString();case`object`:return stringifyInlineTable(e,n,r,i);case`array`:return stringifyArray(e,n,r,i);case`temporal/tz+uc`:if(i){let t=e.timeZoneId,n=t.charCodeAt(0);if(n!==43&&n!==45&&(n!==85&&n!==71&&n!==90&&n!==69||t!==`UTC`&&t!==`UCT`&&t!==`Universal`&&t!==`Zulu`&&!t.startsWith(`GMT`)&&t!==`Greenwich`&&!t.startsWith(`Etc/`)))throw TypeError(`Temporal objects with an IANA timezone are not allowed in Temporal strict mode`)}case`temporal/uc`:if(i&&e.calendarId!==`iso8601`)throw TypeError(`Temporal objects with a non-default calendar are not allowed in Temporal strict mode`);return e.toString({calendarName:`never`,timeZoneName:`never`});case`temporal/x`:throw TypeError(`Unsupported `+e[Symbol.toStringTag])}}function stringifyInlineTable(e,t,n,r){let i=Object.keys(e);if(i.length===0)return`{}`;let a=`{ `;for(let o=0;o<i.length;o++){let s=i[o];o&&(a+=`, `),a+=formatKey(s)+` = `+stringifyValue(e[s],extendedTypeOf(e[s]),t-1,n,r)}return a+` }`}function stringifyArray(e,t,n,r){if(e.length===0)return`[]`;let i=`[ `;for(let a=0;a<e.length;a++){if(a&&(i+=`, `),e[a]===null||e[a]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);i+=stringifyValue(e[a],extendedTypeOf(e[a]),t-1,n,r)}return i+` ]`}function stringifyArrayTable(e,t,n,r,i){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``;for(let o=0;o<e.length;o++)a+=`${a&&`
410
+ let kr=/^[a-z0-9-_]+$/i,Ar=!!``.isWellFormed;function extendedTypeOf(e){let t=typeof e;if(t===`object`){if(Array.isArray(e))return`array`;if(typeof e.getUTCDate==`function`&&e instanceof Date)return`date`;if(globalThis.Temporal){if(e.until){if(e instanceof Temporal.ZonedDateTime)return`temporal/tz+uc`;if(e instanceof Temporal.PlainDateTime||e instanceof Temporal.PlainDate)return`temporal/uc`;if(e instanceof Temporal.PlainTime||e instanceof Temporal.Instant)return`temporal`;if(e instanceof Temporal.PlainYearMonth)return`temporal/x`}else if(e.toPlainDate&&e instanceof Temporal.PlainMonthDay||e.negated&&e instanceof Temporal.Duration)return`temporal/x`}}return t}function isArrayOfTables(e){for(let t=0;t<e.length;t++)if(extendedTypeOf(e[t])!==`object`)return!1;return e.length!=0}function formatWellFormedStringUnchecked(e){return JSON.stringify(e).replaceAll(``,`\\u007f`)}function formatString(e){return formatWellFormedStringUnchecked(Ar?e.toWellFormed():e)}function formatKey(e){if(kr.test(e))return e;if(Ar&&!e.isWellFormed())throw RangeError(`key contains illegal lone surrogates`);return formatWellFormedStringUnchecked(e)}function stringifyValue(e,t,n,r,i){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);switch(t){case`number`:if(isNaN(e))return`nan`;if(e===1/0)return`inf`;if(e===-1/0)return`-inf`;if(Number.isInteger(e)&&(r||!Number.isSafeInteger(e)))return e.toFixed(1);case`bigint`:case`boolean`:case`temporal`:return e.toString();case`string`:return formatString(e);case`date`:if(isNaN(e.getTime()))throw TypeError(`cannot serialize invalid date`);return e.toISOString();case`object`:return stringifyInlineTable(e,n,r,i);case`array`:return stringifyArray(e,n,r,i);case`temporal/tz+uc`:if(i){let t=e.timeZoneId,n=t.charCodeAt(0);if(n!==43&&n!==45&&(n!==85&&n!==71&&n!==90&&n!==69||t!==`UTC`&&t!==`UCT`&&t!==`Universal`&&t!==`Zulu`&&!t.startsWith(`GMT`)&&t!==`Greenwich`&&!t.startsWith(`Etc/`)))throw TypeError(`Temporal objects with an IANA timezone are not allowed in Temporal strict mode`)}case`temporal/uc`:if(i&&e.calendarId!==`iso8601`)throw TypeError(`Temporal objects with a non-default calendar are not allowed in Temporal strict mode`);return e.toString({calendarName:`never`,timeZoneName:`never`});case`temporal/x`:throw TypeError(`Unsupported `+e[Symbol.toStringTag])}}function stringifyInlineTable(e,t,n,r){let i=Object.keys(e);if(i.length===0)return`{}`;let a=`{ `;for(let o=0;o<i.length;o++){let s=i[o];o&&(a+=`, `),a+=formatKey(s)+` = `+stringifyValue(e[s],extendedTypeOf(e[s]),t-1,n,r)}return a+` }`}function stringifyArray(e,t,n,r){if(e.length===0)return`[]`;let i=`[ `;for(let a=0;a<e.length;a++){if(a&&(i+=`, `),e[a]===null||e[a]===void 0)throw TypeError(`arrays cannot contain null or undefined values`);i+=stringifyValue(e[a],extendedTypeOf(e[a]),t-1,n,r)}return i+` ]`}function stringifyArrayTable(e,t,n,r,i){if(n===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let a=``;for(let o=0;o<e.length;o++)a+=`${a&&`
406
411
  `}[[${t}]]\n`,a+=stringifyTable(0,e[o],t,n,r,i);return a}function stringifyTable(e,t,n,r,i,a){if(r===0)throw Error(`Could not stringify the object: maximum object depth exceeded`);let o=``,s=``,c=Object.keys(t);for(let e=0;e<c.length;e++){let l=c[e];if(t[l]!==null&&t[l]!==void 0){let e=extendedTypeOf(t[l]);if(e===`symbol`||e===`function`)throw TypeError(`cannot serialize values of type '${e}'`);let c=formatKey(l);if(e===`array`&&isArrayOfTables(t[l]))s+=(s&&`
407
412
  `)+stringifyArrayTable(t[l],n?`${n}.${c}`:c,r-1,i,a);else if(e===`object`){let e=n?`${n}.${c}`:c;s+=(s&&`
408
413
  `)+stringifyTable(e,t[l],e,r-1,i,a)}else o+=c,o+=` = `,o+=stringifyValue(t[l],e,r,i,a),o+=`
@@ -436,32 +441,34 @@ let yr=/^[a-z0-9-_]+$/i,br=!!``.isWellFormed;function extendedTypeOf(e){let t=ty
436
441
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
437
442
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
438
443
  */
439
- const Y=`.agents/buddy-agent-harness/mcp.toml`;function mcpTargets(e){let t=new Set;return selectHarnesses(e,[]).map(e=>e.project.mcpConfig).filter(e=>e!==void 0).filter(e=>!t.has(e.path)&&t.add(e.path))}function serversUnder(e,t,n=serverFrom){let r=isRecord(e)?e[t]:void 0;return isRecord(r)?new Map(Object.entries(r).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,n(t)])):new Map}function positionOf(e){if(!isRecord(e))return;let{line:t,column:n}=e;return typeof t==`number`&&typeof n==`number`?{line:t,column:n}:void 0}function parseGoldenSet(e){if(e===void 0)return{kind:`absent`};try{return{kind:`servers`,servers:serversUnder(parse(e),`servers`)}}catch(e){return{kind:`unreadable`,position:positionOf(e)}}}function parseTarget(e,t){if(t===void 0)return{kind:`absent`};if(e.format===`toml`)try{return{kind:`servers`,servers:serversUnder(parse(t),e.key,q[e.dialect].read)}}catch{return{kind:`unreadable`}}let n=parseJsonWithComments(t);return n===void 0?{kind:`unreadable`}:{kind:`servers`,servers:serversUnder(n,e.key,q[e.dialect].read)}}const X=`.agents/buddy-agent-harness/mcp.projected.json`;function parseProjectionRecord(e){let t=e===void 0?void 0:parseJsonWithComments(e),n=isRecord(t)?t.targets:void 0;return isRecord(n)?new Map(Object.entries(n).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,new Map(Object.entries(t).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,t]))])):new Map}function formatProjectionRecord(e){let t=Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]));return`${JSON.stringify({targets:t},null,2)}\n`}var McpBaseline=class{options;constructor(e){this.options=e}parsed=new Map;walked=new Map;directionOf(e,t,n,r,i){let a=this.baseFor(e,t,n);if(a===void 0)return`unknown`;let o=!sameField(n,r,a),s=!sameField(n,i,a);return o&&s?`both`:s?`target`:`golden`}baseFor(e,t,n){return this.options.record.get(e.path)?.get(t)||this.lastAgreed(e,t,n)}lastAgreed(e,t,n){for(let r of this.commitsTouching(e)){let i=this.parseAt(r,Y,parseGoldenSet),a=this.parseAt(r,e.path,t=>parseTarget(e,t));if(i.kind!==`servers`||a.kind!==`servers`)continue;let o=i.servers.get(t),s=a.servers.get(t);if(o&&s&&sameField(n,o,s))return o}}commitsTouching(e){let t=this.walked.get(e.path);if(t)return t;let n=this.options.git.commitsTouching([Y,e.path]);return this.walked.set(e.path,n),n}parseAt(e,t,n){let r=`${e}\u0000${t}`,i=this.parsed.get(r);if(i)return i;let a=n(this.options.git.contentAt(e,t));return this.parsed.set(r,a),a}};const xr=/token|secret|password|passwd|credential/i,Sr=new Set([`key`,`apikey`,`auth`,`authorization`,`bearer`]);function segmentsOf(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}const Cr=/\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_]*/;function holdsLiteral(e){return!Cr.test(e)}function credentialKey(e){return xr.test(e)||segmentsOf(e).some(e=>Sr.has(e))}function urlHoldsCredential(e){let t;try{t=new URL(e)}catch{return!1}if(t.password)return!0;for(let[e,n]of t.searchParams)if(credentialKey(e)&&holdsLiteral(n))return!0;return!1}function literalsIn$1(e,t){return Object.entries(t??{}).filter(([e,t])=>credentialKey(e)&&holdsLiteral(t)).map(([t])=>`${e}.${t}`)}__name(literalsIn$1,`literalsIn`);function credentialFields(e){return[...literalsIn$1(`env`,e.env),...literalsIn$1(`headers`,e.headers),...e.url&&urlHoldsCredential(e.url)?[`url`]:[]]}function nonSecretArgs(e){return(e??[]).filter(e=>{let t=e.indexOf(`=`);return t===-1||!(credentialKey(e.slice(0,t))&&holdsLiteral(e.slice(t+1)))})}function read$2(e,t){let r=S(e,t);return n(r)?a(r,`utf8`):void 0}__name(read$2,`read`);const wr={target:`mcp-diverged-target`,golden:`mcp-diverged-golden`,both:`mcp-diverged-both`,unknown:`mcp-diverged-unknown`};function diagnoseMcp({root:e,git:t,cli:n}){let r=[],add=(e,t)=>{let{detail:i,repair:a}=repairFor(t);r.push({path:locatorText(e),problem:t,detail:i,repair:a(e,n)})},reportSecrets=(e,n)=>{let r=t.trackingOf(e)!==`untracked`;for(let[t,i]of n)for(let n of credentialFields(i))add({file:e,server:t,field:n},r?`mcp-committed-secret`:`mcp-literal-secret`)},i=new Map,a=[];for(let t of mcpTargets(e)){let n=parseTarget(t,read$2(e,t.path));if(n.kind===`unreadable`){add({file:t.path},`mcp-target-unreadable`);continue}n.kind!==`absent`&&(reportSecrets(t.path,n.servers),i.set(t.path,n.servers),a.push(t))}let o=parseGoldenSet(read$2(e,Y));if(o.kind===`unreadable`)return add({file:Y,position:o.position},`mcp-golden-unreadable`),r;if(o.kind===`absent`)return r;reportSecrets(Y,o.servers);let s=new McpBaseline({git:t,record:parseProjectionRecord(read$2(e,X))});for(let e of a){let t=i.get(e.path);for(let[n,r]of o.servers){let i=t.get(n);if(!i){add({file:e.path,server:n},`mcp-unprojected`);continue}for(let t of divergingFields(r,i,q[e.dialect].fields))add({file:e.path,server:n,field:t},wr[s.directionOf(e,n,t,r,i)])}for(let n of t.keys())o.servers.has(n)||add({file:e.path,server:n},`mcp-undeclared`)}return r}const Tr={instructions:`nonstandard-instructions`,rule:`nonstandard-rule`,command:`nonstandard-command`,skill:`nonstandard-skill`,subagent:`nonstandard-subagent`};function scopedByGlobs(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);if(!t)return!1;let n=/^globs:[ \t]*(.*)$/m.exec(t[1])?.[1]?.trim();return n!==void 0&&n.length>0&&n!==`[]`}function skillFiles(e){return filesUnder(e).filter(e=>e.endsWith(`SKILL.md`))}function authoredHere(e){try{return!r(e).isSymbolicLink()}catch{return!1}}function artifactFiles(e,t){let n=S(e,t.path);return authoredHere(n)?t.shape===`file`?[t.path]:(t.kind===`skill`?skillFiles(n):filesUnder(n)).map(e=>C.join(t.path,e)):[]}function diagnoseNonstandard({root:e,cli:t}){let n=[];for(let r of Kn)for(let i of r.project.nonstandard??[])for(let r of artifactFiles(e,i)){let o=i.kind===`rule`&&r.endsWith(`.mdc`)&&!scopedByGlobs(a(S(e,r),`utf8`))?`instructions`:i.kind,s=Tr[o],{detail:c,repair:l}=repairFor(s);n.push({path:r,problem:s,detail:c,repair:l({file:r},t)})}return n.sort((e,t)=>e.path.localeCompare(t.path))}function collapseHome(e,t){return e&&t.startsWith(e+E)?`~${t.slice(e.length)}`:t}N.string().optional(),N.boolean().optional(),N.string().optional(),N.string(),N.string().optional();const Z={description:"The repository root: its `.agents/references/` is the repo tier, and its `package.json` names the dependency plugins. Defaults to the nearest folder at or above the current directory holding `.git`, else the current directory.",type:N.string().optional()},Q={description:`Add the trace: every layer checked, with its outcome, and how the result was built.`,type:N.boolean().optional()},Er={description:"The calling skill's folder: its `references/<name>.default.md` joins as the `default` tier.",type:N.string().optional()};function layerSource(e){return(t,n)=>referenceLayers$1({root:t.root,cwd:process.cwd(),home:n,platform:process.platform,env:process.env,plugin:e,defaultSkill:t.default})}function compact(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``&&!(Array.isArray(e)&&!e.length)))}function asCliError(e,t){throw isCliError(e)?e:e instanceof ReferenceFailure?new M(e.message,{code:e.code,exitCode:e.usage?j.usage:j.error,details:e.details,help:e.help}):new M(e instanceof Error?e.message:t,{cause:e})}function writeWarnings(e){for(let{code:t,message:n}of e)process.stderr.write(`warning: ${t}: ${n}\n`)}function displayTrace(e,t){let show=e=>collapseHome(t,e);return{...e,contributions:e.contributions.map(e=>({...e,path:show(e.path)})),layers:e.layers.map(e=>({...e,path:show(e.path)})),projectSections:e.projectSections.map(e=>({...e,path:show(e.path)}))}}function recordLines(e,t){let n=(e.sources??[]).map(e=>`${t}source ${e.default===void 0?`plugin ${e.plugin}`:`default ${e.default}${e.plugin?` (plugin ${e.plugin})`:``}`}: recorded ${e.recorded??`no version`}, installed ${e.status===`missing`?`not installed`:e.installed??`no version`} (${e.status})`);return e.request!==void 0&&n.push(`${t}request:`,...e.request.replace(/\n$/,``).split(`
444
+ const Y=`.agents/buddy-agent-harness/mcp.toml`;function mcpTargets(e){let t=new Set;return selectHarnesses(e,[]).map(e=>e.project.mcpConfig).filter(e=>e!==void 0).filter(e=>!t.has(e.path)&&t.add(e.path))}function serversUnder(e,t,n=serverFrom){let r=isRecord(e)?e[t]:void 0;return isRecord(r)?new Map(Object.entries(r).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,n(t)])):new Map}function positionOf(e){if(!isRecord(e))return;let{line:t,column:n}=e;return typeof t==`number`&&typeof n==`number`?{line:t,column:n}:void 0}function parseGoldenSet(e){if(e===void 0)return{kind:`absent`};try{return{kind:`servers`,servers:serversUnder(parse(e),`servers`)}}catch(e){return{kind:`unreadable`,position:positionOf(e)}}}function parseTarget(e,t){if(t===void 0)return{kind:`absent`};if(e.format===`toml`)try{return{kind:`servers`,servers:serversUnder(parse(t),e.key,Er[e.dialect].read)}}catch{return{kind:`unreadable`}}let n=parseJsonWithComments(t);return n===void 0?{kind:`unreadable`}:{kind:`servers`,servers:serversUnder(n,e.key,Er[e.dialect].read)}}const jr=`.agents/buddy-agent-harness/mcp.projected.json`;function parseProjectionRecord(e){let t=e===void 0?void 0:parseJsonWithComments(e),n=isRecord(t)?t.targets:void 0;return isRecord(n)?new Map(Object.entries(n).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,new Map(Object.entries(t).filter(([,e])=>isRecord(e)).map(([e,t])=>[e,t]))])):new Map}function formatProjectionRecord(e){let t=Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]));return`${JSON.stringify({targets:t},null,2)}\n`}var McpBaseline=class{options;constructor(e){this.options=e}parsed=new Map;walked=new Map;directionOf(e,t,n,r,i){let a=this.baseFor(e,t,n);if(a===void 0)return`unknown`;let o=!sameField(n,r,a),s=!sameField(n,i,a);return o&&s?`both`:s?`target`:`golden`}baseFor(e,t,n){return this.options.record.get(e.path)?.get(t)||this.lastAgreed(e,t,n)}lastAgreed(e,t,n){for(let r of this.commitsTouching(e)){let i=this.parseAt(r,Y,parseGoldenSet),a=this.parseAt(r,e.path,t=>parseTarget(e,t));if(i.kind!==`servers`||a.kind!==`servers`)continue;let o=i.servers.get(t),s=a.servers.get(t);if(o&&s&&sameField(n,o,s))return o}}commitsTouching(e){let t=this.walked.get(e.path);if(t)return t;let n=this.options.git.commitsTouching([Y,e.path]);return this.walked.set(e.path,n),n}parseAt(e,t,n){let r=`${e}\u0000${t}`,i=this.parsed.get(r);if(i)return i;let a=n(this.options.git.contentAt(e,t));return this.parsed.set(r,a),a}};const Mr=/token|secret|password|passwd|credential/i,Nr=new Set([`key`,`apikey`,`auth`,`authorization`,`bearer`]);function segmentsOf(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}const Pr=/\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_]*/;function holdsLiteral(e){return!Pr.test(e)}function credentialKey(e){return Mr.test(e)||segmentsOf(e).some(e=>Nr.has(e))}function urlHoldsCredential(e){let t;try{t=new URL(e)}catch{return!1}if(t.password)return!0;for(let[e,n]of t.searchParams)if(credentialKey(e)&&holdsLiteral(n))return!0;return!1}function literalsIn$1(e,t){return Object.entries(t??{}).filter(([e,t])=>credentialKey(e)&&holdsLiteral(t)).map(([t])=>`${e}.${t}`)}__name(literalsIn$1,`literalsIn`);function credentialFields(e){return[...literalsIn$1(`env`,e.env),...literalsIn$1(`headers`,e.headers),...e.url&&urlHoldsCredential(e.url)?[`url`]:[]]}function nonSecretArgs(e){return(e??[]).filter(e=>{let t=e.indexOf(`=`);return t===-1||!(credentialKey(e.slice(0,t))&&holdsLiteral(e.slice(t+1)))})}function read$2(e,t){let r=C(e,t);return n(r)?a(r,`utf8`):void 0}__name(read$2,`read`);const Fr={target:`mcp-diverged-target`,golden:`mcp-diverged-golden`,both:`mcp-diverged-both`,unknown:`mcp-diverged-unknown`};function diagnoseMcp({root:e,git:t,cli:n}){let r=[],add=(e,t)=>{let{detail:i,repair:a}=repairFor(t);r.push({path:locatorText(e),problem:t,detail:i,repair:a(e,n)})},reportSecrets=(e,n)=>{let r=t.trackingOf(e)!==`untracked`;for(let[t,i]of n)for(let n of credentialFields(i))add({file:e,server:t,field:n},r?`mcp-committed-secret`:`mcp-literal-secret`)},i=new Map,a=[];for(let t of mcpTargets(e)){let n=parseTarget(t,read$2(e,t.path));if(n.kind===`unreadable`){add({file:t.path},`mcp-target-unreadable`);continue}n.kind!==`absent`&&(reportSecrets(t.path,n.servers),i.set(t.path,n.servers),a.push(t))}let o=parseGoldenSet(read$2(e,Y));if(o.kind===`unreadable`)return add({file:Y,position:o.position},`mcp-golden-unreadable`),r;if(o.kind===`absent`)return r;reportSecrets(Y,o.servers);let s=new McpBaseline({git:t,record:parseProjectionRecord(read$2(e,jr))});for(let e of a){let t=i.get(e.path);for(let[n,r]of o.servers){let i=t.get(n);if(!i){add({file:e.path,server:n},`mcp-unprojected`);continue}for(let t of divergingFields(r,i,Er[e.dialect].fields))add({file:e.path,server:n,field:t},Fr[s.directionOf(e,n,t,r,i)])}for(let n of t.keys())o.servers.has(n)||add({file:e.path,server:n},`mcp-undeclared`)}return r}const Ir={instructions:`nonstandard-instructions`,rule:`nonstandard-rule`,command:`nonstandard-command`,skill:`nonstandard-skill`,subagent:`nonstandard-subagent`};function scopedByGlobs(e){let t=/^---\n([\s\S]*?)\n---/.exec(e);if(!t)return!1;let n=/^globs:[ \t]*(.*)$/m.exec(t[1])?.[1]?.trim();return n!==void 0&&n.length>0&&n!==`[]`}function skillFiles(e){return filesUnder(e).filter(e=>e.endsWith(`SKILL.md`))}function authoredHere(e){try{return!r(e).isSymbolicLink()}catch{return!1}}function artifactFiles(e,t){let n=C(e,t.path);return authoredHere(n)?t.shape===`file`?[t.path]:(t.kind===`skill`?skillFiles(n):filesUnder(n)).map(e=>w.join(t.path,e)):[]}function diagnoseNonstandard({root:e,cli:t}){let n=[];for(let r of Gn)for(let i of r.project.nonstandard??[])for(let r of artifactFiles(e,i)){let o=i.kind===`rule`&&r.endsWith(`.mdc`)&&!scopedByGlobs(a(C(e,r),`utf8`))?`instructions`:i.kind,s=Ir[o],{detail:c,repair:l}=repairFor(s);n.push({path:r,problem:s,detail:c,repair:l({file:r},t)})}return n.sort((e,t)=>e.path.localeCompare(t.path))}const Lr=[`biome.json`,`biome.jsonc`],Rr=`.claude/settings.json`;function readJson(e){try{return JSON.parse(a(e,`utf8`))}catch{return}}function diagnoseWorktrees({root:e,git:t,cli:r}){if(!n(C(e,`.claude`)))return[];let i=[],add=(e,t)=>{let{detail:n,repair:a}=repairFor(t);i.push({path:e,problem:t,detail:n,repair:a({file:e},r)})};t.isRepository()&&!t.isIgnored(`.claude/worktrees/`)&&add(`.gitignore`,`worktrees-untracked`);for(let t of Lr){let r=C(e,t);n(r)&&!a(r,`utf8`).includes(`.claude/worktrees`)&&add(t,`worktrees-scanned`)}let o=readJson(C(e,Rr)),s=isRecord(o)?o.worktree:void 0;return(!isRecord(s)||s.baseRef===void 0)&&add(Rr,`worktree-base-unset`),i}function collapseHome(e,t){return e&&t.startsWith(e+D)?`~${t.slice(e.length)}`:t}N.string().optional(),N.boolean().optional(),N.string().optional(),N.string(),N.string().optional();const X=`cyber-agentkit reference`,Z={description:"The repository root: its `.agents/references/` is the repo tier, and its `package.json` names the dependency plugins. Defaults to the nearest folder at or above the current directory holding `.git`, else the current directory.",type:N.string().optional()},Q={description:`Add the trace: every layer checked, with its outcome, and how the result was built.`,type:N.boolean().optional()},zr={description:"The calling skill's folder: its `references/<name>.default.md` joins as the `default` tier.",type:N.string().optional()};function layerSource(e){return(t,n)=>referenceLayers$1({root:t.root,cwd:process.cwd(),home:n,platform:process.platform,env:process.env,plugin:e,defaultSkill:t.default})}function compact(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``&&!(Array.isArray(e)&&!e.length)))}function asCliError(e,t){throw isCliError(e)?e:e instanceof ReferenceFailure?new M(e.message,{code:e.code,exitCode:e.usage?j.usage:j.error,details:e.details,help:e.help}):new M(e instanceof Error?e.message:t,{cause:e})}function writeWarnings(e){for(let{code:t,message:n}of e)process.stderr.write(`warning: ${t}: ${n}\n`)}function displayTrace(e,t){let show=e=>collapseHome(t,e);return{...e,contributions:e.contributions.map(e=>({...e,path:show(e.path)})),layers:e.layers.map(e=>({...e,path:show(e.path)})),projectSections:e.projectSections.map(e=>({...e,path:show(e.path)}))}}function recordLines(e,t){let n=(e.sources??[]).map(e=>`${t}source ${e.default===void 0?`plugin ${e.plugin}`:`default ${e.default}${e.plugin?` (plugin ${e.plugin})`:``}`}: recorded ${e.recorded??`no version`}, installed ${e.status===`missing`?`not installed`:e.installed??`no version`} (${e.status})`);return e.request!==void 0&&n.push(`${t}request:`,...e.request.replace(/\n$/,``).split(`
440
445
  `).map(e=>`${t} ${e}`)),n}function traceText(e,t){let n=displayTrace(e.trace,t),r=[`${e.name}: ${e.status}; stack: ${n.stack.join(` → `)||`none`}; built by ${n.builtBy}; harnesses: ${n.harnesses.join(`, `)||`none detected`}`];if(e.message&&r.push(` ${e.message}`),n.sections.length){r.push(`sections:`);for(let e of n.sections){let t=e.removedBy?`removed by ${e.removedBy}`:e.contributions.map(({contribution:e,operation:t})=>`${e} (${t})`).join(`, `)||`no text`;r.push(` ${e.path}: ${t}`)}}r.push(`layers:`);for(let e of n.layers){let t=e.plugin?` ${e.plugin}`:e.skill?` ${e.skill}`:``,n=e.operation?`; ${e.operation} from ${e.operationFrom}`:``,i=e.extendsOutcome?`; extends ${e.extendsOutcome}`:``,a=e.selection?`; selection`:``,o=e.frontmatter&&Object.keys(e.frontmatter).length?` ${JSON.stringify(e.frontmatter)}`:``;r.push(` ${e.tier}${t} ${e.path}: ${e.outcome}${n}${i}${a}${o}`),r.push(...recordLines(e,` `))}if(n.projectSections.length){r.push(`project sections:`);for(let e of n.projectSections){let t=e.frontmatter&&Object.keys(e.frontmatter).length?` ${JSON.stringify(e.frontmatter)}`:``,n=e.plugin===void 0?``:` (plugin ${e.plugin}${e.version?`@${e.version}`:``})`;r.push(` ${e.folder}${n} ${e.path}: ${e.outcome}${t}`),r.push(...recordLines(e,` `));for(let t of e.sections??[]){let e=t.contributions.map(({contribution:e,operation:t})=>`${e} (${t})`).join(`, `);r.push(` ${t.path}: ${e||`no text`}`)}}}return`${r.join(`
441
446
  `)}\n`}function escapeText(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function escapeAttribute(e){return escapeText(e).replace(/"/g,`&quot;`)}function notFoundTag(e){let t=e.options?.length?`; options: ${e.options.join(`, `)}`:``;return`<reference name="${escapeAttribute(e.name)}" status="${e.status}" code="${e.code}">${escapeText(`${e.message??e.status}${t}`)}</reference>`}function deliveredText(e){let t=e.content??``;return e.projectSections.length?`${[...t.trim()?[t.trimEnd()]:[],...e.projectSections.map(({folder:e,plugin:t,content:n})=>`<project folder="${escapeAttribute(e)}"${t===void 0?``:` plugin="${escapeAttribute(t)}"`}>\n${n}</project>`)].join(`
442
447
 
443
- `)}\n`:t}function referenceTag(e,t){return`<reference name="${escapeAttribute(e)}">\n${t}</reference>`}const Dr={description:"Tier to write: repo (default), `.agents/references/` at the root, or user, `~/.agents/references/`.",type:N.string().optional()},Or={description:"A folder strictly below the root, which must exist and not be ignored by git: acts on its project section, `<folder>/.agents/references/<name>.md`.",type:N.string().optional()};function givenRoot(e){return e===void 0?findRoot(process.cwd()):T(e)}const kr={description:"A plugin's source folder in this repository: acts on its `references/<name>.md`.",type:N.string().optional()},Ar={description:"A skill's source folder in this repository: acts on its `references/<name>.default.md`.",type:N.string().optional()};function checkCommand(e){return command({name:`check`,description:"Check references, each composed as `load` composes it: an interface document against its shape, an implementation against its interface, and every document for the defects composing it raises. With no names, checks every name found. Every warning `load` raises is reported. A failure is an entry in `failed`, not an error; a warning never fails a check.",arguments:[{name:`names`,description:"Reference names, without the `.md` extension; `<plugin>/<name>` builds that plugin’s own stack.",type:N.array(N.string()).optional()}],options:{root:Z,trace:{...Q,description:`Add every entry checked, with its kind and unsupported sections.`}},async run(t){try{let n=g(),r=checkReferences(await e(t,n),{names:t.names??[],display:e=>collapseHome(n,e)}),i=r.filter(e=>e.failures.length),strip=e=>e.map(({check:e,message:t})=>({check:e,message:t}));return result(compact({failed:i.map(({name:e,loadedBy:t,failures:n,warnings:r})=>compact({name:e,loadedBy:t,failures:strip(n),warnings:r})),warned:r.filter(e=>!e.failures.length&&e.warnings.length).map(({name:e,loadedBy:t,warnings:n})=>compact({name:e,loadedBy:t,warnings:n})),passed:r.length-i.length,references:t.trace?r.map(({name:e,loadedBy:t,kind:n,status:r,failures:i,unsupported:a,warnings:o})=>compact({name:e,loadedBy:t,kind:n,status:r,failures:strip(i),unsupported:a,warnings:o})):void 0}))}catch(e){return asCliError(e,`Reference check failed.`)}}})}function createCommand(e){return command({name:`create`,description:`Start a contribution in the repo or user tier, a folder's project section, or a plugin's or a skill's source folder, from a template or an interface. Never overwrites a file with a body; writes a file a contribution above hides, with a warning.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,scope:Dr,in:Or,plugin:kr,default:Ar,merge:{description:`How it applies over what is below: replace, patch (default), combine, or remove. remove writes no body.`,type:N.string().optional()},template:{description:"File whose text is written as it is, frontmatter included. Defaults to a built-in template of top-level `##` sections.",type:N.string().optional()},implements:{description:"Interface id to implement: the interface's sections become `##` headings, each stubbed `**Unsupported.**` with what it holds, and `merge: replace`; with --in, a project section with neither. Not with --template.",type:N.string().optional()},"dry-run":{description:`Print the target path and the exact content, and write nothing.`,type:N.boolean().optional()},trace:{...Q,description:`After the write, add the trace, in which the new file applies.`}},async run(t){let n=this.format;try{let r=g(),display=e=>collapseHome(r,e),i={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,merge:t.merge,template:t.template,implements:t.implements,dryRun:t[`dry-run`]};validateWrite({command:`create`,...i});let a=await e({root:t.root,default:t.default},r),o=createContribution(a,{...i,root:a.root??i.root},{display}),s=compact({path:display(o.path),folder:o.folder,hint:o.dryRun?`Nothing was written. Run again without --dry-run to write it.`:`Run \`load ${o.name}\` for the composed document.`,content:o.dryRun?o.content:void 0,hints:o.hints,warnings:o.warnings,trace:t.trace&&o.after?displayTrace(o.after.trace,r):void 0});if(n!==`text`)return result(s);writeWarnings(o.warnings);for(let e of o.hints)process.stderr.write(`hint: ${e}\n`);return t.trace&&o.after&&process.stderr.write(traceText(o.after,r)),document(o.dryRun?`${s.path}\n\n${o.content}`:`${s.path}\n\n${s.hint}\n`)}catch(e){return asCliError(e,`Reference creation failed.`)}}})}function baseReport(e){let t=e.base,n=t?.resolved;return compact({status:n?.status??`missing`,stack:n?.trace.stack,content:t?.content??``,projectSections:t?.projectSections.map(({folder:e,content:t})=>({folder:e,content:t}))})}function baseText(e){let t=e.base;return t?!t.content&&!t.projectSections.length&&t.resolved.status!==`found`?`${notFoundTag(t.resolved)}\n`:deliveredText({...t.resolved,content:t.content,projectSections:t.projectSections}):``}function report(e,t,n){let display=e=>collapseHome(n,e),r=e.after;return compact({path:display(e.path),folder:e.folder,metadataFile:e.metadataFile===void 0?void 0:display(e.metadataFile),code:e.code,message:e.message,extends:e.extends,deleted:e.deleted,status:r?.status,stack:r?.trace.stack,answer:r?describeAnswer(r,display):void 0,hint:e.dryRun?`Nothing was written. Run again without --dry-run to write it.`:e.code?void 0:`Run \`load ${e.name}\` for the composed document.`,content:e.dryRun?e.content:void 0,metadataContent:e.dryRun?e.metadataContent:void 0,hints:e.hints,warnings:e.warnings,trace:t.trace&&r&&!e.code?displayTrace(r.trace,n):void 0})}function text(e,t){if(e.code)return`${t.path}\n\n${e.code}: ${e.message}\n`;if(e.dryRun){let n=e.deleted?`would delete the file, left with nothing in it.
444
- `:e.content??``,r=e.metadataContent===void 0?``:`\n${t.metadataFile}\n\n${e.metadataContent}`;return`${t.path}\n\n${n}${r}`}if(e.action===`cleared`){let n=e.deleted?`selection removed; the file was left empty and deleted`:`selection removed`;return`${t.path}\n\n${n}. ${t.answer}\n`}if(e.action===`selection`)return`${t.path}\n\nextends: ${JSON.stringify(e.extends)}. ${t.answer}\n`;let n=t.metadataFile?` Its record is in ${t.metadataFile}.`:``;return`${t.path}\n\n${t.hint}${n}\n`}function customizeCommand(e){return command({name:`customize`,description:"Customize a name for the repo or user tier, or a folder's project section, running no model: pick what it builds on (`extends`), write a body generated from a request with its record, or print what the generator reads (--base). Writes a file a contribution above hides, with a warning.",arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()},{name:`steps`,description:"More steps for --extends, so `--extends a b` lists both, bottom first.",type:N.array(N.string()).optional()}],options:{root:Z,scope:Dr,in:{...Or,description:`${Or.description} Takes no --extends or --merge.`},default:{description:"The calling skill's folder, read only: its `references/<name>.default.md` joins the stack as the `default` tier.",type:N.string().optional()},plugin:{description:"Not accepted: customize never writes a plugin's file; an author uses `create --plugin`.",type:N.string().optional()},extends:{description:"The picks, bottom first: each a plugin holding the name, `<plugin>:<merge>` (such as `house-style:combine`), or `default`; `none` removes them. A file with no body is a selection.",type:N.array(N.string()).optional()},"extends-file":{description:"A YAML file holding the whole `extends` list, with every step key (`merge`, `extends`, `sections`).",type:N.string().optional()},request:{description:"A file holding the customizer's request, in their own words; recorded as `request`. Needs --body.",type:N.string().optional()},body:{description:`A file holding the body the generator wrote; written as given, with the picks, sources, and request recorded. Needs --request.`,type:N.string().optional()},merge:{description:`How the body applies over what is below: patch (default), combine, or replace for a whole document.`,type:N.string().optional()},implements:{description:"Interface id the body implements: a whole document recording `implements` and `merge: replace`; with --in, a project section from the interface's stub.",type:N.string().optional()},base:{description:`Print what the generator reads for the target, and write nothing: the name resolved with the picks, leaving out the target file, managed text, the tier above, and personal text; with --implements, the interface's stub first.`,type:N.boolean().optional()},"dry-run":{description:`Print the target path and the exact content, and write nothing.`,type:N.boolean().optional()},trace:{...Q,description:`After the write, add the trace, in which the written file applies.`}},async run(t){let n=this.format;try{let r=g(),display=e=>collapseHome(r,e),i=t.extends===void 0?void 0:[...t.extends,...t.steps??[]],a={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,extends:i,extendsFile:t[`extends-file`],request:t.request,body:t.body,merge:t.merge,implements:t.implements,base:t.base,dryRun:t[`dry-run`]};if(validateWrite({command:`customize`,...a}),t.steps?.length&&t.extends===void 0)throw new ReferenceFailure(`options-missing`,`${t.steps.join(` `)} follow no --extends; pass --extends before the steps.`);let o=await e({root:t.root,default:t.default},r),s=customizeContribution(o,{...a,root:o.root??a.root},{display});if(s.action===`base`)return n===`text`?document(baseText(s)):result(baseReport(s));let c=report(s,t,r);if(n!==`text`)return result(c);writeWarnings(s.warnings);for(let e of s.hints)process.stderr.write(`hint: ${e}\n`);return t.trace&&s.after&&!s.code&&process.stderr.write(traceText(s.after,r)),document(text(s,c))}catch(e){return asCliError(e,`Reference customization failed.`)}}})}function deleteReport(e,t){let n=e.selection?`the selection extends: [${e.selection.join(`, `)}] went with it; run \`reference customize ${e.name} --extends ${e.selection.join(` `)}\` to restore it`:void 0;return compact({path:collapseHome(t,e.path),folder:e.folder,metadataFile:e.metadataFile===void 0?void 0:collapseHome(t,e.metadataFile),code:e.code,message:e.message,dryRun:e.dryRun||void 0,status:e.after.status,stack:e.after.trace.stack,answer:describeAnswer(e.after,e=>collapseHome(t,e)),selection:n,options:e.after.options})}function deleteCommand(e){return command({name:`delete`,description:`Delete a repo or user contribution, a folder's project section, or one in a plugin's or a skill's source folder, with a non-Markdown file's metadata file, and report what answers the name afterwards. Never deletes an installed or managed one.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,scope:{...Dr,description:`Tier to delete from: repo (default) or user.`},in:Or,plugin:kr,default:Ar,"dry-run":{description:`Print the file that would be deleted and what would answer the name then, and delete nothing.`,type:N.boolean().optional()}},async run(t){let n=this.format;try{let r=g(),i={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,dryRun:t[`dry-run`]};validateWrite({command:`delete`,...i});let a=await e({root:t.root,default:t.default},r),o=deleteContribution(a,{...i,root:a.root??i.root},{display:e=>collapseHome(r,e)}),s=deleteReport(o,r);if(n!==`text`)return result(s);if(o.code)return document(`${s.path}\n\n${o.code}: ${o.message}\n`);let c=s.selection?` Also, ${s.selection}.`:``,l=s.metadataFile?` Its metadata file ${s.metadataFile} went with it.`:``;return document(`${s.path}\n\n${o.dryRun?`would delete`:`deleted`}. ${s.answer}${l}${c}\n`)}catch(e){return asCliError(e,`Reference deletion failed.`)}}})}function parseAccept(e){if(e===void 0)return;let t=e.split(`,`).map(e=>e.trim());if(!t.length||t.some(e=>!/^[1-9]\d*$/.test(e)))throw new ReferenceFailure(`option-invalid`,`--accept is a comma-separated list of versions, such as 1,2; got "${e}".`,{details:{option:`--accept`,value:e}});return t.map(Number)}function implementationsCommand(e){return command({name:`implementations`,description:`List the implementations of an interface a consumer can load, each with its pin, description, and unsupported sections.`,arguments:[{name:`id`,description:"Interface id, the name of its `<id>.interface` document without the suffix.",type:N.string()}],options:{root:Z,accept:{description:"Versions the consumer knows, comma-separated, such as 1,2. Defaults to the interface's `versions`.",type:N.string().optional()},trace:{...Q,description:`Add each one's name, tier, and version, the interface's cardinality and accepted versions, and the ones left out with why.`}},async run(t){try{let n=parseAccept(t.accept),r=g(),i=referenceImplementations(t.id,await e(t,r),{accept:n,display:e=>collapseHome(r,e)}),a=i.implementations.map(({pin:e,description:n,unsupported:r,name:i,tier:a,version:o})=>compact(t.trace?{pin:e,description:n,unsupported:r,name:i,tier:a,version:o}:{pin:e,...a===`plugin`?{}:{tier:a},description:n,unsupported:r}));if(!a.length&&!t.trace)return empty(`0 implementations of ${t.id}`,{help:`Run \`reference implementations ${t.id} --trace\` for the ones left out, with why.`});let o={implementations:a};return t.trace&&Object.assign(o,compact({interface:i.interface,cardinality:i.cardinality,accept:i.accept,excluded:i.excluded,warnings:i.warnings})),result(o)}catch(e){return asCliError(e,`Implementation lookup failed.`)}}})}function listCommand(e){return command({name:`list`,description:`List every reference name, one row each, with its description, and its status when not found. A pattern keeps only the names it matches exactly.`,arguments:[{name:`pattern`,description:"Exact name pattern, where `*` stands for any run of characters, such as `project-tracker.capabilities.*`.",type:N.string().optional()}],options:{root:Z,trace:{...Q,description:`Add one row per name per layer holding it, with its outcome.`}},async run(t){try{let n=g(),display=e=>collapseHome(n,e),r=listReferences(await e(t,n),{display,pattern:t.pattern}),i=t.trace&&r.layers.length>0;if(!r.references.length&&!i&&!r.warnings.length)return empty(t.pattern?`0 references match "${t.pattern}"`:`0 references — no layer holds one`,{help:[...r.defaults?[r.defaults]:[],t.pattern?"Run `reference list` with no pattern for every name, or `reference search <query>` by topic.":"Run `reference create <name>` to start one."]});let a={references:r.references.map(e=>compact({name:e.name,description:e.description,format:e.format,status:e.status===`found`?void 0:e.status,code:e.code,options:e.options}))};return r.defaults&&(a.defaults=r.defaults),t.trace&&(a.layers=r.layers.map(e=>compact({...e,path:display(e.path)}))),r.warnings.length&&(a.warnings=r.warnings),result(a)}catch(e){return asCliError(e,`Reference listing failed.`)}}})}function loadEntry(e,t,{metadata:n,trace:r}){return e.status===`found`&&!e.warnings.length&&!e.projectSections.length&&!n&&!r&&e.format===`markdown`?e.content:compact({name:e.name,status:e.status,content:e.content,projectSections:e.projectSections.map(({folder:e,plugin:t,content:n})=>t===void 0?{folder:e,content:n}:{folder:e,plugin:t,content:n}),format:e.format===`markdown`?void 0:e.format,code:e.code,options:e.options,metadata:n?e.metadata:void 0,warnings:e.warnings,trace:r?displayTrace(e.trace,t):void 0})}const jr={toon:e=>encode(e,`toon`),json:e=>encode(e,`json`)};function loadText(e){let tag=e=>e.status===`found`?referenceTag(e.name,deliveredText(e)):notFoundTag(e);if(e.length===1){let[t]=e;return document(t.status===`found`?deliveredText(t):notFoundTag(t))}return document(e.map(tag).join(`
448
+ `)}\n`:t}function referenceTag(e,t){return`<reference name="${escapeAttribute(e)}">\n${t}</reference>`}const Br={description:"Tier to write: repo (default), `.agents/references/` at the root, or user, `~/.agents/references/`.",type:N.string().optional()},Vr={description:"A folder strictly below the root, which must exist and not be ignored by git: acts on its project section, `<folder>/.agents/references/<name>.md`.",type:N.string().optional()};function givenRoot(e){return e===void 0?findRoot(process.cwd()):E(e)}const Hr={description:"A plugin's source folder in this repository: acts on its `references/<name>.md`.",type:N.string().optional()},Ur={description:"A skill's source folder in this repository: acts on its `references/<name>.default.md`.",type:N.string().optional()};function checkCommand(e,t=X){return command({name:`check`,description:"Check references, each composed as `load` composes it: an interface document against its shape, an implementation against its interface, and every document for the defects composing it raises. With no names, checks every name found. Every warning `load` raises is reported. A failure is an entry in `failed`, not an error; a warning never fails a check.",arguments:[{name:`names`,description:"Reference names, without the `.md` extension; `<plugin>/<name>` builds that plugin’s own stack.",type:N.array(N.string()).optional()}],options:{root:Z,trace:{...Q,description:`Add every entry checked, with its kind and unsupported sections.`}},examples:[{command:`${t} check`,description:`Check every reference against its interface`}],async run(t){try{let n=_(),r=checkReferences(await e(t,n),{names:t.names??[],display:e=>collapseHome(n,e)}),i=r.filter(e=>e.failures.length),strip=e=>e.map(({check:e,message:t})=>({check:e,message:t}));return result(compact({failed:i.map(({name:e,loadedBy:t,failures:n,warnings:r})=>compact({name:e,loadedBy:t,failures:strip(n),warnings:r})),warned:r.filter(e=>!e.failures.length&&e.warnings.length).map(({name:e,loadedBy:t,warnings:n})=>compact({name:e,loadedBy:t,warnings:n})),passed:r.length-i.length,references:t.trace?r.map(({name:e,loadedBy:t,kind:n,status:r,failures:i,unsupported:a,warnings:o})=>compact({name:e,loadedBy:t,kind:n,status:r,failures:strip(i),unsupported:a,warnings:o})):void 0}))}catch(e){return asCliError(e,`Reference check failed.`)}}})}function createCommand(e,t=X){return command({name:`create`,description:`Start a contribution in the repo or user tier, a folder's project section, or a plugin's or a skill's source folder, from a template or an interface. Never overwrites a file with a body; writes a file a contribution above hides, with a warning.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,scope:Br,in:Vr,plugin:Hr,default:Ur,merge:{description:`How it applies over what is below: replace, patch (default), combine, or remove. remove writes no body.`,type:N.string().optional()},template:{description:"File whose text is written as it is, frontmatter included. Defaults to a built-in template of top-level `##` sections.",type:N.string().optional()},implements:{description:"Interface id to implement: the interface's sections become `##` headings, each stubbed `**Unsupported.**` with what it holds, and `merge: replace`; with --in, a project section with neither. Not with --template.",type:N.string().optional()},"dry-run":{description:`Print the target path and the exact content, and write nothing.`,type:N.boolean().optional()},trace:{...Q,description:`After the write, add the trace, in which the new file applies.`}},examples:[{command:`${t} create my-topic`,description:`Start a new reference named my-topic`}],async run(t){let n=this.format;try{let r=_(),display=e=>collapseHome(r,e),i={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,merge:t.merge,template:t.template,implements:t.implements,dryRun:t[`dry-run`]};validateWrite({command:`create`,...i});let a=await e({root:t.root,default:t.default},r),o=createContribution(a,{...i,root:a.root??i.root},{display}),s=compact({path:display(o.path),folder:o.folder,hint:o.dryRun?`Nothing was written. Run again without --dry-run to write it.`:`Run \`load ${o.name}\` for the composed document.`,content:o.dryRun?o.content:void 0,hints:o.hints,warnings:o.warnings,trace:t.trace&&o.after?displayTrace(o.after.trace,r):void 0});if(n!==`text`)return result(s);writeWarnings(o.warnings);for(let e of o.hints)process.stderr.write(`hint: ${e}\n`);return t.trace&&o.after&&process.stderr.write(traceText(o.after,r)),document(o.dryRun?`${s.path}\n\n${o.content}`:`${s.path}\n\n${s.hint}\n`)}catch(e){return asCliError(e,`Reference creation failed.`)}}})}function baseReport(e){let t=e.base,n=t?.resolved;return compact({status:n?.status??`missing`,stack:n?.trace.stack,content:t?.content??``,projectSections:t?.projectSections.map(({folder:e,content:t})=>({folder:e,content:t}))})}function baseText(e){let t=e.base;return t?!t.content&&!t.projectSections.length&&t.resolved.status!==`found`?`${notFoundTag(t.resolved)}\n`:deliveredText({...t.resolved,content:t.content,projectSections:t.projectSections}):``}function report(e,t,n){let display=e=>collapseHome(n,e),r=e.after;return compact({path:display(e.path),folder:e.folder,metadataFile:e.metadataFile===void 0?void 0:display(e.metadataFile),code:e.code,message:e.message,extends:e.extends,deleted:e.deleted,status:r?.status,stack:r?.trace.stack,answer:r?describeAnswer(r,display):void 0,hint:e.dryRun?`Nothing was written. Run again without --dry-run to write it.`:e.code?void 0:`Run \`load ${e.name}\` for the composed document.`,content:e.dryRun?e.content:void 0,metadataContent:e.dryRun?e.metadataContent:void 0,hints:e.hints,warnings:e.warnings,trace:t.trace&&r&&!e.code?displayTrace(r.trace,n):void 0})}function text(e,t){if(e.code)return`${t.path}\n\n${e.code}: ${e.message}\n`;if(e.dryRun){let n=e.deleted?`would delete the file, left with nothing in it.
449
+ `:e.content??``,r=e.metadataContent===void 0?``:`\n${t.metadataFile}\n\n${e.metadataContent}`;return`${t.path}\n\n${n}${r}`}if(e.action===`cleared`){let n=e.deleted?`selection removed; the file was left empty and deleted`:`selection removed`;return`${t.path}\n\n${n}. ${t.answer}\n`}if(e.action===`selection`)return`${t.path}\n\nextends: ${JSON.stringify(e.extends)}. ${t.answer}\n`;let n=t.metadataFile?` Its record is in ${t.metadataFile}.`:``;return`${t.path}\n\n${t.hint}${n}\n`}function familyReport(e,t,n){return compact({family:e.family,interfaces:e.interfaces.map(({interface:e,outcome:r,reason:i,result:a})=>compact({interface:e,outcome:r,reason:i,...a?report(a,t,n):{}})),hint:e.dryRun?`Nothing was written. Run again without --dry-run to write it.`:"Run `load <interface>` for each composed document."})}function familyText(e,t){return`${e.interfaces.map(({interface:e,outcome:n,reason:r,result:i},a)=>{if(!i)return`${e}: ${n}. ${r}\n`;let o=t.interfaces[a];return`${e}: ${n}.\n${text(i,o)}`}).join(`
450
+ `)}`}function customizeCommand(e,t=X){return command({name:`customize`,description:"Customize a name for the repo or user tier, or a folder's project section, running no model: pick what it builds on (`extends`), write a body generated from a request with its record, or print what the generator reads (--base). Writes a file a contribution above hides, with a warning.",arguments:[{name:`name`,description:"Reference name, without the `.md` extension; or a family, `<prefix>.*`, to pick for every interface under the prefix at once (takes --extends or --extends-file, no `sections`).",type:N.string()},{name:`steps`,description:"More steps for --extends, so `--extends a b` lists both, bottom first.",type:N.array(N.string()).optional()}],options:{root:Z,scope:Br,in:{...Vr,description:`${Vr.description} Takes no --extends or --merge.`},default:{description:"The calling skill's folder, read only: its `references/<name>.default.md` joins the stack as the `default` tier.",type:N.string().optional()},plugin:{description:"Not accepted: customize never writes a plugin's file; an author uses `create --plugin`.",type:N.string().optional()},extends:{description:"The picks, bottom first: each a plugin holding the name, `<plugin>:<merge>` (such as `house-style:combine`), or `default`; `none` removes them. A file with no body is a selection.",type:N.array(N.string()).optional()},"extends-file":{description:"A YAML file holding the whole `extends` list, with every step key (`merge`, `extends`, `sections`).",type:N.string().optional()},request:{description:"A file holding the customizer's request, in their own words; recorded as `request`. Needs --body.",type:N.string().optional()},body:{description:`A file holding the body the generator wrote; written as given, with the picks, sources, and request recorded. Needs --request.`,type:N.string().optional()},merge:{description:`How the body applies over what is below: patch (default), combine, or replace for a whole document.`,type:N.string().optional()},implements:{description:"Interface id the body implements: a whole document recording `implements` and `merge: replace`; with --in, a project section from the interface's stub.",type:N.string().optional()},base:{description:`Print what the generator reads for the target, and write nothing: the name resolved with the picks, leaving out the target file, managed text, the tier above, and personal text; with --implements, the interface's stub first.`,type:N.boolean().optional()},"dry-run":{description:`Print the target path and the exact content, and write nothing.`,type:N.boolean().optional()},trace:{...Q,description:`After the write, add the trace, in which the written file applies.`}},examples:[{command:`${t} customize my-topic`,description:`Customize a reference for this project`},{command:`${t} customize my-skill.aspects.* --extends house-style`,description:`Pick one plugin for every interface under a prefix`}],async run(t){let n=this.format;try{let r=_(),display=e=>collapseHome(r,e),i=t.extends===void 0?void 0:[...t.extends,...t.steps??[]],a={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,extends:i,extendsFile:t[`extends-file`],request:t.request,body:t.body,merge:t.merge,implements:t.implements,base:t.base,dryRun:t[`dry-run`]},o=isFamilyName(t.name)||t.name.includes(`*`)?parseFamily(t.name):void 0;if(validateWrite({command:`customize`,...a,name:o===void 0||o.invalid!==void 0?t.name:o.prefix}),t.steps?.length&&t.extends===void 0)throw new ReferenceFailure(`options-missing`,`${t.steps.join(` `)} follow no --extends; pass --extends before the steps.`);let s=await e({root:t.root,default:t.default},r);if(o!==void 0){let e=customizeContribution(s,{...a,root:s.root??a.root},{display});if(!(`family`in e))throw Error(`${t.name} was customized as a single name, not a family.`);let i=familyReport(e,t,r);if(n!==`text`)return result(i);for(let{result:t}of e.interfaces)writeWarnings(t?.warnings??[]);return document(familyText(e,i))}let c=customizeContribution(s,{...a,root:s.root??a.root},{display});if(`family`in c)throw Error(`${t.name} was customized as a family, not a single name.`);if(c.action===`base`)return n===`text`?document(baseText(c)):result(baseReport(c));let l=report(c,t,r);if(n!==`text`)return result(l);writeWarnings(c.warnings);for(let e of c.hints)process.stderr.write(`hint: ${e}\n`);return t.trace&&c.after&&!c.code&&process.stderr.write(traceText(c.after,r)),document(text(c,l))}catch(e){return asCliError(e,`Reference customization failed.`)}}})}function deleteReport(e,t){let n=e.selection?`the selection extends: [${e.selection.join(`, `)}] went with it; run \`reference customize ${e.name} --extends ${e.selection.join(` `)}\` to restore it`:void 0;return compact({path:collapseHome(t,e.path),folder:e.folder,metadataFile:e.metadataFile===void 0?void 0:collapseHome(t,e.metadataFile),code:e.code,message:e.message,dryRun:e.dryRun||void 0,status:e.after.status,stack:e.after.trace.stack,answer:describeAnswer(e.after,e=>collapseHome(t,e)),selection:n,options:e.after.options})}function deleteCommand(e,t=X){return command({name:`delete`,description:`Delete a repo or user contribution, a folder's project section, or one in a plugin's or a skill's source folder, with a non-Markdown file's metadata file, and report what answers the name afterwards. Never deletes an installed or managed one.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,scope:{...Br,description:`Tier to delete from: repo (default) or user.`},in:Vr,plugin:Hr,default:Ur,"dry-run":{description:`Print the file that would be deleted and what would answer the name then, and delete nothing.`,type:N.boolean().optional()}},examples:[{command:`${t} delete my-topic`,description:`Delete your contribution to my-topic`}],async run(t){let n=this.format;try{let r=_(),i={root:givenRoot(t.root),home:r,name:t.name,scope:t.scope,in:t.in,plugin:t.plugin,default:t.default,dryRun:t[`dry-run`]};validateWrite({command:`delete`,...i});let a=await e({root:t.root,default:t.default},r),o=deleteContribution(a,{...i,root:a.root??i.root},{display:e=>collapseHome(r,e)}),s=deleteReport(o,r);if(n!==`text`)return result(s);if(o.code)return document(`${s.path}\n\n${o.code}: ${o.message}\n`);let c=s.selection?` Also, ${s.selection}.`:``,l=s.metadataFile?` Its metadata file ${s.metadataFile} went with it.`:``;return document(`${s.path}\n\n${o.dryRun?`would delete`:`deleted`}. ${s.answer}${l}${c}\n`)}catch(e){return asCliError(e,`Reference deletion failed.`)}}})}function parseAccept(e){if(e===void 0)return;let t=e.split(`,`).map(e=>e.trim());if(!t.length||t.some(e=>!/^[1-9]\d*$/.test(e)))throw new ReferenceFailure(`option-invalid`,`--accept is a comma-separated list of versions, such as 1,2; got "${e}".`,{details:{option:`--accept`,value:e}});return t.map(Number)}function rowsOf(e,t){return e.implementations.map(({pin:e,description:n,unsupported:r,name:i,tier:a,version:o})=>compact(t?{pin:e,description:n,unsupported:r,name:i,tier:a,version:o}:{pin:e,...a===`plugin`?{}:{tier:a},description:n,unsupported:r}))}function reportOf(e,t){let n={implementations:rowsOf(e,t)};return e.inUse!==void 0&&(n.inUse=e.inUse),t&&Object.assign(n,compact({interface:e.interface,cardinality:e.cardinality,accept:e.accept,excluded:e.excluded,warnings:e.warnings})),n}function implementationsCommand(e,t=X){return command({name:`implementations`,description:`List the implementations of an interface a consumer can load, each with its pin, description, and unsupported sections.`,arguments:[{name:`id`,description:"Interface id, the name of its `<id>.interface` document without the suffix; or a family, `<prefix>.*`, for every interface under the prefix.",type:N.string()}],options:{root:Z,accept:{description:"Versions the consumer knows, comma-separated, such as 1,2. Defaults to the interface's `versions`.",type:N.string().optional()},trace:{...Q,description:`Add each one's name, tier, and version, the interface's cardinality and accepted versions, and the ones left out with why.`}},examples:[{command:`${t} implementations my-interface`,description:`List what implements an interface`},{command:`${t} implementations my-skill.aspects.*`,description:`List, for every interface under a prefix, what implements it and which one is in use`}],async run(t){try{let n=parseAccept(t.accept),r=_(),i={accept:n,display:e=>collapseHome(r,e)},a=referenceImplementations(t.id,await e(t,r),i);if(`family`in a){let e=a;return result({family:e.family,interfaces:e.interfaces.map(e=>({...reportOf(e,t.trace),interface:e.interface}))})}let o=reportOf(a,t.trace);return!o.implementations.length&&o.inUse===void 0&&!t.trace?empty(`0 implementations of ${t.id}`,{help:`Run \`reference implementations ${t.id} --trace\` for the ones left out, with why.`}):result(o)}catch(e){return asCliError(e,`Implementation lookup failed.`)}}})}function listCommand(e,t=X){return command({name:`list`,description:`List every reference name, one row each, with its description, and its status when not found. A pattern keeps only the names it matches exactly.`,arguments:[{name:`pattern`,description:"Exact name pattern, where `*` stands for any run of characters, such as `project-tracker.capabilities.*`.",type:N.string().optional()}],options:{root:Z,trace:{...Q,description:`Add one row per name per layer holding it, with its outcome.`}},examples:[{command:`${t} list`,description:`List every reference name`},{command:`${t} list 'project-tracker.*'`,description:`List the names matching a pattern`}],async run(t){try{let n=_(),display=e=>collapseHome(n,e),r=listReferences(await e(t,n),{display,pattern:t.pattern}),i=t.trace&&r.layers.length>0;if(!r.references.length&&!i&&!r.warnings.length)return empty(t.pattern?`0 references match "${t.pattern}"`:`0 references — no layer holds one`,{help:[...r.defaults?[r.defaults]:[],t.pattern?"Run `reference list` with no pattern for every name, or `reference search <query>` by topic.":"Run `reference create <name>` to start one."]});let a={references:r.references.map(e=>compact({name:e.name,description:e.description,format:e.format,status:e.status===`found`?void 0:e.status,code:e.code,options:e.options}))};return r.defaults&&(a.defaults=r.defaults),t.trace&&(a.layers=r.layers.map(e=>compact({...e,path:display(e.path)}))),r.warnings.length&&(a.warnings=r.warnings),result(a)}catch(e){return asCliError(e,`Reference listing failed.`)}}})}function loadEntry(e,t,{metadata:n,trace:r}){return e.status===`found`&&!e.warnings.length&&!e.projectSections.length&&!n&&!r&&e.format===`markdown`?e.content:compact({name:e.name,status:e.status,content:e.content,projectSections:e.projectSections.map(({folder:e,plugin:t,content:n})=>t===void 0?{folder:e,content:n}:{folder:e,plugin:t,content:n}),format:e.format===`markdown`?void 0:e.format,code:e.code,options:e.options,metadata:n?e.metadata:void 0,warnings:e.warnings,trace:r?displayTrace(e.trace,t):void 0})}const Wr={toon:e=>encode(e,`toon`),json:e=>encode(e,`json`)};function loadText(e){let tag=e=>e.status===`found`?referenceTag(e.name,deliveredText(e)):notFoundTag(e);if(e.length===1){let[t]=e;return document(t.status===`found`?deliveredText(t):notFoundTag(t))}return document(e.map(tag).join(`
445
451
 
446
- `))}function loadCommand(e){return command({name:`load`,description:`Print one or more references, each composed from its contributions as their extends and merge declare.`,arguments:[{name:`names`,description:"Reference names, without the `.md` extension; `<plugin>/<name>` builds that plugin’s own stack.",type:N.array(N.string())}],options:{root:Z,default:Er,metadata:{description:`Make every entry a record with its status and composed frontmatter.`,type:N.boolean().optional()},trace:Q},async run(t){let n=this.format;try{if(!t.names.length)throw new ReferenceFailure(`name-missing`,`name at least one reference to load.`,{help:"Run `reference load <name>...`, or `reference list` for every name."});for(let e of t.names)requireName(e);let r=g(),i=await e(t,r),display=e=>collapseHome(r,e),a=interfaceLookup(i,{display}),o=t.names.map(e=>{let t=resolveReference(parseReferenceName(e),i,{display}),n=checkResolved(t,a);t.warnings.push(...n.warnings);for(let e of n.failures)e.check!==`compose`&&t.warnings.push({code:`interface-check`,message:`it fails its interface check (${e.check}): ${e.message}`});return t});if(n===`text`){for(let e of o)writeWarnings(e.warnings),t.trace&&process.stderr.write(traceText(e,r));return loadText(o)}let s={metadata:!!t.metadata,trace:!!t.trace};return result(o.map(e=>loadEntry(e,r,s)),{render:jr})}catch(e){return asCliError(e,`Reference lookup failed.`)}}})}function searchCommand(e){return command({name:`search`,description:`Find references by name, description, tags, headings, or body, best match first.`,arguments:[{name:`query`,description:`What the reference is about.`,type:N.string()}],options:{root:Z,trace:{...Q,description:`Add the tier and plugin or skill of each match.`}},async run(t){let n=t.query.trim();try{let r=g(),{matches:i,defaults:a}=searchReferences(n,await e(t,r),{display:e=>collapseHome(r,e)});return i.length?result(compact({references:i.map(({name:e,description:n,match:r,folder:i,tier:a,plugin:o,skill:s,loadedBy:c})=>compact(t.trace?{name:e,description:n,match:r,folder:i,loadedBy:c,tier:a,plugin:o,skill:s}:{name:e,description:n,match:r,folder:i,loadedBy:c})),defaults:a})):empty(`0 references match "${n}"`,{help:[...a?[a]:[],"Try other words, or run `reference list` for every name."]})}catch(e){return asCliError(e,`Reference search failed.`)}}})}function whereCommand(e){return command({name:`where`,description:`Give the repo and user files, and with --in a folder's project section, a customization or a selection of a reference is written to, who each reaches and what hides it, the main document's heading paths, and the read-only plugins and default the stack uses.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,default:Er,in:{...Or,description:`A folder strictly below the root: also give its project section's file.`},trace:{...Q,description:`Add every layer checked, with its outcome.`}},async run(t){let n=this.format;try{let r=g(),display=e=>collapseHome(r,e),i=await e(t,r),a=whereReference(t.name,i,{root:i.root??givenRoot(t.root),display,in:t.in}),o=compact({name:a.name,status:a.status,files:a.files,headings:a.headings,used:a.used,options:a.options,hint:a.used.length?`${a.used.join(`, `)} ${a.used.length===1?`is`:`are`} read-only; a customization goes in one of the files.`:void 0,layers:t.trace?a.layers.map(e=>({...e,path:display(e.path)})):void 0,warnings:a.warnings});return n===`text`&&writeWarnings(a.warnings),result(o)}catch(e){return asCliError(e,`Reference placement lookup failed.`)}}})}function createReferenceCommands({plugin:e}={}){let t=layerSource(e);return{load:loadCommand(t),list:listCommand(t),search:searchCommand(t),where:whereCommand(t),create:createCommand(t),customize:customizeCommand(t),delete:deleteCommand(t),check:checkCommand(t),implementations:implementationsCommand(t)}}function createReferenceCommand(e={}){let{load:t,list:n,search:r,where:i,create:a,customize:o,delete:s,check:c,implementations:l}=createReferenceCommands(e);return command({name:`reference`,description:`Read reference documents by name, composed from the managed, repo, user, plugin, and default tiers, and create, customize, or delete a contribution.`,commands:[t,n,r,i,a,o,s,l,c]})}function machineWideDir(e,t,n){return e===`darwin`?S(`/Library/Application Support`,n.macos,`governances`):e===`win32`?S(t||`C:\\ProgramData`,n.windows,`governances`):S(`/etc`,n.posix,`governances`)}function managedGovernancesDir(e,t){return machineWideDir(e,t,{posix:`buddy-agent-harness`,macos:`BuddyAgentHarness`,windows:`BuddyAgentHarness`})}function deprecatedManagedGovernancesDir(e,t){return machineWideDir(e,t,{posix:`universal-plugin`,macos:`UniPlugin`,windows:`UniPlugin`})}function projectGovernancesDir(e){return S(e,`.agents`,`governances`)}function userGovernancesDir(e){return S(e,`.agents`,`governances`)}function packageGovernancesDir(e=te(import.meta.url)){let t=y(e);for(;;){if(n(S(t,`package.json`)))return S(t,`governances`);let e=y(t);if(e===t)return S(t,`governances`);t=e}}function governanceLayers({root:e,home:t,platform:n,programData:r}){return[{scope:`project`,dir:projectGovernancesDir(e)},{scope:`user`,dir:userGovernancesDir(t)},{scope:`managed`,dir:managedGovernancesDir(n,r)},{scope:`managed-deprecated`,dir:deprecatedManagedGovernancesDir(n,r)},{scope:`package`,dir:packageGovernancesDir()}]}function overrideLayers(e){return e.filter(e=>e.scope!==`package`)}const Mr=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/i;function parseGovernanceName(e){if(e.endsWith(`.md`))throw Error(`"${e}" names a file. Ask for the governance by name, without the .md extension.`);if(!Mr.test(e))throw Error(`"${e}" is not a governance name. A name is letters, digits, hyphens, and dots — not a path.`);return e}function tryReadDocument(e){try{return a(e,`utf8`)}catch{return}}function documentNames(e){try{return o(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name.slice(0,-3))}catch{return[]}}function resolveGovernance(e,t){for(let{scope:n,dir:r}of t){let t=S(r,`${e}.md`),i=tryReadDocument(t);if(i!==void 0)return{name:e,scope:n,path:t,content:i}}}function listGovernances(e){let t=new Map;for(let{scope:n,dir:r}of e)for(let e of documentNames(r))t.has(e)||t.set(e,{name:e,scope:n,path:S(r,`${e}.md`)});return[...t.values()].sort((e,t)=>e.name.localeCompare(t.name))}const Nr=`buddy-agent-harness`;function referenceLayers({packageRoot:e=y(packageGovernancesDir()),...t}){return referenceLayers$1({...t,plugin:{name:Nr,root:e}})}const Pr=createReferenceCommand({plugin:{name:Nr,root:y(packageGovernancesDir())}});function skillNames(e){return o(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}function pathOccupied(e){try{return r(e),!0}catch{return!1}}function linksTo(e,t){try{return r(e).isSymbolicLink()?c(e)===c(t):!1}catch{return!1}}function countSkills(e){return i(e,{recursive:!0}),skillNames(e).length}function linkTarget(e,t){return _()===`win32`?T(t):w(y(e),t)}function parseForce(e){return e===`true`||e!==`false`&&e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function namesTarget(e,t,n){return T(e,n)===T(t)}function projectSkills({root:e,canonicalSkills:n,harnesses:r,copy:a,force:o}){let s=r.filter(e=>e.project.skillsDirectory).map(t=>({harness:t,target:S(e,t.project.skillsDirectory)})),c=Array.isArray(o)?o:[],u=c.filter(t=>!s.some(({target:n})=>namesTarget(e,n,t)));if(u.length)throw Error(`No skill target matches:\n${u.map(e=>`- ${e}`).join(`
447
- `)}\nTargets for the enabled harnesses:\n${s.map(({target:t})=>`- ${w(e,t)}`).join(`
448
- `)}`);let forces=t=>o===!0||c.some(n=>namesTarget(e,t,n)),d=s.filter(({target:e})=>pathOccupied(e)&&!linksTo(e,n)).filter(({target:e})=>!forces(e));if(d.length&&c.length===0)throw Error(`Refusing to replace existing skill targets:\n${d.map(({target:t})=>`- ${w(e,t)}`).join(`
449
- `)}`);let p=new Set(d.map(({harness:e})=>e.name));for(let{harness:e,target:r}of s)if(!p.has(e.name)&&(i(y(r),{recursive:!0}),!linksTo(r,n))){if(pathOccupied(r)&&l(r,{recursive:!0,force:!0}),a){t(n,r,{recursive:!0});continue}try{f(linkTarget(r,n),r,_()===`win32`?`junction`:void 0)}catch(e){if(pathOccupied(r))throw e;t(n,r,{recursive:!0})}}return{linked:s.filter(({harness:e})=>!p.has(e.name)).map(({harness:e})=>e.name),skipped:s.filter(({harness:e})=>p.has(e.name)).map(({harness:e})=>e.name)}}function isDirectory$1(e){try{return r(e).isDirectory()}catch{return!1}}__name(isDirectory$1,`isDirectory`);function exists$1(e){try{return r(e),!0}catch{return!1}}__name(exists$1,`exists`);function importsGlobal(e,t,n){let r=t.kind===`import`?[t.line,`@${S(n,Gn)}`]:[];return e.split(`
450
- `).some(e=>r.includes(e.trim()))}function base(e,t,n){let r=e.relocatedBy,i=r===void 0?void 0:t[r];return r===void 0||i===void 0?{}:i===``?e.emptyRelocatesToStart?{moved:{root:n,display:`.`},emptied:r}:{}:{moved:{root:T(i),display:`$${r}`}}}function locate(e,t,{moved:n},r){if(!n||r!==t.detect&&!r.startsWith(`${t.detect}/`))return{absolute:S(e,r),display:`~/${r}`};let i=r.slice(t.detect.length);return{absolute:S(n.root,i),display:`${n.display}${i}`}}function readsAsShadow(e){try{return d(e).isFile()&&a(e,`utf8`).trim()!==``}catch{return!1}}function inspect$2(e,t,n){let i;try{i=r(t)}catch{return{kind:`none`,status:`missing`,problem:`global-instructions-missing`}}if(i.isSymbolicLink())return T(y(t),s(t))===S(e,`.agents/AGENTS.md`)?{kind:`symlink`,status:`ok`}:{kind:`symlink`,status:`unbridged`,problem:`global-instructions-unbridged`};let o;try{o=a(t,`utf8`)}catch{return{kind:`file`,status:`unbridged`,problem:`global-instructions-unbridged`}}return importsGlobal(o,n,e)?{kind:`import`,status:`ok`}:{kind:`file`,status:`unbridged`,problem:`global-instructions-unbridged`}}__name(inspect$2,`inspect`);function finding(e,t,n){let{detail:r,repair:i}=repairFor(t);return{path:e,problem:t,detail:r,repair:i({file:e},n)}}function diagnoseGlobalInstructions(e,t,n,r={},i=process.cwd()){let a=exists$1(S(e,Gn)),o=[],s=[];for(let c of Kn){let l=c.user,u=l?.instructionBridge;if(!l||!u)continue;let d=base(l,r,i);if(!t.includes(c.name)&&!isDirectory$1(locate(e,l,d,l.detect).absolute))continue;let f=locate(e,l,d,u.path),p=inspect$2(e,f.absolute,u),m=(l.shadowedBy??[]).map(t=>locate(e,l,d,t)).find(({absolute:e})=>readsAsShadow(e));if(m!==void 0){let t=inspect$2(e,m.absolute,u);if(t.status===`ok`){o.push({harness:c.name,path:m.display,kind:t.kind,status:`ok`});continue}o.push({harness:c.name,path:f.display,kind:p.kind,status:`overridden`}),a&&s.push(finding(m.display,`global-instructions-overridden`,n))}else o.push({harness:c.name,path:f.display,kind:p.kind,status:p.status});a&&d.emptied?s.push(finding(`$${d.emptied}`,`global-instructions-emptied`,n)):a&&p.problem&&s.push(finding(f.display,p.problem,n))}return{globalInstructions:o,findings:s}}const Fr=new Set([`node_modules`]);function agentsFileDirectories(e){let t=[],walk=r=>{n(S(e,r,`AGENTS.md`))&&t.push(r);let i;try{i=o(S(e,r),{withFileTypes:!0})}catch{return}for(let e of i)!e.isDirectory()||e.name.startsWith(`.`)||Fr.has(e.name)||walk(r?C.join(r,e.name):e.name)};return walk(``),t.sort()}const Ir=`AGENTS.md`;function valueAt(e,t){return t.split(`.`).reduce((e,t)=>{if(typeof e==`object`&&e)return e[t]},e)}function exists(e){try{return r(e),!0}catch{return!1}}function inspectSettingsEntry(e,t){let n;try{n=a(e,`utf8`)}catch{return{kind:`none`,status:`missing`,problem:`instructions-missing`}}let r=parseJsonWithComments(n);if(r===void 0)return{kind:`file`,status:`unreadable`,problem:`instructions-unreadable`};let i=valueAt(r,t);return Array.isArray(i)&&i.includes(`AGENTS.md`)?{kind:`settings-entry`,status:`ok`}:{kind:`file`,status:`unbridged`,problem:`instructions-unbridged`}}function inspectShadow(e){let t;try{t=r(e)}catch{return}if(t.isSymbolicLink())return s(e)===`AGENTS.md`?{kind:`symlink`,status:`superseded`,problem:`instructions-superseded`}:{kind:`symlink`,status:`shadowing`,problem:`instructions-shadowing`};let n;try{n=a(e,`utf8`)}catch{return{kind:`file`,status:`unreadable`,problem:`instructions-unreadable`}}return n.split(`
451
- `).some(e=>e.trim()===`@AGENTS.md`)?{kind:`import`,status:`superseded`,problem:`instructions-superseded`}:{kind:`file`,status:`shadowing`,problem:`instructions-shadowing`}}function diagnoseInstructions(e,t,n){let r=t.map(e=>({name:e.name,bridge:e.project.instructionBridge})).filter(e=>e.bridge?.kind===`settings-entry`),i=[],a=[],o=agentsFileDirectories(e),s=t.some(t=>(t.project.shadowedBy??[]).some(t=>exists(S(e,t))));if((r.length||s)&&!o.includes(``)){let{detail:e,repair:t}=repairFor(`no-instructions`);a.push({path:Ir,problem:`no-instructions`,detail:e,repair:t({file:Ir},n)})}for(let{name:t,bridge:o}of r){let r=inspectSettingsEntry(S(e,o.path),o.key);if(i.push({harness:t,path:o.path,kind:r.kind,status:r.status}),r.problem){let{detail:e,repair:t}=repairFor(r.problem);a.push({path:o.path,problem:r.problem,detail:e,repair:t({file:o.path},n)})}}for(let r of t)for(let t of r.project.shadowedBy??[])for(let s of o){let o=s?C.join(s,t):t,c=inspectShadow(S(e,o));if(!c)continue;i.push({harness:r.name,path:o,kind:c.kind,status:c.status});let{detail:l,repair:u}=repairFor(c.problem);a.push({path:o,problem:c.problem,detail:l,repair:u({file:o},n)})}return{instructions:i,findings:a}}function git(e,t,n){try{return k(`git`,t,{cwd:e,encoding:`utf8`,...n===void 0?{}:{input:n},stdio:[`pipe`,`pipe`,`pipe`]})}catch{return}}function lines(e){return(e??``).split(`
452
- `).filter(Boolean)}var GitBridgeState=class{root;repoRootPrefix;constructor(e){this.root=e,this.repoRootPrefix=git(e,[`rev-parse`,`--show-prefix`])?.trim()}trackingOf(e){if(this.repoRootPrefix===void 0)return`untracked`;let t=lines(git(this.root,[`ls-files`,`-v`,`--`,e]));return t.length?t.every(e=>e.startsWith(`S`))?`skip-worktree`:`tracked`:`untracked`}isIgnored(e){return this.repoRootPrefix!==void 0&&git(this.root,[`check-ignore`,`-q`,`--`,e])!==void 0}commitsTouching(e){return this.repoRootPrefix===void 0?[]:lines(git(this.root,[`rev-list`,`-n`,`200`,`HEAD`,`--`,...e]))}contentAt(e,t){if(this.repoRootPrefix!==void 0)return git(this.root,[`show`,`${e}:${this.repoRootPrefix}${t}`])}directionOf(e,t){if(this.repoRootPrefix===void 0)return`unknown`;let n=this.lastAgreedTree(e,t);if(n===void 0)return`unknown`;let r=!this.matchesTree(e,n),i=!this.matchesTree(t,n);return r&&i?`both`:r?`bridge`:`canonical`}lastAgreedTree(e,t){for(let n of lines(git(this.root,[`rev-list`,`-n`,`200`,`HEAD`,`--`,e,t]))){let r=git(this.root,[`rev-parse`,`-q`,`--verify`,`${n}:${this.repoRootPrefix}${e}`])?.trim();if(r&&r===git(this.root,[`rev-parse`,`-q`,`--verify`,`${n}:${this.repoRootPrefix}${t}`])?.trim())return r}}matchesTree(e,t){let n=new Map(lines(git(this.root,[`ls-tree`,`-r`,t])).map(e=>{let[t,n]=e.split(` `);return[n,t.split(` `)[2]]})),r=filesUnder(S(this.root,e));if(r.length!==n.size||r.some(e=>!n.has(e)))return!1;let i=lines(git(this.root,[`hash-object`,`--stdin-paths`],r.map(t=>S(e,t)).join(`
453
- `)));return i.length===r.length&&r.every((e,t)=>n.get(e)===i[t])}};const Lr=`.agents/skills`;function pathState(e){try{let t=r(e);return t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`}catch{return`missing`}}function isDirectory(e){try{return d(e).isDirectory()}catch{return!1}}function sameContent(e,t){let n=filesUnder(e),r=filesUnder(t);return n.length===r.length&&n.every((n,i)=>r[i]===n&&a(S(e,n)).equals(a(S(t,n))))}function inspect$1(e,t,n,r){switch(pathState(e)){case`missing`:return{kind:`none`,status:`missing`,problem:`missing`};case`file`:return{kind:`file`,status:`degraded`,problem:`degraded`};case`symlink`:return linksTo(e,n)?{kind:`symlink`,status:`ok`}:{kind:`symlink`,status:`stale`,problem:`stale`};default:if(!sameContent(e,n)){let e=r.directionOf(t,Lr);return{kind:`copy`,status:`diverged`,problem:`diverged-${e}`,direction:e}}return r.trackingOf(t)===`tracked`?{kind:`copy`,status:`ok`,problem:`unpinned-copy`}:{kind:`copy`,status:`ok`}}}__name(inspect$1,`inspect`);function diagnoseBridges({root:e,harnesses:t=[],cli:n,home:r,env:i}){let a=S(e,`.agents`,`skills`),o=new GitBridgeState(e),s=selectHarnesses(e,t),c=s.map(e=>({name:e.name,skillsDirectory:e.project.skillsDirectory})).filter(e=>!!e.skillsDirectory),l=[],u=[],d=[];if(!isDirectory(a)){let{detail:e,repair:t}=repairFor(`no-canonical`);d.push({path:Lr,problem:`no-canonical`,detail:e,repair:t({file:Lr},n)})}for(let t of c){let r=t.skillsDirectory,i=inspect$1(S(e,r),r,a,o);if(l.push({harness:t.name,path:r,kind:i.kind,status:i.status}),i.direction&&u.push({path:r,direction:i.direction}),i.problem){let{detail:e,repair:t}=repairFor(i.problem);d.push({path:r,problem:i.problem,detail:e,repair:t({file:r},n)})}}let f=diagnoseInstructions(e,s,n);d.push(...f.findings);let p=r===void 0?{globalInstructions:[],findings:[]}:diagnoseGlobalInstructions(r,t,n,i,e);return d.push(...p.findings),{bridges:l,instructions:f.instructions,globalInstructions:p.globalInstructions,divergence:u,findings:d}}function buildDoctorReport(e,t,n=[],r=[]){let i=[...t.findings,...n],a=r.length?r:`0 references — no layer outside the plugin tier holds one`;if(!i.length){let n=t.bridges.length+t.instructions.length,r=n===1?`the 1 bridge resolves`:`all ${n} bridges resolve`;return{bin:e,bridges:t.bridges,instructions:t.instructions,globalInstructions:t.globalInstructions,references:a,findings:`0 problems found — ${r} and the configuration around them is current`}}return{bin:e,bridges:t.bridges,instructions:t.instructions,globalInstructions:t.globalInstructions,references:a,...t.divergence.length?{divergence:t.divergence}:{},findings:i.map(({path:e,problem:t,detail:n})=>({path:e,problem:t,detail:n})),help:[...new Map(i.map(e=>[`${e.repair.command}\u0000${e.repair.instruction}`,e.repair])).values()]}}const Rr=command({name:`doctor`,description:`Report whether this repository's harness bridges still resolve — skills into .agents/skills, instructions into AGENTS.md — and whether each harness's user-scope file loads ~/.agents/AGENTS.md. Read-only.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},harness:{description:`Comma-separated harnesses to check in addition to Claude Code and Cursor, e.g. codex,gemini-cli.`,type:N.string().optional()}},async run(e){try{let t=parseHarnesses(e.harness),n=e.root??process.cwd(),r=g(),i=diagnoseBridges({root:n,...t.length?{harnesses:t}:{},cli:Yn,home:r,env:process.env}),a=new GitBridgeState(n),o=[...diagnoseConfiguration({root:n,git:a,cli:Yn}),...diagnoseMcp({root:n,git:a,cli:Yn}),...diagnoseNonstandard({root:n,cli:Yn})],{layers:s}=listReferences(await referenceLayers({root:n,home:r,platform:process.platform,env:process.env})),c=s.filter(({tier:e})=>e!==`plugin`).map(({name:e,tier:t,path:n,outcome:i})=>({name:e,tier:t,path:collapseHome$1(r,n),status:i}));return result(buildDoctorReport(displayBinPath(r,process.argv[1]),i,o,c))}catch(e){return fail(e,`Harness diagnosis failed.`)}}});function layersFor(e){let t=governanceLayers({root:e.root??process.cwd(),home:g(),platform:process.platform,programData:process.env.ProgramData});return e[`overrides-only`]?overrideLayers(t):t}const zr=`warning: "governance" is deprecated and will be removed in the next major version; use "reference load|list" instead.
454
- `,Br={description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},Vr={description:`Resolve only the project, user, and machine-wide layers. Never returns a governance this package ships, and exits non-zero when no layer has one.`,type:N.boolean().optional()},Hr=command({name:`governance`,description:"Deprecated: use `reference`. Read the governance documents the project, user, and machine-wide override layers hold. Read-only.",commands:[command({name:`list`,description:`List every governance the override layers hold, each at the layer that would win.`,options:{root:Br,"overrides-only":Vr},run(e){process.stderr.write(zr);try{let t=g(),n=layersFor(e),r=listGovernances(n);return result({layers:n.map(({scope:e,dir:n})=>({scope:e,path:collapseHome$1(t,n),status:e===`managed-deprecated`?`deprecated — move these documents to the managed layer above`:``})),governances:r.length?r.map(({name:e,scope:n,path:r})=>({name:e,scope:n,path:collapseHome$1(t,r)})):`0 governances — no layer holds one`})}catch(e){return fail(e,`Governance listing failed.`)}}}),command({name:`show`,description:`Print one governance document, resolved through the layers in order.`,arguments:[{name:`name`,description:"The governance name, without the `.md` extension.",type:N.string()}],options:{root:Br,"overrides-only":Vr},run(e){let t=this.format;process.stderr.write(zr);try{let n=parseGovernanceName(e.name),r=resolveGovernance(n,layersFor(e));if(!r)throw process.stderr.write(e[`overrides-only`]?`error: no override for governance "${n}" in the project, user, or machine-wide layer.\n`:`error: no governance named "${n}" in any layer.\n`),M.reported(j.error);let i={name:r.name,scope:r.scope,path:collapseHome$1(g(),r.path),content:r.content};return t===`text`?document(i.content):result(i)}catch(e){return fail(e,`Governance lookup failed.`)}}})]});function keepWhenEmpty(e){o(e).length===0&&p(S(e,`.gitkeep`),``)}function initializeHarnesses({root:e,harnesses:t=[],copy:n=!1,force:r=!1}){let a=S(e,`.agents`,`skills`),o=countSkills(a);i(repoReferencesDir(e),{recursive:!0});let s=referenceNames([{tier:`repo`,dir:repoReferencesDir(e)}]).length;keepWhenEmpty(a),keepWhenEmpty(repoReferencesDir(e));let c=selectHarnesses(e,t),{linked:l,skipped:u}=projectSkills({root:e,canonicalSkills:a,harnesses:c,copy:n,force:r});return{root:e,harnesses:c.map(e=>e.name),native:c.filter(e=>!e.project.skillsDirectory).map(e=>e.name),linked:l,skipped:u,deprecated:c.filter(e=>e.deprecated).map(e=>({name:e.name,replacedBy:e.deprecated})),skills:o,references:s,copied:n}}const Ur=command({name:`init`,description:`Set up canonical agent skills for the harnesses already enabled in a repository.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},harness:{description:`Comma-separated harnesses to enable in addition to Claude Code and Cursor, e.g. codex,gemini-cli.`,type:N.string().optional()},copy:{description:`Copy skills instead of linking them.`,type:N.boolean().optional()},force:{description:`Replace conflicting target skill directories. Names the targets to replace, comma-separated (e.g. .claude/skills); given alone it replaces every conflicting target.`,type:N.string().optional()}},run(e){try{let t=parseHarnesses(e.harness);return result(initializeHarnesses({root:e.root??process.cwd(),...t.length?{harnesses:t}:{},...e.copy===void 0?{}:{copy:e.copy},...e.force===void 0?{}:{force:parseForce(e.force)}}))}catch(e){return fail(e,`Harness initialization failed.`)}}}),Wr={ArrayExpression:[`elements`],ArrayPattern:[`elements`],ArrowFunctionExpression:[`params`,`body`],AssignmentExpression:[`left`,`right`],AssignmentPattern:[`left`,`right`],AwaitExpression:[`argument`],BinaryExpression:[`left`,`right`],BlockStatement:[`body`],BreakStatement:[`label`],CallExpression:[`callee`,`arguments`],CatchClause:[`param`,`body`],ChainExpression:[`expression`],ClassBody:[`body`],ClassDeclaration:[`id`,`superClass`,`body`],ClassExpression:[`id`,`superClass`,`body`],ConditionalExpression:[`test`,`consequent`,`alternate`],ContinueStatement:[`label`],DebuggerStatement:[],DoWhileStatement:[`body`,`test`],EmptyStatement:[],ExperimentalRestProperty:[`argument`],ExperimentalSpreadProperty:[`argument`],ExportAllDeclaration:[`exported`,`source`,`attributes`],ExportDefaultDeclaration:[`declaration`],ExportNamedDeclaration:[`declaration`,`specifiers`,`source`,`attributes`],ExportSpecifier:[`local`,`exported`],ExpressionStatement:[`expression`],ForInStatement:[`left`,`right`,`body`],ForOfStatement:[`left`,`right`,`body`],ForStatement:[`init`,`test`,`update`,`body`],FunctionDeclaration:[`id`,`params`,`body`],FunctionExpression:[`id`,`params`,`body`],Identifier:[],IfStatement:[`test`,`consequent`,`alternate`],ImportAttribute:[`key`,`value`],ImportDeclaration:[`specifiers`,`source`,`attributes`],ImportDefaultSpecifier:[`local`],ImportExpression:[`source`,`options`],ImportNamespaceSpecifier:[`local`],ImportSpecifier:[`imported`,`local`],JSXAttribute:[`name`,`value`],JSXClosingElement:[`name`],JSXClosingFragment:[],JSXElement:[`openingElement`,`children`,`closingElement`],JSXEmptyExpression:[],JSXExpressionContainer:[`expression`],JSXFragment:[`openingFragment`,`children`,`closingFragment`],JSXIdentifier:[],JSXMemberExpression:[`object`,`property`],JSXNamespacedName:[`namespace`,`name`],JSXOpeningElement:[`name`,`attributes`],JSXOpeningFragment:[],JSXSpreadAttribute:[`argument`],JSXSpreadChild:[`expression`],JSXText:[],LabeledStatement:[`label`,`body`],Literal:[],LogicalExpression:[`left`,`right`],MemberExpression:[`object`,`property`],MetaProperty:[`meta`,`property`],MethodDefinition:[`key`,`value`],NewExpression:[`callee`,`arguments`],ObjectExpression:[`properties`],ObjectPattern:[`properties`],PrivateIdentifier:[],Program:[`body`],Property:[`key`,`value`],PropertyDefinition:[`key`,`value`],RestElement:[`argument`],ReturnStatement:[`argument`],SequenceExpression:[`expressions`],SpreadElement:[`argument`],StaticBlock:[`body`],Super:[],SwitchCase:[`test`,`consequent`],SwitchStatement:[`discriminant`,`cases`],TaggedTemplateExpression:[`tag`,`quasi`],TemplateElement:[],TemplateLiteral:[`quasis`,`expressions`],ThisExpression:[],ThrowStatement:[`argument`],TryStatement:[`block`,`handler`,`finalizer`],UnaryExpression:[`argument`],UpdateExpression:[`argument`],VariableDeclaration:[`declarations`],VariableDeclarator:[`id`,`init`],WhileStatement:[`test`,`body`],WithStatement:[`object`,`body`],YieldExpression:[`argument`]},Gr=Object.keys(Wr);for(let e of Gr)Object.freeze(Wr[e]);Object.freeze(Wr);function unionWith(e){let t=Object.assign({},Wr);for(let n of Object.keys(e))if(Object.hasOwn(t,n)){let r=new Set(e[n]);for(let e of t[n])r.add(e);t[n]=Object.freeze(Array.from(r))}else t[n]=Object.freeze(Array.from(e[n]));return Object.freeze(t)}function last(e){return e[e.length-1]??null}function toKeyName(e){return e.type===`TOMLBare`?e.name:e.value}var TOMLVerImpl=class{constructor(e,t){this.major=e,this.minor=t}lt(e,t){return this.major<e||this.major===e&&this.minor<t}gte(e,t){return this.major>e||this.major===e&&this.minor>=t}};const Kr=new TOMLVerImpl(1,0),qr=new TOMLVerImpl(1,1),Jr=qr,Yr={"1.0":Kr,"1.0.0":Kr,"1.1":qr,"1.1.0":qr,latest:qr,next:qr};function getTOMLVer(e){return e&&Yr[e]||Jr}const Xr={"unterminated-string":`Unterminated string constant`,"unterminated-table-key":`Unterminated table-key`,"unterminated-array":`Unterminated array`,"unterminated-inline-table":`Unterminated inline table`,"missing-key":`Empty bare keys are not allowed`,"missing-newline":`Must be a newline`,"missing-equals-sign":`Expected equal (=) token`,"missing-value":`Unspecified values are invalid`,"missing-comma":`Expected comma (,) token`,"dupe-keys":`Defining a key multiple times is invalid`,"unexpected-char":`Unexpected character`,"unexpected-token":`Unexpected token`,"invalid-control-character":`Control characters (codes < 0x1f and 0x7f) are not allowed`,"invalid-comment-character":`Invalid code point {{cp}} within comments`,"invalid-key-value-newline":`The key, equals sign, and value must be on the same line`,"invalid-inline-table-newline":`No newlines are allowed between the curly braces unless they are valid within a value`,"invalid-underscore":`Underscores are allowed between digits`,"invalid-space":`Unexpected spaces`,"invalid-three-quotes":`Three or more quotes are not permitted`,"invalid-date":`Unexpected invalid date`,"invalid-time":`Unexpected invalid time`,"invalid-leading-zero":`Leading zeros are not allowed`,"invalid-trailing-comma-in-inline-table":`Trailing comma is not permitted in an inline table`,"invalid-char-in-escape-sequence":`Invalid character in escape sequence`,"invalid-consecutive-dots-in-key":`Consecutive dots are not permitted in keys`,"invalid-code-point":`Invalid code point {{cp}}`,"invalid-trailing-dot-in-key":`Keys cannot end with a dot`,"invalid-leading-dot-in-key":`Keys cannot start with a dot`};function getMessage(e,t){return t?Xr[e].replace(/\{\{(.*?)\}\}/gu,(e,n)=>n in t?t[n]:`{{${n}}}`):Xr[e]}var ParseError=class extends SyntaxError{constructor(e,t,n,r,i){super(getMessage(e,i)),this.index=t,this.lineNumber=n,this.column=r}};const $={EOF:-1,NULL:0,SOH:1,BACKSPACE:8,TABULATION:9,LINE_FEED:10,FORM_FEED:12,CARRIAGE_RETURN:13,ESCAPE:27,SO:14,US:31,SPACE:32,QUOTATION_MARK:34,HASH:35,SINGLE_QUOTE:39,PLUS_SIGN:43,COMMA:44,DASH:45,DOT:46,DIGIT_0:48,DIGIT_1:49,DIGIT_2:50,DIGIT_3:51,DIGIT_7:55,DIGIT_9:57,COLON:58,EQUALS_SIGN:61,LATIN_CAPITAL_A:65,LATIN_CAPITAL_E:69,LATIN_CAPITAL_F:70,LATIN_CAPITAL_T:84,LATIN_CAPITAL_U:85,LATIN_CAPITAL_Z:90,LEFT_BRACKET:91,BACKSLASH:92,RIGHT_BRACKET:93,UNDERSCORE:95,LATIN_SMALL_A:97,LATIN_SMALL_B:98,LATIN_SMALL_E:101,LATIN_SMALL_F:102,LATIN_SMALL_I:105,LATIN_SMALL_L:108,LATIN_SMALL_N:110,LATIN_SMALL_O:111,LATIN_SMALL_R:114,LATIN_SMALL_S:115,LATIN_SMALL_T:116,LATIN_SMALL_U:117,LATIN_SMALL_X:120,LATIN_SMALL_Z:122,LEFT_BRACE:123,RIGHT_BRACE:125,TILDE:126,DELETE:127,PAD:128,SUPERSCRIPT_TWO:178,SUPERSCRIPT_THREE:179,SUPERSCRIPT_ONE:185,VULGAR_FRACTION_ONE_QUARTER:188,VULGAR_FRACTION_THREE_QUARTERS:190,LATIN_CAPITAL_LETTER_A_WITH_GRAVE:192,LATIN_CAPITAL_LETTER_O_WITH_DIAERESIS:214,LATIN_CAPITAL_LETTER_O_WITH_STROKE:216,LATIN_SMALL_LETTER_O_WITH_DIAERESIS:246,LATIN_SMALL_LETTER_O_WITH_STROKE:248,GREEK_SMALL_REVERSED_DOTTED_LUNATE_SIGMA_SYMBOL:891,GREEK_CAPITAL_LETTER_YOT:895,CP_1FFF:8191,ZERO_WIDTH_NON_JOINER:8204,ZERO_WIDTH_JOINER:8205,UNDERTIE:8255,CHARACTER_TIE:8256,SUPERSCRIPT_ZERO:8304,CP_218F:8591,CIRCLED_DIGIT_ONE:9312,NEGATIVE_CIRCLED_DIGIT_ZERO:9471,GLAGOLITIC_CAPITAL_LETTER_AZU:11264,CP_2FEF:12271,IDEOGRAPHIC_COMMA:12289,CP_D7FF:55295,CP_E000:57344,CJK_COMPATIBILITY_IDEOGRAPH_F900:63744,ARABIC_LIGATURE_SALAAMUHU_ALAYNAA:64975,ARABIC_LIGATURE_SALLA_USED_AS_KORANIC_STOP_SIGN_ISOLATED_FORM:65008,REPLACEMENT_CHARACTER:65533,LINEAR_B_SYLLABLE_B008_A:65536,CP_EFFFF:983039,CP_10FFFF:1114111};function isControl(e){return e>=$.NULL&&e<=$.US}function isWhitespace(e){return e===$.TABULATION||e===$.SPACE}function isEOL(e){return e===$.LINE_FEED||e===$.CARRIAGE_RETURN}function isUpperLetter(e){return e>=$.LATIN_CAPITAL_A&&e<=$.LATIN_CAPITAL_Z}function isLowerLetter(e){return e>=$.LATIN_SMALL_A&&e<=$.LATIN_SMALL_Z}function isLetter(e){return isLowerLetter(e)||isUpperLetter(e)}function isDigit$1(e){return e>=$.DIGIT_0&&e<=$.DIGIT_9}__name(isDigit$1,`isDigit`);function isHexDig(e){return isDigit$1(e)||e>=$.LATIN_SMALL_A&&e<=$.LATIN_SMALL_F||e>=$.LATIN_CAPITAL_A&&e<=$.LATIN_CAPITAL_F}function isOctalDig(e){return e>=$.DIGIT_0&&e<=$.DIGIT_7}function isUnicodeScalarValue(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function sortedLastIndex(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1,a=e[i];if(a===t)return i+1;a<t?n=i+1:r=i}return n}var Locations=class{constructor(){this.offsets=[]}addOffset(e){for(let t=this.offsets.length-1;t>=0;t--){let n=this.offsets[t];if(n===e)return;if(n<e)break}this.offsets.push(e)}getLocFromIndex(e){let t=sortedLastIndex(this.offsets,e)+1;return{line:t,column:e-(t===1?0:this.offsets[t-2])}}},CodePointIterator=class{constructor(e){this.locs=new Locations,this.lastCodePoint=$.NULL,this.start=-1,this.end=0,this.text=e}next(){return this.lastCodePoint===$.EOF?$.EOF:this.lastCodePoint=this.moveAt(this.end)}getLocFromIndex(e){return this.locs.getLocFromIndex(e)}eat(e){return this.text.codePointAt(this.end)===e&&(this.next(),!0)}moveAt(e){this.start=this.end=e;let t=this.text.codePointAt(this.start)??$.EOF;if(t===$.EOF)return this.end=this.start,t;if(this.end+=t>=65536?2:1,t===$.LINE_FEED)this.locs.addOffset(this.end);else if(t===$.CARRIAGE_RETURN)return this.text.codePointAt(this.end)===$.LINE_FEED&&(this.end++,this.locs.addOffset(this.end)),$.LINE_FEED;return t}};const Zr=typeof BigInt<`u`,Qr={16:`0x`,10:``,8:`0o`,2:`0b`},$r={[$.QUOTATION_MARK]:$.QUOTATION_MARK,[$.BACKSLASH]:$.BACKSLASH,[$.LATIN_SMALL_B]:$.BACKSPACE,[$.LATIN_SMALL_F]:$.FORM_FEED,[$.LATIN_SMALL_N]:$.LINE_FEED,[$.LATIN_SMALL_R]:$.CARRIAGE_RETURN,[$.LATIN_SMALL_T]:$.TABULATION},ei={...$r,[$.LATIN_SMALL_E]:$.ESCAPE};var Tokenizer=class{constructor(e,t){this.backCode=!1,this.lastCodePoint=$.NULL,this.state=`DATA`,this.token=null,this.tokenStart=-1,this.valuesEnabled=!1,this.text=e,this.parserOptions=t||{},this.codePointIterator=new CodePointIterator(e),this.tomlVersion=getTOMLVer(this.parserOptions.tomlVersion),this.ESCAPES=this.tomlVersion.gte(1,1)?ei:$r}get start(){return this.codePointIterator.start}get end(){return this.codePointIterator.end}getLocFromIndex(e){return this.codePointIterator.getLocFromIndex(e)}reportParseError(e,t){let n=this.codePointIterator.start,r=this.codePointIterator.getLocFromIndex(n);throw new ParseError(e,n,r.line,r.column,t)}nextToken(){let e=this.token;if(e!=null)return this.token=null,e;let t=this.lastCodePoint;for(;t!==$.EOF&&!this.token;){t=this.nextCode();let e=this[this.state](t);if(!e)throw Error(`Unknown error: pre state=${this.state}`);this.state=e}return e=this.token,this.token=null,e}nextCode(){return this.lastCodePoint===$.EOF?$.EOF:this.backCode?(this.backCode=!1,this.lastCodePoint):this.lastCodePoint=this.codePointIterator.next()}eatCode(e){return this.lastCodePoint===$.EOF?!1:this.backCode?this.lastCodePoint===e&&(this.backCode=!1,!0):this.codePointIterator.eat(e)}moveAt(e){this.backCode&&=!1,this.lastCodePoint=this.codePointIterator.moveAt(e)}back(e){return this.backCode=!0,e}punctuatorToken(){this.startToken(),this.endToken(`Punctuator`,`end`)}startToken(){this.tokenStart=this.codePointIterator.start}endToken(e,t,n,r){let{tokenStart:i}=this,a=this.codePointIterator[t],o=[i,a],s={start:this.codePointIterator.getLocFromIndex(i),end:this.codePointIterator.getLocFromIndex(a)};if(e===`Block`)this.token={type:e,value:this.text.slice(i+1,a),range:o,loc:s};else{let t,c=this.text.slice(i,a);if(e===`BasicString`||e===`LiteralString`||e===`MultiLineBasicString`||e===`MultiLineLiteralString`)t={type:e,value:c,string:n,range:o,loc:s};else if(e===`Integer`){let i=n;t={type:e,value:c,number:parseInt(i,r),bigint:Zr?BigInt(Qr[r]+i):null,range:o,loc:s}}else t=e===`Float`?{type:e,value:c,number:n,range:o,loc:s}:e===`Boolean`?{type:e,value:c,boolean:n,range:o,loc:s}:e===`LocalDate`||e===`LocalTime`||e===`LocalDateTime`||e===`OffsetDateTime`?{type:e,value:c,date:n,range:o,loc:s}:{type:e,value:c,range:o,loc:s};this.token=t}}DATA(e){for(;isWhitespace(e)||isEOL(e);)e=this.nextCode();if(e===$.HASH)return this.startToken(),`COMMENT`;if(e===$.QUOTATION_MARK)return this.startToken(),`BASIC_STRING`;if(e===$.SINGLE_QUOTE)return this.startToken(),`LITERAL_STRING`;if(e===$.DOT||e===$.EQUALS_SIGN||e===$.LEFT_BRACKET||e===$.RIGHT_BRACKET||e===$.LEFT_BRACE||e===$.RIGHT_BRACE||e===$.COMMA)return this.punctuatorToken(),`DATA`;if(this.valuesEnabled){if(e===$.DASH||e===$.PLUS_SIGN)return this.startToken(),`SIGN`;if(e===$.LATIN_SMALL_N||e===$.LATIN_SMALL_I)return this.startToken(),this.back(`NAN_OR_INF`);if(isDigit$1(e))return this.startToken(),this.back(`NUMBER`);if(e===$.LATIN_SMALL_T||e===$.LATIN_SMALL_F)return this.startToken(),this.back(`BOOLEAN`)}else if(isUnquotedKeyChar(e,this.tomlVersion))return this.startToken(),`BARE`;return e===$.EOF?`DATA`:this.reportParseError(`unexpected-char`)}COMMENT(e){let t=this.tomlVersion.gte(1,1)?e=>{isNonEOL(e)||this.reportParseError(`invalid-comment-character`,{cp:JSON.stringify(String.fromCodePoint(e)).slice(1,-1)})}:e=>{isControlOtherThanTab(e)&&this.reportParseErrorControlChar()};for(;!isEOL(e)&&e!==$.EOF;)t(e),e=this.nextCode();return this.endToken(`Block`,`start`),`DATA`}BARE(e){for(;isUnquotedKeyChar(e,this.tomlVersion);)e=this.nextCode();return this.endToken(`Bare`,`start`),this.back(`DATA`)}BASIC_STRING(e){if(e===$.QUOTATION_MARK)return e=this.nextCode(),e===$.QUOTATION_MARK?`MULTI_LINE_BASIC_STRING`:(this.endToken(`BasicString`,`start`,``),this.back(`DATA`));let t=[];for(;e!==$.QUOTATION_MARK&&e!==$.EOF&&e!==$.LINE_FEED;){if(isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.BACKSLASH){e=this.nextCode();let n=this.ESCAPES[e];if(n){t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}return this.reportParseError(`invalid-char-in-escape-sequence`)}t.push(e),e=this.nextCode()}return e===$.QUOTATION_MARK?(this.endToken(`BasicString`,`end`,String.fromCodePoint(...t)),`DATA`):this.reportParseError(`unterminated-string`)}MULTI_LINE_BASIC_STRING(e){let t=[];for(e===$.LINE_FEED&&(e=this.nextCode());e!==$.EOF;){if(e!==$.LINE_FEED&&isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.QUOTATION_MARK){let e=this.codePointIterator.start;if(this.eatCode($.QUOTATION_MARK)&&this.eatCode($.QUOTATION_MARK))return this.eatCode($.QUOTATION_MARK)&&(t.push($.QUOTATION_MARK),this.eatCode($.QUOTATION_MARK)&&(t.push($.QUOTATION_MARK),this.eatCode($.QUOTATION_MARK)))?(this.moveAt(e),this.reportParseError(`invalid-three-quotes`)):(this.endToken(`MultiLineBasicString`,`end`,String.fromCodePoint(...t)),`DATA`);this.moveAt(e)}if(e===$.BACKSLASH){e=this.nextCode();let n=this.ESCAPES[e];if(n){t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}if(e===$.LINE_FEED){for(e=this.nextCode();isWhitespace(e)||e===$.LINE_FEED;)e=this.nextCode();continue}if(isWhitespace(e)){let t=!0,n=this.codePointIterator.start,r;for(;(r=this.nextCode())!==$.EOF&&r!==$.LINE_FEED;)if(!isWhitespace(r)){this.moveAt(n),t=!1;break}if(t){for(e=this.nextCode();isWhitespace(e)||e===$.LINE_FEED;)e=this.nextCode();continue}}return this.reportParseError(`invalid-char-in-escape-sequence`)}t.push(e),e=this.nextCode()}return this.reportParseError(`unterminated-string`)}LITERAL_STRING(e){if(e===$.SINGLE_QUOTE)return e=this.nextCode(),e===$.SINGLE_QUOTE?`MULTI_LINE_LITERAL_STRING`:(this.endToken(`LiteralString`,`start`,``),this.back(`DATA`));let t=[];for(;e!==$.SINGLE_QUOTE&&e!==$.EOF&&e!==$.LINE_FEED;){if(isControlOtherThanTab(e))return this.reportParseErrorControlChar();t.push(e),e=this.nextCode()}return e===$.SINGLE_QUOTE?(this.endToken(`LiteralString`,`end`,String.fromCodePoint(...t)),`DATA`):this.reportParseError(`unterminated-string`)}MULTI_LINE_LITERAL_STRING(e){let t=[];for(e===$.LINE_FEED&&(e=this.nextCode());e!==$.EOF;){if(e!==$.LINE_FEED&&isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.SINGLE_QUOTE){let e=this.codePointIterator.start;if(this.eatCode($.SINGLE_QUOTE)&&this.eatCode($.SINGLE_QUOTE))return this.eatCode($.SINGLE_QUOTE)&&(t.push($.SINGLE_QUOTE),this.eatCode($.SINGLE_QUOTE)&&(t.push($.SINGLE_QUOTE),this.eatCode($.SINGLE_QUOTE)))?(this.moveAt(e),this.reportParseError(`invalid-three-quotes`)):(this.endToken(`MultiLineLiteralString`,`end`,String.fromCodePoint(...t)),`DATA`);this.moveAt(e)}t.push(e),e=this.nextCode()}return this.reportParseError(`unterminated-string`)}SIGN(e){return e===$.LATIN_SMALL_N||e===$.LATIN_SMALL_I?this.back(`NAN_OR_INF`):isDigit$1(e)?this.back(`NUMBER`):this.reportParseError(`unexpected-char`)}NAN_OR_INF(e){if(e===$.LATIN_SMALL_N){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_A)&&this.eatCode($.LATIN_SMALL_N))return this.endToken(`Float`,`end`,NaN),`DATA`;this.moveAt(e)}else if(e===$.LATIN_SMALL_I){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_N)&&this.eatCode($.LATIN_SMALL_F))return this.endToken(`Float`,`end`,this.text[this.tokenStart]===`-`?-1/0:1/0),`DATA`;this.moveAt(e)}return this.reportParseError(`unexpected-char`)}NUMBER(e){let t=this.text[this.tokenStart],n=t===`+`?$.PLUS_SIGN:t===`-`?$.DASH:$.NULL;if(e===$.DIGIT_0){if(n===$.NULL){let e=this.codePointIterator.start,t=this.nextCode();if(isDigit$1(t)){let n=this.nextCode();if(n===$.COLON)return this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint($.DIGIT_0,t)),minute:0,second:0},`TIME_MINUTE`;if(isDigit$1(n)){let e=this.nextCode();if(isDigit$1(e)&&this.eatCode($.DASH))return this.data={hasDate:!0,year:Number(String.fromCodePoint($.DIGIT_0,t,n,e)),month:0,day:0,hour:0,minute:0,second:0},`DATE_MONTH`}return this.moveAt(e),this.reportParseError(`invalid-leading-zero`)}this.moveAt(e)}return e=this.nextCode(),e===$.LATIN_SMALL_X||e===$.LATIN_SMALL_O||e===$.LATIN_SMALL_B?n===$.NULL?e===$.LATIN_SMALL_X?`HEX`:e===$.LATIN_SMALL_O?`OCTAL`:`BINARY`:this.reportParseError(`unexpected-char`):e===$.LATIN_SMALL_E||e===$.LATIN_CAPITAL_E?(this.data={minus:n===$.DASH,left:[$.DIGIT_0]},`EXPONENT_RIGHT`):e===$.DOT?(this.data={minus:n===$.DASH,absInt:[$.DIGIT_0]},`FRACTIONAL_RIGHT`):(this.endToken(`Integer`,`start`,`0`,10),this.back(`DATA`))}let{out:r,nextCp:i,hasUnderscore:a}=this.parseDigits(e,isDigit$1);return i===$.DASH&&n===$.NULL&&!a&&r.length===4?(this.data={hasDate:!0,year:Number(String.fromCodePoint(...r)),month:0,day:0,hour:0,minute:0,second:0},`DATE_MONTH`):i===$.COLON&&n===$.NULL&&!a&&r.length===2?(this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint(...r)),minute:0,second:0},`TIME_MINUTE`):i===$.LATIN_SMALL_E||i===$.LATIN_CAPITAL_E?(this.data={minus:n===$.DASH,left:r},`EXPONENT_RIGHT`):i===$.DOT?(this.data={minus:n===$.DASH,absInt:r},`FRACTIONAL_RIGHT`):(this.endToken(`Integer`,`start`,n===$.DASH?String.fromCodePoint($.DASH,...r):String.fromCodePoint(...r),10),this.back(`DATA`))}HEX(e){let{out:t}=this.parseDigits(e,isHexDig);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),16),this.back(`DATA`)}OCTAL(e){let{out:t}=this.parseDigits(e,isOctalDig);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),8),this.back(`DATA`)}BINARY(e){let{out:t}=this.parseDigits(e,e=>e===$.DIGIT_0||e===$.DIGIT_1);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),2),this.back(`DATA`)}FRACTIONAL_RIGHT(e){let{minus:t,absInt:n}=this.data,{out:r,nextCp:i}=this.parseDigits(e,isDigit$1),a=[...n,$.DOT,...r];if(i===$.LATIN_SMALL_E||i===$.LATIN_CAPITAL_E)return this.data={minus:t,left:a},`EXPONENT_RIGHT`;let o=Number(t?String.fromCodePoint($.DASH,...a):String.fromCodePoint(...a));return this.endToken(`Float`,`start`,o),this.back(`DATA`)}EXPONENT_RIGHT(e){let{left:t,minus:n}=this.data,r=!1;(e===$.DASH||e===$.PLUS_SIGN)&&(r=e===$.DASH,e=this.nextCode());let{out:i}=this.parseDigits(e,isDigit$1),a=i;r&&a.unshift($.DASH);let o=Number(n?String.fromCodePoint($.DASH,...t,$.LATIN_SMALL_E,...a):String.fromCodePoint(...t,$.LATIN_SMALL_E,...a));return this.endToken(`Float`,`start`,o),this.back(`DATA`)}BOOLEAN(e){if(e===$.LATIN_SMALL_T){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_R)&&this.eatCode($.LATIN_SMALL_U)&&this.eatCode($.LATIN_SMALL_E))return this.endToken(`Boolean`,`end`,!0),`DATA`;this.moveAt(e)}else if(e===$.LATIN_SMALL_F){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_A)&&this.eatCode($.LATIN_SMALL_L)&&this.eatCode($.LATIN_SMALL_S)&&this.eatCode($.LATIN_SMALL_E))return this.endToken(`Boolean`,`end`,!1),`DATA`;this.moveAt(e)}return this.reportParseError(`unexpected-char`)}DATE_MONTH(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e))||(e=this.nextCode(),e!==$.DASH))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start,r=this.data;return r.month=Number(this.text.slice(t,n)),`DATE_DAY`}DATE_DAY(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;if(r.day=Number(this.text.slice(t,n)),!isValidDate(r.year,r.month,r.day))return this.reportParseError(`invalid-date`);if(e=this.nextCode(),e===$.LATIN_CAPITAL_T||e===$.LATIN_SMALL_T)return`TIME_HOUR`;if(e===$.SPACE){let e=this.codePointIterator.start;if(isDigit$1(this.nextCode())&&isDigit$1(this.nextCode()))return this.moveAt(e),`TIME_HOUR`;this.moveAt(e)}let i=getDateFromDateTimeData(r,``);return this.endToken(`LocalDate`,`start`,i),this.back(`DATA`)}TIME_HOUR(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e))||(e=this.nextCode(),e!==$.COLON))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start,r=this.data;return r.hour=Number(this.text.slice(t,n)),`TIME_MINUTE`}TIME_MINUTE(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;return r.minute=Number(this.text.slice(t,n)),e=this.nextCode(),e===$.COLON?`TIME_SECOND`:this.tomlVersion.lt(1,1)?this.reportParseError(`unexpected-char`):isValidTime(r.hour,r.minute,r.second)?this.processTimeEnd(e,r):this.reportParseError(`invalid-time`)}TIME_SECOND(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;return r.second=Number(this.text.slice(t,n)),isValidTime(r.hour,r.minute,r.second)?(e=this.nextCode(),e===$.DOT?`TIME_SEC_FRAC`:this.processTimeEnd(e,r)):this.reportParseError(`invalid-time`)}TIME_SEC_FRAC(e){if(!isDigit$1(e))return this.reportParseError(`unexpected-char`);let t=this.codePointIterator.start;for(;isDigit$1(e);)e=this.nextCode();let n=this.codePointIterator.start,r=this.data;return r.frac=this.text.slice(t,n),this.processTimeEnd(e,r)}processTimeEnd(e,t){if(t.hasDate){if(e===$.DASH||e===$.PLUS_SIGN)return t.offsetSign=e,`TIME_OFFSET`;if(e===$.LATIN_CAPITAL_Z||e===$.LATIN_SMALL_Z){let e=getDateFromDateTimeData(t,`Z`);return this.endToken(`OffsetDateTime`,`end`,e),`DATA`}let n=getDateFromDateTimeData(t,``);return this.endToken(`LocalDateTime`,`start`,n),this.back(`DATA`)}let n=getDateFromDateTimeData(t,``);return this.endToken(`LocalTime`,`start`,n),this.back(`DATA`)}TIME_OFFSET(e){if(!isDigit$1(e))return this.reportParseError(`unexpected-char`);let t=this.codePointIterator.start;if(e=this.nextCode(),!isDigit$1(e)||(e=this.nextCode(),e!==$.COLON))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start;e=this.nextCode();let r=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let i=this.codePointIterator.end,a=Number(this.text.slice(t,n)),o=Number(this.text.slice(r,i));if(!isValidTime(a,o,0))return this.reportParseError(`invalid-time`);let s=this.data,c=getDateFromDateTimeData(s,`${String.fromCodePoint(s.offsetSign)}${padStart(a,2)}:${padStart(o,2)}`);return this.endToken(`OffsetDateTime`,`end`,c),`DATA`}parseDigits(e,t){if(e===$.UNDERSCORE)return this.reportParseError(`invalid-underscore`);if(!t(e))return this.reportParseError(`unexpected-char`);let n=[],r=$.NULL,i=!1;for(;t(e)||e===$.UNDERSCORE;){if(e===$.UNDERSCORE){if(i=!0,r===$.UNDERSCORE)return this.reportParseError(`invalid-underscore`)}else n.push(e);r=e,e=this.nextCode()}return r===$.UNDERSCORE?this.reportParseError(`invalid-underscore`):{out:n,nextCp:e,hasUnderscore:i}}parseUnicode(e){let t=this.codePointIterator.start,n=this.codePointIterator.end,r=0,i;for(;(i=this.nextCode())!==$.EOF;){if(!isHexDig(i))return this.moveAt(t),this.reportParseError(`invalid-char-in-escape-sequence`);if(r++,r>=e)break}let a=this.codePointIterator.end,o=this.text.slice(n,a),s=parseInt(o,16);return isUnicodeScalarValue(s)?s:this.reportParseError(`invalid-code-point`,{cp:o})}reportParseErrorControlChar(){return this.reportParseError(`invalid-control-character`)}};function isUnquotedKeyChar(e,t){return isLetter(e)||isDigit$1(e)||e===$.UNDERSCORE||e===$.DASH?!0:(t.lt(1,1),!1)}function isControlOtherThanTab(e){return isControl(e)&&e!==$.TABULATION||e===$.DELETE}function isNonEOL(e){return e===$.TABULATION||$.SPACE<=e&&e<=$.TILDE||isNonAscii(e)}function isNonAscii(e){return $.PAD<=e&&e<=$.CP_D7FF||$.CP_E000<=e&&e<=$.CP_10FFFF}function isValidDate(e,t,n){return e>=0&&t<=12&&t>=1&&n>=1&&n<=(t===2?e&3||!(e%25)&&e&15?28:29:30+(t+(t>>3)&1))}function isValidTime(e,t,n){return!(e>=24||e<0||t>59||t<0||n>60||n<0)}function getDateFromDateTimeData(e,t){let n=padStart(e.year,4),r=e.month?padStart(e.month,2):`01`,i=e.day?padStart(e.day,2):`01`,a=padStart(e.hour,2),o=padStart(e.minute,2),s=padStart(e.second,2),c=`${n}-${r}-${i}`,l=e.frac?`.${e.frac}`:``,u=new Date(`${c}T${a}:${o}:${s}${l}${t}`);return!isNaN(u.getTime())||e.second!==60?u:new Date(`${c}T${a}:${o}:59${l}${t}`)}function padStart(e,t){return String(e).padStart(t,`0`)}const ti=Symbol(`VALUE_KIND_VALUE`),ni=Symbol(`VALUE_KIND_INTERMEDIATE`);var KeysResolver=class{constructor(e){this.rootKeys=new Map,this.tables=[],this.ctx=e}applyResolveKeyForTable(e){let t=this.rootKeys,n=e.key.keys.length-1;for(let r=0;r<n;r++){let n=e.key.keys[r],i=toKeyName(n);e.resolvedKey.push(i);let a=t.get(i);if(!a)a={node:n,keys:new Map},t.set(i,a);else if(a.table===`array`){let t=a.peekIndex;e.resolvedKey.push(t),a=a.keys.get(t)}t=a.keys}let r=e.key.keys[n],i=toKeyName(r);e.resolvedKey.push(i);let a=t.get(i);if(!a){if(e.kind===`array`){e.resolvedKey.push(0);let n={node:r,keys:new Map};t.set(i,{table:e.kind,node:r,keys:new Map([[0,n]]),peekIndex:0}),this.tables.push({node:e,keys:n.keys})}else{let n={table:e.kind,node:r,keys:new Map};t.set(i,n),this.tables.push({node:e,keys:n.keys})}}else if(!a.table){if(e.kind===`array`)this.ctx.reportParseError(`dupe-keys`,r);else{let n={table:e.kind,node:r,keys:a.keys};t.set(i,n),this.tables.push({node:e,keys:n.keys})}}else if(a.table===`array`){if(e.kind===`array`){let t={node:r,keys:new Map},n=a.peekIndex+1;e.resolvedKey.push(n),a.keys.set(n,t),a.peekIndex=n,this.tables.push({node:e,keys:t.keys})}else this.ctx.reportParseError(`dupe-keys`,r)}else this.ctx.reportParseError(`dupe-keys`,r)}verifyDuplicateKeys(e){for(let t of e.body)t.type===`TOMLKeyValue`&&verifyDuplicateKeysForKeyValue(this.ctx,this.rootKeys,t);for(let{node:e,keys:t}of this.tables)for(let n of e.body)verifyDuplicateKeysForKeyValue(this.ctx,t,n)}};function verifyDuplicateKeysForKeyValue(e,t,n){let r=t,i=last(n.key.keys);for(let t of n.key.keys){let n=toKeyName(t),a=r.get(n);a?((a.value===ti||i===t||a.table)&&e.reportParseError(`dupe-keys`,getAfterNode(t,a.node)),a.value=ni):(a=i===t?{value:ti,node:t,keys:new Map}:{value:ni,node:t,keys:new Map},r.set(n,a)),r=a.keys}n.value.type===`TOMLInlineTable`?verifyDuplicateKeysForInlineTable(e,r,n.value):n.value.type===`TOMLArray`&&verifyDuplicateKeysForArray(e,r,n.value)}function verifyDuplicateKeysForInlineTable(e,t,n){for(let r of n.body)verifyDuplicateKeysForKeyValue(e,t,r)}function verifyDuplicateKeysForArray(e,t,n){let r=t;for(let i=0;i<n.elements.length;i++){let a=n.elements[i],o=r.get(i);o?e.reportParseError(`dupe-keys`,getAfterNode(a,o.node)):(o={value:ti,node:a,keys:new Map},t.set(i,o),a.type===`TOMLInlineTable`?verifyDuplicateKeysForInlineTable(e,o.keys,a):a.type===`TOMLArray`&&verifyDuplicateKeysForArray(e,o.keys,a))}}function getAfterNode(e,t){return e.range[0]<=t.range[0]?t:e}var Context=class{constructor(e){this.tokens=[],this.comments=[],this.back=null,this.stateStack=[],this.needNewLine=!1,this.needSameLine=!1,this.currToken=null,this.prevToken=null,this.valueContainerStack=[],this.tokenizer=new Tokenizer(e.text,e.parserOptions),this.topLevelTable=e.topLevelTable,this.table=e.topLevelTable,this.keysResolver=new KeysResolver(this)}nextToken(e){if(this.prevToken=this.currToken,this.back?(this.currToken=this.back,this.back=null):this.currToken=this._nextTokenFromTokenizer(e),(this.needNewLine||this.needSameLine||e?.needSameLine)&&this.prevToken&&this.currToken){if(this.prevToken.loc.end.line===this.currToken.loc.start.line){if(this.needNewLine)return this.reportParseError(`missing-newline`,this.currToken)}else{let t=this.needSameLine||e?.needSameLine;if(t)return this.reportParseError(t,this.currToken)}}return this.needNewLine=!1,this.needSameLine=!1,this.currToken}_nextTokenFromTokenizer(e){let t=this.tokenizer.valuesEnabled;e?.valuesEnabled&&(this.tokenizer.valuesEnabled=e.valuesEnabled);let n=this.tokenizer.nextToken();for(;n&&n.type===`Block`;)this.comments.push(n),n=this.tokenizer.nextToken();return n&&this.tokens.push(n),this.tokenizer.valuesEnabled=t,n}backToken(){if(this.back)throw Error(`Illegal state`);this.back=this.currToken,this.currToken=this.prevToken}addValueContainer(e){this.valueContainerStack.push(e),this.tokenizer.valuesEnabled=!0}consumeValueContainer(){let e=this.valueContainerStack.pop();return this.tokenizer.valuesEnabled=this.valueContainerStack.length>0,e}applyResolveKeyForTable(e){this.keysResolver.applyResolveKeyForTable(e)}verifyDuplicateKeys(){this.keysResolver.verifyDuplicateKeys(this.topLevelTable)}reportParseError(e,t){let n,r,i;if(t)n=t.range[0],r=t.loc.start.line,i=t.loc.start.column;else{n=this.tokenizer.start;let e=this.tokenizer.getLocFromIndex(n);r=e.line,i=e.column}throw new ParseError(e,n,r,i)}};const ri={VALUE:`missing-value`},ii={BasicString:`basic`,MultiLineBasicString:`basic`,LiteralString:`literal`,MultiLineLiteralString:`literal`},ai={BasicString:`basic`,LiteralString:`literal`},oi={OffsetDateTime:`offset-date-time`,LocalDateTime:`local-date-time`,LocalDate:`local-date`,LocalTime:`local-time`};var TOMLParser=class{constructor(e,t){this.text=e,this.parserOptions=t||{},this.tomlVersion=getTOMLVer(this.parserOptions.tomlVersion)}parse(){let e={type:`Program`,body:[],sourceType:`module`,tokens:[],comments:[],parent:null,range:[0,0],loc:{start:{line:1,column:0},end:{line:1,column:0}}},t={type:`TOMLTopLevelTable`,body:[],parent:e,range:cloneRange(e.range),loc:cloneLoc(e.loc)};e.body=[t];let n=new Context({text:this.text,parserOptions:this.parserOptions,topLevelTable:t}),r=n.nextToken();if(r){for(t.range[0]=r.range[0],t.loc.start=clonePos(r.loc.start);r;){let e=n.stateStack.pop()||`TABLE`;n.stateStack.push(...this[e](r,n)),r=n.nextToken()}let e=n.stateStack.pop()||`TABLE`;if(e in ri)return n.reportParseError(ri[e],null);n.table.type===`TOMLTable`&&applyEndLoc(n.table,last(n.table.body)),applyEndLoc(t,last(t.body))}n.verifyDuplicateKeys(),e.tokens=n.tokens,e.comments=n.comments;let i=n.tokenizer.end,a=n.tokenizer.getLocFromIndex(i);return e.range[1]=i,e.loc.end={line:a.line,column:a.column},e}TABLE(e,t){return isBare(e)||isString(e)?this.processKeyValue(e,t.table,t):isLeftBracket(e)?this.processTable(e,t.topLevelTable,t):t.reportParseError(`unexpected-token`,e)}VALUE(e,t){return isString(e)||isMultiLineString(e)?this.processStringValue(e,t):isNumber(e)?this.processNumberValue(e,t):isBoolean(e)?this.processBooleanValue(e,t):isDateTime(e)?this.processDateTimeValue(e,t):isLeftBracket(e)?this.processArray(e,t):isLeftBrace(e)?this.processInlineTable(e,t):t.reportParseError(`unexpected-token`,e)}processTable(e,t,n){let r={type:`TOMLTable`,kind:`standard`,key:null,resolvedKey:[],body:[],parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};n.table.type===`TOMLTable`&&applyEndLoc(n.table,last(n.table.body)),t.body.push(r),n.table=r;let i=n.nextToken({needSameLine:`invalid-key-value-newline`});if(isLeftBracket(i)){if(e.range[1]<i.range[0])return n.reportParseError(`invalid-space`,i);r.kind=`array`,i=n.nextToken({needSameLine:`invalid-key-value-newline`})}if(isRightBracket(i))return n.reportParseError(`missing-key`,i);if(!i)return n.reportParseError(`unterminated-table-key`,null);if(i=this.processKeyNode(i,r,n).nextToken,!isRightBracket(i))return n.reportParseError(`unterminated-table-key`,i);if(r.kind===`array`){let e=i;if(i=n.nextToken({needSameLine:`invalid-key-value-newline`}),!isRightBracket(i))return n.reportParseError(`unterminated-table-key`,i);if(e.range[1]<i.range[0])return n.reportParseError(`invalid-space`,i)}return applyEndLoc(r,i),n.applyResolveKeyForTable(r),n.needNewLine=!0,[]}processKeyValue(e,t,n){let r={type:`TOMLKeyValue`,key:null,value:null,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.body.push(r);let{nextToken:i}=this.processKeyNode(e,r,n);return isEq(i)?(n.addValueContainer({parent:r,set:e=>(r.value=e,applyEndLoc(r,e),n.needNewLine=!0,[])}),n.needSameLine=`invalid-key-value-newline`,[`VALUE`]):n.reportParseError(`missing-equals-sign`,i)}processKeyNode(e,t,n){isDot(e)&&n.reportParseError(`invalid-leading-dot-in-key`,e);let r={type:`TOMLKey`,keys:[],parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.key=r;let i=e,a=null;do{if(isBare(i))this.processBareKey(i,r);else if(isString(i))this.processStringKey(i,r);else break;if(a=null,i=n.nextToken({needSameLine:`invalid-key-value-newline`}),!isDot(i))break;a=i,i=n.nextToken({needSameLine:`invalid-key-value-newline`})}while(i);return a&&n.reportParseError(isDot(i)?`invalid-consecutive-dots-in-key`:`invalid-trailing-dot-in-key`,a),applyEndLoc(r,last(r.keys)),{keyNode:r,nextToken:i}}processBareKey(e,t){let n={type:`TOMLBare`,name:e.value,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.keys.push(n)}processStringKey(e,t){let n={type:`TOMLQuoted`,kind:`string`,value:e.string,style:ai[e.type],multiline:!1,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.keys.push(n)}processStringValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:`string`,value:e.string,style:ii[e.type],multiline:isMultiLineString(e),parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processNumberValue(e,t){let n=t.consumeValueContainer(),r=this.text,[i,a]=e.range,o=null,getNumberText=()=>o??=r.slice(i,a).replace(/_/g,``),s;return s=e.type===`Integer`?{type:`TOMLValue`,kind:`integer`,value:e.number,bigint:e.bigint,get number(){return getNumberText()},parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)}:{type:`TOMLValue`,kind:`float`,value:e.number,get number(){return getNumberText()},parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},n.set(s)}processBooleanValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:`boolean`,value:e.boolean,parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processDateTimeValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:oi[e.type],value:e.date,datetime:e.value,parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processArray(e,t){let n=t.consumeValueContainer(),r={type:`TOMLArray`,elements:[],parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},i=t.nextToken({valuesEnabled:!0});return isRightBracket(i)?(applyEndLoc(r,i),n.set(r)):(t.backToken(),this.processArrayValue(r,n,t))}processArrayValue(e,t,n){return n.addValueContainer({parent:e,set:r=>{e.elements.push(r);let i=n.nextToken({valuesEnabled:!0}),a=isComma(i);return a&&(i=n.nextToken({valuesEnabled:!0})),isRightBracket(i)?(applyEndLoc(e,i),t.set(e)):a?(n.backToken(),this.processArrayValue(e,t,n)):n.reportParseError(i?`missing-comma`:`unterminated-array`,i)}}),[`VALUE`]}processInlineTable(e,t){let n=t.consumeValueContainer(),r={type:`TOMLInlineTable`,body:[],parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},i=this.tomlVersion.gte(1,1)?void 0:`invalid-inline-table-newline`,a=t.nextToken({needSameLine:i});if(a){if(isBare(a)||isString(a))return this.processInlineTableKeyValue(a,r,n,t);if(isRightBrace(a))return applyEndLoc(r,a),n.set(r)}return t.reportParseError(`unexpected-token`,a)}processInlineTableKeyValue(e,t,n,r){let i={type:`TOMLKeyValue`,key:null,value:null,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.body.push(i);let{nextToken:a}=this.processKeyNode(e,i,r);if(!isEq(a))return r.reportParseError(`missing-equals-sign`,a);let o=this.tomlVersion.gte(1,1)?void 0:`invalid-inline-table-newline`;return r.addValueContainer({parent:i,set:e=>{i.value=e,applyEndLoc(i,e);let a=r.nextToken({needSameLine:o});if(isComma(a)){if(a=r.nextToken({needSameLine:o}),a&&(isBare(a)||isString(a)))return this.processInlineTableKeyValue(a,t,n,r);if(isRightBrace(a)){if(this.tomlVersion.lt(1,1))return r.reportParseError(`invalid-trailing-comma-in-inline-table`,a)}else return r.reportParseError(a?`unexpected-token`:`unterminated-inline-table`,a)}return isRightBrace(a)?(applyEndLoc(t,a),n.set(t)):r.reportParseError(a?`missing-comma`:`unterminated-inline-table`,a)}}),r.needSameLine=`invalid-key-value-newline`,[`VALUE`]}};function isDot(e){return isPunctuator(e)&&e.value===`.`}function isEq(e){return isPunctuator(e)&&e.value===`=`}function isLeftBracket(e){return isPunctuator(e)&&e.value===`[`}function isRightBracket(e){return isPunctuator(e)&&e.value===`]`}function isLeftBrace(e){return isPunctuator(e)&&e.value===`{`}function isRightBrace(e){return isPunctuator(e)&&e.value===`}`}function isComma(e){return isPunctuator(e)&&e.value===`,`}function isPunctuator(e){return!!(e&&e.type===`Punctuator`)}function isBare(e){return e.type===`Bare`}function isString(e){return e.type===`BasicString`||e.type===`LiteralString`}function isMultiLineString(e){return e.type===`MultiLineBasicString`||e.type===`MultiLineLiteralString`}function isNumber(e){return e.type===`Integer`||e.type===`Float`}function isBoolean(e){return e.type===`Boolean`}function isDateTime(e){return e.type===`OffsetDateTime`||e.type===`LocalDateTime`||e.type===`LocalDate`||e.type===`LocalTime`}function applyEndLoc(e,t){t&&(e.range[1]=t.range[1],e.loc.end=clonePos(t.loc.end))}function cloneRange(e){return[e[0],e[1]]}function cloneLoc(e){return{start:clonePos(e.start),end:clonePos(e.end)}}function clonePos(e){return{line:e.line,column:e.column}}const si=unionWith({Program:[`body`],TOMLTopLevelTable:[`body`],TOMLTable:[`key`,`body`],TOMLKeyValue:[`key`,`value`],TOMLKey:[`keys`],TOMLArray:[`elements`],TOMLInlineTable:[`body`],TOMLBare:[],TOMLQuoted:[],TOMLValue:[]});function parseForESLint(e,t){return{ast:new TOMLParser(e,t).parse(),visitorKeys:si,services:{isTOML:!0}}}function parseTOML(e,t){return parseForESLint(e,t).ast}function nested(e,t){return e.reduceRight((e,t)=>({[t]:e}),t)}function renderTomlTable(e,t){return stringify(nested(e,t))}function appendTomlTable(e,t,n){return`${e}${e===``||e.endsWith(`
452
+ `))}function loadCommand(e,t=X){return command({name:`load`,description:`Print one or more references, each composed from its contributions as their extends and merge declare.`,arguments:[{name:`names`,description:"Reference names, without the `.md` extension; `<plugin>/<name>` builds that plugin’s own stack.",type:N.array(N.string())}],options:{root:Z,default:zr,metadata:{description:`Make every entry a record with its status and composed frontmatter.`,type:N.boolean().optional()},trace:Q},examples:[{command:`${t} load my-topic`,description:`Print one reference`},{command:`${t} load my-topic other-topic --format json`,description:`Print several as JSON`}],async run(t){let n=this.format;try{if(!t.names.length)throw new ReferenceFailure(`name-missing`,`name at least one reference to load.`,{help:"Run `reference load <name>...`, or `reference list` for every name."});for(let e of t.names)requireName(e);let r=_(),i=await e(t,r),display=e=>collapseHome(r,e),a=interfaceLookup(i,{display}),o=t.names.map(e=>{let t=resolveReference(parseReferenceName(e),i,{display}),n=checkResolved(t,a);t.warnings.push(...n.warnings);for(let e of n.failures)e.check!==`compose`&&t.warnings.push({code:`interface-check`,message:`it fails its interface check (${e.check}): ${e.message}`});return t});if(n===`text`){for(let e of o)writeWarnings(e.warnings),t.trace&&process.stderr.write(traceText(e,r));return loadText(o)}let s={metadata:!!t.metadata,trace:!!t.trace};return result(o.map(e=>loadEntry(e,r,s)),{render:Wr})}catch(e){return asCliError(e,`Reference lookup failed.`)}}})}function rowLine(e){let t=e.folder===void 0?e.tier:`${e.tier} ${e.folder}`,n=e.manual===void 0?`${e.from} → ${e.to}`:`${e.from}: manual: ${e.manual}`,r=e.by===void 0?``:` (by ${e.by})`,i=e.tier===`user`?`; a user file, which no git history restores`:``;return`${e.path} (${t}): ${e.form}: ${n}${r}${i}`}function summary(e,t){let n=e.filter(e=>e.manual!==void 0).length,r=e.length-n,i=n?` ${n} ${n===1?`needs`:`need`} a person, as each says.`:``;return t?`migrated ${r} ${r===1?`change`:`changes`}.${i}`:r?`${r} ${r===1?`change`:`changes`} to make; run \`reference migrate --write\` with the same arguments to apply ${r===1?`it`:`them`}.${i}`:`nothing to apply.${i}`}function migrateCommand(e,t=X){return command({name:`migrate`,description:"Rewrite reference files still in a form version 1 wrote, and rename files under a name a plugin renamed, in the repo and user tiers and every project section, or in one plugin or skill source folder. Prints the plan; `--write` applies it. Never changes a managed or installed file.",arguments:[{name:`names`,description:"Reference names to limit the run to, without the `.md` extension; a file under an older name of one is included.",type:N.array(N.string()).optional()}],options:{root:Z,plugin:{description:"A plugin's source folder in this repository: migrate only its `references/`, in place of the tiers.",type:N.string().optional()},default:{description:"A skill's source folder in this repository: migrate only its `references/`, in place of the tiers. A default at `references/<name>.md` is renamed only for a name given.",type:N.string().optional()},write:{description:"Apply the changes. It edits `user` files too, which no git history restores.",type:N.boolean().optional()}},examples:[{command:`${t} migrate`,description:`Migrate version 1 reference files`}],async run(t){let n=this.format;try{let r=_();if(t.plugin!==void 0&&t.default!==void 0)throw new ReferenceFailure(`options-conflict`,`pass one of --plugin and --default.`);let i=await e({root:t.root},r),a=migrateReferences(i,{root:i.root??givenRoot(t.root),home:r,names:t.names,plugin:t.plugin,default:t.default,write:t.write}),o=a.rows.map(e=>({...e,path:collapseHome(r,e.path)}));if(!o.length&&!a.warnings.length)return empty(`0 changes — no reference file is in a version 1 form or under a renamed name`,{help:["Run `reference check` for every warning `load` raises."]});let s=compact({changes:o,written:a.written?!0:void 0,warnings:a.warnings});return n===`text`?(writeWarnings(a.warnings),document(`${[...o.map(rowLine),``,summary(o,a.written)].join(`
453
+ `).trimStart()}\n`)):result(s)}catch(e){return asCliError(e,`Reference migration failed.`)}}})}function searchCommand(e,t=X){return command({name:`search`,description:`Find references by name, description, tags, headings, or body, best match first.`,arguments:[{name:`query`,description:`What the reference is about.`,type:N.string()}],options:{root:Z,trace:{...Q,description:`Add the tier and plugin or skill of each match.`},full:{...ze,description:`Show every match, not only the best 10.`}},examples:[{command:`${t} search "worktree leases"`,description:`Find references by topic`}],async run(t){let n=t.query.trim();try{let r=_(),{matches:i,defaults:a}=searchReferences(n,await e(t,r),{display:e=>collapseHome(r,e)});if(!i.length)return empty(`0 references match "${n}"`,{help:[...a?[a]:[],"Try other words, or run `reference list` for every name."]});let o=truncateList(i,{limit:10,full:t.full}),s=compact({count:o.truncated?o.count:void 0,references:o.items.map(({name:e,description:n,match:r,folder:i,tier:a,plugin:o,skill:s,loadedBy:c})=>compact(t.trace?{name:e,description:n,match:r,folder:i,loadedBy:c,tier:a,plugin:o,skill:s}:{name:e,description:n,match:r,folder:i,loadedBy:c})),defaults:a});return o.truncated?result(s,{help:[`Run \`reference search ${JSON.stringify(n)} --full\` for every match.`]}):result(s)}catch(e){return asCliError(e,`Reference search failed.`)}}})}function whereCommand(e,t=X){return command({name:`where`,description:`Give the repo and user files, and with --in a folder's project section, a customization or a selection of a reference is written to, who each reaches and what hides it, the main document's heading paths, and the read-only plugins and default the stack uses.`,arguments:[{name:`name`,description:"Reference name, without the `.md` extension.",type:N.string()}],options:{root:Z,default:zr,in:{...Vr,description:`A folder strictly below the root: also give its project section's file.`},trace:{...Q,description:`Add every layer checked, with its outcome.`}},examples:[{command:`${t} where my-topic`,description:`Show which layers hold my-topic`}],async run(t){let n=this.format;try{let r=_(),display=e=>collapseHome(r,e),i=await e(t,r),a=whereReference(t.name,i,{root:i.root??givenRoot(t.root),display,in:t.in}),o=compact({name:a.name,status:a.status,files:a.files,headings:a.headings,used:a.used,options:a.options,hint:a.used.length?`${a.used.join(`, `)} ${a.used.length===1?`is`:`are`} read-only; a customization goes in one of the files.`:void 0,layers:t.trace?a.layers.map(e=>({...e,path:display(e.path)})):void 0,warnings:a.warnings});return n===`text`&&writeWarnings(a.warnings),result(o)}catch(e){return asCliError(e,`Reference placement lookup failed.`)}}})}function createReferenceCommands({plugin:e,path:t=X}={}){let n=layerSource(e);return{load:loadCommand(n,t),list:listCommand(n,t),search:searchCommand(n,t),where:whereCommand(n,t),create:createCommand(n,t),customize:customizeCommand(n,t),delete:deleteCommand(n,t),migrate:migrateCommand(n,t),check:checkCommand(n,t),implementations:implementationsCommand(n,t)}}function createReferenceCommand(e={}){let{load:t,list:n,search:r,where:i,create:a,customize:o,delete:s,migrate:c,check:l,implementations:u}=createReferenceCommands(e);return command({name:`reference`,description:`Read reference documents by name, composed from the managed, repo, user, plugin, and default tiers, create, customize, or delete a contribution, and migrate version 1 files.`,commands:[t,n,r,i,a,o,s,c,u,l]})}function machineWideDir(e,t,n){return e===`darwin`?C(`/Library/Application Support`,n.macos,`governances`):e===`win32`?C(t||`C:\\ProgramData`,n.windows,`governances`):C(`/etc`,n.posix,`governances`)}function managedGovernancesDir(e,t){return machineWideDir(e,t,{posix:`buddy-agent-harness`,macos:`BuddyAgentHarness`,windows:`BuddyAgentHarness`})}function deprecatedManagedGovernancesDir(e,t){return machineWideDir(e,t,{posix:`universal-plugin`,macos:`UniPlugin`,windows:`UniPlugin`})}function projectGovernancesDir(e){return C(e,`.agents`,`governances`)}function userGovernancesDir(e){return C(e,`.agents`,`governances`)}function packageGovernancesDir(e=te(import.meta.url)){let t=b(e);for(;;){if(n(C(t,`package.json`)))return C(t,`governances`);let e=b(t);if(e===t)return C(t,`governances`);t=e}}function governanceLayers({root:e,home:t,platform:n,programData:r}){return[{scope:`project`,dir:projectGovernancesDir(e)},{scope:`user`,dir:userGovernancesDir(t)},{scope:`managed`,dir:managedGovernancesDir(n,r)},{scope:`managed-deprecated`,dir:deprecatedManagedGovernancesDir(n,r)},{scope:`package`,dir:packageGovernancesDir()}]}function overrideLayers(e){return e.filter(e=>e.scope!==`package`)}const Gr=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/i;function parseGovernanceName(e){if(e.endsWith(`.md`))throw Error(`"${e}" names a file. Ask for the governance by name, without the .md extension.`);if(!Gr.test(e))throw Error(`"${e}" is not a governance name. A name is letters, digits, hyphens, and dots — not a path.`);return e}function tryReadDocument(e){try{return a(e,`utf8`)}catch{return}}function documentNames(e){try{return o(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.md`)).map(e=>e.name.slice(0,-3))}catch{return[]}}function resolveGovernance(e,t){for(let{scope:n,dir:r}of t){let t=C(r,`${e}.md`),i=tryReadDocument(t);if(i!==void 0)return{name:e,scope:n,path:t,content:i}}}function listGovernances(e){let t=new Map;for(let{scope:n,dir:r}of e)for(let e of documentNames(r))t.has(e)||t.set(e,{name:e,scope:n,path:C(r,`${e}.md`)});return[...t.values()].sort((e,t)=>e.name.localeCompare(t.name))}const Kr=`buddy-agent-harness`;function referenceLayers({packageRoot:e=b(packageGovernancesDir()),...t}){return referenceLayers$1({...t,plugin:{name:Kr,root:e}})}const qr=createReferenceCommand({plugin:{name:Kr,root:b(packageGovernancesDir())},path:`buddy-agent-harness reference`});function skillNames(e){return o(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}function pathOccupied(e){try{return r(e),!0}catch{return!1}}function linksTo(e,t){try{return r(e).isSymbolicLink()?c(e)===c(t):!1}catch{return!1}}function countSkills(e){return i(e,{recursive:!0}),skillNames(e).length}function linkTarget(e,t){return v()===`win32`?E(t):T(b(e),t)}function parseForce(e){return e===`true`||e!==`false`&&e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function namesTarget(e,t,n){return E(e,n)===E(t)}function projectSkills({root:e,canonicalSkills:n,harnesses:r,copy:a,force:o}){let s=r.filter(e=>e.project.skillsDirectory).map(t=>({harness:t,target:C(e,t.project.skillsDirectory)})),c=Array.isArray(o)?o:[],l=c.filter(t=>!s.some(({target:n})=>namesTarget(e,n,t)));if(l.length)throw Error(`No skill target matches:\n${l.map(e=>`- ${e}`).join(`
454
+ `)}\nTargets for the enabled harnesses:\n${s.map(({target:t})=>`- ${T(e,t)}`).join(`
455
+ `)}`);let forces=t=>o===!0||c.some(n=>namesTarget(e,t,n)),d=s.filter(({target:e})=>pathOccupied(e)&&!linksTo(e,n)).filter(({target:e})=>!forces(e));if(d.length&&c.length===0)throw Error(`Refusing to replace existing skill targets:\n${d.map(({target:t})=>`- ${T(e,t)}`).join(`
456
+ `)}`);let f=new Set(d.map(({harness:e})=>e.name));for(let{harness:e,target:r}of s)if(!f.has(e.name)&&(i(b(r),{recursive:!0}),!linksTo(r,n))){if(pathOccupied(r)&&u(r,{recursive:!0,force:!0}),a){t(n,r,{recursive:!0});continue}try{p(linkTarget(r,n),r,v()===`win32`?`junction`:void 0)}catch(e){if(pathOccupied(r))throw e;t(n,r,{recursive:!0})}}return{linked:s.filter(({harness:e})=>!f.has(e.name)).map(({harness:e})=>e.name),skipped:s.filter(({harness:e})=>f.has(e.name)).map(({harness:e})=>e.name)}}function isDirectory$1(e){try{return r(e).isDirectory()}catch{return!1}}__name(isDirectory$1,`isDirectory`);function exists$1(e){try{return r(e),!0}catch{return!1}}__name(exists$1,`exists`);function importsGlobal(e,t,n){let r=t.kind===`import`?[t.line,`@${C(n,Wn)}`]:[];return e.split(`
457
+ `).some(e=>r.includes(e.trim()))}function base(e,t,n){let r=e.relocatedBy,i=r===void 0?void 0:t[r];return r===void 0||i===void 0?{}:i===``?e.emptyRelocatesToStart?{moved:{root:n,display:`.`},emptied:r}:{}:{moved:{root:E(i),display:`$${r}`}}}function locate(e,t,{moved:n},r){if(!n||r!==t.detect&&!r.startsWith(`${t.detect}/`))return{absolute:C(e,r),display:`~/${r}`};let i=r.slice(t.detect.length);return{absolute:C(n.root,i),display:`${n.display}${i}`}}function readsAsShadow(e){try{return f(e).isFile()&&a(e,`utf8`).trim()!==``}catch{return!1}}function inspect$2(e,t,n){let i;try{i=r(t)}catch{return{kind:`none`,status:`missing`,problem:`global-instructions-missing`}}if(i.isSymbolicLink())return E(b(t),s(t))===C(e,`.agents/AGENTS.md`)?{kind:`symlink`,status:`ok`}:{kind:`symlink`,status:`unbridged`,problem:`global-instructions-unbridged`};let o;try{o=a(t,`utf8`)}catch{return{kind:`file`,status:`unbridged`,problem:`global-instructions-unbridged`}}return importsGlobal(o,n,e)?{kind:`import`,status:`ok`}:{kind:`file`,status:`unbridged`,problem:`global-instructions-unbridged`}}__name(inspect$2,`inspect`);function finding(e,t,n){let{detail:r,repair:i}=repairFor(t);return{path:e,problem:t,detail:r,repair:i({file:e},n)}}function diagnoseGlobalInstructions(e,t,n,r={},i=process.cwd()){let a=exists$1(C(e,Wn)),o=[],s=[];for(let c of Gn){let l=c.user,u=l?.instructionBridge;if(!l||!u)continue;let d=base(l,r,i);if(!t.includes(c.name)&&!isDirectory$1(locate(e,l,d,l.detect).absolute))continue;let f=locate(e,l,d,u.path),p=inspect$2(e,f.absolute,u),m=(l.shadowedBy??[]).map(t=>locate(e,l,d,t)).find(({absolute:e})=>readsAsShadow(e));if(m!==void 0){let t=inspect$2(e,m.absolute,u);if(t.status===`ok`){o.push({harness:c.name,path:m.display,kind:t.kind,status:`ok`});continue}o.push({harness:c.name,path:f.display,kind:p.kind,status:`overridden`}),a&&s.push(finding(m.display,`global-instructions-overridden`,n))}else o.push({harness:c.name,path:f.display,kind:p.kind,status:p.status});a&&d.emptied?s.push(finding(`$${d.emptied}`,`global-instructions-emptied`,n)):a&&p.problem&&s.push(finding(f.display,p.problem,n))}return{globalInstructions:o,findings:s}}const Jr=new Set([`node_modules`]);function agentsFileDirectories(e){let t=[],walk=r=>{n(C(e,r,`AGENTS.md`))&&t.push(r);let i;try{i=o(C(e,r),{withFileTypes:!0})}catch{return}for(let e of i)!e.isDirectory()||e.name.startsWith(`.`)||Jr.has(e.name)||walk(r?w.join(r,e.name):e.name)};return walk(``),t.sort()}const Yr=`AGENTS.md`;function valueAt(e,t){return t.split(`.`).reduce((e,t)=>{if(typeof e==`object`&&e)return e[t]},e)}function exists(e){try{return r(e),!0}catch{return!1}}function inspectSettingsEntry(e,t){let n;try{n=a(e,`utf8`)}catch{return{kind:`none`,status:`missing`,problem:`instructions-missing`}}let r=parseJsonWithComments(n);if(r===void 0)return{kind:`file`,status:`unreadable`,problem:`instructions-unreadable`};let i=valueAt(r,t);return Array.isArray(i)&&i.includes(`AGENTS.md`)?{kind:`settings-entry`,status:`ok`}:{kind:`file`,status:`unbridged`,problem:`instructions-unbridged`}}function inspectShadow(e){let t;try{t=r(e)}catch{return}if(t.isSymbolicLink())return s(e)===`AGENTS.md`?{kind:`symlink`,status:`superseded`,problem:`instructions-superseded`}:{kind:`symlink`,status:`shadowing`,problem:`instructions-shadowing`};let n;try{n=a(e,`utf8`)}catch{return{kind:`file`,status:`unreadable`,problem:`instructions-unreadable`}}return n.split(`
458
+ `).some(e=>e.trim()===`@AGENTS.md`)?{kind:`import`,status:`superseded`,problem:`instructions-superseded`}:{kind:`file`,status:`shadowing`,problem:`instructions-shadowing`}}function diagnoseInstructions(e,t,n){let r=t.map(e=>({name:e.name,bridge:e.project.instructionBridge})).filter(e=>e.bridge?.kind===`settings-entry`),i=[],a=[],o=agentsFileDirectories(e),s=t.some(t=>(t.project.shadowedBy??[]).some(t=>exists(C(e,t))));if((r.length||s)&&!o.includes(``)){let{detail:e,repair:t}=repairFor(`no-instructions`);a.push({path:Yr,problem:`no-instructions`,detail:e,repair:t({file:Yr},n)})}for(let{name:t,bridge:o}of r){let r=inspectSettingsEntry(C(e,o.path),o.key);if(i.push({harness:t,path:o.path,kind:r.kind,status:r.status}),r.problem){let{detail:e,repair:t}=repairFor(r.problem);a.push({path:o.path,problem:r.problem,detail:e,repair:t({file:o.path},n)})}}for(let r of t)for(let t of r.project.shadowedBy??[])for(let s of o){let o=s?w.join(s,t):t,c=inspectShadow(C(e,o));if(!c)continue;i.push({harness:r.name,path:o,kind:c.kind,status:c.status});let{detail:l,repair:u}=repairFor(c.problem);a.push({path:o,problem:c.problem,detail:l,repair:u({file:o},n)})}return{instructions:i,findings:a}}function git(e,t,n){try{return A(`git`,t,{cwd:e,encoding:`utf8`,...n===void 0?{}:{input:n},stdio:[`pipe`,`pipe`,`pipe`]})}catch{return}}function lines(e){return(e??``).split(`
459
+ `).filter(Boolean)}var GitBridgeState=class{root;repoRootPrefix;constructor(e){this.root=e,this.repoRootPrefix=git(e,[`rev-parse`,`--show-prefix`])?.trim()}isRepository(){return this.repoRootPrefix!==void 0}trackingOf(e){if(this.repoRootPrefix===void 0)return`untracked`;let t=lines(git(this.root,[`ls-files`,`-v`,`--`,e]));return t.length?t.every(e=>e.startsWith(`S`))?`skip-worktree`:`tracked`:`untracked`}isIgnored(e){return this.repoRootPrefix!==void 0&&git(this.root,[`check-ignore`,`-q`,`--`,e])!==void 0}commitsTouching(e){return this.repoRootPrefix===void 0?[]:lines(git(this.root,[`rev-list`,`-n`,`200`,`HEAD`,`--`,...e]))}contentAt(e,t){if(this.repoRootPrefix!==void 0)return git(this.root,[`show`,`${e}:${this.repoRootPrefix}${t}`])}directionOf(e,t){if(this.repoRootPrefix===void 0)return`unknown`;let n=this.lastAgreedTree(e,t);if(n===void 0)return`unknown`;let r=!this.matchesTree(e,n),i=!this.matchesTree(t,n);return r&&i?`both`:r?`bridge`:`canonical`}lastAgreedTree(e,t){for(let n of lines(git(this.root,[`rev-list`,`-n`,`200`,`HEAD`,`--`,e,t]))){let r=git(this.root,[`rev-parse`,`-q`,`--verify`,`${n}:${this.repoRootPrefix}${e}`])?.trim();if(r&&r===git(this.root,[`rev-parse`,`-q`,`--verify`,`${n}:${this.repoRootPrefix}${t}`])?.trim())return r}}matchesTree(e,t){let n=new Map(lines(git(this.root,[`ls-tree`,`-r`,t])).map(e=>{let[t,n]=e.split(` `);return[n,t.split(` `)[2]]})),r=filesUnder(C(this.root,e));if(r.length!==n.size||r.some(e=>!n.has(e)))return!1;let i=lines(git(this.root,[`hash-object`,`--stdin-paths`],r.map(t=>C(e,t)).join(`
460
+ `)));return i.length===r.length&&r.every((e,t)=>n.get(e)===i[t])}};const Xr=`.agents/skills`;function pathState(e){try{let t=r(e);return t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`}catch{return`missing`}}function isDirectory(e){try{return f(e).isDirectory()}catch{return!1}}function sameContent(e,t){let n=filesUnder(e),r=filesUnder(t);return n.length===r.length&&n.every((n,i)=>r[i]===n&&a(C(e,n)).equals(a(C(t,n))))}function inspect$1(e,t,n,r){switch(pathState(e)){case`missing`:return{kind:`none`,status:`missing`,problem:`missing`};case`file`:return{kind:`file`,status:`degraded`,problem:`degraded`};case`symlink`:return linksTo(e,n)?{kind:`symlink`,status:`ok`}:{kind:`symlink`,status:`stale`,problem:`stale`};default:if(!sameContent(e,n)){let e=r.directionOf(t,Xr);return{kind:`copy`,status:`diverged`,problem:`diverged-${e}`,direction:e}}return r.trackingOf(t)===`tracked`?{kind:`copy`,status:`ok`,problem:`unpinned-copy`}:{kind:`copy`,status:`ok`}}}__name(inspect$1,`inspect`);function diagnoseBridges({root:e,harnesses:t=[],cli:n,home:r,env:i}){let a=C(e,`.agents`,`skills`),o=new GitBridgeState(e),s=selectHarnesses(e,t),c=s.map(e=>({name:e.name,skillsDirectory:e.project.skillsDirectory})).filter(e=>!!e.skillsDirectory),l=[],u=[],d=[];if(!isDirectory(a)){let{detail:e,repair:t}=repairFor(`no-canonical`);d.push({path:Xr,problem:`no-canonical`,detail:e,repair:t({file:Xr},n)})}for(let t of c){let r=t.skillsDirectory,i=inspect$1(C(e,r),r,a,o);if(l.push({harness:t.name,path:r,kind:i.kind,status:i.status}),i.direction&&u.push({path:r,direction:i.direction}),i.problem){let{detail:e,repair:t}=repairFor(i.problem);d.push({path:r,problem:i.problem,detail:e,repair:t({file:r},n)})}}let f=diagnoseInstructions(e,s,n);d.push(...f.findings);let p=r===void 0?{globalInstructions:[],findings:[]}:diagnoseGlobalInstructions(r,t,n,i,e);return d.push(...p.findings),{bridges:l,instructions:f.instructions,globalInstructions:p.globalInstructions,divergence:u,findings:d}}function buildDoctorReport(e,t,n=[],r=[]){let i=[...t.findings,...n],a=r.length?r:`0 references — no layer outside the plugin tier holds one`;if(!i.length){let n=t.bridges.length+t.instructions.length,r=n===1?`the 1 bridge resolves`:`all ${n} bridges resolve`;return{bin:e,bridges:t.bridges,instructions:t.instructions,globalInstructions:t.globalInstructions,references:a,findings:`0 problems found — ${r} and the configuration around them is current`}}return{bin:e,bridges:t.bridges,instructions:t.instructions,globalInstructions:t.globalInstructions,references:a,...t.divergence.length?{divergence:t.divergence}:{},findings:i.map(({path:e,problem:t,detail:n})=>({path:e,problem:t,detail:n})),help:[...new Map(i.map(e=>[`${e.repair.command}\u0000${e.repair.instruction}`,e.repair])).values()]}}const Zr={root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},harness:{description:`Comma-separated harnesses to check in addition to Claude Code and Cursor, e.g. codex,gemini-cli.`,type:N.string().optional()}};async function diagnoseReport(e){try{let t=parseHarnessOption(e.harness),n=e.root??process.cwd(),r=_(),i=diagnoseBridges({root:n,...t.length?{harnesses:t}:{},cli:er,home:r,env:process.env}),a=new GitBridgeState(n),o=[...diagnoseConfiguration({root:n,git:a,cli:er}),...diagnoseMcp({root:n,git:a,cli:er}),...diagnoseNonstandard({root:n,cli:er}),...diagnoseWorktrees({root:n,git:a,cli:er})],{layers:s}=listReferences(await referenceLayers({root:n,home:r,platform:process.platform,env:process.env})),c=s.filter(({tier:e})=>e!==`plugin`).map(({name:e,tier:t,path:n,outcome:i})=>({name:e,tier:t,path:collapseHome$1(r,n),status:i}));return buildDoctorReport(displayBinPath(r,process.argv[1]),i,o,c)}catch(e){return fail(e,`Harness diagnosis failed.`)}}const Qr=command({name:`doctor`,description:`Report whether this repository's harness bridges still resolve — skills into .agents/skills, instructions into AGENTS.md — and whether each harness's user-scope file loads ~/.agents/AGENTS.md. Read-only.`,options:Zr,examples:[{command:`buddy-agent-harness doctor`,description:`Check the current repository`},{command:`buddy-agent-harness doctor --harness codex,gemini-cli`,description:`Also check Codex and Gemini CLI`}],async run(e){return result(await diagnoseReport(e))}});function layersFor(e){let t=governanceLayers({root:e.root??process.cwd(),home:_(),platform:process.platform,programData:process.env.ProgramData});return e[`overrides-only`]?overrideLayers(t):t}const $r=`warning: "governance" is deprecated and will be removed in the next major version; use "reference load|list" instead.
461
+ `,ei={description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},ti={description:`Resolve only the project, user, and machine-wide layers. Never returns a governance this package ships, and exits non-zero when no layer has one.`,type:N.boolean().optional()},ni=command({name:`governance`,description:"Deprecated: use `reference`. Read the governance documents the project, user, and machine-wide override layers hold. Read-only.",commands:[command({name:`list`,description:`List every governance the override layers hold, each at the layer that would win.`,options:{root:ei,"overrides-only":ti},examples:[{command:`buddy-agent-harness governance list`,description:`List the governances the layers hold`}],run(e){process.stderr.write($r);try{let t=_(),n=layersFor(e),r=listGovernances(n);return result({layers:n.map(({scope:e,dir:n})=>({scope:e,path:collapseHome$1(t,n),status:e===`managed-deprecated`?`deprecated — move these documents to the managed layer above`:``})),governances:r.length?r.map(({name:e,scope:n,path:r})=>({name:e,scope:n,path:collapseHome$1(t,r)})):`0 governances — no layer holds one`})}catch(e){return fail(e,`Governance listing failed.`)}}}),command({name:`show`,description:`Print one governance document, resolved through the layers in order.`,arguments:[{name:`name`,description:"The governance name, without the `.md` extension.",type:N.string()}],options:{root:ei,"overrides-only":ti},examples:[{command:`buddy-agent-harness governance show skill-design`,description:`Print one governance document`}],run(e){let t=this.format;process.stderr.write($r);try{let n=parseGovernanceName(e.name),r=resolveGovernance(n,layersFor(e));if(!r)throw new M(e[`overrides-only`]?`no override for governance "${n}" in the project, user, or machine-wide layer.`:`no governance named "${n}" in any layer.`,{code:`governance-not-found`,details:{name:n},help:ref(`reference list`,{},`see what is available`)});let i={name:r.name,scope:r.scope,path:collapseHome$1(_(),r.path),content:r.content};return t===`text`?document(i.content):result(i)}catch(e){return fail(e,`Governance lookup failed.`)}}})]});function keepWhenEmpty(e){o(e).length===0&&m(C(e,`.gitkeep`),``)}function initializeHarnesses({root:e,harnesses:t=[],copy:n=!1,force:r=!1}){let a=C(e,`.agents`,`skills`),o=countSkills(a);i(repoReferencesDir(e),{recursive:!0});let s=referenceNames([{tier:`repo`,dir:repoReferencesDir(e)}]).length;keepWhenEmpty(a),keepWhenEmpty(repoReferencesDir(e));let c=selectHarnesses(e,t),{linked:l,skipped:u}=projectSkills({root:e,canonicalSkills:a,harnesses:c,copy:n,force:r});return{root:e,harnesses:c.map(e=>e.name),native:c.filter(e=>!e.project.skillsDirectory).map(e=>e.name),linked:l,skipped:u,deprecated:c.filter(e=>e.deprecated).map(e=>({name:e.name,replacedBy:e.deprecated})),skills:o,references:s,copied:n}}const ri=command({name:`init`,description:`Set up canonical agent skills for the harnesses already enabled in a repository.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},harness:{description:`Comma-separated harnesses to enable in addition to Claude Code and Cursor, e.g. codex,gemini-cli.`,type:N.string().optional()},copy:{description:`Copy skills instead of linking them.`,type:N.boolean().optional()},force:{description:`Replace conflicting target skill directories. Names the targets to replace, comma-separated (e.g. .claude/skills); given alone it replaces every conflicting target.`,type:N.string().optional()}},examples:[{command:`buddy-agent-harness init`,description:`Set up skills for Claude Code and Cursor`},{command:`buddy-agent-harness init --harness codex --copy`,description:`Also enable Codex, copying skills instead of linking`}],run(e){try{let t=parseHarnessOption(e.harness);return result(initializeHarnesses({root:e.root??process.cwd(),...t.length?{harnesses:t}:{},...e.copy===void 0?{}:{copy:e.copy},...e.force===void 0?{}:{force:parseForce(e.force)}}))}catch(e){return fail(e,`Harness initialization failed.`)}}}),ii={ArrayExpression:[`elements`],ArrayPattern:[`elements`],ArrowFunctionExpression:[`params`,`body`],AssignmentExpression:[`left`,`right`],AssignmentPattern:[`left`,`right`],AwaitExpression:[`argument`],BinaryExpression:[`left`,`right`],BlockStatement:[`body`],BreakStatement:[`label`],CallExpression:[`callee`,`arguments`],CatchClause:[`param`,`body`],ChainExpression:[`expression`],ClassBody:[`body`],ClassDeclaration:[`id`,`superClass`,`body`],ClassExpression:[`id`,`superClass`,`body`],ConditionalExpression:[`test`,`consequent`,`alternate`],ContinueStatement:[`label`],DebuggerStatement:[],DoWhileStatement:[`body`,`test`],EmptyStatement:[],ExperimentalRestProperty:[`argument`],ExperimentalSpreadProperty:[`argument`],ExportAllDeclaration:[`exported`,`source`,`attributes`],ExportDefaultDeclaration:[`declaration`],ExportNamedDeclaration:[`declaration`,`specifiers`,`source`,`attributes`],ExportSpecifier:[`local`,`exported`],ExpressionStatement:[`expression`],ForInStatement:[`left`,`right`,`body`],ForOfStatement:[`left`,`right`,`body`],ForStatement:[`init`,`test`,`update`,`body`],FunctionDeclaration:[`id`,`params`,`body`],FunctionExpression:[`id`,`params`,`body`],Identifier:[],IfStatement:[`test`,`consequent`,`alternate`],ImportAttribute:[`key`,`value`],ImportDeclaration:[`specifiers`,`source`,`attributes`],ImportDefaultSpecifier:[`local`],ImportExpression:[`source`,`options`],ImportNamespaceSpecifier:[`local`],ImportSpecifier:[`imported`,`local`],JSXAttribute:[`name`,`value`],JSXClosingElement:[`name`],JSXClosingFragment:[],JSXElement:[`openingElement`,`children`,`closingElement`],JSXEmptyExpression:[],JSXExpressionContainer:[`expression`],JSXFragment:[`openingFragment`,`children`,`closingFragment`],JSXIdentifier:[],JSXMemberExpression:[`object`,`property`],JSXNamespacedName:[`namespace`,`name`],JSXOpeningElement:[`name`,`attributes`],JSXOpeningFragment:[],JSXSpreadAttribute:[`argument`],JSXSpreadChild:[`expression`],JSXText:[],LabeledStatement:[`label`,`body`],Literal:[],LogicalExpression:[`left`,`right`],MemberExpression:[`object`,`property`],MetaProperty:[`meta`,`property`],MethodDefinition:[`key`,`value`],NewExpression:[`callee`,`arguments`],ObjectExpression:[`properties`],ObjectPattern:[`properties`],PrivateIdentifier:[],Program:[`body`],Property:[`key`,`value`],PropertyDefinition:[`key`,`value`],RestElement:[`argument`],ReturnStatement:[`argument`],SequenceExpression:[`expressions`],SpreadElement:[`argument`],StaticBlock:[`body`],Super:[],SwitchCase:[`test`,`consequent`],SwitchStatement:[`discriminant`,`cases`],TaggedTemplateExpression:[`tag`,`quasi`],TemplateElement:[],TemplateLiteral:[`quasis`,`expressions`],ThisExpression:[],ThrowStatement:[`argument`],TryStatement:[`block`,`handler`,`finalizer`],UnaryExpression:[`argument`],UpdateExpression:[`argument`],VariableDeclaration:[`declarations`],VariableDeclarator:[`id`,`init`],WhileStatement:[`test`,`body`],WithStatement:[`object`,`body`],YieldExpression:[`argument`]},ai=Object.keys(ii);for(let e of ai)Object.freeze(ii[e]);Object.freeze(ii);function unionWith(e){let t=Object.assign({},ii);for(let n of Object.keys(e))if(Object.hasOwn(t,n)){let r=new Set(e[n]);for(let e of t[n])r.add(e);t[n]=Object.freeze(Array.from(r))}else t[n]=Object.freeze(Array.from(e[n]));return Object.freeze(t)}function last(e){return e[e.length-1]??null}function toKeyName(e){return e.type===`TOMLBare`?e.name:e.value}var TOMLVerImpl=class{constructor(e,t){this.major=e,this.minor=t}lt(e,t){return this.major<e||this.major===e&&this.minor<t}gte(e,t){return this.major>e||this.major===e&&this.minor>=t}};const oi=new TOMLVerImpl(1,0),si=new TOMLVerImpl(1,1),ci=si,li={"1.0":oi,"1.0.0":oi,"1.1":si,"1.1.0":si,latest:si,next:si};function getTOMLVer(e){return e&&li[e]||ci}const ui={"unterminated-string":`Unterminated string constant`,"unterminated-table-key":`Unterminated table-key`,"unterminated-array":`Unterminated array`,"unterminated-inline-table":`Unterminated inline table`,"missing-key":`Empty bare keys are not allowed`,"missing-newline":`Must be a newline`,"missing-equals-sign":`Expected equal (=) token`,"missing-value":`Unspecified values are invalid`,"missing-comma":`Expected comma (,) token`,"dupe-keys":`Defining a key multiple times is invalid`,"unexpected-char":`Unexpected character`,"unexpected-token":`Unexpected token`,"invalid-control-character":`Control characters (codes < 0x1f and 0x7f) are not allowed`,"invalid-comment-character":`Invalid code point {{cp}} within comments`,"invalid-key-value-newline":`The key, equals sign, and value must be on the same line`,"invalid-inline-table-newline":`No newlines are allowed between the curly braces unless they are valid within a value`,"invalid-underscore":`Underscores are allowed between digits`,"invalid-space":`Unexpected spaces`,"invalid-three-quotes":`Three or more quotes are not permitted`,"invalid-date":`Unexpected invalid date`,"invalid-time":`Unexpected invalid time`,"invalid-leading-zero":`Leading zeros are not allowed`,"invalid-trailing-comma-in-inline-table":`Trailing comma is not permitted in an inline table`,"invalid-char-in-escape-sequence":`Invalid character in escape sequence`,"invalid-consecutive-dots-in-key":`Consecutive dots are not permitted in keys`,"invalid-code-point":`Invalid code point {{cp}}`,"invalid-trailing-dot-in-key":`Keys cannot end with a dot`,"invalid-leading-dot-in-key":`Keys cannot start with a dot`};function getMessage(e,t){return t?ui[e].replace(/\{\{(.*?)\}\}/gu,(e,n)=>n in t?t[n]:`{{${n}}}`):ui[e]}var ParseError=class extends SyntaxError{constructor(e,t,n,r,i){super(getMessage(e,i)),this.index=t,this.lineNumber=n,this.column=r}};const $={EOF:-1,NULL:0,SOH:1,BACKSPACE:8,TABULATION:9,LINE_FEED:10,FORM_FEED:12,CARRIAGE_RETURN:13,ESCAPE:27,SO:14,US:31,SPACE:32,QUOTATION_MARK:34,HASH:35,SINGLE_QUOTE:39,PLUS_SIGN:43,COMMA:44,DASH:45,DOT:46,DIGIT_0:48,DIGIT_1:49,DIGIT_2:50,DIGIT_3:51,DIGIT_7:55,DIGIT_9:57,COLON:58,EQUALS_SIGN:61,LATIN_CAPITAL_A:65,LATIN_CAPITAL_E:69,LATIN_CAPITAL_F:70,LATIN_CAPITAL_T:84,LATIN_CAPITAL_U:85,LATIN_CAPITAL_Z:90,LEFT_BRACKET:91,BACKSLASH:92,RIGHT_BRACKET:93,UNDERSCORE:95,LATIN_SMALL_A:97,LATIN_SMALL_B:98,LATIN_SMALL_E:101,LATIN_SMALL_F:102,LATIN_SMALL_I:105,LATIN_SMALL_L:108,LATIN_SMALL_N:110,LATIN_SMALL_O:111,LATIN_SMALL_R:114,LATIN_SMALL_S:115,LATIN_SMALL_T:116,LATIN_SMALL_U:117,LATIN_SMALL_X:120,LATIN_SMALL_Z:122,LEFT_BRACE:123,RIGHT_BRACE:125,TILDE:126,DELETE:127,PAD:128,SUPERSCRIPT_TWO:178,SUPERSCRIPT_THREE:179,SUPERSCRIPT_ONE:185,VULGAR_FRACTION_ONE_QUARTER:188,VULGAR_FRACTION_THREE_QUARTERS:190,LATIN_CAPITAL_LETTER_A_WITH_GRAVE:192,LATIN_CAPITAL_LETTER_O_WITH_DIAERESIS:214,LATIN_CAPITAL_LETTER_O_WITH_STROKE:216,LATIN_SMALL_LETTER_O_WITH_DIAERESIS:246,LATIN_SMALL_LETTER_O_WITH_STROKE:248,GREEK_SMALL_REVERSED_DOTTED_LUNATE_SIGMA_SYMBOL:891,GREEK_CAPITAL_LETTER_YOT:895,CP_1FFF:8191,ZERO_WIDTH_NON_JOINER:8204,ZERO_WIDTH_JOINER:8205,UNDERTIE:8255,CHARACTER_TIE:8256,SUPERSCRIPT_ZERO:8304,CP_218F:8591,CIRCLED_DIGIT_ONE:9312,NEGATIVE_CIRCLED_DIGIT_ZERO:9471,GLAGOLITIC_CAPITAL_LETTER_AZU:11264,CP_2FEF:12271,IDEOGRAPHIC_COMMA:12289,CP_D7FF:55295,CP_E000:57344,CJK_COMPATIBILITY_IDEOGRAPH_F900:63744,ARABIC_LIGATURE_SALAAMUHU_ALAYNAA:64975,ARABIC_LIGATURE_SALLA_USED_AS_KORANIC_STOP_SIGN_ISOLATED_FORM:65008,REPLACEMENT_CHARACTER:65533,LINEAR_B_SYLLABLE_B008_A:65536,CP_EFFFF:983039,CP_10FFFF:1114111};function isControl(e){return e>=$.NULL&&e<=$.US}function isWhitespace(e){return e===$.TABULATION||e===$.SPACE}function isEOL(e){return e===$.LINE_FEED||e===$.CARRIAGE_RETURN}function isUpperLetter(e){return e>=$.LATIN_CAPITAL_A&&e<=$.LATIN_CAPITAL_Z}function isLowerLetter(e){return e>=$.LATIN_SMALL_A&&e<=$.LATIN_SMALL_Z}function isLetter(e){return isLowerLetter(e)||isUpperLetter(e)}function isDigit$1(e){return e>=$.DIGIT_0&&e<=$.DIGIT_9}__name(isDigit$1,`isDigit`);function isHexDig(e){return isDigit$1(e)||e>=$.LATIN_SMALL_A&&e<=$.LATIN_SMALL_F||e>=$.LATIN_CAPITAL_A&&e<=$.LATIN_CAPITAL_F}function isOctalDig(e){return e>=$.DIGIT_0&&e<=$.DIGIT_7}function isUnicodeScalarValue(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function sortedLastIndex(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1,a=e[i];if(a===t)return i+1;a<t?n=i+1:r=i}return n}var Locations=class{constructor(){this.offsets=[]}addOffset(e){for(let t=this.offsets.length-1;t>=0;t--){let n=this.offsets[t];if(n===e)return;if(n<e)break}this.offsets.push(e)}getLocFromIndex(e){let t=sortedLastIndex(this.offsets,e)+1;return{line:t,column:e-(t===1?0:this.offsets[t-2])}}},CodePointIterator=class{constructor(e){this.locs=new Locations,this.lastCodePoint=$.NULL,this.start=-1,this.end=0,this.text=e}next(){return this.lastCodePoint===$.EOF?$.EOF:this.lastCodePoint=this.moveAt(this.end)}getLocFromIndex(e){return this.locs.getLocFromIndex(e)}eat(e){return this.text.codePointAt(this.end)===e&&(this.next(),!0)}moveAt(e){this.start=this.end=e;let t=this.text.codePointAt(this.start)??$.EOF;if(t===$.EOF)return this.end=this.start,t;if(this.end+=t>=65536?2:1,t===$.LINE_FEED)this.locs.addOffset(this.end);else if(t===$.CARRIAGE_RETURN)return this.text.codePointAt(this.end)===$.LINE_FEED&&(this.end++,this.locs.addOffset(this.end)),$.LINE_FEED;return t}};const di=typeof BigInt<`u`,fi={16:`0x`,10:``,8:`0o`,2:`0b`},pi={[$.QUOTATION_MARK]:$.QUOTATION_MARK,[$.BACKSLASH]:$.BACKSLASH,[$.LATIN_SMALL_B]:$.BACKSPACE,[$.LATIN_SMALL_F]:$.FORM_FEED,[$.LATIN_SMALL_N]:$.LINE_FEED,[$.LATIN_SMALL_R]:$.CARRIAGE_RETURN,[$.LATIN_SMALL_T]:$.TABULATION},mi={...pi,[$.LATIN_SMALL_E]:$.ESCAPE};var Tokenizer=class{constructor(e,t){this.backCode=!1,this.lastCodePoint=$.NULL,this.state=`DATA`,this.token=null,this.tokenStart=-1,this.valuesEnabled=!1,this.text=e,this.parserOptions=t||{},this.codePointIterator=new CodePointIterator(e),this.tomlVersion=getTOMLVer(this.parserOptions.tomlVersion),this.ESCAPES=this.tomlVersion.gte(1,1)?mi:pi}get start(){return this.codePointIterator.start}get end(){return this.codePointIterator.end}getLocFromIndex(e){return this.codePointIterator.getLocFromIndex(e)}reportParseError(e,t){let n=this.codePointIterator.start,r=this.codePointIterator.getLocFromIndex(n);throw new ParseError(e,n,r.line,r.column,t)}nextToken(){let e=this.token;if(e!=null)return this.token=null,e;let t=this.lastCodePoint;for(;t!==$.EOF&&!this.token;){t=this.nextCode();let e=this[this.state](t);if(!e)throw Error(`Unknown error: pre state=${this.state}`);this.state=e}return e=this.token,this.token=null,e}nextCode(){return this.lastCodePoint===$.EOF?$.EOF:this.backCode?(this.backCode=!1,this.lastCodePoint):this.lastCodePoint=this.codePointIterator.next()}eatCode(e){return this.lastCodePoint===$.EOF?!1:this.backCode?this.lastCodePoint===e&&(this.backCode=!1,!0):this.codePointIterator.eat(e)}moveAt(e){this.backCode&&=!1,this.lastCodePoint=this.codePointIterator.moveAt(e)}back(e){return this.backCode=!0,e}punctuatorToken(){this.startToken(),this.endToken(`Punctuator`,`end`)}startToken(){this.tokenStart=this.codePointIterator.start}endToken(e,t,n,r){let{tokenStart:i}=this,a=this.codePointIterator[t],o=[i,a],s={start:this.codePointIterator.getLocFromIndex(i),end:this.codePointIterator.getLocFromIndex(a)};if(e===`Block`)this.token={type:e,value:this.text.slice(i+1,a),range:o,loc:s};else{let t,c=this.text.slice(i,a);if(e===`BasicString`||e===`LiteralString`||e===`MultiLineBasicString`||e===`MultiLineLiteralString`)t={type:e,value:c,string:n,range:o,loc:s};else if(e===`Integer`){let i=n;t={type:e,value:c,number:parseInt(i,r),bigint:di?BigInt(fi[r]+i):null,range:o,loc:s}}else t=e===`Float`?{type:e,value:c,number:n,range:o,loc:s}:e===`Boolean`?{type:e,value:c,boolean:n,range:o,loc:s}:e===`LocalDate`||e===`LocalTime`||e===`LocalDateTime`||e===`OffsetDateTime`?{type:e,value:c,date:n,range:o,loc:s}:{type:e,value:c,range:o,loc:s};this.token=t}}DATA(e){for(;isWhitespace(e)||isEOL(e);)e=this.nextCode();if(e===$.HASH)return this.startToken(),`COMMENT`;if(e===$.QUOTATION_MARK)return this.startToken(),`BASIC_STRING`;if(e===$.SINGLE_QUOTE)return this.startToken(),`LITERAL_STRING`;if(e===$.DOT||e===$.EQUALS_SIGN||e===$.LEFT_BRACKET||e===$.RIGHT_BRACKET||e===$.LEFT_BRACE||e===$.RIGHT_BRACE||e===$.COMMA)return this.punctuatorToken(),`DATA`;if(this.valuesEnabled){if(e===$.DASH||e===$.PLUS_SIGN)return this.startToken(),`SIGN`;if(e===$.LATIN_SMALL_N||e===$.LATIN_SMALL_I)return this.startToken(),this.back(`NAN_OR_INF`);if(isDigit$1(e))return this.startToken(),this.back(`NUMBER`);if(e===$.LATIN_SMALL_T||e===$.LATIN_SMALL_F)return this.startToken(),this.back(`BOOLEAN`)}else if(isUnquotedKeyChar(e,this.tomlVersion))return this.startToken(),`BARE`;return e===$.EOF?`DATA`:this.reportParseError(`unexpected-char`)}COMMENT(e){let t=this.tomlVersion.gte(1,1)?e=>{isNonEOL(e)||this.reportParseError(`invalid-comment-character`,{cp:JSON.stringify(String.fromCodePoint(e)).slice(1,-1)})}:e=>{isControlOtherThanTab(e)&&this.reportParseErrorControlChar()};for(;!isEOL(e)&&e!==$.EOF;)t(e),e=this.nextCode();return this.endToken(`Block`,`start`),`DATA`}BARE(e){for(;isUnquotedKeyChar(e,this.tomlVersion);)e=this.nextCode();return this.endToken(`Bare`,`start`),this.back(`DATA`)}BASIC_STRING(e){if(e===$.QUOTATION_MARK)return e=this.nextCode(),e===$.QUOTATION_MARK?`MULTI_LINE_BASIC_STRING`:(this.endToken(`BasicString`,`start`,``),this.back(`DATA`));let t=[];for(;e!==$.QUOTATION_MARK&&e!==$.EOF&&e!==$.LINE_FEED;){if(isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.BACKSLASH){e=this.nextCode();let n=this.ESCAPES[e];if(n){t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}return this.reportParseError(`invalid-char-in-escape-sequence`)}t.push(e),e=this.nextCode()}return e===$.QUOTATION_MARK?(this.endToken(`BasicString`,`end`,String.fromCodePoint(...t)),`DATA`):this.reportParseError(`unterminated-string`)}MULTI_LINE_BASIC_STRING(e){let t=[];for(e===$.LINE_FEED&&(e=this.nextCode());e!==$.EOF;){if(e!==$.LINE_FEED&&isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.QUOTATION_MARK){let e=this.codePointIterator.start;if(this.eatCode($.QUOTATION_MARK)&&this.eatCode($.QUOTATION_MARK))return this.eatCode($.QUOTATION_MARK)&&(t.push($.QUOTATION_MARK),this.eatCode($.QUOTATION_MARK)&&(t.push($.QUOTATION_MARK),this.eatCode($.QUOTATION_MARK)))?(this.moveAt(e),this.reportParseError(`invalid-three-quotes`)):(this.endToken(`MultiLineBasicString`,`end`,String.fromCodePoint(...t)),`DATA`);this.moveAt(e)}if(e===$.BACKSLASH){e=this.nextCode();let n=this.ESCAPES[e];if(n){t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_U){let n=this.parseUnicode(4);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_CAPITAL_U){let n=this.parseUnicode(8);t.push(n),e=this.nextCode();continue}if(e===$.LATIN_SMALL_X&&this.tomlVersion.gte(1,1)){let n=this.parseUnicode(2);t.push(n),e=this.nextCode();continue}if(e===$.LINE_FEED){for(e=this.nextCode();isWhitespace(e)||e===$.LINE_FEED;)e=this.nextCode();continue}if(isWhitespace(e)){let t=!0,n=this.codePointIterator.start,r;for(;(r=this.nextCode())!==$.EOF&&r!==$.LINE_FEED;)if(!isWhitespace(r)){this.moveAt(n),t=!1;break}if(t){for(e=this.nextCode();isWhitespace(e)||e===$.LINE_FEED;)e=this.nextCode();continue}}return this.reportParseError(`invalid-char-in-escape-sequence`)}t.push(e),e=this.nextCode()}return this.reportParseError(`unterminated-string`)}LITERAL_STRING(e){if(e===$.SINGLE_QUOTE)return e=this.nextCode(),e===$.SINGLE_QUOTE?`MULTI_LINE_LITERAL_STRING`:(this.endToken(`LiteralString`,`start`,``),this.back(`DATA`));let t=[];for(;e!==$.SINGLE_QUOTE&&e!==$.EOF&&e!==$.LINE_FEED;){if(isControlOtherThanTab(e))return this.reportParseErrorControlChar();t.push(e),e=this.nextCode()}return e===$.SINGLE_QUOTE?(this.endToken(`LiteralString`,`end`,String.fromCodePoint(...t)),`DATA`):this.reportParseError(`unterminated-string`)}MULTI_LINE_LITERAL_STRING(e){let t=[];for(e===$.LINE_FEED&&(e=this.nextCode());e!==$.EOF;){if(e!==$.LINE_FEED&&isControlOtherThanTab(e))return this.reportParseErrorControlChar();if(e===$.SINGLE_QUOTE){let e=this.codePointIterator.start;if(this.eatCode($.SINGLE_QUOTE)&&this.eatCode($.SINGLE_QUOTE))return this.eatCode($.SINGLE_QUOTE)&&(t.push($.SINGLE_QUOTE),this.eatCode($.SINGLE_QUOTE)&&(t.push($.SINGLE_QUOTE),this.eatCode($.SINGLE_QUOTE)))?(this.moveAt(e),this.reportParseError(`invalid-three-quotes`)):(this.endToken(`MultiLineLiteralString`,`end`,String.fromCodePoint(...t)),`DATA`);this.moveAt(e)}t.push(e),e=this.nextCode()}return this.reportParseError(`unterminated-string`)}SIGN(e){return e===$.LATIN_SMALL_N||e===$.LATIN_SMALL_I?this.back(`NAN_OR_INF`):isDigit$1(e)?this.back(`NUMBER`):this.reportParseError(`unexpected-char`)}NAN_OR_INF(e){if(e===$.LATIN_SMALL_N){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_A)&&this.eatCode($.LATIN_SMALL_N))return this.endToken(`Float`,`end`,NaN),`DATA`;this.moveAt(e)}else if(e===$.LATIN_SMALL_I){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_N)&&this.eatCode($.LATIN_SMALL_F))return this.endToken(`Float`,`end`,this.text[this.tokenStart]===`-`?-1/0:1/0),`DATA`;this.moveAt(e)}return this.reportParseError(`unexpected-char`)}NUMBER(e){let t=this.text[this.tokenStart],n=t===`+`?$.PLUS_SIGN:t===`-`?$.DASH:$.NULL;if(e===$.DIGIT_0){if(n===$.NULL){let e=this.codePointIterator.start,t=this.nextCode();if(isDigit$1(t)){let n=this.nextCode();if(n===$.COLON)return this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint($.DIGIT_0,t)),minute:0,second:0},`TIME_MINUTE`;if(isDigit$1(n)){let e=this.nextCode();if(isDigit$1(e)&&this.eatCode($.DASH))return this.data={hasDate:!0,year:Number(String.fromCodePoint($.DIGIT_0,t,n,e)),month:0,day:0,hour:0,minute:0,second:0},`DATE_MONTH`}return this.moveAt(e),this.reportParseError(`invalid-leading-zero`)}this.moveAt(e)}return e=this.nextCode(),e===$.LATIN_SMALL_X||e===$.LATIN_SMALL_O||e===$.LATIN_SMALL_B?n===$.NULL?e===$.LATIN_SMALL_X?`HEX`:e===$.LATIN_SMALL_O?`OCTAL`:`BINARY`:this.reportParseError(`unexpected-char`):e===$.LATIN_SMALL_E||e===$.LATIN_CAPITAL_E?(this.data={minus:n===$.DASH,left:[$.DIGIT_0]},`EXPONENT_RIGHT`):e===$.DOT?(this.data={minus:n===$.DASH,absInt:[$.DIGIT_0]},`FRACTIONAL_RIGHT`):(this.endToken(`Integer`,`start`,`0`,10),this.back(`DATA`))}let{out:r,nextCp:i,hasUnderscore:a}=this.parseDigits(e,isDigit$1);return i===$.DASH&&n===$.NULL&&!a&&r.length===4?(this.data={hasDate:!0,year:Number(String.fromCodePoint(...r)),month:0,day:0,hour:0,minute:0,second:0},`DATE_MONTH`):i===$.COLON&&n===$.NULL&&!a&&r.length===2?(this.data={hasDate:!1,year:0,month:0,day:0,hour:Number(String.fromCodePoint(...r)),minute:0,second:0},`TIME_MINUTE`):i===$.LATIN_SMALL_E||i===$.LATIN_CAPITAL_E?(this.data={minus:n===$.DASH,left:r},`EXPONENT_RIGHT`):i===$.DOT?(this.data={minus:n===$.DASH,absInt:r},`FRACTIONAL_RIGHT`):(this.endToken(`Integer`,`start`,n===$.DASH?String.fromCodePoint($.DASH,...r):String.fromCodePoint(...r),10),this.back(`DATA`))}HEX(e){let{out:t}=this.parseDigits(e,isHexDig);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),16),this.back(`DATA`)}OCTAL(e){let{out:t}=this.parseDigits(e,isOctalDig);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),8),this.back(`DATA`)}BINARY(e){let{out:t}=this.parseDigits(e,e=>e===$.DIGIT_0||e===$.DIGIT_1);return this.endToken(`Integer`,`start`,String.fromCodePoint(...t),2),this.back(`DATA`)}FRACTIONAL_RIGHT(e){let{minus:t,absInt:n}=this.data,{out:r,nextCp:i}=this.parseDigits(e,isDigit$1),a=[...n,$.DOT,...r];if(i===$.LATIN_SMALL_E||i===$.LATIN_CAPITAL_E)return this.data={minus:t,left:a},`EXPONENT_RIGHT`;let o=Number(t?String.fromCodePoint($.DASH,...a):String.fromCodePoint(...a));return this.endToken(`Float`,`start`,o),this.back(`DATA`)}EXPONENT_RIGHT(e){let{left:t,minus:n}=this.data,r=!1;(e===$.DASH||e===$.PLUS_SIGN)&&(r=e===$.DASH,e=this.nextCode());let{out:i}=this.parseDigits(e,isDigit$1),a=i;r&&a.unshift($.DASH);let o=Number(n?String.fromCodePoint($.DASH,...t,$.LATIN_SMALL_E,...a):String.fromCodePoint(...t,$.LATIN_SMALL_E,...a));return this.endToken(`Float`,`start`,o),this.back(`DATA`)}BOOLEAN(e){if(e===$.LATIN_SMALL_T){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_R)&&this.eatCode($.LATIN_SMALL_U)&&this.eatCode($.LATIN_SMALL_E))return this.endToken(`Boolean`,`end`,!0),`DATA`;this.moveAt(e)}else if(e===$.LATIN_SMALL_F){let e=this.codePointIterator.start;if(this.eatCode($.LATIN_SMALL_A)&&this.eatCode($.LATIN_SMALL_L)&&this.eatCode($.LATIN_SMALL_S)&&this.eatCode($.LATIN_SMALL_E))return this.endToken(`Boolean`,`end`,!1),`DATA`;this.moveAt(e)}return this.reportParseError(`unexpected-char`)}DATE_MONTH(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e))||(e=this.nextCode(),e!==$.DASH))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start,r=this.data;return r.month=Number(this.text.slice(t,n)),`DATE_DAY`}DATE_DAY(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;if(r.day=Number(this.text.slice(t,n)),!isValidDate(r.year,r.month,r.day))return this.reportParseError(`invalid-date`);if(e=this.nextCode(),e===$.LATIN_CAPITAL_T||e===$.LATIN_SMALL_T)return`TIME_HOUR`;if(e===$.SPACE){let e=this.codePointIterator.start;if(isDigit$1(this.nextCode())&&isDigit$1(this.nextCode()))return this.moveAt(e),`TIME_HOUR`;this.moveAt(e)}let i=getDateFromDateTimeData(r,``);return this.endToken(`LocalDate`,`start`,i),this.back(`DATA`)}TIME_HOUR(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e))||(e=this.nextCode(),e!==$.COLON))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start,r=this.data;return r.hour=Number(this.text.slice(t,n)),`TIME_MINUTE`}TIME_MINUTE(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;return r.minute=Number(this.text.slice(t,n)),e=this.nextCode(),e===$.COLON?`TIME_SECOND`:this.tomlVersion.lt(1,1)?this.reportParseError(`unexpected-char`):isValidTime(r.hour,r.minute,r.second)?this.processTimeEnd(e,r):this.reportParseError(`invalid-time`)}TIME_SECOND(e){let t=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.end,r=this.data;return r.second=Number(this.text.slice(t,n)),isValidTime(r.hour,r.minute,r.second)?(e=this.nextCode(),e===$.DOT?`TIME_SEC_FRAC`:this.processTimeEnd(e,r)):this.reportParseError(`invalid-time`)}TIME_SEC_FRAC(e){if(!isDigit$1(e))return this.reportParseError(`unexpected-char`);let t=this.codePointIterator.start;for(;isDigit$1(e);)e=this.nextCode();let n=this.codePointIterator.start,r=this.data;return r.frac=this.text.slice(t,n),this.processTimeEnd(e,r)}processTimeEnd(e,t){if(t.hasDate){if(e===$.DASH||e===$.PLUS_SIGN)return t.offsetSign=e,`TIME_OFFSET`;if(e===$.LATIN_CAPITAL_Z||e===$.LATIN_SMALL_Z){let e=getDateFromDateTimeData(t,`Z`);return this.endToken(`OffsetDateTime`,`end`,e),`DATA`}let n=getDateFromDateTimeData(t,``);return this.endToken(`LocalDateTime`,`start`,n),this.back(`DATA`)}let n=getDateFromDateTimeData(t,``);return this.endToken(`LocalTime`,`start`,n),this.back(`DATA`)}TIME_OFFSET(e){if(!isDigit$1(e))return this.reportParseError(`unexpected-char`);let t=this.codePointIterator.start;if(e=this.nextCode(),!isDigit$1(e)||(e=this.nextCode(),e!==$.COLON))return this.reportParseError(`unexpected-char`);let n=this.codePointIterator.start;e=this.nextCode();let r=this.codePointIterator.start;if(!isDigit$1(e)||(e=this.nextCode(),!isDigit$1(e)))return this.reportParseError(`unexpected-char`);let i=this.codePointIterator.end,a=Number(this.text.slice(t,n)),o=Number(this.text.slice(r,i));if(!isValidTime(a,o,0))return this.reportParseError(`invalid-time`);let s=this.data,c=getDateFromDateTimeData(s,`${String.fromCodePoint(s.offsetSign)}${padStart(a,2)}:${padStart(o,2)}`);return this.endToken(`OffsetDateTime`,`end`,c),`DATA`}parseDigits(e,t){if(e===$.UNDERSCORE)return this.reportParseError(`invalid-underscore`);if(!t(e))return this.reportParseError(`unexpected-char`);let n=[],r=$.NULL,i=!1;for(;t(e)||e===$.UNDERSCORE;){if(e===$.UNDERSCORE){if(i=!0,r===$.UNDERSCORE)return this.reportParseError(`invalid-underscore`)}else n.push(e);r=e,e=this.nextCode()}return r===$.UNDERSCORE?this.reportParseError(`invalid-underscore`):{out:n,nextCp:e,hasUnderscore:i}}parseUnicode(e){let t=this.codePointIterator.start,n=this.codePointIterator.end,r=0,i;for(;(i=this.nextCode())!==$.EOF;){if(!isHexDig(i))return this.moveAt(t),this.reportParseError(`invalid-char-in-escape-sequence`);if(r++,r>=e)break}let a=this.codePointIterator.end,o=this.text.slice(n,a),s=parseInt(o,16);return isUnicodeScalarValue(s)?s:this.reportParseError(`invalid-code-point`,{cp:o})}reportParseErrorControlChar(){return this.reportParseError(`invalid-control-character`)}};function isUnquotedKeyChar(e,t){return isLetter(e)||isDigit$1(e)||e===$.UNDERSCORE||e===$.DASH?!0:(t.lt(1,1),!1)}function isControlOtherThanTab(e){return isControl(e)&&e!==$.TABULATION||e===$.DELETE}function isNonEOL(e){return e===$.TABULATION||$.SPACE<=e&&e<=$.TILDE||isNonAscii(e)}function isNonAscii(e){return $.PAD<=e&&e<=$.CP_D7FF||$.CP_E000<=e&&e<=$.CP_10FFFF}function isValidDate(e,t,n){return e>=0&&t<=12&&t>=1&&n>=1&&n<=(t===2?e&3||!(e%25)&&e&15?28:29:30+(t+(t>>3)&1))}function isValidTime(e,t,n){return!(e>=24||e<0||t>59||t<0||n>60||n<0)}function getDateFromDateTimeData(e,t){let n=padStart(e.year,4),r=e.month?padStart(e.month,2):`01`,i=e.day?padStart(e.day,2):`01`,a=padStart(e.hour,2),o=padStart(e.minute,2),s=padStart(e.second,2),c=`${n}-${r}-${i}`,l=e.frac?`.${e.frac}`:``,u=new Date(`${c}T${a}:${o}:${s}${l}${t}`);return!isNaN(u.getTime())||e.second!==60?u:new Date(`${c}T${a}:${o}:59${l}${t}`)}function padStart(e,t){return String(e).padStart(t,`0`)}const hi=Symbol(`VALUE_KIND_VALUE`),gi=Symbol(`VALUE_KIND_INTERMEDIATE`);var KeysResolver=class{constructor(e){this.rootKeys=new Map,this.tables=[],this.ctx=e}applyResolveKeyForTable(e){let t=this.rootKeys,n=e.key.keys.length-1;for(let r=0;r<n;r++){let n=e.key.keys[r],i=toKeyName(n);e.resolvedKey.push(i);let a=t.get(i);if(!a)a={node:n,keys:new Map},t.set(i,a);else if(a.table===`array`){let t=a.peekIndex;e.resolvedKey.push(t),a=a.keys.get(t)}t=a.keys}let r=e.key.keys[n],i=toKeyName(r);e.resolvedKey.push(i);let a=t.get(i);if(!a){if(e.kind===`array`){e.resolvedKey.push(0);let n={node:r,keys:new Map};t.set(i,{table:e.kind,node:r,keys:new Map([[0,n]]),peekIndex:0}),this.tables.push({node:e,keys:n.keys})}else{let n={table:e.kind,node:r,keys:new Map};t.set(i,n),this.tables.push({node:e,keys:n.keys})}}else if(!a.table){if(e.kind===`array`)this.ctx.reportParseError(`dupe-keys`,r);else{let n={table:e.kind,node:r,keys:a.keys};t.set(i,n),this.tables.push({node:e,keys:n.keys})}}else if(a.table===`array`){if(e.kind===`array`){let t={node:r,keys:new Map},n=a.peekIndex+1;e.resolvedKey.push(n),a.keys.set(n,t),a.peekIndex=n,this.tables.push({node:e,keys:t.keys})}else this.ctx.reportParseError(`dupe-keys`,r)}else this.ctx.reportParseError(`dupe-keys`,r)}verifyDuplicateKeys(e){for(let t of e.body)t.type===`TOMLKeyValue`&&verifyDuplicateKeysForKeyValue(this.ctx,this.rootKeys,t);for(let{node:e,keys:t}of this.tables)for(let n of e.body)verifyDuplicateKeysForKeyValue(this.ctx,t,n)}};function verifyDuplicateKeysForKeyValue(e,t,n){let r=t,i=last(n.key.keys);for(let t of n.key.keys){let n=toKeyName(t),a=r.get(n);a?((a.value===hi||i===t||a.table)&&e.reportParseError(`dupe-keys`,getAfterNode(t,a.node)),a.value=gi):(a=i===t?{value:hi,node:t,keys:new Map}:{value:gi,node:t,keys:new Map},r.set(n,a)),r=a.keys}n.value.type===`TOMLInlineTable`?verifyDuplicateKeysForInlineTable(e,r,n.value):n.value.type===`TOMLArray`&&verifyDuplicateKeysForArray(e,r,n.value)}function verifyDuplicateKeysForInlineTable(e,t,n){for(let r of n.body)verifyDuplicateKeysForKeyValue(e,t,r)}function verifyDuplicateKeysForArray(e,t,n){let r=t;for(let i=0;i<n.elements.length;i++){let a=n.elements[i],o=r.get(i);o?e.reportParseError(`dupe-keys`,getAfterNode(a,o.node)):(o={value:hi,node:a,keys:new Map},t.set(i,o),a.type===`TOMLInlineTable`?verifyDuplicateKeysForInlineTable(e,o.keys,a):a.type===`TOMLArray`&&verifyDuplicateKeysForArray(e,o.keys,a))}}function getAfterNode(e,t){return e.range[0]<=t.range[0]?t:e}var Context=class{constructor(e){this.tokens=[],this.comments=[],this.back=null,this.stateStack=[],this.needNewLine=!1,this.needSameLine=!1,this.currToken=null,this.prevToken=null,this.valueContainerStack=[],this.tokenizer=new Tokenizer(e.text,e.parserOptions),this.topLevelTable=e.topLevelTable,this.table=e.topLevelTable,this.keysResolver=new KeysResolver(this)}nextToken(e){if(this.prevToken=this.currToken,this.back?(this.currToken=this.back,this.back=null):this.currToken=this._nextTokenFromTokenizer(e),(this.needNewLine||this.needSameLine||e?.needSameLine)&&this.prevToken&&this.currToken){if(this.prevToken.loc.end.line===this.currToken.loc.start.line){if(this.needNewLine)return this.reportParseError(`missing-newline`,this.currToken)}else{let t=this.needSameLine||e?.needSameLine;if(t)return this.reportParseError(t,this.currToken)}}return this.needNewLine=!1,this.needSameLine=!1,this.currToken}_nextTokenFromTokenizer(e){let t=this.tokenizer.valuesEnabled;e?.valuesEnabled&&(this.tokenizer.valuesEnabled=e.valuesEnabled);let n=this.tokenizer.nextToken();for(;n&&n.type===`Block`;)this.comments.push(n),n=this.tokenizer.nextToken();return n&&this.tokens.push(n),this.tokenizer.valuesEnabled=t,n}backToken(){if(this.back)throw Error(`Illegal state`);this.back=this.currToken,this.currToken=this.prevToken}addValueContainer(e){this.valueContainerStack.push(e),this.tokenizer.valuesEnabled=!0}consumeValueContainer(){let e=this.valueContainerStack.pop();return this.tokenizer.valuesEnabled=this.valueContainerStack.length>0,e}applyResolveKeyForTable(e){this.keysResolver.applyResolveKeyForTable(e)}verifyDuplicateKeys(){this.keysResolver.verifyDuplicateKeys(this.topLevelTable)}reportParseError(e,t){let n,r,i;if(t)n=t.range[0],r=t.loc.start.line,i=t.loc.start.column;else{n=this.tokenizer.start;let e=this.tokenizer.getLocFromIndex(n);r=e.line,i=e.column}throw new ParseError(e,n,r,i)}};const _i={VALUE:`missing-value`},vi={BasicString:`basic`,MultiLineBasicString:`basic`,LiteralString:`literal`,MultiLineLiteralString:`literal`},yi={BasicString:`basic`,LiteralString:`literal`},bi={OffsetDateTime:`offset-date-time`,LocalDateTime:`local-date-time`,LocalDate:`local-date`,LocalTime:`local-time`};var TOMLParser=class{constructor(e,t){this.text=e,this.parserOptions=t||{},this.tomlVersion=getTOMLVer(this.parserOptions.tomlVersion)}parse(){let e={type:`Program`,body:[],sourceType:`module`,tokens:[],comments:[],parent:null,range:[0,0],loc:{start:{line:1,column:0},end:{line:1,column:0}}},t={type:`TOMLTopLevelTable`,body:[],parent:e,range:cloneRange(e.range),loc:cloneLoc(e.loc)};e.body=[t];let n=new Context({text:this.text,parserOptions:this.parserOptions,topLevelTable:t}),r=n.nextToken();if(r){for(t.range[0]=r.range[0],t.loc.start=clonePos(r.loc.start);r;){let e=n.stateStack.pop()||`TABLE`;n.stateStack.push(...this[e](r,n)),r=n.nextToken()}let e=n.stateStack.pop()||`TABLE`;if(e in _i)return n.reportParseError(_i[e],null);n.table.type===`TOMLTable`&&applyEndLoc(n.table,last(n.table.body)),applyEndLoc(t,last(t.body))}n.verifyDuplicateKeys(),e.tokens=n.tokens,e.comments=n.comments;let i=n.tokenizer.end,a=n.tokenizer.getLocFromIndex(i);return e.range[1]=i,e.loc.end={line:a.line,column:a.column},e}TABLE(e,t){return isBare(e)||isString(e)?this.processKeyValue(e,t.table,t):isLeftBracket(e)?this.processTable(e,t.topLevelTable,t):t.reportParseError(`unexpected-token`,e)}VALUE(e,t){return isString(e)||isMultiLineString(e)?this.processStringValue(e,t):isNumber(e)?this.processNumberValue(e,t):isBoolean(e)?this.processBooleanValue(e,t):isDateTime(e)?this.processDateTimeValue(e,t):isLeftBracket(e)?this.processArray(e,t):isLeftBrace(e)?this.processInlineTable(e,t):t.reportParseError(`unexpected-token`,e)}processTable(e,t,n){let r={type:`TOMLTable`,kind:`standard`,key:null,resolvedKey:[],body:[],parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};n.table.type===`TOMLTable`&&applyEndLoc(n.table,last(n.table.body)),t.body.push(r),n.table=r;let i=n.nextToken({needSameLine:`invalid-key-value-newline`});if(isLeftBracket(i)){if(e.range[1]<i.range[0])return n.reportParseError(`invalid-space`,i);r.kind=`array`,i=n.nextToken({needSameLine:`invalid-key-value-newline`})}if(isRightBracket(i))return n.reportParseError(`missing-key`,i);if(!i)return n.reportParseError(`unterminated-table-key`,null);if(i=this.processKeyNode(i,r,n).nextToken,!isRightBracket(i))return n.reportParseError(`unterminated-table-key`,i);if(r.kind===`array`){let e=i;if(i=n.nextToken({needSameLine:`invalid-key-value-newline`}),!isRightBracket(i))return n.reportParseError(`unterminated-table-key`,i);if(e.range[1]<i.range[0])return n.reportParseError(`invalid-space`,i)}return applyEndLoc(r,i),n.applyResolveKeyForTable(r),n.needNewLine=!0,[]}processKeyValue(e,t,n){let r={type:`TOMLKeyValue`,key:null,value:null,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.body.push(r);let{nextToken:i}=this.processKeyNode(e,r,n);return isEq(i)?(n.addValueContainer({parent:r,set:e=>(r.value=e,applyEndLoc(r,e),n.needNewLine=!0,[])}),n.needSameLine=`invalid-key-value-newline`,[`VALUE`]):n.reportParseError(`missing-equals-sign`,i)}processKeyNode(e,t,n){isDot(e)&&n.reportParseError(`invalid-leading-dot-in-key`,e);let r={type:`TOMLKey`,keys:[],parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.key=r;let i=e,a=null;do{if(isBare(i))this.processBareKey(i,r);else if(isString(i))this.processStringKey(i,r);else break;if(a=null,i=n.nextToken({needSameLine:`invalid-key-value-newline`}),!isDot(i))break;a=i,i=n.nextToken({needSameLine:`invalid-key-value-newline`})}while(i);return a&&n.reportParseError(isDot(i)?`invalid-consecutive-dots-in-key`:`invalid-trailing-dot-in-key`,a),applyEndLoc(r,last(r.keys)),{keyNode:r,nextToken:i}}processBareKey(e,t){let n={type:`TOMLBare`,name:e.value,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.keys.push(n)}processStringKey(e,t){let n={type:`TOMLQuoted`,kind:`string`,value:e.string,style:yi[e.type],multiline:!1,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.keys.push(n)}processStringValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:`string`,value:e.string,style:vi[e.type],multiline:isMultiLineString(e),parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processNumberValue(e,t){let n=t.consumeValueContainer(),r=this.text,[i,a]=e.range,o=null,getNumberText=()=>o??=r.slice(i,a).replace(/_/g,``),s;return s=e.type===`Integer`?{type:`TOMLValue`,kind:`integer`,value:e.number,bigint:e.bigint,get number(){return getNumberText()},parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)}:{type:`TOMLValue`,kind:`float`,value:e.number,get number(){return getNumberText()},parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},n.set(s)}processBooleanValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:`boolean`,value:e.boolean,parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processDateTimeValue(e,t){let n=t.consumeValueContainer(),r={type:`TOMLValue`,kind:bi[e.type],value:e.date,datetime:e.value,parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)};return n.set(r)}processArray(e,t){let n=t.consumeValueContainer(),r={type:`TOMLArray`,elements:[],parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},i=t.nextToken({valuesEnabled:!0});return isRightBracket(i)?(applyEndLoc(r,i),n.set(r)):(t.backToken(),this.processArrayValue(r,n,t))}processArrayValue(e,t,n){return n.addValueContainer({parent:e,set:r=>{e.elements.push(r);let i=n.nextToken({valuesEnabled:!0}),a=isComma(i);return a&&(i=n.nextToken({valuesEnabled:!0})),isRightBracket(i)?(applyEndLoc(e,i),t.set(e)):a?(n.backToken(),this.processArrayValue(e,t,n)):n.reportParseError(i?`missing-comma`:`unterminated-array`,i)}}),[`VALUE`]}processInlineTable(e,t){let n=t.consumeValueContainer(),r={type:`TOMLInlineTable`,body:[],parent:n.parent,range:cloneRange(e.range),loc:cloneLoc(e.loc)},i=this.tomlVersion.gte(1,1)?void 0:`invalid-inline-table-newline`,a=t.nextToken({needSameLine:i});if(a){if(isBare(a)||isString(a))return this.processInlineTableKeyValue(a,r,n,t);if(isRightBrace(a))return applyEndLoc(r,a),n.set(r)}return t.reportParseError(`unexpected-token`,a)}processInlineTableKeyValue(e,t,n,r){let i={type:`TOMLKeyValue`,key:null,value:null,parent:t,range:cloneRange(e.range),loc:cloneLoc(e.loc)};t.body.push(i);let{nextToken:a}=this.processKeyNode(e,i,r);if(!isEq(a))return r.reportParseError(`missing-equals-sign`,a);let o=this.tomlVersion.gte(1,1)?void 0:`invalid-inline-table-newline`;return r.addValueContainer({parent:i,set:e=>{i.value=e,applyEndLoc(i,e);let a=r.nextToken({needSameLine:o});if(isComma(a)){if(a=r.nextToken({needSameLine:o}),a&&(isBare(a)||isString(a)))return this.processInlineTableKeyValue(a,t,n,r);if(isRightBrace(a)){if(this.tomlVersion.lt(1,1))return r.reportParseError(`invalid-trailing-comma-in-inline-table`,a)}else return r.reportParseError(a?`unexpected-token`:`unterminated-inline-table`,a)}return isRightBrace(a)?(applyEndLoc(t,a),n.set(t)):r.reportParseError(a?`missing-comma`:`unterminated-inline-table`,a)}}),r.needSameLine=`invalid-key-value-newline`,[`VALUE`]}};function isDot(e){return isPunctuator(e)&&e.value===`.`}function isEq(e){return isPunctuator(e)&&e.value===`=`}function isLeftBracket(e){return isPunctuator(e)&&e.value===`[`}function isRightBracket(e){return isPunctuator(e)&&e.value===`]`}function isLeftBrace(e){return isPunctuator(e)&&e.value===`{`}function isRightBrace(e){return isPunctuator(e)&&e.value===`}`}function isComma(e){return isPunctuator(e)&&e.value===`,`}function isPunctuator(e){return!!(e&&e.type===`Punctuator`)}function isBare(e){return e.type===`Bare`}function isString(e){return e.type===`BasicString`||e.type===`LiteralString`}function isMultiLineString(e){return e.type===`MultiLineBasicString`||e.type===`MultiLineLiteralString`}function isNumber(e){return e.type===`Integer`||e.type===`Float`}function isBoolean(e){return e.type===`Boolean`}function isDateTime(e){return e.type===`OffsetDateTime`||e.type===`LocalDateTime`||e.type===`LocalDate`||e.type===`LocalTime`}function applyEndLoc(e,t){t&&(e.range[1]=t.range[1],e.loc.end=clonePos(t.loc.end))}function cloneRange(e){return[e[0],e[1]]}function cloneLoc(e){return{start:clonePos(e.start),end:clonePos(e.end)}}function clonePos(e){return{line:e.line,column:e.column}}const xi=unionWith({Program:[`body`],TOMLTopLevelTable:[`body`],TOMLTable:[`key`,`body`],TOMLKeyValue:[`key`,`value`],TOMLKey:[`keys`],TOMLArray:[`elements`],TOMLInlineTable:[`body`],TOMLBare:[],TOMLQuoted:[],TOMLValue:[]});function parseForESLint(e,t){return{ast:new TOMLParser(e,t).parse(),visitorKeys:xi,services:{isTOML:!0}}}function parseTOML(e,t){return parseForESLint(e,t).ast}function nested(e,t){return e.reduceRight((e,t)=>({[t]:e}),t)}function renderTomlTable(e,t){return stringify(nested(e,t))}function appendTomlTable(e,t,n){return`${e}${e===``||e.endsWith(`
455
462
  `)?``:`
456
- `}\n${renderTomlTable(t,n)}`}function keyNames(e){return e.keys.map(e=>e.type===`TOMLBare`?e.name:e.value)}function startsWith(e,t){return t.length<=e.length&&t.every((t,n)=>e[n]===t)}function overlaps(e,t){return startsWith(e,t)||startsWith(t,e)}function replaceTomlTable(e,t,n){let r;try{r=parseTOML(e)}catch{return{kind:`refused`,reason:`unreadable`}}let i=[];for(let e of r.body[0].body){if(e.type===`TOMLKeyValue`){if(overlaps(keyNames(e.key),t))return{kind:`refused`,reason:`shape`};continue}if(startsWith(e.resolvedKey,t)){if(e.kind===`array`)return{kind:`refused`,reason:`shape`};i.push(e);continue}let n=e.resolvedKey;if(e.body.some(e=>overlaps([...n,...keyNames(e.key)],t)))return{kind:`refused`,reason:`shape`}}if(!i.length)return{kind:`refused`,reason:`absent`};if(!i.some(e=>e.resolvedKey.length===t.length))return{kind:`refused`,reason:`shape`};let a=i.map(t=>{let n=e.slice(t.range[1]).search(/\r?\n/);return[t.range[0],n<0?e.length:t.range[1]+n]}),inside=e=>a.some(([t,n])=>t<=e&&e<n);if(r.comments.some(e=>inside(e.range[0])))return{kind:`refused`,reason:`comment`};let[o,...s]=a,c=e;for(let[e,t]of s.reverse()){let n=c.slice(0,e),r=c.slice(t).replace(/^\r?\n/,``);c=/\n\r?\n$/.test(n)?`${n}${r.replace(/^\r?\n/,``)}`:`${n}${r}`}let l=renderTomlTable(t,n).trimEnd();return{kind:`edited`,text:`${c.slice(0,o[0])}${l}${c.slice(o[1])}`}}const ci=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return ci.test(e)?e:JSON.stringify(e)}function renderTomlInline(e){return typeof e==`object`&&e&&!Array.isArray(e)?`{ ${Object.entries(e).map(([e,t])=>`${tomlKey(e)} = ${renderTomlInline(t)}`).join(`, `)} }`:stringify({v:e}).slice(4).trimEnd()}function appendInlineTomlTable(e,t,n){let r=e===``||e.endsWith(`
463
+ `}\n${renderTomlTable(t,n)}`}function keyNames(e){return e.keys.map(e=>e.type===`TOMLBare`?e.name:e.value)}function startsWith(e,t){return t.length<=e.length&&t.every((t,n)=>e[n]===t)}function overlaps(e,t){return startsWith(e,t)||startsWith(t,e)}function replaceTomlTable(e,t,n){let r;try{r=parseTOML(e)}catch{return{kind:`refused`,reason:`unreadable`}}let i=[];for(let e of r.body[0].body){if(e.type===`TOMLKeyValue`){if(overlaps(keyNames(e.key),t))return{kind:`refused`,reason:`shape`};continue}if(startsWith(e.resolvedKey,t)){if(e.kind===`array`)return{kind:`refused`,reason:`shape`};i.push(e);continue}let n=e.resolvedKey;if(e.body.some(e=>overlaps([...n,...keyNames(e.key)],t)))return{kind:`refused`,reason:`shape`}}if(!i.length)return{kind:`refused`,reason:`absent`};if(!i.some(e=>e.resolvedKey.length===t.length))return{kind:`refused`,reason:`shape`};let a=i.map(t=>{let n=e.slice(t.range[1]).search(/\r?\n/);return[t.range[0],n<0?e.length:t.range[1]+n]}),inside=e=>a.some(([t,n])=>t<=e&&e<n);if(r.comments.some(e=>inside(e.range[0])))return{kind:`refused`,reason:`comment`};let[o,...s]=a,c=e;for(let[e,t]of s.reverse()){let n=c.slice(0,e),r=c.slice(t).replace(/^\r?\n/,``);c=/\n\r?\n$/.test(n)?`${n}${r.replace(/^\r?\n/,``)}`:`${n}${r}`}let l=renderTomlTable(t,n).trimEnd();return{kind:`edited`,text:`${c.slice(0,o[0])}${l}${c.slice(o[1])}`}}const Si=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return Si.test(e)?e:JSON.stringify(e)}function renderTomlInline(e){return typeof e==`object`&&e&&!Array.isArray(e)?`{ ${Object.entries(e).map(([e,t])=>`${tomlKey(e)} = ${renderTomlInline(t)}`).join(`, `)} }`:stringify({v:e}).slice(4).trimEnd()}function appendInlineTomlTable(e,t,n){let r=e===``||e.endsWith(`
457
464
  `)?``:`
458
465
  `,i=Object.entries(n).map(([e,t])=>`${tomlKey(e)} = ${renderTomlInline(t)}\n`);return`${e}${r}\n[${t.map(tomlKey).join(`.`)}]\n${i.join(``)}`}function lineEndAt(e,t){let n=e.indexOf(`
459
466
  `,t);return n===-1?e.length:n}function setTomlKey(e,t,n,r){let i;try{i=parseTOML(e)}catch{return{kind:`refused`,reason:`unreadable`}}let a=i.body[0].body.filter(e=>e.type===`TOMLTable`),o=a.find(e=>e.kind===`standard`&&e.resolvedKey.length===t.length&&startsWith(e.resolvedKey,t));if(!o)return{kind:`refused`,reason:`absent`};let s=o.body;if(a.some(e=>startsWith(e.resolvedKey,[...t,n]))||s.some(e=>keyNames(e.key)[0]===n&&e.key.keys.length>1))return{kind:`refused`,reason:`shape`};let c=s.find(e=>e.key.keys.length===1&&keyNames(e.key)[0]===n);if(c&&r!==void 0)return{kind:`edited`,text:`${e.slice(0,c.value.range[0])}${renderTomlInline(r)}${e.slice(c.value.range[1])}`};if(c){let t=e.lastIndexOf(`
460
- `,c.range[0]-1)+1,n=lineEndAt(e,c.range[1]);return{kind:`edited`,text:`${e.slice(0,t)}${e.slice(Math.min(n+1,e.length))}`}}if(r===void 0)return{kind:`edited`,text:e};let l=lineEndAt(e,s.at(-1)?.range[1]??o.range[0]);return{kind:`edited`,text:`${e.slice(0,l)}\n${tomlKey(n)} = ${renderTomlInline(r)}${e.slice(l)}`}}function read$1(e,t){let r=S(e,t);return n(r)?a(r,`utf8`):void 0}__name(read$1,`read`);const li={both:`both sides changed since the last projection — a three-way conflict for a person to settle, never imported`,unknown:`no baseline says which side changed — compare the two by hand; never imported`};function inferredTransport(e){return e.url===void 0?`stdio`:`http`}function mapValue(e,t){let n=Object.entries(e).flatMap(([e])=>{let n=isRecord(t)?t[e]:void 0;return typeof n==`string`?[[e,n]]:[]});return n.length?Object.fromEntries(n):void 0}function reconcileMcp({root:e,git:t,accept:n}){let r=read$1(e,Y),i=parseGoldenSet(r);if(i.kind!==`servers`)return i;let a=parseProjectionRecord(read$1(e,X)),o=new McpBaseline({git:t,record:a}),s=[],c=[];for(let t of mcpTargets(e)){let n=parseTarget(t,read$1(e,t.path));if(n.kind===`unreadable`){s.push({path:t.path,action:`refuse`,detail:`the target does not parse`});continue}if(n.kind===`absent`)continue;let r=q[t.dialect];for(let[e,a]of n.servers){let n=i.servers.get(e),at=n=>locatorText({file:t.path,server:e,field:n}),offer=(i,o)=>{let l=literalsIn(i,o);for(let e of l)s.push({path:at(e),action:`refuse`,detail:`${e} holds a literal credential, which never enters the golden set — set it in the environment and reference it as \${VAR}`});let u=withoutLiterals(i,o,l,n);if(l.length&&(u===void 0||sameField(i,{[i]:u},n)))return;let d=r.defaults?.[i];if(d!==void 0&&sameField(i,{[i]:u},{[i]:d})){s.push({path:at(i),action:`skip`,detail:`${t.dialect} fills this in by default, so it may not be the user's — set it in the golden set by hand if it is`});return}let f={path:at(i),action:`import`,detail:n?`only the harness changed it — approve to take it into the golden set`:`the golden set does not declare this server — approve each field to add it`,value:u===void 0?`(unset)`:`${i} = ${renderTomlInline(u)}`};s.push(f),c.push({row:f,config:t,server:e,field:i,value:u,carried:a,adds:!n})};if(!n){for(let e of cr)r.fields.has(e)&&a[e]!==void 0&&(e!==`transport`||a.transport!==inferredTransport(a))&&offer(e,a[e]);continue}for(let i of divergingFields(n,a,r.fields)){let r=o.directionOf(t,e,i,n,a);r!==`golden`&&(r===`target`?offer(i,i===`env`||i===`headers`?mapValue(n[i],a[i]):a[i]):s.push({path:at(i),action:`skip`,detail:li[r]}))}}}if(!n.length)return{kind:`planned`,rows:s,written:!1};let l=approve(c,s,n);if(l.kind===`rejected`)return l;let u=r,d=[];for(let[e,t]of groupByServer(l.offers)){if(t[0]?.adds){let n=Object.fromEntries(cr.flatMap(e=>{let n=t.find(t=>t.field===e);return n?[[e,n.value]]:[]}));u=land(u,appendInlineTomlTable(u,[`servers`,e],n),e,n,t,d);continue}for(let n of t){let t={...parseGoldenSet(u).servers.get(e),[n.field]:n.value};n.value===void 0&&delete t[n.field];let r=setTomlKey(u,[`servers`,e],n.field,n.value);u=land(u,r.kind===`edited`?r.text:void 0,e,t,[n],d)}}return u!==r&&(p(S(e,Y),u),writeRecord$1(e,a,o,d,parseGoldenSet(u))),{kind:`planned`,rows:s,written:!0}}function literalsIn(e,t){return t===void 0?[]:e===`args`?nonSecretArgs(t).length===t.length?[]:[`args`]:e!==`env`&&e!==`headers`&&e!==`url`?[]:credentialFields({[e]:t})}function withoutLiterals(e,t,n,r){if(!n.length)return t;if(e!==`env`&&e!==`headers`)return;let i={...t};for(let t of n){let n=t.slice(e.length+1),a=r?.[e]?.[n];a===void 0?delete i[n]:i[n]=a}return Object.keys(i).length?i:void 0}function approve(e,t,n){let r=[],i=[];for(let a of new Set(n)){let n=e.find(e=>e.row.path===a);if(n)i.push(n);else{let e=t.find(e=>e.path===a);r.push(e?`${a} is ${e.action}, not importable: ${e.detail}`:`${a} names no importable field`)}}for(let[e,t]of groupByServer(i)){for(let n of new Set(t.map(e=>e.field))){let i=t.filter(e=>e.field===n);i.some(e=>!sameField(n,{[n]:e.value},{[n]:i[0]?.value}))&&r.push(`servers.${e}.${n} is approved from more than one target with different values — approve one`)}t[0]?.adds&&!t.some(e=>e.field===`command`||e.field===`url`)&&r.push(`servers.${e} would be added with nothing to run — approve its command or url too`)}return r.length?{kind:`rejected`,reasons:r}:{kind:`approved`,offers:i}}function groupByServer(e){let t=new Map;for(let n of e)t.set(n.server,[...t.get(n.server)??[],n]);return t}function land(e,t,n,r,i,a){let o=parseGoldenSet(e),s=t===void 0?void 0:parseGoldenSet(t),c=s?.kind===`servers`&&cr.every(e=>e===`transport`&&r.transport===void 0||sameField(e,s.servers.get(n),r))&&[...o.servers].every(([e,t])=>e===n||JSON.stringify(s.servers.get(e))===JSON.stringify(t));for(let e of i)e.row.action=c?`imported`:`edit`,e.row.detail=c?`written into the golden set`:`the golden set writes this server in a shape that cannot be edited byte-safely — apply the value by hand`;return c?(a.push(...i),t):e}function writeRecord$1(e,t,n,r,a){for(let e of r){let r=t.get(e.config.path)??new Map,i=r.get(e.server),o=i?{...i,[e.field]:e.value}:baseEntry(e,n,a.servers.get(e.server));o&&(e.value===void 0&&delete o[e.field],r.set(e.server,o),t.set(e.config.path,r))}let o=S(e,X);i(y(o),{recursive:!0}),p(o,formatProjectionRecord(t))}__name(writeRecord$1,`writeRecord`);function baseEntry(e,t,n){if(e.adds)return{...n};let r={};for(let i of q[e.config.dialect].fields){if(n[i]===void 0)continue;if(sameField(i,n,e.carried)){r[i]=n[i];continue}let a=t.baseFor(e.config,e.server,i);if(!a)return;r[i]=a[i]}return r}const ui=command({name:`reconcile`,description:`Import a harness-side MCP change into the golden set, one approved field at a time. A dry run unless --accept names a field.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},accept:{description:`Approve one field by the path a dry run lists for it; repeat for each field. There is no approve-all.`,type:N.array(N.string()).optional()}},run(e){try{let t=e.root??process.cwd(),n=e.accept??[],r=reconcileMcp({root:t,git:new GitBridgeState(t),accept:n});if(r.kind===`unreadable`){let e=r.position?` at line ${r.position.line}, column ${r.position.column}`:``;throw process.stderr.write(`error: ${Y} does not parse${e}.\n`),M.reported(j.error)}if(r.kind===`rejected`)throw process.stderr.write(`error: nothing written.\n${r.reasons.map(e=>`- ${e}\n`).join(``)}`),M.reported(j.error);return r.kind===`absent`?result({golden:`0 servers — no golden set at ${Y}`,mode:`nothing to reconcile into`,fields:`0 fields`,record:`not written`}):result({golden:Y,mode:r.written?`written — only the fields named by --accept`:`dry run — nothing written; re-run with --accept <path> for each approved field`,fields:r.rows.length?r.rows:`0 fields — no harness holds a change the golden set lacks`,record:r.written?X:`not written — dry run`})}catch(e){return fail(e,`MCP reconcile failed.`)}}});function createScanner(e,t=!1){let n=e.length,r=0,i=``,a=0,o=16,s=0,c=0,l=0,u=0,d=0;function scanHexDigits(t,n){let i=0,a=0;for(;i<t||!n;){let t=e.charCodeAt(r);if(t>=48&&t<=57)a=a*16+t-48;else if(t>=65&&t<=70)a=a*16+t-65+10;else if(t>=97&&t<=102)a=a*16+t-97+10;else break;r++,i++}return i<t&&(a=-1),a}function setPosition(e){r=e,i=``,a=0,o=16,d=0}function scanNumber(){let t=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46){if(r++,r<e.length&&isDigit(e.charCodeAt(r)))for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;else return d=3,e.substring(t,r)}let n=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101)){if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&isDigit(e.charCodeAt(r))){for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;n=r}else d=3}return e.substring(t,n)}function scanString(){let t=``,i=r;for(;;){if(r>=n){t+=e.substring(i,r),d=2;break}let a=e.charCodeAt(r);if(a===34){t+=e.substring(i,r),r++;break}if(a===92){if(t+=e.substring(i,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:t+=`"`;break;case 92:t+=`\\`;break;case 47:t+=`/`;break;case 98:t+=`\b`;break;case 102:t+=`\f`;break;case 110:t+=`
467
+ `,c.range[0]-1)+1,n=lineEndAt(e,c.range[1]);return{kind:`edited`,text:`${e.slice(0,t)}${e.slice(Math.min(n+1,e.length))}`}}if(r===void 0)return{kind:`edited`,text:e};let l=lineEndAt(e,s.at(-1)?.range[1]??o.range[0]);return{kind:`edited`,text:`${e.slice(0,l)}\n${tomlKey(n)} = ${renderTomlInline(r)}${e.slice(l)}`}}function read$1(e,t){let r=C(e,t);return n(r)?a(r,`utf8`):void 0}__name(read$1,`read`);const Ci={both:`both sides changed since the last projection — a three-way conflict for a person to settle, never imported`,unknown:`no baseline says which side changed — compare the two by hand; never imported`};function inferredTransport(e){return e.url===void 0?`stdio`:`http`}function mapValue(e,t){let n=Object.entries(e).flatMap(([e])=>{let n=isRecord(t)?t[e]:void 0;return typeof n==`string`?[[e,n]]:[]});return n.length?Object.fromEntries(n):void 0}function reconcileMcp({root:e,git:t,accept:n}){let r=read$1(e,Y),i=parseGoldenSet(r);if(i.kind!==`servers`)return i;let a=parseProjectionRecord(read$1(e,jr)),o=new McpBaseline({git:t,record:a}),s=[],c=[];for(let t of mcpTargets(e)){let n=parseTarget(t,read$1(e,t.path));if(n.kind===`unreadable`){s.push({path:t.path,action:`refuse`,detail:`the target does not parse`});continue}if(n.kind===`absent`)continue;let r=Er[t.dialect];for(let[e,a]of n.servers){let n=i.servers.get(e),at=n=>locatorText({file:t.path,server:e,field:n}),offer=(i,o)=>{let l=literalsIn(i,o);for(let e of l)s.push({path:at(e),action:`refuse`,detail:`${e} holds a literal credential, which never enters the golden set — set it in the environment and reference it as \${VAR}`});let u=withoutLiterals(i,o,l,n);if(l.length&&(u===void 0||sameField(i,{[i]:u},n)))return;let d=r.defaults?.[i];if(d!==void 0&&sameField(i,{[i]:u},{[i]:d})){s.push({path:at(i),action:`skip`,detail:`${t.dialect} fills this in by default, so it may not be the user's — set it in the golden set by hand if it is`});return}let f={path:at(i),action:`import`,detail:n?`only the harness changed it — approve to take it into the golden set`:`the golden set does not declare this server — approve each field to add it`,value:u===void 0?`(unset)`:`${i} = ${renderTomlInline(u)}`};s.push(f),c.push({row:f,config:t,server:e,field:i,value:u,carried:a,adds:!n})};if(!n){for(let e of _r)r.fields.has(e)&&a[e]!==void 0&&(e!==`transport`||a.transport!==inferredTransport(a))&&offer(e,a[e]);continue}for(let i of divergingFields(n,a,r.fields)){let r=o.directionOf(t,e,i,n,a);r!==`golden`&&(r===`target`?offer(i,i===`env`||i===`headers`?mapValue(n[i],a[i]):a[i]):s.push({path:at(i),action:`skip`,detail:Ci[r]}))}}}if(!n.length)return{kind:`planned`,rows:s,written:!1};let l=approve(c,s,n);if(l.kind===`rejected`)return l;let u=r,d=[];for(let[e,t]of groupByServer(l.offers)){if(t[0]?.adds){let n=Object.fromEntries(_r.flatMap(e=>{let n=t.find(t=>t.field===e);return n?[[e,n.value]]:[]}));u=land(u,appendInlineTomlTable(u,[`servers`,e],n),e,n,t,d);continue}for(let n of t){let t={...parseGoldenSet(u).servers.get(e),[n.field]:n.value};n.value===void 0&&delete t[n.field];let r=setTomlKey(u,[`servers`,e],n.field,n.value);u=land(u,r.kind===`edited`?r.text:void 0,e,t,[n],d)}}return u!==r&&(m(C(e,Y),u),writeRecord$1(e,a,o,d,parseGoldenSet(u))),{kind:`planned`,rows:s,written:!0}}function literalsIn(e,t){return t===void 0?[]:e===`args`?nonSecretArgs(t).length===t.length?[]:[`args`]:e!==`env`&&e!==`headers`&&e!==`url`?[]:credentialFields({[e]:t})}function withoutLiterals(e,t,n,r){if(!n.length)return t;if(e!==`env`&&e!==`headers`)return;let i={...t};for(let t of n){let n=t.slice(e.length+1),a=r?.[e]?.[n];a===void 0?delete i[n]:i[n]=a}return Object.keys(i).length?i:void 0}function approve(e,t,n){let r=[],i=[];for(let a of new Set(n)){let n=e.find(e=>e.row.path===a);if(n)i.push(n);else{let e=t.find(e=>e.path===a);r.push(e?`${a} is ${e.action}, not importable: ${e.detail}`:`${a} names no importable field`)}}for(let[e,t]of groupByServer(i)){for(let n of new Set(t.map(e=>e.field))){let i=t.filter(e=>e.field===n);i.some(e=>!sameField(n,{[n]:e.value},{[n]:i[0]?.value}))&&r.push(`servers.${e}.${n} is approved from more than one target with different values — approve one`)}t[0]?.adds&&!t.some(e=>e.field===`command`||e.field===`url`)&&r.push(`servers.${e} would be added with nothing to run — approve its command or url too`)}return r.length?{kind:`rejected`,reasons:r}:{kind:`approved`,offers:i}}function groupByServer(e){let t=new Map;for(let n of e)t.set(n.server,[...t.get(n.server)??[],n]);return t}function land(e,t,n,r,i,a){let o=parseGoldenSet(e),s=t===void 0?void 0:parseGoldenSet(t),c=s?.kind===`servers`&&_r.every(e=>e===`transport`&&r.transport===void 0||sameField(e,s.servers.get(n),r))&&[...o.servers].every(([e,t])=>e===n||JSON.stringify(s.servers.get(e))===JSON.stringify(t));for(let e of i)e.row.action=c?`imported`:`edit`,e.row.detail=c?`written into the golden set`:`the golden set writes this server in a shape that cannot be edited byte-safely — apply the value by hand`;return c?(a.push(...i),t):e}function writeRecord$1(e,t,n,r,a){for(let e of r){let r=t.get(e.config.path)??new Map,i=r.get(e.server),o=i?{...i,[e.field]:e.value}:baseEntry(e,n,a.servers.get(e.server));o&&(e.value===void 0&&delete o[e.field],r.set(e.server,o),t.set(e.config.path,r))}let o=C(e,jr);i(b(o),{recursive:!0}),m(o,formatProjectionRecord(t))}__name(writeRecord$1,`writeRecord`);function baseEntry(e,t,n){if(e.adds)return{...n};let r={};for(let i of Er[e.config.dialect].fields){if(n[i]===void 0)continue;if(sameField(i,n,e.carried)){r[i]=n[i];continue}let a=t.baseFor(e.config,e.server,i);if(!a)return;r[i]=a[i]}return r}const wi=command({name:`reconcile`,description:`Import a harness-side MCP change into the golden set, one approved field at a time. A dry run unless --accept names a field.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},accept:{description:`Approve one field by the path a dry run lists for it; repeat for each field. There is no approve-all.`,type:N.array(N.string()).optional()}},examples:[{command:`buddy-agent-harness mcp reconcile`,description:`List harness-side changes the golden set lacks`},{command:`buddy-agent-harness mcp reconcile --accept <path>`,description:`Import one approved field`}],run(e){try{let t=e.root??process.cwd(),n=e.accept??[],r=reconcileMcp({root:t,git:new GitBridgeState(t),accept:n});if(r.kind===`unreadable`){let e=r.position?` at line ${r.position.line}, column ${r.position.column}`:``;throw new M(`${Y} does not parse${e}.`,{code:`golden-set-unreadable`,help:`Fix the TOML syntax in ${Y}, then re-run.`})}if(r.kind===`rejected`)throw new M(`nothing written.`,{code:`accept-rejected`,details:{reasons:r.reasons},help:ref(`mcp reconcile`,{},`list the fields that can be approved`)});return r.kind===`absent`?empty(`0 servers — no golden set at ${Y}`,{help:`Create ${Y} first; there is nothing to reconcile into.`}):result({golden:Y,mode:r.written?`written — only the fields named by --accept`:`dry run — nothing written; re-run with --accept <path> for each approved field`,fields:r.rows.length?r.rows:`0 fields — no harness holds a change the golden set lacks`,record:r.written?jr:`not written — dry run`})}catch(e){return fail(e,`MCP reconcile failed.`)}}});function createScanner(e,t=!1){let n=e.length,r=0,i=``,a=0,o=16,s=0,c=0,l=0,u=0,d=0;function scanHexDigits(t,n){let i=0,a=0;for(;i<t||!n;){let t=e.charCodeAt(r);if(t>=48&&t<=57)a=a*16+t-48;else if(t>=65&&t<=70)a=a*16+t-65+10;else if(t>=97&&t<=102)a=a*16+t-97+10;else break;r++,i++}return i<t&&(a=-1),a}function setPosition(e){r=e,i=``,a=0,o=16,d=0}function scanNumber(){let t=r;if(e.charCodeAt(r)===48)r++;else for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;if(r<e.length&&e.charCodeAt(r)===46){if(r++,r<e.length&&isDigit(e.charCodeAt(r)))for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;else return d=3,e.substring(t,r)}let n=r;if(r<e.length&&(e.charCodeAt(r)===69||e.charCodeAt(r)===101)){if(r++,(r<e.length&&e.charCodeAt(r)===43||e.charCodeAt(r)===45)&&r++,r<e.length&&isDigit(e.charCodeAt(r))){for(r++;r<e.length&&isDigit(e.charCodeAt(r));)r++;n=r}else d=3}return e.substring(t,n)}function scanString(){let t=``,i=r;for(;;){if(r>=n){t+=e.substring(i,r),d=2;break}let a=e.charCodeAt(r);if(a===34){t+=e.substring(i,r),r++;break}if(a===92){if(t+=e.substring(i,r),r++,r>=n){d=2;break}switch(e.charCodeAt(r++)){case 34:t+=`"`;break;case 92:t+=`\\`;break;case 47:t+=`/`;break;case 98:t+=`\b`;break;case 102:t+=`\f`;break;case 110:t+=`
461
468
  `;break;case 114:t+=`\r`;break;case 116:t+=` `;break;case 117:let e=scanHexDigits(4,!0);e>=0?t+=String.fromCharCode(e):d=4;break;default:d=5}i=r;continue}if(a>=0&&a<=31){if(isLineBreak(a)){t+=e.substring(i,r),d=2;break}d=6}r++}return t}function scanNext(){if(i=``,d=0,a=r,c=s,u=l,r>=n)return a=n,o=17;let t=e.charCodeAt(r);if(isWhiteSpace(t)){do r++,i+=String.fromCharCode(t),t=e.charCodeAt(r);while(isWhiteSpace(t));return o=15}if(isLineBreak(t))return r++,i+=String.fromCharCode(t),t===13&&e.charCodeAt(r)===10&&(r++,i+=`
462
- `),s++,l=r,o=14;switch(t){case 123:return r++,o=1;case 125:return r++,o=2;case 91:return r++,o=3;case 93:return r++,o=4;case 58:return r++,o=6;case 44:return r++,o=5;case 34:return r++,i=scanString(),o=10;case 47:let c=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!isLineBreak(e.charCodeAt(r));)r++;return i=e.substring(c,r),o=12}if(e.charCodeAt(r+1)===42){r+=2;let t=n-1,a=!1;for(;r<t;){let t=e.charCodeAt(r);if(t===42&&e.charCodeAt(r+1)===47){r+=2,a=!0;break}r++,isLineBreak(t)&&(t===13&&e.charCodeAt(r)===10&&r++,s++,l=r)}return a||(r++,d=1),i=e.substring(c,r),o=13}return i+=String.fromCharCode(t),r++,o=16;case 45:if(i+=String.fromCharCode(t),r++,r===n||!isDigit(e.charCodeAt(r)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=scanNumber(),o=11;default:for(;r<n&&isUnknownContentCharacter(t);)r++,t=e.charCodeAt(r);if(a!==r){switch(i=e.substring(a,r),i){case`true`:return o=8;case`false`:return o=9;case`null`:return o=7}return o=16}return i+=String.fromCharCode(t),r++,o=16}}function isUnknownContentCharacter(e){if(isWhiteSpace(e)||isLineBreak(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function scanNextNonTrivia(){let e;do e=scanNext();while(e>=12&&e<=15);return e}return{setPosition,getPosition:()=>r,scan:t?scanNextNonTrivia:scanNext,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>a,getTokenLength:()=>r-a,getTokenStartLine:()=>c,getTokenStartCharacter:()=>a-u,getTokenError:()=>d}}function isWhiteSpace(e){return e===32||e===9}function isLineBreak(e){return e===10||e===13}function isDigit(e){return e>=48&&e<=57}var di;(function(e){e[e.lineFeed=10]=`lineFeed`,e[e.carriageReturn=13]=`carriageReturn`,e[e.space=32]=`space`,e[e._0=48]=`_0`,e[e._1=49]=`_1`,e[e._2=50]=`_2`,e[e._3=51]=`_3`,e[e._4=52]=`_4`,e[e._5=53]=`_5`,e[e._6=54]=`_6`,e[e._7=55]=`_7`,e[e._8=56]=`_8`,e[e._9=57]=`_9`,e[e.a=97]=`a`,e[e.b=98]=`b`,e[e.c=99]=`c`,e[e.d=100]=`d`,e[e.e=101]=`e`,e[e.f=102]=`f`,e[e.g=103]=`g`,e[e.h=104]=`h`,e[e.i=105]=`i`,e[e.j=106]=`j`,e[e.k=107]=`k`,e[e.l=108]=`l`,e[e.m=109]=`m`,e[e.n=110]=`n`,e[e.o=111]=`o`,e[e.p=112]=`p`,e[e.q=113]=`q`,e[e.r=114]=`r`,e[e.s=115]=`s`,e[e.t=116]=`t`,e[e.u=117]=`u`,e[e.v=118]=`v`,e[e.w=119]=`w`,e[e.x=120]=`x`,e[e.y=121]=`y`,e[e.z=122]=`z`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.asterisk=42]=`asterisk`,e[e.backslash=92]=`backslash`,e[e.closeBrace=125]=`closeBrace`,e[e.closeBracket=93]=`closeBracket`,e[e.colon=58]=`colon`,e[e.comma=44]=`comma`,e[e.dot=46]=`dot`,e[e.doubleQuote=34]=`doubleQuote`,e[e.minus=45]=`minus`,e[e.openBrace=123]=`openBrace`,e[e.openBracket=91]=`openBracket`,e[e.plus=43]=`plus`,e[e.slash=47]=`slash`,e[e.formFeed=12]=`formFeed`,e[e.tab=9]=`tab`})(di||={}),Array(20).fill(0).map((e,t)=>` `.repeat(t)),Array(200).fill(0).map((e,t)=>`
469
+ `),s++,l=r,o=14;switch(t){case 123:return r++,o=1;case 125:return r++,o=2;case 91:return r++,o=3;case 93:return r++,o=4;case 58:return r++,o=6;case 44:return r++,o=5;case 34:return r++,i=scanString(),o=10;case 47:let c=r-1;if(e.charCodeAt(r+1)===47){for(r+=2;r<n&&!isLineBreak(e.charCodeAt(r));)r++;return i=e.substring(c,r),o=12}if(e.charCodeAt(r+1)===42){r+=2;let t=n-1,a=!1;for(;r<t;){let t=e.charCodeAt(r);if(t===42&&e.charCodeAt(r+1)===47){r+=2,a=!0;break}r++,isLineBreak(t)&&(t===13&&e.charCodeAt(r)===10&&r++,s++,l=r)}return a||(r++,d=1),i=e.substring(c,r),o=13}return i+=String.fromCharCode(t),r++,o=16;case 45:if(i+=String.fromCharCode(t),r++,r===n||!isDigit(e.charCodeAt(r)))return o=16;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return i+=scanNumber(),o=11;default:for(;r<n&&isUnknownContentCharacter(t);)r++,t=e.charCodeAt(r);if(a!==r){switch(i=e.substring(a,r),i){case`true`:return o=8;case`false`:return o=9;case`null`:return o=7}return o=16}return i+=String.fromCharCode(t),r++,o=16}}function isUnknownContentCharacter(e){if(isWhiteSpace(e)||isLineBreak(e))return!1;switch(e){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return!1}return!0}function scanNextNonTrivia(){let e;do e=scanNext();while(e>=12&&e<=15);return e}return{setPosition,getPosition:()=>r,scan:t?scanNextNonTrivia:scanNext,getToken:()=>o,getTokenValue:()=>i,getTokenOffset:()=>a,getTokenLength:()=>r-a,getTokenStartLine:()=>c,getTokenStartCharacter:()=>a-u,getTokenError:()=>d}}function isWhiteSpace(e){return e===32||e===9}function isLineBreak(e){return e===10||e===13}function isDigit(e){return e>=48&&e<=57}var Ti;(function(e){e[e.lineFeed=10]=`lineFeed`,e[e.carriageReturn=13]=`carriageReturn`,e[e.space=32]=`space`,e[e._0=48]=`_0`,e[e._1=49]=`_1`,e[e._2=50]=`_2`,e[e._3=51]=`_3`,e[e._4=52]=`_4`,e[e._5=53]=`_5`,e[e._6=54]=`_6`,e[e._7=55]=`_7`,e[e._8=56]=`_8`,e[e._9=57]=`_9`,e[e.a=97]=`a`,e[e.b=98]=`b`,e[e.c=99]=`c`,e[e.d=100]=`d`,e[e.e=101]=`e`,e[e.f=102]=`f`,e[e.g=103]=`g`,e[e.h=104]=`h`,e[e.i=105]=`i`,e[e.j=106]=`j`,e[e.k=107]=`k`,e[e.l=108]=`l`,e[e.m=109]=`m`,e[e.n=110]=`n`,e[e.o=111]=`o`,e[e.p=112]=`p`,e[e.q=113]=`q`,e[e.r=114]=`r`,e[e.s=115]=`s`,e[e.t=116]=`t`,e[e.u=117]=`u`,e[e.v=118]=`v`,e[e.w=119]=`w`,e[e.x=120]=`x`,e[e.y=121]=`y`,e[e.z=122]=`z`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.asterisk=42]=`asterisk`,e[e.backslash=92]=`backslash`,e[e.closeBrace=125]=`closeBrace`,e[e.closeBracket=93]=`closeBracket`,e[e.colon=58]=`colon`,e[e.comma=44]=`comma`,e[e.dot=46]=`dot`,e[e.doubleQuote=34]=`doubleQuote`,e[e.minus=45]=`minus`,e[e.openBrace=123]=`openBrace`,e[e.openBracket=91]=`openBracket`,e[e.plus=43]=`plus`,e[e.slash=47]=`slash`,e[e.formFeed=12]=`formFeed`,e[e.tab=9]=`tab`})(Ti||={}),Array(20).fill(0).map((e,t)=>` `.repeat(t)),Array(200).fill(0).map((e,t)=>`
463
470
  `+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r
464
471
  `+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`
465
472
  `+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r`+` `.repeat(t)),Array(200).fill(0).map((e,t)=>`\r
466
- `+` `.repeat(t));var fi;(function(e){e.DEFAULT={allowTrailingComma:!1}})(fi||={});function parseTree$1(e,t=[],n=fi.DEFAULT){let r={type:`array`,offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(e){r.type===`property`&&(r.length=e-r.offset,r=r.parent)}function onValue(e){return r.children.push(e),e}visit(e,{onObjectBegin:e=>{r=onValue({type:`object`,offset:e,length:-1,parent:r,children:[]})},onObjectProperty:(e,t,n)=>{r=onValue({type:`property`,offset:t,length:-1,parent:r,children:[]}),r.children.push({type:`string`,value:e,offset:t,length:n,parent:r})},onObjectEnd:(e,t)=>{ensurePropertyComplete(e+t),r.length=e+t-r.offset,r=r.parent,ensurePropertyComplete(e+t)},onArrayBegin:(e,t)=>{r=onValue({type:`array`,offset:e,length:-1,parent:r,children:[]})},onArrayEnd:(e,t)=>{r.length=e+t-r.offset,r=r.parent,ensurePropertyComplete(e+t)},onLiteralValue:(e,t,n)=>{onValue({type:getNodeType(e),offset:t,length:n,parent:r,value:e}),ensurePropertyComplete(t+n)},onSeparator:(e,t,n)=>{r.type===`property`&&(e===`:`?r.colonOffset=t:e===`,`&&ensurePropertyComplete(t))},onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n);let i=r.children[0];return i&&delete i.parent,i}__name(parseTree$1,`parseTree`);function findNodeAtLocation$1(e,t){if(!e)return;let n=e;for(let e of t)if(typeof e==`string`){if(n.type!==`object`||!Array.isArray(n.children))return;let t=!1;for(let r of n.children)if(Array.isArray(r.children)&&r.children[0].value===e&&r.children.length===2){n=r.children[1],t=!0;break}if(!t)return}else{let t=e;if(n.type!==`array`||t<0||!Array.isArray(n.children)||t>=n.children.length)return;n=n.children[t]}return n}__name(findNodeAtLocation$1,`findNodeAtLocation`);function visit(e,t,n=fi.DEFAULT){let r=createScanner(e,!1),i=[],a=0;function toNoArgVisit(e){return e?()=>a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function toOneArgVisit(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function toOneArgVisitWithPath(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice()):()=>!0}function toBeginVisit(e){return e?()=>{a>0?a++:e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice())===!1&&(a=1)}:()=>!0}function toEndVisit(e){return e?()=>{a>0&&a--,a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let o=toBeginVisit(t.onObjectBegin),s=toOneArgVisitWithPath(t.onObjectProperty),c=toEndVisit(t.onObjectEnd),l=toBeginVisit(t.onArrayBegin),u=toEndVisit(t.onArrayEnd),d=toOneArgVisitWithPath(t.onLiteralValue),f=toOneArgVisit(t.onSeparator),p=toNoArgVisit(t.onComment),m=toOneArgVisit(t.onError),h=n&&n.disallowComments,g=n&&n.allowTrailingComma;function scanNext(){for(;;){let e=r.scan();switch(r.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:h||handleError(11);break;case 2:handleError(12);break;case 6:handleError(16)}switch(e){case 12:case 13:h?handleError(10):p();break;case 16:handleError(1);break;case 15:case 14:break;default:return e}}}function handleError(e,t=[],n=[]){if(m(e),t.length+n.length>0){let e=r.getToken();for(;e!==17;){if(t.indexOf(e)!==-1){scanNext();break}if(n.indexOf(e)!==-1)break;e=scanNext()}}}function parseString(e){let t=r.getTokenValue();return e?d(t):(s(t),i.push(t)),scanNext(),!0}function parseLiteral(){switch(r.getToken()){case 11:let e=r.getTokenValue(),t=Number(e);isNaN(t)&&(handleError(2),t=0),d(t);break;case 7:d(null);break;case 8:d(!0);break;case 9:d(!1);break;default:return!1}return scanNext(),!0}function parseProperty(){return r.getToken()===10?(parseString(!1),r.getToken()===6?(f(`:`),scanNext(),parseValue()||handleError(4,[],[2,5])):handleError(5,[],[2,5]),i.pop(),!0):(handleError(3,[],[2,5]),!1)}function parseObject(){o(),scanNext();let e=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(e||handleError(4,[],[]),f(`,`),scanNext(),r.getToken()===2&&g)break}else e&&handleError(6,[],[]);parseProperty()||handleError(4,[],[2,5]),e=!0}return c(),r.getToken()===2?scanNext():handleError(7,[2],[]),!0}function parseArray(){l(),scanNext();let e=!0,t=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(t||handleError(4,[],[]),f(`,`),scanNext(),r.getToken()===4&&g)break}else t&&handleError(6,[],[]);e?(i.push(0),e=!1):i[i.length-1]++,parseValue()||handleError(4,[],[4,5]),t=!0}return u(),e||i.pop(),r.getToken()===4?scanNext():handleError(8,[4],[]),!0}function parseValue(){switch(r.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(!0);default:return parseLiteral()}}return scanNext(),r.getToken()===17?n.allowEmptyContent?!0:(handleError(4,[],[]),!1):parseValue()?(r.getToken()!==17&&handleError(9,[],[]),!0):(handleError(4,[],[]),!1)}function getNodeType(e){switch(typeof e){case`boolean`:return`boolean`;case`number`:return`number`;case`string`:return`string`;case`object`:return e?Array.isArray(e)?`array`:`object`:`null`;default:return`null`}}var pi;(function(e){e[e.None=0]=`None`,e[e.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=4]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=6]=`InvalidCharacter`})(pi||={});var mi;(function(e){e[e.OpenBraceToken=1]=`OpenBraceToken`,e[e.CloseBraceToken=2]=`CloseBraceToken`,e[e.OpenBracketToken=3]=`OpenBracketToken`,e[e.CloseBracketToken=4]=`CloseBracketToken`,e[e.CommaToken=5]=`CommaToken`,e[e.ColonToken=6]=`ColonToken`,e[e.NullKeyword=7]=`NullKeyword`,e[e.TrueKeyword=8]=`TrueKeyword`,e[e.FalseKeyword=9]=`FalseKeyword`,e[e.StringLiteral=10]=`StringLiteral`,e[e.NumericLiteral=11]=`NumericLiteral`,e[e.LineCommentTrivia=12]=`LineCommentTrivia`,e[e.BlockCommentTrivia=13]=`BlockCommentTrivia`,e[e.LineBreakTrivia=14]=`LineBreakTrivia`,e[e.Trivia=15]=`Trivia`,e[e.Unknown=16]=`Unknown`,e[e.EOF=17]=`EOF`})(mi||={});const hi=parseTree$1,gi=findNodeAtLocation$1;var _i;(function(e){e[e.InvalidSymbol=1]=`InvalidSymbol`,e[e.InvalidNumberFormat=2]=`InvalidNumberFormat`,e[e.PropertyNameExpected=3]=`PropertyNameExpected`,e[e.ValueExpected=4]=`ValueExpected`,e[e.ColonExpected=5]=`ColonExpected`,e[e.CommaExpected=6]=`CommaExpected`,e[e.CloseBraceExpected=7]=`CloseBraceExpected`,e[e.CloseBracketExpected=8]=`CloseBracketExpected`,e[e.EndOfFileExpected=9]=`EndOfFileExpected`,e[e.InvalidCommentToken=10]=`InvalidCommentToken`,e[e.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=14]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=16]=`InvalidCharacter`})(_i||={});function indentUnit(e){let t=/\n([ \t]+)\S/.exec(e);return t?t[1]:` `}function jsonAt(e,t,n){return JSON.stringify(e,null,t).replaceAll(`
467
- `,`\n${t.repeat(n)}`)}function objectAt(e,t){let n=e&&(t.length?gi(e,t):e);return n?.type===`object`?n:void 0}function insertJsonProperty(e,t,n,r){let i=objectAt(hi(e),t);if(!i||gi(i,[n]))return;let a=t.length+1,o=indentUnit(e),s=`${o.repeat(a)}${JSON.stringify(n)}: ${jsonAt(r,o,a)}`,c=i.children?.at(-1);if(c){let t=c.offset+c.length;return`${e.slice(0,t)},\n${s}${e.slice(t)}`}let l=i.offset+1,u=i.offset+i.length-1;return`${e.slice(0,l)}\n${s}\n${o.repeat(a-1)}${e.slice(u)}`}function replaceJsonValue(e,t,n){let r=hi(e),i=r&&gi(r,t);if(!i)return{kind:`refused`,reason:`absent`};let a=i.offset+i.length,o=e.slice(i.offset,a);return stripJsonComments(o)===o?{kind:`edited`,text:`${e.slice(0,i.offset)}${jsonAt(n,indentUnit(e),t.length)}${e.slice(a)}`}:{kind:`refused`,reason:`comment`}}function createFile(e,t,n){return e.format===`toml`?renderTomlTable([e.key,t],n):`${JSON.stringify({[e.key]:{[t]:n}},null,2)}\n`}function appendServer(e,t,n,r){return e.format===`toml`?appendTomlTable(t,[e.key,n],r):insertJsonProperty(t,[e.key],n,r)??insertJsonProperty(t,[],e.key,{[n]:r})}function replaceServer(e,t,n,r){let i=e.format===`toml`?replaceTomlTable(t,[e.key,n],r):replaceJsonValue(t,[e.key,n],r);return i.kind===`edited`?i.text:void 0}function renderEntry(e,t,n){return e.format===`toml`?renderTomlTable([e.key,t],n):JSON.stringify({[t]:n},null,2)}function read(e,t){let r=S(e,t);return n(r)?a(r,`utf8`):void 0}const vi={target:`the target changed since the last projection — reconcile it into the golden set first`,both:`both sides changed since the last projection — a three-way conflict for a person to settle`,unknown:`no baseline says which side changed — compare the two by hand`};function heldBack(e){return[`both`,`unknown`,`target`].find(t=>e.includes(t))}function projectMcp({root:e,git:t,write:n}){let r=parseGoldenSet(read(e,Y));if(r.kind!==`servers`)return r;let i=parseProjectionRecord(read(e,X)),a=new McpBaseline({git:t,record:i}),o=[],s=[],c=[];for(let t of mcpTargets(e)){let n=read(e,t.path),i=parseTarget(t,n);if(i.kind===`unreadable`){o.push({target:t.path,server:``,action:`refuse`,detail:`the target does not parse`});continue}let l={config:t,source:n,created:n===void 0,servers:i.kind===`servers`?i.servers:new Map,agreed:new Map};c.push(l);let u=q[t.dialect];for(let[e,n]of r.servers){let row=(n,r)=>o.push({target:t.path,server:e,action:n,detail:r}),r=credentialFields(n)[0];if(r){row(`refuse`,`the golden set holds a literal credential at ${r} — reference it as \${VAR} first`);continue}let i=u.write(n);if(i.kind===`refused`){row(`refuse`,`${i.field}: ${i.reason}`);continue}let c=l.servers.get(e);if(!c){let r=l.source===void 0?createFile(t,e,i.entry):appendServer(t,l.source,e,i.entry);apply(l,e,n,i.entry,r,l.created?`creates the file`:`appends the server`,row,s);continue}let d=divergingFields(n,c,u.fields);if(!d.length){l.agreed.set(e,n);continue}let f=heldBack(d.map(r=>a.directionOf(t,e,r,n,c)));if(f){row(`skip`,vi[f]);continue}let p=replaceServer(t,l.source,e,i.entry);apply(l,e,n,i.entry,p,`replaces ${d.join(`, `)}`,row,s)}}if(n){for(let t of c)t.source!==void 0&&t.source!==read(e,t.config.path)&&writeTarget(e,t);writeRecord(e,i,c)}return{kind:`planned`,rows:o,entries:s,written:n}}function apply(e,t,n,r,i,a,o,s){let c=!e.servers.has(t),l=i!==void 0&&readsBack(e,t,n,i),u=l?c?`add`:`update`:`edit`;if(s.push({target:e.config.path,server:t,action:u,entry:renderEntry(e.config,t,r)}),!l){o(`edit`,c?`the file has no safe place to add it — apply the entry by hand`:`an in-place change here is applied by hand`);return}e.source=i,e.servers=parseTarget(e.config,i).servers,e.agreed.set(t,n),o(u,a)}function readsBack(e,t,n,r){let i=parseTarget(e.config,r);if(i.kind!==`servers`)return!1;let a=i.servers.get(t),o=q[e.config.dialect].fields;return!a||divergingFields(n,a,o).length?!1:[...e.servers].every(([e,n])=>{if(e===t)return!0;let r=i.servers.get(e);return r!==void 0&&JSON.stringify(r)===JSON.stringify(n)})}function writeTarget(e,t){let n=S(e,t.config.path);i(y(n),{recursive:!0}),p(n,t.source)}function writeRecord(e,t,n){for(let e of n){let n=t.get(e.config.path)??new Map;for(let[t,r]of e.agreed)n.set(t,r);n.size&&t.set(e.config.path,n)}let r=S(e,X);i(y(r),{recursive:!0}),p(r,formatProjectionRecord(t))}const yi={name:`buddy-agent-harness`,description:`Initialize agent harness skill compatibility in consumer repositories.`,commands:[Ur,Rr,command({name:`mcp`,description:`Work with the golden MCP server set at .agents/buddy-agent-harness/mcp.toml.`,commands:[command({name:`project`,description:`Project the golden MCP server set into each enabled harness. A dry run unless --write; never overwrites a change made on the harness side.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},write:{description:`Apply the plan and record what was projected. Without it nothing on disk changes.`,type:N.boolean().optional()}},run(e){try{let t=e.root??process.cwd(),n=e.write===!0,r=projectMcp({root:t,git:new GitBridgeState(t),write:n});if(r.kind===`unreadable`){let e=r.position?` at line ${r.position.line}, column ${r.position.column}`:``;throw process.stderr.write(`error: ${Y} does not parse${e}.\n`),M.reported(j.error)}return r.kind===`absent`?result({golden:`0 servers — no golden set at ${Y}`,mode:`nothing to project`,actions:`0 changes`,record:`not written`}):result({golden:Y,mode:n?`written`:`dry run — nothing written; re-run with --write to apply`,actions:r.rows.length?r.rows:`0 changes — every enabled harness already carries the golden set`,...r.entries.length?{entries:r.entries}:{},record:n?X:`not written — dry run`})}catch(e){return fail(e,`MCP projection failed.`)}}}),ui]}),Wn,Pr,Hr]};function app(e){let[t,...n]=yi.commands;return n.reduce((e,t)=>e.command(t),cli({name:yi.name,version:`1.0.1`,description:yi.description,format:e}).command(t))}const bi={reference:[`load`,`create`,`delete`],governance:[`show`]};function defaultFormat(e){let t=e.slice(2);if(t.some(e=>e===`--format`||e.startsWith(`--format=`)))return`toon`;let[n,r]=t;return n!==void 0&&r!==void 0&&bi[n]?.includes(r)?`text`:`toon`}async function run(e){try{let t=await app(defaultFormat(e)).parse(e);return typeof t==`number`?t:j.success}catch(e){return process.stderr.write(`error: ${e instanceof Error?e.message:`Invalid command.`}\n`),j.usage}}process.exitCode=await run([...process.argv.slice(0,2),`init`,...process.argv.slice(2)]);export{};
473
+ `+` `.repeat(t));var Ei;(function(e){e.DEFAULT={allowTrailingComma:!1}})(Ei||={});function parseTree$1(e,t=[],n=Ei.DEFAULT){let r={type:`array`,offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(e){r.type===`property`&&(r.length=e-r.offset,r=r.parent)}function onValue(e){return r.children.push(e),e}visit(e,{onObjectBegin:e=>{r=onValue({type:`object`,offset:e,length:-1,parent:r,children:[]})},onObjectProperty:(e,t,n)=>{r=onValue({type:`property`,offset:t,length:-1,parent:r,children:[]}),r.children.push({type:`string`,value:e,offset:t,length:n,parent:r})},onObjectEnd:(e,t)=>{ensurePropertyComplete(e+t),r.length=e+t-r.offset,r=r.parent,ensurePropertyComplete(e+t)},onArrayBegin:(e,t)=>{r=onValue({type:`array`,offset:e,length:-1,parent:r,children:[]})},onArrayEnd:(e,t)=>{r.length=e+t-r.offset,r=r.parent,ensurePropertyComplete(e+t)},onLiteralValue:(e,t,n)=>{onValue({type:getNodeType(e),offset:t,length:n,parent:r,value:e}),ensurePropertyComplete(t+n)},onSeparator:(e,t,n)=>{r.type===`property`&&(e===`:`?r.colonOffset=t:e===`,`&&ensurePropertyComplete(t))},onError:(e,n,r)=>{t.push({error:e,offset:n,length:r})}},n);let i=r.children[0];return i&&delete i.parent,i}__name(parseTree$1,`parseTree`);function findNodeAtLocation$1(e,t){if(!e)return;let n=e;for(let e of t)if(typeof e==`string`){if(n.type!==`object`||!Array.isArray(n.children))return;let t=!1;for(let r of n.children)if(Array.isArray(r.children)&&r.children[0].value===e&&r.children.length===2){n=r.children[1],t=!0;break}if(!t)return}else{let t=e;if(n.type!==`array`||t<0||!Array.isArray(n.children)||t>=n.children.length)return;n=n.children[t]}return n}__name(findNodeAtLocation$1,`findNodeAtLocation`);function visit(e,t,n=Ei.DEFAULT){let r=createScanner(e,!1),i=[],a=0;function toNoArgVisit(e){return e?()=>a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function toOneArgVisit(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter()):()=>!0}function toOneArgVisitWithPath(e){return e?t=>a===0&&e(t,r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice()):()=>!0}function toBeginVisit(e){return e?()=>{a>0?a++:e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter(),()=>i.slice())===!1&&(a=1)}:()=>!0}function toEndVisit(e){return e?()=>{a>0&&a--,a===0&&e(r.getTokenOffset(),r.getTokenLength(),r.getTokenStartLine(),r.getTokenStartCharacter())}:()=>!0}let o=toBeginVisit(t.onObjectBegin),s=toOneArgVisitWithPath(t.onObjectProperty),c=toEndVisit(t.onObjectEnd),l=toBeginVisit(t.onArrayBegin),u=toEndVisit(t.onArrayEnd),d=toOneArgVisitWithPath(t.onLiteralValue),f=toOneArgVisit(t.onSeparator),p=toNoArgVisit(t.onComment),m=toOneArgVisit(t.onError),h=n&&n.disallowComments,g=n&&n.allowTrailingComma;function scanNext(){for(;;){let e=r.scan();switch(r.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:h||handleError(11);break;case 2:handleError(12);break;case 6:handleError(16)}switch(e){case 12:case 13:h?handleError(10):p();break;case 16:handleError(1);break;case 15:case 14:break;default:return e}}}function handleError(e,t=[],n=[]){if(m(e),t.length+n.length>0){let e=r.getToken();for(;e!==17;){if(t.indexOf(e)!==-1){scanNext();break}if(n.indexOf(e)!==-1)break;e=scanNext()}}}function parseString(e){let t=r.getTokenValue();return e?d(t):(s(t),i.push(t)),scanNext(),!0}function parseLiteral(){switch(r.getToken()){case 11:let e=r.getTokenValue(),t=Number(e);isNaN(t)&&(handleError(2),t=0),d(t);break;case 7:d(null);break;case 8:d(!0);break;case 9:d(!1);break;default:return!1}return scanNext(),!0}function parseProperty(){return r.getToken()===10?(parseString(!1),r.getToken()===6?(f(`:`),scanNext(),parseValue()||handleError(4,[],[2,5])):handleError(5,[],[2,5]),i.pop(),!0):(handleError(3,[],[2,5]),!1)}function parseObject(){o(),scanNext();let e=!1;for(;r.getToken()!==2&&r.getToken()!==17;){if(r.getToken()===5){if(e||handleError(4,[],[]),f(`,`),scanNext(),r.getToken()===2&&g)break}else e&&handleError(6,[],[]);parseProperty()||handleError(4,[],[2,5]),e=!0}return c(),r.getToken()===2?scanNext():handleError(7,[2],[]),!0}function parseArray(){l(),scanNext();let e=!0,t=!1;for(;r.getToken()!==4&&r.getToken()!==17;){if(r.getToken()===5){if(t||handleError(4,[],[]),f(`,`),scanNext(),r.getToken()===4&&g)break}else t&&handleError(6,[],[]);e?(i.push(0),e=!1):i[i.length-1]++,parseValue()||handleError(4,[],[4,5]),t=!0}return u(),e||i.pop(),r.getToken()===4?scanNext():handleError(8,[4],[]),!0}function parseValue(){switch(r.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(!0);default:return parseLiteral()}}return scanNext(),r.getToken()===17?n.allowEmptyContent?!0:(handleError(4,[],[]),!1):parseValue()?(r.getToken()!==17&&handleError(9,[],[]),!0):(handleError(4,[],[]),!1)}function getNodeType(e){switch(typeof e){case`boolean`:return`boolean`;case`number`:return`number`;case`string`:return`string`;case`object`:return e?Array.isArray(e)?`array`:`object`:`null`;default:return`null`}}var Di;(function(e){e[e.None=0]=`None`,e[e.UnexpectedEndOfComment=1]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=2]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=3]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=4]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=5]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=6]=`InvalidCharacter`})(Di||={});var Oi;(function(e){e[e.OpenBraceToken=1]=`OpenBraceToken`,e[e.CloseBraceToken=2]=`CloseBraceToken`,e[e.OpenBracketToken=3]=`OpenBracketToken`,e[e.CloseBracketToken=4]=`CloseBracketToken`,e[e.CommaToken=5]=`CommaToken`,e[e.ColonToken=6]=`ColonToken`,e[e.NullKeyword=7]=`NullKeyword`,e[e.TrueKeyword=8]=`TrueKeyword`,e[e.FalseKeyword=9]=`FalseKeyword`,e[e.StringLiteral=10]=`StringLiteral`,e[e.NumericLiteral=11]=`NumericLiteral`,e[e.LineCommentTrivia=12]=`LineCommentTrivia`,e[e.BlockCommentTrivia=13]=`BlockCommentTrivia`,e[e.LineBreakTrivia=14]=`LineBreakTrivia`,e[e.Trivia=15]=`Trivia`,e[e.Unknown=16]=`Unknown`,e[e.EOF=17]=`EOF`})(Oi||={});const ki=parseTree$1,Ai=findNodeAtLocation$1;var ji;(function(e){e[e.InvalidSymbol=1]=`InvalidSymbol`,e[e.InvalidNumberFormat=2]=`InvalidNumberFormat`,e[e.PropertyNameExpected=3]=`PropertyNameExpected`,e[e.ValueExpected=4]=`ValueExpected`,e[e.ColonExpected=5]=`ColonExpected`,e[e.CommaExpected=6]=`CommaExpected`,e[e.CloseBraceExpected=7]=`CloseBraceExpected`,e[e.CloseBracketExpected=8]=`CloseBracketExpected`,e[e.EndOfFileExpected=9]=`EndOfFileExpected`,e[e.InvalidCommentToken=10]=`InvalidCommentToken`,e[e.UnexpectedEndOfComment=11]=`UnexpectedEndOfComment`,e[e.UnexpectedEndOfString=12]=`UnexpectedEndOfString`,e[e.UnexpectedEndOfNumber=13]=`UnexpectedEndOfNumber`,e[e.InvalidUnicode=14]=`InvalidUnicode`,e[e.InvalidEscapeCharacter=15]=`InvalidEscapeCharacter`,e[e.InvalidCharacter=16]=`InvalidCharacter`})(ji||={});function indentUnit(e){let t=/\n([ \t]+)\S/.exec(e);return t?t[1]:` `}function jsonAt(e,t,n){return JSON.stringify(e,null,t).replaceAll(`
474
+ `,`\n${t.repeat(n)}`)}function objectAt(e,t){let n=e&&(t.length?Ai(e,t):e);return n?.type===`object`?n:void 0}function insertJsonProperty(e,t,n,r){let i=objectAt(ki(e),t);if(!i||Ai(i,[n]))return;let a=t.length+1,o=indentUnit(e),s=`${o.repeat(a)}${JSON.stringify(n)}: ${jsonAt(r,o,a)}`,c=i.children?.at(-1);if(c){let t=c.offset+c.length;return`${e.slice(0,t)},\n${s}${e.slice(t)}`}let l=i.offset+1,u=i.offset+i.length-1;return`${e.slice(0,l)}\n${s}\n${o.repeat(a-1)}${e.slice(u)}`}function replaceJsonValue(e,t,n){let r=ki(e),i=r&&Ai(r,t);if(!i)return{kind:`refused`,reason:`absent`};let a=i.offset+i.length,o=e.slice(i.offset,a);return stripJsonComments(o)===o?{kind:`edited`,text:`${e.slice(0,i.offset)}${jsonAt(n,indentUnit(e),t.length)}${e.slice(a)}`}:{kind:`refused`,reason:`comment`}}function createFile(e,t,n){return e.format===`toml`?renderTomlTable([e.key,t],n):`${JSON.stringify({[e.key]:{[t]:n}},null,2)}\n`}function appendServer(e,t,n,r){return e.format===`toml`?appendTomlTable(t,[e.key,n],r):insertJsonProperty(t,[e.key],n,r)??insertJsonProperty(t,[],e.key,{[n]:r})}function replaceServer(e,t,n,r){let i=e.format===`toml`?replaceTomlTable(t,[e.key,n],r):replaceJsonValue(t,[e.key,n],r);return i.kind===`edited`?i.text:void 0}function renderEntry(e,t,n){return e.format===`toml`?renderTomlTable([e.key,t],n):JSON.stringify({[t]:n},null,2)}function read(e,t){let r=C(e,t);return n(r)?a(r,`utf8`):void 0}const Mi={target:`the target changed since the last projection — reconcile it into the golden set first`,both:`both sides changed since the last projection — a three-way conflict for a person to settle`,unknown:`no baseline says which side changed — compare the two by hand`};function heldBack(e){return[`both`,`unknown`,`target`].find(t=>e.includes(t))}function projectMcp({root:e,git:t,write:n}){let r=parseGoldenSet(read(e,Y));if(r.kind!==`servers`)return r;let i=parseProjectionRecord(read(e,jr)),a=new McpBaseline({git:t,record:i}),o=[],s=[],c=[];for(let t of mcpTargets(e)){let n=read(e,t.path),i=parseTarget(t,n);if(i.kind===`unreadable`){o.push({target:t.path,server:``,action:`refuse`,detail:`the target does not parse`});continue}let l={config:t,source:n,created:n===void 0,servers:i.kind===`servers`?i.servers:new Map,agreed:new Map};c.push(l);let u=Er[t.dialect];for(let[e,n]of r.servers){let row=(n,r)=>o.push({target:t.path,server:e,action:n,detail:r}),r=credentialFields(n)[0];if(r){row(`refuse`,`the golden set holds a literal credential at ${r} — reference it as \${VAR} first`);continue}let i=u.write(n);if(i.kind===`refused`){row(`refuse`,`${i.field}: ${i.reason}`);continue}let c=l.servers.get(e);if(!c){let r=l.source===void 0?createFile(t,e,i.entry):appendServer(t,l.source,e,i.entry);apply(l,e,n,i.entry,r,l.created?`creates the file`:`appends the server`,row,s);continue}let d=divergingFields(n,c,u.fields);if(!d.length){l.agreed.set(e,n);continue}let f=heldBack(d.map(r=>a.directionOf(t,e,r,n,c)));if(f){row(`skip`,Mi[f]);continue}let p=replaceServer(t,l.source,e,i.entry);apply(l,e,n,i.entry,p,`replaces ${d.join(`, `)}`,row,s)}}if(n){for(let t of c)t.source!==void 0&&t.source!==read(e,t.config.path)&&writeTarget(e,t);writeRecord(e,i,c)}return{kind:`planned`,rows:o,entries:s,written:n}}function apply(e,t,n,r,i,a,o,s){let c=!e.servers.has(t),l=i!==void 0&&readsBack(e,t,n,i),u=l?c?`add`:`update`:`edit`;if(s.push({target:e.config.path,server:t,action:u,entry:renderEntry(e.config,t,r)}),!l){o(`edit`,c?`the file has no safe place to add it — apply the entry by hand`:`an in-place change here is applied by hand`);return}e.source=i,e.servers=parseTarget(e.config,i).servers,e.agreed.set(t,n),o(u,a)}function readsBack(e,t,n,r){let i=parseTarget(e.config,r);if(i.kind!==`servers`)return!1;let a=i.servers.get(t),o=Er[e.config.dialect].fields;return!a||divergingFields(n,a,o).length?!1:[...e.servers].every(([e,n])=>{if(e===t)return!0;let r=i.servers.get(e);return r!==void 0&&JSON.stringify(r)===JSON.stringify(n)})}function writeTarget(e,t){let n=C(e,t.config.path);i(b(n),{recursive:!0}),m(n,t.source)}function writeRecord(e,t,n){for(let e of n){let n=t.get(e.config.path)??new Map;for(let[t,r]of e.agreed)n.set(t,r);n.size&&t.set(e.config.path,n)}let r=C(e,jr);i(b(r),{recursive:!0}),m(r,formatProjectionRecord(t))}const Ni={name:`buddy-agent-harness`,description:`Initialize agent harness skill compatibility in consumer repositories.`,commands:[ri,Qr,command({name:`mcp`,description:`Work with the golden MCP server set at .agents/buddy-agent-harness/mcp.toml.`,commands:[command({name:`project`,description:`Project the golden MCP server set into each enabled harness. A dry run unless --write; never overwrites a change made on the harness side.`,options:{root:{description:`Repository or package directory. Defaults to the current directory.`,type:N.string().optional()},write:{description:`Apply the plan and record what was projected. Without it nothing on disk changes.`,type:N.boolean().optional()}},examples:[{command:`buddy-agent-harness mcp project`,description:`Preview what would be projected`},{command:`buddy-agent-harness mcp project --write`,description:`Project the golden set into each harness`}],run(e){try{let t=e.root??process.cwd(),n=e.write===!0,r=projectMcp({root:t,git:new GitBridgeState(t),write:n});if(r.kind===`unreadable`){let e=r.position?` at line ${r.position.line}, column ${r.position.column}`:``;throw new M(`${Y} does not parse${e}.`,{code:`golden-set-unreadable`,help:`Fix the TOML syntax in ${Y}, then re-run.`})}return r.kind===`absent`?empty(`0 servers — no golden set at ${Y}`,{help:[`Create ${Y} with the MCP servers to project.`,ref(`mcp project`,{},`preview the projection`)]}):result({golden:Y,mode:n?`written`:`dry run — nothing written; re-run with --write to apply`,actions:r.rows.length?r.rows:`0 changes — every enabled harness already carries the golden set`,...r.entries.length?{entries:r.entries}:{},record:n?jr:`not written — dry run`})}catch(e){return fail(e,`MCP projection failed.`)}}}),wi]}),$n,qr,ni]};function app(e){let[t,...n]=Ni.commands;return n.reduce((e,t)=>e.command(t),cli({name:Ni.name,version:`1.2.0`,description:Ni.description,format:e}).default({description:"Report whether this repository's harness bridges resolve (the same as `doctor`).",options:Qr.options,async run(e){let{bin:t,...n}=await diagnoseReport({root:e.root,harness:e.harness});return result({...homeHeader({description:Ni.description}),...n})}}).command(t))}const Pi={reference:[`load`,`create`,`delete`],governance:[`show`]};function defaultFormat(e){let t=e.slice(2);if(t.some(e=>e===`--format`||e.startsWith(`--format=`)))return`toon`;let[n,r]=t;return n!==void 0&&r!==void 0&&Pi[n]?.includes(r)?`text`:`toon`}async function run(e){try{let t=await app(defaultFormat(e)).parse(e);return typeof t==`number`?t:j.success}catch(e){return process.stderr.write(`error: ${e instanceof Error?e.message:`Invalid command.`}\n`),j.usage}}process.exitCode=await run([...process.argv.slice(0,2),`init`,...process.argv.slice(2)]);export{};