@iinm/plain-agent 1.8.3 → 1.8.4

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 (86) hide show
  1. package/README.md +2 -2
  2. package/bin/plain +1 -1
  3. package/config/config.predefined.json +1 -1
  4. package/config/prompts.predefined/shortcuts/configure.md +1 -1
  5. package/dist/main.mjs +473 -0
  6. package/dist/main.mjs.map +7 -0
  7. package/package.json +5 -7
  8. package/src/agent.d.ts +0 -52
  9. package/src/agent.mjs +0 -204
  10. package/src/agentLoop.mjs +0 -419
  11. package/src/agentState.mjs +0 -41
  12. package/src/claudeCodePlugin.mjs +0 -164
  13. package/src/cliArgs.mjs +0 -175
  14. package/src/cliBatch.mjs +0 -147
  15. package/src/cliCommands.mjs +0 -283
  16. package/src/cliCompleter.mjs +0 -227
  17. package/src/cliCost.mjs +0 -309
  18. package/src/cliFormatter.mjs +0 -413
  19. package/src/cliInteractive.mjs +0 -529
  20. package/src/cliInterruptTransform.mjs +0 -51
  21. package/src/cliMuteTransform.mjs +0 -26
  22. package/src/cliPasteTransform.mjs +0 -183
  23. package/src/config.d.ts +0 -36
  24. package/src/config.mjs +0 -197
  25. package/src/context/loadAgentRoles.mjs +0 -283
  26. package/src/context/loadPrompts.mjs +0 -324
  27. package/src/context/loadUserMessageContext.mjs +0 -147
  28. package/src/costTracker.mjs +0 -210
  29. package/src/env.mjs +0 -44
  30. package/src/main.mjs +0 -279
  31. package/src/mcpClient.mjs +0 -351
  32. package/src/mcpIntegration.mjs +0 -160
  33. package/src/model.d.ts +0 -109
  34. package/src/modelCaller.mjs +0 -32
  35. package/src/modelDefinition.d.ts +0 -92
  36. package/src/prompt.mjs +0 -138
  37. package/src/providers/anthropic.d.ts +0 -248
  38. package/src/providers/anthropic.mjs +0 -587
  39. package/src/providers/bedrock.d.ts +0 -249
  40. package/src/providers/bedrock.mjs +0 -700
  41. package/src/providers/gemini.d.ts +0 -208
  42. package/src/providers/gemini.mjs +0 -754
  43. package/src/providers/openai.d.ts +0 -281
  44. package/src/providers/openai.mjs +0 -544
  45. package/src/providers/openaiCompatible.d.ts +0 -147
  46. package/src/providers/openaiCompatible.mjs +0 -652
  47. package/src/providers/platform/awsSigV4.mjs +0 -184
  48. package/src/providers/platform/azure.mjs +0 -42
  49. package/src/providers/platform/bedrock.mjs +0 -78
  50. package/src/providers/platform/googleCloud.mjs +0 -34
  51. package/src/subagent.mjs +0 -265
  52. package/src/tmpfile.mjs +0 -27
  53. package/src/tool.d.ts +0 -74
  54. package/src/toolExecutor.mjs +0 -236
  55. package/src/toolInputValidator.mjs +0 -183
  56. package/src/toolUseApprover.mjs +0 -99
  57. package/src/tools/askURL.mjs +0 -209
  58. package/src/tools/askWeb.mjs +0 -208
  59. package/src/tools/compactContext.d.ts +0 -4
  60. package/src/tools/compactContext.mjs +0 -87
  61. package/src/tools/delegateToSubagent.d.ts +0 -4
  62. package/src/tools/delegateToSubagent.mjs +0 -48
  63. package/src/tools/execCommand.d.ts +0 -22
  64. package/src/tools/execCommand.mjs +0 -200
  65. package/src/tools/patchFile.d.ts +0 -4
  66. package/src/tools/patchFile.mjs +0 -133
  67. package/src/tools/reportAsSubagent.d.ts +0 -3
  68. package/src/tools/reportAsSubagent.mjs +0 -44
  69. package/src/tools/tmuxCommand.d.ts +0 -14
  70. package/src/tools/tmuxCommand.mjs +0 -194
  71. package/src/tools/writeFile.d.ts +0 -4
  72. package/src/tools/writeFile.mjs +0 -56
  73. package/src/usageStore.mjs +0 -167
  74. package/src/utils/evalJSONConfig.mjs +0 -72
  75. package/src/utils/matchValue.d.ts +0 -6
  76. package/src/utils/matchValue.mjs +0 -40
  77. package/src/utils/noThrow.mjs +0 -31
  78. package/src/utils/notify.mjs +0 -29
  79. package/src/utils/parseFileRange.mjs +0 -18
  80. package/src/utils/readFileRange.mjs +0 -33
  81. package/src/utils/retryOnError.mjs +0 -41
  82. package/src/voiceInput.mjs +0 -61
  83. package/src/voiceInputGemini.mjs +0 -105
  84. package/src/voiceInputOpenAI.mjs +0 -104
  85. package/src/voiceInputSession.mjs +0 -543
  86. package/src/voiceToggleKey.mjs +0 -62
package/dist/main.mjs ADDED
@@ -0,0 +1,473 @@
1
+ import { createRequire } from "node:module";const require=createRequire(import.meta.url);
2
+ var Wl=Object.create;var So=Object.defineProperty;var Hl=Object.getOwnPropertyDescriptor;var Yl=Object.getOwnPropertyNames;var Vl=Object.getPrototypeOf,zl=Object.prototype.hasOwnProperty;var Ut=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var x=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ql=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Yl(e))!zl.call(n,r)&&r!==t&&So(n,r,{get:()=>e[r],enumerable:!(s=Hl(e,r))||s.enumerable});return n};var vo=(n,e,t)=>(t=n!=null?Wl(Vl(n)):{},Ql(e||!n||!n.__esModule?So(t,"default",{value:n,enumerable:!0}):t,n));var I=x(j=>{"use strict";var Ts=Symbol.for("yaml.alias"),oi=Symbol.for("yaml.document"),Xt=Symbol.for("yaml.map"),ii=Symbol.for("yaml.pair"),As=Symbol.for("yaml.scalar"),Zt=Symbol.for("yaml.seq"),se=Symbol.for("yaml.node.type"),Cu=n=>!!n&&typeof n=="object"&&n[se]===Ts,Eu=n=>!!n&&typeof n=="object"&&n[se]===oi,Nu=n=>!!n&&typeof n=="object"&&n[se]===Xt,_u=n=>!!n&&typeof n=="object"&&n[se]===ii,ai=n=>!!n&&typeof n=="object"&&n[se]===As,Iu=n=>!!n&&typeof n=="object"&&n[se]===Zt;function ci(n){if(n&&typeof n=="object")switch(n[se]){case Xt:case Zt:return!0}return!1}function Ou(n){if(n&&typeof n=="object")switch(n[se]){case Ts:case Xt:case As:case Zt:return!0}return!1}var Pu=n=>(ai(n)||ci(n))&&!!n.anchor;j.ALIAS=Ts;j.DOC=oi;j.MAP=Xt;j.NODE_TYPE=se;j.PAIR=ii;j.SCALAR=As;j.SEQ=Zt;j.hasAnchor=Pu;j.isAlias=Cu;j.isCollection=ci;j.isDocument=Eu;j.isMap=Nu;j.isNode=Ou;j.isPair=_u;j.isScalar=ai;j.isSeq=Iu});var ot=x(xs=>{"use strict";var U=I(),B=Symbol("break visit"),li=Symbol("skip children"),Z=Symbol("remove node");function en(n,e){let t=ui(e);U.isDocument(n)?Pe(null,n.contents,t,Object.freeze([n]))===Z&&(n.contents=null):Pe(null,n,t,Object.freeze([]))}en.BREAK=B;en.SKIP=li;en.REMOVE=Z;function Pe(n,e,t,s){let r=fi(n,e,t,s);if(U.isNode(r)||U.isPair(r))return di(n,s,r),Pe(n,r,t,s);if(typeof r!="symbol"){if(U.isCollection(e)){s=Object.freeze(s.concat(e));for(let o=0;o<e.items.length;++o){let i=Pe(o,e.items[o],t,s);if(typeof i=="number")o=i-1;else{if(i===B)return B;i===Z&&(e.items.splice(o,1),o-=1)}}}else if(U.isPair(e)){s=Object.freeze(s.concat(e));let o=Pe("key",e.key,t,s);if(o===B)return B;o===Z&&(e.key=null);let i=Pe("value",e.value,t,s);if(i===B)return B;i===Z&&(e.value=null)}}return r}async function tn(n,e){let t=ui(e);U.isDocument(n)?await Me(null,n.contents,t,Object.freeze([n]))===Z&&(n.contents=null):await Me(null,n,t,Object.freeze([]))}tn.BREAK=B;tn.SKIP=li;tn.REMOVE=Z;async function Me(n,e,t,s){let r=await fi(n,e,t,s);if(U.isNode(r)||U.isPair(r))return di(n,s,r),Me(n,r,t,s);if(typeof r!="symbol"){if(U.isCollection(e)){s=Object.freeze(s.concat(e));for(let o=0;o<e.items.length;++o){let i=await Me(o,e.items[o],t,s);if(typeof i=="number")o=i-1;else{if(i===B)return B;i===Z&&(e.items.splice(o,1),o-=1)}}}else if(U.isPair(e)){s=Object.freeze(s.concat(e));let o=await Me("key",e.key,t,s);if(o===B)return B;o===Z&&(e.key=null);let i=await Me("value",e.value,t,s);if(i===B)return B;i===Z&&(e.value=null)}}return r}function ui(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function fi(n,e,t,s){if(typeof t=="function")return t(n,e,s);if(U.isMap(e))return t.Map?.(n,e,s);if(U.isSeq(e))return t.Seq?.(n,e,s);if(U.isPair(e))return t.Pair?.(n,e,s);if(U.isScalar(e))return t.Scalar?.(n,e,s);if(U.isAlias(e))return t.Alias?.(n,e,s)}function di(n,e,t){let s=e[e.length-1];if(U.isCollection(s))s.items[n]=t;else if(U.isPair(s))n==="key"?s.key=t:s.value=t;else if(U.isDocument(s))s.contents=t;else{let r=U.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}xs.visit=en;xs.visitAsync=tn});var $s=x(mi=>{"use strict";var pi=I(),Mu=ot(),Lu={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ru=n=>n.replace(/[!,[\]{}]/g,e=>Lu[e]),it=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let s=e.trim().split(/[ \t]+/),r=s.shift();switch(r){case"%TAG":{if(s.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;let[o,i]=s;return this.tags[o]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[o]=s;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let i=/^\d+\.\d+$/.test(o);return t(6,`Unsupported YAML version ${o}`,i),!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 i=e.slice(2,-1);return i==="!"||i==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),i)}let[,s,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let o=this.tags[s];if(o)try{return o+decodeURIComponent(r)}catch(i){return t(String(i)),null}return s==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,s]of Object.entries(this.tags))if(e.startsWith(s))return t+Ru(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags),r;if(e&&s.length>0&&pi.isNode(e.contents)){let o={};Mu.visit(e.contents,(i,a)=>{pi.isNode(a)&&a.tag&&(o[a.tag]=!0)}),r=Object.keys(o)}else r=[];for(let[o,i]of s)o==="!!"&&i==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(i)))&&t.push(`%TAG ${o} ${i}`);return t.join(`
3
+ `)}};it.defaultYaml={explicit:!1,version:"1.2"};it.defaultTags={"!!":"tag:yaml.org,2002:"};mi.Directives=it});var nn=x(at=>{"use strict";var hi=I(),Du=ot();function qu(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function gi(n){let e=new Set;return Du.visit(n,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}function yi(n,e){for(let t=1;;++t){let s=`${n}${t}`;if(!e.has(s))return s}}function Uu(n,e){let t=[],s=new Map,r=null;return{onAnchor:o=>{t.push(o),r??(r=gi(n));let i=yi(e,r);return r.add(i),i},setAnchors:()=>{for(let o of t){let i=s.get(o);if(typeof i=="object"&&i.anchor&&(hi.isScalar(i.node)||hi.isCollection(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:s}}at.anchorIsValid=qu;at.anchorNames=gi;at.createNodeAnchors=Uu;at.findNewAnchor=yi});var Cs=x(wi=>{"use strict";function ct(n,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let r=0,o=s.length;r<o;++r){let i=s[r],a=ct(n,s,String(r),i);a===void 0?delete s[r]:a!==i&&(s[r]=a)}else if(s instanceof Map)for(let r of Array.from(s.keys())){let o=s.get(r),i=ct(n,s,r,o);i===void 0?s.delete(r):i!==o&&s.set(r,i)}else if(s instanceof Set)for(let r of Array.from(s)){let o=ct(n,s,r,r);o===void 0?s.delete(r):o!==r&&(s.delete(r),s.add(o))}else for(let[r,o]of Object.entries(s)){let i=ct(n,s,r,o);i===void 0?delete s[r]:i!==o&&(s[r]=i)}return n.call(e,t,s)}wi.applyReviver=ct});var ie=x(Si=>{"use strict";var ju=I();function bi(n,e,t){if(Array.isArray(n))return n.map((s,r)=>bi(s,String(r),t));if(n&&typeof n.toJSON=="function"){if(!t||!ju.hasAnchor(n))return n.toJSON(e,t);let s={aliasCount:0,count:1,res:void 0};t.anchors.set(n,s),t.onCreate=o=>{s.res=o,delete t.onCreate};let r=n.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof n=="bigint"&&!t?.keep?Number(n):n}Si.toJS=bi});var sn=x(ki=>{"use strict";var Fu=Cs(),vi=I(),Bu=ie(),Es=class{constructor(e){Object.defineProperty(this,vi.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:t,maxAliasCount:s,onAnchor:r,reviver:o}={}){if(!vi.isDocument(e))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},a=Bu.toJS(this,"",i);if(typeof r=="function")for(let{count:c,res:l}of i.anchors.values())r(l,c);return typeof o=="function"?Fu.applyReviver(o,{"":a},"",a):a}};ki.NodeBase=Es});var lt=x(Ti=>{"use strict";var Ku=nn(),Gu=ot(),Le=I(),Ju=sn(),Wu=ie(),Ns=class extends Ju.NodeBase{constructor(e){super(Le.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let s;t?.aliasResolveCache?s=t.aliasResolveCache:(s=[],Gu.visit(e,{Node:(o,i)=>{(Le.isAlias(i)||Le.hasAnchor(i))&&s.push(i)}}),t&&(t.aliasResolveCache=s));let r;for(let o of s){if(o===this)break;o.anchor===this.source&&(r=o)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:s,doc:r,maxAliasCount:o}=t,i=this.resolve(r,t);if(!i){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=s.get(i);if(a||(Wu.toJS(i,null,t),a=s.get(i)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=rn(r,i,s)),a.count*a.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,s){let r=`*${this.source}`;if(e){if(Ku.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${r} `}return r}};function rn(n,e,t){if(Le.isAlias(e)){let s=e.resolve(n),r=t&&s&&t.get(s);return r?r.count*r.aliasCount:0}else if(Le.isCollection(e)){let s=0;for(let r of e.items){let o=rn(n,r,t);o>s&&(s=o)}return s}else if(Le.isPair(e)){let s=rn(n,e.key,t),r=rn(n,e.value,t);return Math.max(s,r)}return 1}Ti.Alias=Ns});var R=x(_s=>{"use strict";var Hu=I(),Yu=sn(),Vu=ie(),zu=n=>!n||typeof n!="function"&&typeof n!="object",ae=class extends Yu.NodeBase{constructor(e){super(Hu.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Vu.toJS(this.value,e,t)}toString(){return String(this.value)}};ae.BLOCK_FOLDED="BLOCK_FOLDED";ae.BLOCK_LITERAL="BLOCK_LITERAL";ae.PLAIN="PLAIN";ae.QUOTE_DOUBLE="QUOTE_DOUBLE";ae.QUOTE_SINGLE="QUOTE_SINGLE";_s.Scalar=ae;_s.isScalarValue=zu});var ut=x(xi=>{"use strict";var Qu=lt(),Se=I(),Ai=R(),Xu="tag:yaml.org,2002:";function Zu(n,e,t){if(e){let s=t.filter(o=>o.tag===e),r=s.find(o=>!o.format)??s[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(s=>s.identify?.(n)&&!s.format)}function ef(n,e,t){if(Se.isDocument(n)&&(n=n.contents),Se.isNode(n))return n;if(Se.isPair(n)){let u=t.schema[Se.MAP].createNode?.(t.schema,null,t);return u.items.push(n),u}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:s,onAnchor:r,onTagObj:o,schema:i,sourceObjects:a}=t,c;if(s&&n&&typeof n=="object"){if(c=a.get(n),c)return c.anchor??(c.anchor=r(n)),new Qu.Alias(c.anchor);c={anchor:null,node:null},a.set(n,c)}e?.startsWith("!!")&&(e=Xu+e.slice(2));let l=Zu(n,e,i.tags);if(!l){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let u=new Ai.Scalar(n);return c&&(c.node=u),u}l=n instanceof Map?i[Se.MAP]:Symbol.iterator in Object(n)?i[Se.SEQ]:i[Se.MAP]}o&&(o(l),delete t.onTagObj);let f=l?.createNode?l.createNode(t.schema,n,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,n,t):new Ai.Scalar(n);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}xi.createNode=ef});var an=x(on=>{"use strict";var tf=ut(),ee=I(),nf=sn();function Is(n,e,t){let s=t;for(let r=e.length-1;r>=0;--r){let o=e[r];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let i=[];i[o]=s,s=i}else s=new Map([[o,s]])}return tf.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var $i=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Os=class extends nf.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(s=>ee.isNode(s)||ee.isPair(s)?s.clone(e):s),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if($i(e))this.add(t);else{let[s,...r]=e,o=this.get(s,!0);if(ee.isCollection(o))o.addIn(r,t);else if(o===void 0&&this.schema)this.set(s,Is(this.schema,r,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}deleteIn(e){let[t,...s]=e;if(s.length===0)return this.delete(t);let r=this.get(t,!0);if(ee.isCollection(r))return r.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){let[s,...r]=e,o=this.get(s,!0);return r.length===0?!t&&ee.isScalar(o)?o.value:o:ee.isCollection(o)?o.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ee.isPair(t))return!1;let s=t.value;return s==null||e&&ee.isScalar(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){let[t,...s]=e;if(s.length===0)return this.has(t);let r=this.get(t,!0);return ee.isCollection(r)?r.hasIn(s):!1}setIn(e,t){let[s,...r]=e;if(r.length===0)this.set(s,t);else{let o=this.get(s,!0);if(ee.isCollection(o))o.setIn(r,t);else if(o===void 0&&this.schema)this.set(s,Is(this.schema,r,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}};on.Collection=Os;on.collectionFromPath=Is;on.isEmptyPath=$i});var ft=x(cn=>{"use strict";var sf=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function Ps(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var rf=(n,e,t)=>n.endsWith(`
4
+ `)?Ps(t,e):t.includes(`
5
+ `)?`
6
+ `+Ps(t,e):(n.endsWith(" ")?"":" ")+t;cn.indentComment=Ps;cn.lineComment=rf;cn.stringifyComment=sf});var Ei=x(dt=>{"use strict";var of="flow",Ms="block",ln="quoted";function af(n,e,t="flow",{indentAtStart:s,lineWidth:r=80,minContentWidth:o=20,onFold:i,onOverflow:a}={}){if(!r||r<0)return n;r<o&&(o=0);let c=Math.max(1+o,1+r-e.length);if(n.length<=c)return n;let l=[],f={},u=r-e.length;typeof s=="number"&&(s>r-Math.max(2,o)?l.push(0):u=r-s);let d,p,g=!1,m=-1,h=-1,b=-1;t===Ms&&(m=Ci(n,m,e.length),m!==-1&&(u=m+c));for(let S;S=n[m+=1];){if(t===ln&&S==="\\"){switch(h=m,n[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(S===`
7
+ `)t===Ms&&(m=Ci(n,m,e.length)),u=m+e.length+c,d=void 0;else{if(S===" "&&p&&p!==" "&&p!==`
8
+ `&&p!==" "){let w=n[m+1];w&&w!==" "&&w!==`
9
+ `&&w!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===ln){for(;p===" "||p===" ";)p=S,S=n[m+=1],g=!0;let w=m>b+1?m-2:h-1;if(f[w])return n;l.push(w),f[w]=!0,u=w+c,d=void 0}else g=!0}p=S}if(g&&a&&a(),l.length===0)return n;i&&i();let y=n.slice(0,l[0]);for(let S=0;S<l.length;++S){let w=l[S],k=l[S+1]||n.length;w===0?y=`
10
+ ${e}${n.slice(0,k)}`:(t===ln&&f[w]&&(y+=`${n[w]}\\`),y+=`
11
+ ${e}${n.slice(w+1,k)}`)}return y}function Ci(n,e,t){let s=e,r=e+1,o=n[r];for(;o===" "||o===" ";)if(e<r+t)o=n[++e];else{do o=n[++e];while(o&&o!==`
12
+ `);s=e,r=e+1,o=n[r]}return s}dt.FOLD_BLOCK=Ms;dt.FOLD_FLOW=of;dt.FOLD_QUOTED=ln;dt.foldFlowLines=af});var mt=x(Ni=>{"use strict";var H=R(),ce=Ei(),fn=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),dn=n=>/^(%|---|\.\.\.)/m.test(n);function cf(n,e,t){if(!e||e<0)return!1;let s=e-t,r=n.length;if(r<=s)return!1;for(let o=0,i=0;o<r;++o)if(n[o]===`
13
+ `){if(o-i>s)return!0;if(i=o+1,r-i<=s)return!1}return!0}function pt(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:s}=e,r=e.options.doubleQuotedMinMultiLineLength,o=e.indent||(dn(n)?" ":""),i="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(i+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{i+=t.slice(a,c);let f=t.substr(c+2,4);switch(f){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:f.substr(0,2)==="00"?i+="\\x"+f.substr(2):i+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(s||t[c+2]==='"'||t.length<r)c+=1;else{for(i+=t.slice(a,c)+`
14
+
15
+ `;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)i+=`
16
+ `,c+=2;i+=o,t[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+t.slice(a):t,s?i:ce.foldFlowLines(i,o,ce.FOLD_QUOTED,fn(e,!1))}function Ls(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`
17
+ `)||/[ \t]\n|\n[ \t]/.test(n))return pt(n,e);let t=e.indent||(dn(n)?" ":""),s="'"+n.replace(/'/g,"''").replace(/\n+/g,`$&
18
+ ${t}`)+"'";return e.implicitKey?s:ce.foldFlowLines(s,t,ce.FOLD_FLOW,fn(e,!1))}function Re(n,e){let{singleQuote:t}=e.options,s;if(t===!1)s=pt;else{let r=n.includes('"'),o=n.includes("'");r&&!o?s=Ls:o&&!r?s=pt:s=t?Ls:pt}return s(n,e)}var Rs;try{Rs=new RegExp(`(^|(?<!
19
+ ))
20
+ +(?!
21
+ |$)`,"g")}catch{Rs=/\n+(?!\n|$)/g}function un({comment:n,type:e,value:t},s,r,o){let{blockQuote:i,commentString:a,lineWidth:c}=s.options;if(!i||/\n[\t ]+$/.test(t))return Re(t,s);let l=s.indent||(s.forceBlockIndent||dn(t)?" ":""),f=i==="literal"?!0:i==="folded"||e===H.Scalar.BLOCK_FOLDED?!1:e===H.Scalar.BLOCK_LITERAL?!0:!cf(t,c,l.length);if(!t)return f?`|
22
+ `:`>
23
+ `;let u,d;for(d=t.length;d>0;--d){let k=t[d-1];if(k!==`
24
+ `&&k!==" "&&k!==" ")break}let p=t.substring(d),g=p.indexOf(`
25
+ `);g===-1?u="-":t===p||g!==p.length-1?(u="+",o&&o()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
26
+ `&&(p=p.slice(0,-1)),p=p.replace(Rs,`$&${l}`));let m=!1,h,b=-1;for(h=0;h<t.length;++h){let k=t[h];if(k===" ")m=!0;else if(k===`
27
+ `)b=h;else break}let y=t.substring(0,b<h?b+1:h);y&&(t=t.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let w=(m?l?"2":"1":"")+u;if(n&&(w+=" "+a(n.replace(/ ?[\r\n]+/g," ")),r&&r()),!f){let k=t.replace(/\n+/g,`
28
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),v=!1,T=fn(s,!0);i!=="folded"&&e!==H.Scalar.BLOCK_FOLDED&&(T.onOverflow=()=>{v=!0});let A=ce.foldFlowLines(`${y}${k}${p}`,l,ce.FOLD_BLOCK,T);if(!v)return`>${w}
29
+ ${l}${A}`}return t=t.replace(/\n+/g,`$&${l}`),`|${w}
30
+ ${l}${y}${t}${p}`}function lf(n,e,t,s){let{type:r,value:o}=n,{actualString:i,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&o.includes(`
31
+ `)||f&&/[[\]{},]/.test(o))return Re(o,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||f||!o.includes(`
32
+ `)?Re(o,e):un(n,e,t,s);if(!a&&!f&&r!==H.Scalar.PLAIN&&o.includes(`
33
+ `))return un(n,e,t,s);if(dn(o)){if(c==="")return e.forceBlockIndent=!0,un(n,e,t,s);if(a&&c===l)return Re(o,e)}let u=o.replace(/\n+/g,`$&
34
+ ${c}`);if(i){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:g}=e.doc.schema;if(g.some(d)||p?.some(d))return Re(o,e)}return a?u:ce.foldFlowLines(u,c,ce.FOLD_FLOW,fn(e,!1))}function uf(n,e,t,s){let{implicitKey:r,inFlow:o}=e,i=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==H.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=H.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case H.Scalar.BLOCK_FOLDED:case H.Scalar.BLOCK_LITERAL:return r||o?Re(i.value,e):un(i,e,t,s);case H.Scalar.QUOTE_DOUBLE:return pt(i.value,e);case H.Scalar.QUOTE_SINGLE:return Ls(i.value,e);case H.Scalar.PLAIN:return lf(i,e,t,s);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Ni.stringifyString=uf});var ht=x(Ds=>{"use strict";var ff=nn(),le=I(),df=ft(),pf=mt();function mf(n,e){let t=Object.assign({blockQuote:!0,commentString:df.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},n.schema.toStringOptions,e),s;switch(t.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:s,options:t}}function hf(n,e){if(e.tag){let r=n.filter(o=>o.tag===e.tag);if(r.length>0)return r.find(o=>o.format===e.format)??r[0]}let t,s;if(le.isScalar(e)){s=e.value;let r=n.filter(o=>o.identify?.(s));if(r.length>1){let o=r.filter(i=>i.test);o.length>0&&(r=o)}t=r.find(o=>o.format===e.format)??r.find(o=>!o.format)}else s=e,t=n.find(r=>r.nodeClass&&s instanceof r.nodeClass);if(!t){let r=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${r} value`)}return t}function gf(n,e,{anchors:t,doc:s}){if(!s.directives)return"";let r=[],o=(le.isScalar(n)||le.isCollection(n))&&n.anchor;o&&ff.anchorIsValid(o)&&(t.add(o),r.push(`&${o}`));let i=n.tag??(e.default?null:e.tag);return i&&r.push(s.directives.tagString(i)),r.join(" ")}function yf(n,e,t,s){if(le.isPair(n))return n.toString(e,t,s);if(le.isAlias(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let r,o=le.isNode(n)?n:e.doc.createNode(n,{onTagObj:c=>r=c});r??(r=hf(e.doc.schema.tags,o));let i=gf(o,r,e);i.length>0&&(e.indentAtStart=(e.indentAtStart??0)+i.length+1);let a=typeof r.stringify=="function"?r.stringify(o,e,t,s):le.isScalar(o)?pf.stringifyString(o,e,t,s):o.toString(e,t,s);return i?le.isScalar(o)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
35
+ ${e.indent}${a}`:a}Ds.createStringifyContext=mf;Ds.stringify=yf});var Pi=x(Oi=>{"use strict";var re=I(),_i=R(),Ii=ht(),gt=ft();function wf({key:n,value:e},t,s,r){let{allNullValues:o,doc:i,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=t,d=re.isNode(n)&&n.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(re.isCollection(n)||!re.isNode(n)&&typeof n=="object"){let T="With simple keys, collection cannot be used as a key value";throw new Error(T)}}let p=!u&&(!n||d&&e==null&&!t.inFlow||re.isCollection(n)||(re.isScalar(n)?n.type===_i.Scalar.BLOCK_FOLDED||n.type===_i.Scalar.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!o),indent:a+c});let g=!1,m=!1,h=Ii.stringify(n,t,()=>g=!0,()=>m=!0);if(!p&&!t.inFlow&&h.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(o||e==null)return g&&s&&s(),h===""?"?":p?`? ${h}`:h}else if(o&&!u||e==null&&p)return h=`? ${h}`,d&&!g?h+=gt.lineComment(h,t.indent,l(d)):m&&r&&r(),h;g&&(d=null),p?(d&&(h+=gt.lineComment(h,t.indent,l(d))),h=`? ${h}
36
+ ${a}:`):(h=`${h}:`,d&&(h+=gt.lineComment(h,t.indent,l(d))));let b,y,S;re.isNode(e)?(b=!!e.spaceBefore,y=e.commentBefore,S=e.comment):(b=!1,y=null,S=null,e&&typeof e=="object"&&(e=i.createNode(e))),t.implicitKey=!1,!p&&!d&&re.isScalar(e)&&(t.indentAtStart=h.length+1),m=!1,!f&&c.length>=2&&!t.inFlow&&!p&&re.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let w=!1,k=Ii.stringify(e,t,()=>w=!0,()=>m=!0),v=" ";if(d||b||y){if(v=b?`
37
+ `:"",y){let T=l(y);v+=`
38
+ ${gt.indentComment(T,t.indent)}`}k===""&&!t.inFlow?v===`
39
+ `&&S&&(v=`
40
+
41
+ `):v+=`
42
+ ${t.indent}`}else if(!p&&re.isCollection(e)){let T=k[0],A=k.indexOf(`
43
+ `),$=A!==-1,C=t.inFlow??e.flow??e.items.length===0;if($||!C){let N=!1;if($&&(T==="&"||T==="!")){let E=k.indexOf(" ");T==="&"&&E!==-1&&E<A&&k[E+1]==="!"&&(E=k.indexOf(" ",E+1)),(E===-1||A<E)&&(N=!0)}N||(v=`
44
+ ${t.indent}`)}}else(k===""||k[0]===`
45
+ `)&&(v="");return h+=v+k,t.inFlow?w&&s&&s():S&&!w?h+=gt.lineComment(h,t.indent,l(S)):m&&r&&r(),h}Oi.stringifyPair=wf});var Us=x(qs=>{"use strict";var Mi=Ut("process");function bf(n,...e){n==="debug"&&console.log(...e)}function Sf(n,e){(n==="debug"||n==="warn")&&(typeof Mi.emitWarning=="function"?Mi.emitWarning(e):console.warn(e))}qs.debug=bf;qs.warn=Sf});var gn=x(hn=>{"use strict";var yt=I(),Li=R(),pn="<<",mn={identify:n=>n===pn||typeof n=="symbol"&&n.description===pn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Li.Scalar(Symbol(pn)),{addToJSMap:Ri}),stringify:()=>pn},vf=(n,e)=>(mn.identify(e)||yt.isScalar(e)&&(!e.type||e.type===Li.Scalar.PLAIN)&&mn.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===mn.tag&&t.default);function Ri(n,e,t){if(t=n&&yt.isAlias(t)?t.resolve(n.doc):t,yt.isSeq(t))for(let s of t.items)js(n,e,s);else if(Array.isArray(t))for(let s of t)js(n,e,s);else js(n,e,t)}function js(n,e,t){let s=n&&yt.isAlias(t)?t.resolve(n.doc):t;if(!yt.isMap(s))throw new Error("Merge sources must be maps or map aliases");let r=s.toJSON(null,n,Map);for(let[o,i]of r)e instanceof Map?e.has(o)||e.set(o,i):e instanceof Set?e.add(o):Object.prototype.hasOwnProperty.call(e,o)||Object.defineProperty(e,o,{value:i,writable:!0,enumerable:!0,configurable:!0});return e}hn.addMergeToJSMap=Ri;hn.isMergeKey=vf;hn.merge=mn});var Bs=x(Ui=>{"use strict";var kf=Us(),Di=gn(),Tf=ht(),qi=I(),Fs=ie();function Af(n,e,{key:t,value:s}){if(qi.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,s);else if(Di.isMergeKey(n,t))Di.addMergeToJSMap(n,e,s);else{let r=Fs.toJS(t,"",n);if(e instanceof Map)e.set(r,Fs.toJS(s,r,n));else if(e instanceof Set)e.add(r);else{let o=xf(t,r,n),i=Fs.toJS(s,o,n);o in e?Object.defineProperty(e,o,{value:i,writable:!0,enumerable:!0,configurable:!0}):e[o]=i}}return e}function xf(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(qi.isNode(n)&&t?.doc){let s=Tf.createStringifyContext(t.doc,{});s.anchors=new Set;for(let o of t.anchors.keys())s.anchors.add(o.anchor);s.inFlow=!0,s.inStringifyKey=!0;let r=n.toString(s);if(!t.mapKeyWarned){let o=JSON.stringify(r);o.length>40&&(o=o.substring(0,36)+'..."'),kf.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}Ui.addPairToJSMap=Af});var ue=x(Ks=>{"use strict";var ji=ut(),$f=Pi(),Cf=Bs(),yn=I();function Ef(n,e,t){let s=ji.createNode(n,void 0,t),r=ji.createNode(e,void 0,t);return new wn(s,r)}var wn=class n{constructor(e,t=null){Object.defineProperty(this,yn.NODE_TYPE,{value:yn.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:s}=this;return yn.isNode(t)&&(t=t.clone(e)),yn.isNode(s)&&(s=s.clone(e)),new n(t,s)}toJSON(e,t){let s=t?.mapAsMap?new Map:{};return Cf.addPairToJSMap(t,s,this)}toString(e,t,s){return e?.doc?$f.stringifyPair(this,e,t,s):JSON.stringify(this)}};Ks.Pair=wn;Ks.createPair=Ef});var Gs=x(Bi=>{"use strict";var ve=I(),Fi=ht(),bn=ft();function Nf(n,e,t){return(e.inFlow??n.flow?If:_f)(n,e,t)}function _f({comment:n,items:e},t,{blockItemPrefix:s,flowChars:r,itemIndent:o,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:l}}=t,f=Object.assign({},t,{indent:o,type:null}),u=!1,d=[];for(let g=0;g<e.length;++g){let m=e[g],h=null;if(ve.isNode(m))!u&&m.spaceBefore&&d.push(""),Sn(t,d,m.commentBefore,u),m.comment&&(h=m.comment);else if(ve.isPair(m)){let y=ve.isNode(m.key)?m.key:null;y&&(!u&&y.spaceBefore&&d.push(""),Sn(t,d,y.commentBefore,u))}u=!1;let b=Fi.stringify(m,f,()=>h=null,()=>u=!0);h&&(b+=bn.lineComment(b,o,l(h))),u&&h&&(u=!1),d.push(s+b)}let p;if(d.length===0)p=r.start+r.end;else{p=d[0];for(let g=1;g<d.length;++g){let m=d[g];p+=m?`
46
+ ${c}${m}`:`
47
+ `}}return n?(p+=`
48
+ `+bn.indentComment(l(n),c),a&&a()):u&&i&&i(),p}function If({items:n},e,{flowChars:t,itemIndent:s}){let{indent:r,indentStep:o,flowCollectionPadding:i,options:{commentString:a}}=e;s+=o;let c=Object.assign({},e,{indent:s,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let g=0;g<n.length;++g){let m=n[g],h=null;if(ve.isNode(m))m.spaceBefore&&u.push(""),Sn(e,u,m.commentBefore,!1),m.comment&&(h=m.comment);else if(ve.isPair(m)){let y=ve.isNode(m.key)?m.key:null;y&&(y.spaceBefore&&u.push(""),Sn(e,u,y.commentBefore,!1),y.comment&&(l=!0));let S=ve.isNode(m.value)?m.value:null;S?(S.comment&&(h=S.comment),S.commentBefore&&(l=!0)):m.value==null&&y?.comment&&(h=y.comment)}h&&(l=!0);let b=Fi.stringify(m,c,()=>h=null);l||(l=u.length>f||b.includes(`
49
+ `)),g<n.length-1?b+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=u.reduce((y,S)=>y+S.length+2,2)+(b.length+2)>e.options.lineWidth)),l&&(b+=",")),h&&(b+=bn.lineComment(b,s,a(h))),u.push(b),f=u.length}let{start:d,end:p}=t;if(u.length===0)return d+p;if(!l){let g=u.reduce((m,h)=>m+h.length+2,2);l=e.options.lineWidth>0&&g>e.options.lineWidth}if(l){let g=d;for(let m of u)g+=m?`
50
+ ${o}${r}${m}`:`
51
+ `;return`${g}
52
+ ${r}${p}`}else return`${d}${i}${u.join(" ")}${i}${p}`}function Sn({indent:n,options:{commentString:e}},t,s,r){if(s&&r&&(s=s.replace(/^\n+/,"")),s){let o=bn.indentComment(e(s),n);t.push(o.trimStart())}}Bi.stringifyCollection=Nf});var de=x(Ws=>{"use strict";var Of=Gs(),Pf=Bs(),Mf=an(),fe=I(),vn=ue(),Lf=R();function wt(n,e){let t=fe.isScalar(e)?e.value:e;for(let s of n)if(fe.isPair(s)&&(s.key===e||s.key===t||fe.isScalar(s.key)&&s.key.value===t))return s}var Js=class extends Mf.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(fe.MAP,e),this.items=[]}static from(e,t,s){let{keepUndefined:r,replacer:o}=s,i=new this(e),a=(c,l)=>{if(typeof o=="function")l=o.call(t,c,l);else if(Array.isArray(o)&&!o.includes(c))return;(l!==void 0||r)&&i.items.push(vn.createPair(c,l,s))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&i.items.sort(e.sortMapEntries),i}add(e,t){let s;fe.isPair(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new vn.Pair(e,e?.value):s=new vn.Pair(e.key,e.value);let r=wt(this.items,s.key),o=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${s.key} already set`);fe.isScalar(r.value)&&Lf.isScalarValue(s.value)?r.value.value=s.value:r.value=s.value}else if(o){let i=this.items.findIndex(a=>o(s,a)<0);i===-1?this.items.push(s):this.items.splice(i,0,s)}else this.items.push(s)}delete(e){let t=wt(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let r=wt(this.items,e)?.value;return(!t&&fe.isScalar(r)?r.value:r)??void 0}has(e){return!!wt(this.items,e)}set(e,t){this.add(new vn.Pair(e,t),!0)}toJSON(e,t,s){let r=s?new s:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let o of this.items)Pf.addPairToJSMap(t,r,o);return r}toString(e,t,s){if(!e)return JSON.stringify(this);for(let r of this.items)if(!fe.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Of.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:t})}};Ws.YAMLMap=Js;Ws.findPair=wt});var De=x(Gi=>{"use strict";var Rf=I(),Ki=de(),Df={collection:"map",default:!0,nodeClass:Ki.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(n,e){return Rf.isMap(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>Ki.YAMLMap.from(n,e,t)};Gi.map=Df});var pe=x(Ji=>{"use strict";var qf=ut(),Uf=Gs(),jf=an(),Tn=I(),Ff=R(),Bf=ie(),Hs=class extends jf.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Tn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=kn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let s=kn(e);if(typeof s!="number")return;let r=this.items[s];return!t&&Tn.isScalar(r)?r.value:r}has(e){let t=kn(e);return typeof t=="number"&&t<this.items.length}set(e,t){let s=kn(e);if(typeof s!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[s];Tn.isScalar(r)&&Ff.isScalarValue(t)?r.value=t:this.items[s]=t}toJSON(e,t){let s=[];t?.onCreate&&t.onCreate(s);let r=0;for(let o of this.items)s.push(Bf.toJS(o,String(r++),t));return s}toString(e,t,s){return e?Uf.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:t}):JSON.stringify(this)}static from(e,t,s){let{replacer:r}=s,o=new this(e);if(t&&Symbol.iterator in Object(t)){let i=0;for(let a of t){if(typeof r=="function"){let c=t instanceof Set?a:String(i++);a=r.call(t,c,a)}o.items.push(qf.createNode(a,void 0,s))}}return o}};function kn(n){let e=Tn.isScalar(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Ji.YAMLSeq=Hs});var qe=x(Hi=>{"use strict";var Kf=I(),Wi=pe(),Gf={collection:"seq",default:!0,nodeClass:Wi.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(n,e){return Kf.isSeq(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>Wi.YAMLSeq.from(n,e,t)};Hi.seq=Gf});var bt=x(Yi=>{"use strict";var Jf=mt(),Wf={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,s){return e=Object.assign({actualString:!0},e),Jf.stringifyString(n,e,t,s)}};Yi.string=Wf});var An=x(Qi=>{"use strict";var Vi=R(),zi={identify:n=>n==null,createNode:()=>new Vi.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Vi.Scalar(null),stringify:({source:n},e)=>typeof n=="string"&&zi.test.test(n)?n:e.options.nullStr};Qi.nullTag=zi});var Ys=x(Zi=>{"use strict";var Hf=R(),Xi={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new Hf.Scalar(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&Xi.test.test(n)){let s=n[0]==="t"||n[0]==="T";if(e===s)return n}return e?t.options.trueStr:t.options.falseStr}};Zi.boolTag=Xi});var Ue=x(ea=>{"use strict";function Yf({format:n,minFractionDigits:e,tag:t,value:s}){if(typeof s=="bigint")return String(s);let r=typeof s=="number"?s:Number(s);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=Object.is(s,-0)?"-0":JSON.stringify(s);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let i=o.indexOf(".");i<0&&(i=o.length,o+=".");let a=e-(o.length-i-1);for(;a-- >0;)o+="0"}return o}ea.stringifyNumber=Yf});var zs=x(xn=>{"use strict";var Vf=R(),Vs=Ue(),zf={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Vs.stringifyNumber},Qf={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():Vs.stringifyNumber(n)}},Xf={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new Vf.Scalar(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:Vs.stringifyNumber};xn.float=Xf;xn.floatExp=Qf;xn.floatNaN=zf});var Xs=x(Cn=>{"use strict";var ta=Ue(),$n=n=>typeof n=="bigint"||Number.isInteger(n),Qs=(n,e,t,{intAsBigInt:s})=>s?BigInt(n):parseInt(n.substring(e),t);function na(n,e,t){let{value:s}=n;return $n(s)&&s>=0?t+s.toString(e):ta.stringifyNumber(n)}var Zf={identify:n=>$n(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>Qs(n,2,8,t),stringify:n=>na(n,8,"0o")},ed={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>Qs(n,0,10,t),stringify:ta.stringifyNumber},td={identify:n=>$n(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>Qs(n,2,16,t),stringify:n=>na(n,16,"0x")};Cn.int=ed;Cn.intHex=td;Cn.intOct=Zf});var ra=x(sa=>{"use strict";var nd=De(),sd=An(),rd=qe(),od=bt(),id=Ys(),Zs=zs(),er=Xs(),ad=[nd.map,rd.seq,od.string,sd.nullTag,id.boolTag,er.intOct,er.int,er.intHex,Zs.floatNaN,Zs.floatExp,Zs.float];sa.schema=ad});var aa=x(ia=>{"use strict";var cd=R(),ld=De(),ud=qe();function oa(n){return typeof n=="bigint"||Number.isInteger(n)}var En=({value:n})=>JSON.stringify(n),fd=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:En},{identify:n=>n==null,createNode:()=>new cd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:En},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:En},{identify:oa,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>oa(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:En}],dd={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},pd=[ld.map,ud.seq].concat(fd,dd);ia.schema=pd});var nr=x(ca=>{"use strict";var St=Ut("buffer"),tr=R(),md=mt(),hd={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof St.Buffer=="function")return St.Buffer.from(n,"base64");if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),s=new Uint8Array(t.length);for(let r=0;r<t.length;++r)s[r]=t.charCodeAt(r);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},s,r,o){if(!t)return"";let i=t,a;if(typeof St.Buffer=="function")a=i instanceof St.Buffer?i.toString("base64"):St.Buffer.from(i.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<i.length;++l)c+=String.fromCharCode(i[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=tr.Scalar.BLOCK_LITERAL),e!==tr.Scalar.QUOTE_DOUBLE){let c=Math.max(s.options.lineWidth-s.indent.length,s.options.minContentWidth),l=Math.ceil(a.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=a.substr(d,c);a=f.join(e===tr.Scalar.BLOCK_LITERAL?`
53
+ `:" ")}return md.stringifyString({comment:n,type:e,value:a},s,r,o)}};ca.binary=hd});var In=x(_n=>{"use strict";var Nn=I(),sr=ue(),gd=R(),yd=pe();function la(n,e){if(Nn.isSeq(n))for(let t=0;t<n.items.length;++t){let s=n.items[t];if(!Nn.isPair(s)){if(Nn.isMap(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");let r=s.items[0]||new sr.Pair(new gd.Scalar(null));if(s.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${s.commentBefore}
54
+ ${r.key.commentBefore}`:s.commentBefore),s.comment){let o=r.value??r.key;o.comment=o.comment?`${s.comment}
55
+ ${o.comment}`:s.comment}s=r}n.items[t]=Nn.isPair(s)?s:new sr.Pair(s)}}else e("Expected a sequence for this tag");return n}function ua(n,e,t){let{replacer:s}=t,r=new yd.YAMLSeq(n);r.tag="tag:yaml.org,2002:pairs";let o=0;if(e&&Symbol.iterator in Object(e))for(let i of e){typeof s=="function"&&(i=s.call(e,String(o++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let l=Object.keys(i);if(l.length===1)a=l[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=i;r.items.push(sr.createPair(a,c,t))}return r}var wd={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:la,createNode:ua};_n.createPairs=ua;_n.pairs=wd;_n.resolvePairs=la});var ir=x(or=>{"use strict";var fa=I(),rr=ie(),vt=de(),bd=pe(),da=In(),ke=class n extends bd.YAMLSeq{constructor(){super(),this.add=vt.YAMLMap.prototype.add.bind(this),this.delete=vt.YAMLMap.prototype.delete.bind(this),this.get=vt.YAMLMap.prototype.get.bind(this),this.has=vt.YAMLMap.prototype.has.bind(this),this.set=vt.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let s=new Map;t?.onCreate&&t.onCreate(s);for(let r of this.items){let o,i;if(fa.isPair(r)?(o=rr.toJS(r.key,"",t),i=rr.toJS(r.value,o,t)):o=rr.toJS(r,"",t),s.has(o))throw new Error("Ordered maps must not include duplicate keys");s.set(o,i)}return s}static from(e,t,s){let r=da.createPairs(e,t,s),o=new this;return o.items=r.items,o}};ke.tag="tag:yaml.org,2002:omap";var Sd={collection:"seq",identify:n=>n instanceof Map,nodeClass:ke,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=da.resolvePairs(n,e),s=[];for(let{key:r}of t.items)fa.isScalar(r)&&(s.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):s.push(r.value));return Object.assign(new ke,t)},createNode:(n,e,t)=>ke.from(n,e,t)};or.YAMLOMap=ke;or.omap=Sd});var ya=x(ar=>{"use strict";var pa=R();function ma({value:n,source:e},t){return e&&(n?ha:ga).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var ha={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new pa.Scalar(!0),stringify:ma},ga={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new pa.Scalar(!1),stringify:ma};ar.falseTag=ga;ar.trueTag=ha});var wa=x(On=>{"use strict";var vd=R(),cr=Ue(),kd={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:cr.stringifyNumber},Td={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():cr.stringifyNumber(n)}},Ad={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new vd.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let s=n.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:cr.stringifyNumber};On.float=Ad;On.floatExp=Td;On.floatNaN=kd});var Sa=x(Tt=>{"use strict";var ba=Ue(),kt=n=>typeof n=="bigint"||Number.isInteger(n);function Pn(n,e,t,{intAsBigInt:s}){let r=n[0];if((r==="-"||r==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),s){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let i=BigInt(n);return r==="-"?BigInt(-1)*i:i}let o=parseInt(n,t);return r==="-"?-1*o:o}function lr(n,e,t){let{value:s}=n;if(kt(s)){let r=s.toString(e);return s<0?"-"+t+r.substr(1):t+r}return ba.stringifyNumber(n)}var xd={identify:kt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>Pn(n,2,2,t),stringify:n=>lr(n,2,"0b")},$d={identify:kt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>Pn(n,1,8,t),stringify:n=>lr(n,8,"0")},Cd={identify:kt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>Pn(n,0,10,t),stringify:ba.stringifyNumber},Ed={identify:kt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>Pn(n,2,16,t),stringify:n=>lr(n,16,"0x")};Tt.int=Cd;Tt.intBin=xd;Tt.intHex=Ed;Tt.intOct=$d});var fr=x(ur=>{"use strict";var Rn=I(),Mn=ue(),Ln=de(),Te=class n extends Ln.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;Rn.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Mn.Pair(e.key,null):t=new Mn.Pair(e,null),Ln.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let s=Ln.findPair(this.items,e);return!t&&Rn.isPair(s)?Rn.isScalar(s.key)?s.key.value:s.key:s}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let s=Ln.findPair(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new Mn.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,s);throw new Error("Set items must all have null values")}static from(e,t,s){let{replacer:r}=s,o=new this(e);if(t&&Symbol.iterator in Object(t))for(let i of t)typeof r=="function"&&(i=r.call(t,i,i)),o.items.push(Mn.createPair(i,null,s));return o}};Te.tag="tag:yaml.org,2002:set";var Nd={collection:"map",identify:n=>n instanceof Set,nodeClass:Te,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>Te.from(n,e,t),resolve(n,e){if(Rn.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new Te,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};ur.YAMLSet=Te;ur.set=Nd});var pr=x(Dn=>{"use strict";var _d=Ue();function dr(n,e){let t=n[0],s=t==="-"||t==="+"?n.substring(1):n,r=i=>e?BigInt(i):Number(i),o=s.replace(/_/g,"").split(":").reduce((i,a)=>i*r(60)+r(a),r(0));return t==="-"?r(-1)*o:o}function va(n){let{value:e}=n,t=i=>i;if(typeof e=="bigint")t=i=>BigInt(i);else if(isNaN(e)||!isFinite(e))return _d.stringifyNumber(n);let s="";e<0&&(s="-",e*=t(-1));let r=t(60),o=[e%r];return e<60?o.unshift(0):(e=(e-o[0])/r,o.unshift(e%r),e>=60&&(e=(e-o[0])/r,o.unshift(e))),s+o.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Id={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>dr(n,t),stringify:va},Od={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>dr(n,!1),stringify:va},ka={identify:n=>n 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(n){let e=n.match(ka.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,s,r,o,i,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,s-1,r,o||0,i||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=dr(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Dn.floatTime=Od;Dn.intTime=Id;Dn.timestamp=ka});var xa=x(Aa=>{"use strict";var Pd=De(),Md=An(),Ld=qe(),Rd=bt(),Dd=nr(),Ta=ya(),mr=wa(),qn=Sa(),qd=gn(),Ud=ir(),jd=In(),Fd=fr(),hr=pr(),Bd=[Pd.map,Ld.seq,Rd.string,Md.nullTag,Ta.trueTag,Ta.falseTag,qn.intBin,qn.intOct,qn.int,qn.intHex,mr.floatNaN,mr.floatExp,mr.float,Dd.binary,qd.merge,Ud.omap,jd.pairs,Fd.set,hr.intTime,hr.floatTime,hr.timestamp];Aa.schema=Bd});var La=x(wr=>{"use strict";var Na=De(),Kd=An(),_a=qe(),Gd=bt(),Jd=Ys(),gr=zs(),yr=Xs(),Wd=ra(),Hd=aa(),Ia=nr(),At=gn(),Oa=ir(),Pa=In(),$a=xa(),Ma=fr(),Un=pr(),Ca=new Map([["core",Wd.schema],["failsafe",[Na.map,_a.seq,Gd.string]],["json",Hd.schema],["yaml11",$a.schema],["yaml-1.1",$a.schema]]),Ea={binary:Ia.binary,bool:Jd.boolTag,float:gr.float,floatExp:gr.floatExp,floatNaN:gr.floatNaN,floatTime:Un.floatTime,int:yr.int,intHex:yr.intHex,intOct:yr.intOct,intTime:Un.intTime,map:Na.map,merge:At.merge,null:Kd.nullTag,omap:Oa.omap,pairs:Pa.pairs,seq:_a.seq,set:Ma.set,timestamp:Un.timestamp},Yd={"tag:yaml.org,2002:binary":Ia.binary,"tag:yaml.org,2002:merge":At.merge,"tag:yaml.org,2002:omap":Oa.omap,"tag:yaml.org,2002:pairs":Pa.pairs,"tag:yaml.org,2002:set":Ma.set,"tag:yaml.org,2002:timestamp":Un.timestamp};function Vd(n,e,t){let s=Ca.get(e);if(s&&!n)return t&&!s.includes(At.merge)?s.concat(At.merge):s.slice();let r=s;if(!r)if(Array.isArray(n))r=[];else{let o=Array.from(Ca.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${o} or define customTags array`)}if(Array.isArray(n))for(let o of n)r=r.concat(o);else typeof n=="function"&&(r=n(r.slice()));return t&&(r=r.concat(At.merge)),r.reduce((o,i)=>{let a=typeof i=="string"?Ea[i]:i;if(!a){let c=JSON.stringify(i),l=Object.keys(Ea).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return o.includes(a)||o.push(a),o},[])}wr.coreKnownTags=Yd;wr.getTags=Vd});var vr=x(Ra=>{"use strict";var br=I(),zd=De(),Qd=qe(),Xd=bt(),jn=La(),Zd=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0,Sr=class n{constructor({compat:e,customTags:t,merge:s,resolveKnownTags:r,schema:o,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(e)?jn.getTags(e,"compat"):e?jn.getTags(null,e):null,this.name=typeof o=="string"&&o||"core",this.knownTags=r?jn.coreKnownTags:{},this.tags=jn.getTags(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,br.MAP,{value:zd.map}),Object.defineProperty(this,br.SCALAR,{value:Xd.string}),Object.defineProperty(this,br.SEQ,{value:Qd.seq}),this.sortMapEntries=typeof i=="function"?i:i===!0?Zd:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Ra.Schema=Sr});var qa=x(Da=>{"use strict";var ep=I(),kr=ht(),xt=ft();function tp(n,e){let t=[],s=e.directives===!0;if(e.directives!==!1&&n.directives){let c=n.directives.toString(n);c?(t.push(c),s=!0):n.directives.docStart&&(s=!0)}s&&t.push("---");let r=kr.createStringifyContext(n,e),{commentString:o}=r.options;if(n.commentBefore){t.length!==1&&t.unshift("");let c=o(n.commentBefore);t.unshift(xt.indentComment(c,""))}let i=!1,a=null;if(n.contents){if(ep.isNode(n.contents)){if(n.contents.spaceBefore&&s&&t.push(""),n.contents.commentBefore){let f=o(n.contents.commentBefore);t.push(xt.indentComment(f,""))}r.forceBlockIndent=!!n.comment,a=n.contents.comment}let c=a?void 0:()=>i=!0,l=kr.stringify(n.contents,r,()=>a=null,c);a&&(l+=xt.lineComment(l,"",o(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(kr.stringify(n.contents,r));if(n.directives?.docEnd)if(n.comment){let c=o(n.comment);c.includes(`
56
+ `)?(t.push("..."),t.push(xt.indentComment(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=n.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&t[t.length-1]!==""&&t.push(""),t.push(xt.indentComment(o(c),"")))}return t.join(`
57
+ `)+`
58
+ `}Da.stringifyDocument=tp});var $t=x(Ua=>{"use strict";var np=lt(),je=an(),J=I(),sp=ue(),rp=ie(),op=vr(),ip=qa(),Tr=nn(),ap=Cs(),cp=ut(),Ar=$s(),xr=class n{constructor(e,t,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,J.NODE_TYPE,{value:J.DOC});let r=null;typeof t=="function"||Array.isArray(t)?r=t:s===void 0&&t&&(s=t,t=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},s);this.options=o;let{version:i}=o;s?._directives?(this.directives=s._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Ar.Directives({version:i}),this.setSchema(i,s),this.contents=e===void 0?null:this.createNode(e,r,s)}clone(){let e=Object.create(n.prototype,{[J.NODE_TYPE]:{value:J.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=J.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Fe(this.contents)&&this.contents.add(e)}addIn(e,t){Fe(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let s=Tr.anchorNames(this);e.anchor=!t||s.has(t)?Tr.findNewAnchor(t||"a",s):t}return new np.Alias(e.anchor)}createNode(e,t,s){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){let h=y=>typeof y=="number"||y instanceof String||y instanceof Number,b=t.filter(h).map(String);b.length>0&&(t=t.concat(b)),r=t}else s===void 0&&t&&(s=t,t=void 0);let{aliasDuplicateObjects:o,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:l,tag:f}=s??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=Tr.createNodeAnchors(this,i||"a"),g={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},m=cp.createNode(e,f,g);return a&&J.isCollection(m)&&(m.flow=!0),d(),m}createPair(e,t,s={}){let r=this.createNode(e,null,s),o=this.createNode(t,null,s);return new sp.Pair(r,o)}delete(e){return Fe(this.contents)?this.contents.delete(e):!1}deleteIn(e){return je.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Fe(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return J.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return je.isEmptyPath(e)?!t&&J.isScalar(this.contents)?this.contents.value:this.contents:J.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return J.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return je.isEmptyPath(e)?this.contents!==void 0:J.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=je.collectionFromPath(this.schema,[e],t):Fe(this.contents)&&this.contents.set(e,t)}setIn(e,t){je.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=je.collectionFromPath(this.schema,Array.from(e),t):Fe(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let s;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ar.Directives({version:"1.1"}),s={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Ar.Directives({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(s)this.schema=new op.Schema(Object.assign(s,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:s,maxAliasCount:r,onAnchor:o,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=rp.toJS(this.contents,t??"",a);if(typeof o=="function")for(let{count:l,res:f}of a.anchors.values())o(f,l);return typeof i=="function"?ap.applyReviver(i,{"":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 new 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 new Error(`"indent" option must be a positive integer, not ${t}`)}return ip.stringifyDocument(this,e)}};function Fe(n){if(J.isCollection(n))return!0;throw new Error("Expected a YAML collection as document contents")}Ua.Document=xr});var Nt=x(Et=>{"use strict";var Ct=class extends Error{constructor(e,t,s,r){super(),this.name=e,this.code=s,this.message=r,this.pos=t}},$r=class extends Ct{constructor(e,t,s){super("YAMLParseError",e,t,s)}},Cr=class extends Ct{constructor(e,t,s){super("YAMLWarning",e,t,s)}},lp=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:s,col:r}=t.linePos[0];t.message+=` at line ${s}, column ${r}`;let o=r-1,i=n.substring(e.lineStarts[s-1],e.lineStarts[s]).replace(/[\n\r]+$/,"");if(o>=60&&i.length>80){let a=Math.min(o-39,i.length-79);i="\u2026"+i.substring(a),o-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),s>1&&/^ *$/.test(i.substring(0,o))){let a=n.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
59
+ `),i=a+i}if(/[^ ]/.test(i)){let a=1,c=t.linePos[1];c?.line===s&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-o)));let l=" ".repeat(o)+"^".repeat(a);t.message+=`:
60
+
61
+ ${i}
62
+ ${l}
63
+ `}};Et.YAMLError=Ct;Et.YAMLParseError=$r;Et.YAMLWarning=Cr;Et.prettifyError=lp});var _t=x(ja=>{"use strict";function up(n,{flow:e,indicator:t,next:s,offset:r,onError:o,parentIndent:i,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",p=!1,g=!1,m=null,h=null,b=null,y=null,S=null,w=null,k=null;for(let A of n)switch(g&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&o(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),m&&(l&&A.type!=="comment"&&A.type!=="newline"&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),A.type){case"space":!e&&(t!=="doc-start"||s?.type!=="flow-collection")&&A.source.includes(" ")&&(m=A),f=!0;break;case"comment":{f||o(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let $=A.source.substring(1)||" ";u?u+=d+$:u=$,d="",l=!1;break}case"newline":l?u?u+=A.source:(!w||t!=="seq-item-ind")&&(c=!0):d+=A.source,l=!0,p=!0,(h||b)&&(y=A),f=!0;break;case"anchor":h&&o(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&o(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=A,k??(k=A.offset),l=!1,f=!1,g=!0;break;case"tag":{b&&o(A,"MULTIPLE_TAGS","A node can have at most one tag"),b=A,k??(k=A.offset),l=!1,f=!1,g=!0;break}case t:(h||b)&&o(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),w&&o(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),w=A,l=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){S&&o(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),S=A,l=!1,f=!1;break}default:o(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),l=!1,f=!1}let v=n[n.length-1],T=v?v.offset+v.source.length:r;return g&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!=="")&&o(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=i||s?.type==="block-map"||s?.type==="block-seq")&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:w,spaceBefore:c,comment:u,hasNewline:p,anchor:h,tag:b,newlineAfterProp:y,end:T,start:k??T}}ja.resolveProps=up});var Fn=x(Fa=>{"use strict";function Er(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
64
+ `))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Er(e.key)||Er(e.value))return!0}return!1;default:return!0}}Fa.containsNewline=Er});var Nr=x(Ba=>{"use strict";var fp=Fn();function dp(n,e,t){if(e?.type==="flow-collection"){let s=e.end[0];s.indent===n&&(s.source==="]"||s.source==="}")&&fp.containsNewline(e)&&t(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ba.flowIndentCheck=dp});var _r=x(Ga=>{"use strict";var Ka=I();function pp(n,e,t){let{uniqueKeys:s}=n.options;if(s===!1)return!1;let r=typeof s=="function"?s:(o,i)=>o===i||Ka.isScalar(o)&&Ka.isScalar(i)&&o.value===i.value;return e.some(o=>r(o.key,t))}Ga.mapIncludes=pp});var za=x(Va=>{"use strict";var Ja=ue(),mp=de(),Wa=_t(),hp=Fn(),Ha=Nr(),gp=_r(),Ya="All mapping items must start at the same column";function yp({composeNode:n,composeEmptyNode:e},t,s,r,o){let i=o?.nodeClass??mp.YAMLMap,a=new i(t.schema);t.atRoot&&(t.atRoot=!1);let c=s.offset,l=null;for(let f of s.items){let{start:u,key:d,sep:p,value:g}=f,m=Wa.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:r,parentIndent:s.indent,startOnNewline:!0}),h=!m.found;if(h){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==s.indent&&r(c,"BAD_INDENT",Ya)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
65
+ `+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||hp.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==s.indent&&r(c,"BAD_INDENT",Ya);t.atKey=!0;let b=m.end,y=d?n(t,d,m,r):e(t,b,u,null,m,r);t.schema.compat&&Ha.flowIndentCheck(s.indent,d,r),t.atKey=!1,gp.mapIncludes(t,a.items,y)&&r(b,"DUPLICATE_KEY","Map keys must be unique");let S=Wa.resolveProps(p??[],{indicator:"map-value-ind",next:g,offset:y.range[2],onError:r,parentIndent:s.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=S.end,S.found){h&&(g?.type==="block-map"&&!S.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<S.found.offset-1024&&r(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let w=g?n(t,g,S,r):e(t,c,p,null,S,r);t.schema.compat&&Ha.flowIndentCheck(s.indent,g,r),c=w.range[2];let k=new Ja.Pair(y,w);t.options.keepSourceTokens&&(k.srcToken=f),a.items.push(k)}else{h&&r(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(y.comment?y.comment+=`
66
+ `+S.comment:y.comment=S.comment);let w=new Ja.Pair(y);t.options.keepSourceTokens&&(w.srcToken=f),a.items.push(w)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,c,l??c],a}Va.resolveBlockMap=yp});var Xa=x(Qa=>{"use strict";var wp=pe(),bp=_t(),Sp=Nr();function vp({composeNode:n,composeEmptyNode:e},t,s,r,o){let i=o?.nodeClass??wp.YAMLSeq,a=new i(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=s.offset,l=null;for(let{start:f,value:u}of s.items){let d=bp.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:s.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?n(t,u,d,r):e(t,d.end,f,null,d,r);t.schema.compat&&Sp.flowIndentCheck(s.indent,u,r),c=p.range[2],a.items.push(p)}return a.range=[s.offset,c,l??c],a}Qa.resolveBlockSeq=vp});var Be=x(Za=>{"use strict";function kp(n,e,t,s){let r="";if(n){let o=!1,i="";for(let a of n){let{source:c,type:l}=a;switch(l){case"space":o=!0;break;case"comment":{t&&!o&&s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=i+f:r=f,i="";break}case"newline":r&&(i+=c),o=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:r,offset:e}}Za.resolveEnd=kp});var sc=x(nc=>{"use strict";var Tp=I(),Ap=ue(),ec=de(),xp=pe(),$p=Be(),tc=_t(),Cp=Fn(),Ep=_r(),Ir="Block collections are not allowed within flow collections",Or=n=>n&&(n.type==="block-map"||n.type==="block-seq");function Np({composeNode:n,composeEmptyNode:e},t,s,r,o){let i=s.start.source==="{",a=i?"flow map":"flow sequence",c=o?.nodeClass??(i?ec.YAMLMap:xp.YAMLSeq),l=new c(t.schema);l.flow=!0;let f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=s.offset+s.start.source.length;for(let h=0;h<s.items.length;++h){let b=s.items[h],{start:y,key:S,sep:w,value:k}=b,v=tc.resolveProps(y,{flow:a,indicator:"explicit-key-ind",next:S??w?.[0],offset:u,onError:r,parentIndent:s.indent,startOnNewline:!1});if(!v.found){if(!v.anchor&&!v.tag&&!w&&!k){h===0&&v.comma?r(v.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<s.items.length-1&&r(v.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),v.comment&&(l.comment?l.comment+=`
67
+ `+v.comment:l.comment=v.comment),u=v.end;continue}!i&&t.options.strict&&Cp.containsNewline(S)&&r(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)v.comma&&r(v.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(v.comma||r(v.start,"MISSING_CHAR",`Missing , between ${a} items`),v.comment){let T="";e:for(let A of y)switch(A.type){case"comma":case"space":break;case"comment":T=A.source.substring(1);break e;default:break e}if(T){let A=l.items[l.items.length-1];Tp.isPair(A)&&(A=A.value??A.key),A.comment?A.comment+=`
68
+ `+T:A.comment=T,v.comment=v.comment.substring(T.length+1)}}if(!i&&!w&&!v.found){let T=k?n(t,k,v,r):e(t,v.end,w,null,v,r);l.items.push(T),u=T.range[2],Or(k)&&r(T.range,"BLOCK_IN_FLOW",Ir)}else{t.atKey=!0;let T=v.end,A=S?n(t,S,v,r):e(t,T,y,null,v,r);Or(S)&&r(A.range,"BLOCK_IN_FLOW",Ir),t.atKey=!1;let $=tc.resolveProps(w??[],{flow:a,indicator:"map-value-ind",next:k,offset:A.range[2],onError:r,parentIndent:s.indent,startOnNewline:!1});if($.found){if(!i&&!v.found&&t.options.strict){if(w)for(let E of w){if(E===$.found)break;if(E.type==="newline"){r(E,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}v.start<$.found.offset-1024&&r($.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?r(k,"MISSING_CHAR",`Missing space after : in ${a}`):r($.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let C=k?n(t,k,$,r):$.found?e(t,$.end,w,null,$,r):null;C?Or(k)&&r(C.range,"BLOCK_IN_FLOW",Ir):$.comment&&(A.comment?A.comment+=`
69
+ `+$.comment:A.comment=$.comment);let N=new Ap.Pair(A,C);if(t.options.keepSourceTokens&&(N.srcToken=b),i){let E=l;Ep.mapIncludes(t,E.items,A)&&r(T,"DUPLICATE_KEY","Map keys must be unique"),E.items.push(N)}else{let E=new ec.YAMLMap(t.schema);E.flow=!0,E.items.push(N);let D=(C??A).range;E.range=[A.range[0],D[1],D[2]],l.items.push(E)}u=C?C.range[2]:$.end}}let d=i?"}":"]",[p,...g]=s.end,m=u;if(p?.source===d)m=p.offset+p.source.length;else{let h=a[0].toUpperCase()+a.substring(1),b=f?`${h} must end with a ${d}`:`${h} in block collection must be sufficiently indented and end with a ${d}`;r(u,f?"MISSING_CHAR":"BAD_INDENT",b),p&&p.source.length!==1&&g.unshift(p)}if(g.length>0){let h=$p.resolveEnd(g,m,t.options.strict,r);h.comment&&(l.comment?l.comment+=`
70
+ `+h.comment:l.comment=h.comment),l.range=[s.offset,m,h.offset]}else l.range=[s.offset,m,m];return l}nc.resolveFlowCollection=Np});var oc=x(rc=>{"use strict";var _p=I(),Ip=R(),Op=de(),Pp=pe(),Mp=za(),Lp=Xa(),Rp=sc();function Pr(n,e,t,s,r,o){let i=t.type==="block-map"?Mp.resolveBlockMap(n,e,t,s,o):t.type==="block-seq"?Lp.resolveBlockSeq(n,e,t,s,o):Rp.resolveFlowCollection(n,e,t,s,o),a=i.constructor;return r==="!"||r===a.tagName?(i.tag=a.tagName,i):(r&&(i.tag=r),i)}function Dp(n,e,t,s,r){let o=s.tag,i=o?e.directives.tagName(o.source,d=>r(o,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=s,g=d&&o?d.offset>o.offset?d:o:d??o;g&&(!p||p.offset<g.offset)&&r(g,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!o||!i||i==="!"||i===Op.YAMLMap.tagName&&a==="map"||i===Pp.YAMLSeq.tagName&&a==="seq")return Pr(n,e,t,r,i);let c=e.schema.tags.find(d=>d.tag===i&&d.collection===a);if(!c){let d=e.schema.knownTags[i];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(o,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),Pr(n,e,t,r,i)}let l=Pr(n,e,t,r,i,c),f=c.resolve?.(l,d=>r(o,"TAG_RESOLVE_FAILED",d),e.options)??l,u=_p.isNode(f)?f:new Ip.Scalar(f);return u.range=l.range,u.tag=i,c?.format&&(u.format=c.format),u}rc.composeCollection=Dp});var Lr=x(ic=>{"use strict";var Mr=R();function qp(n,e,t){let s=e.offset,r=Up(e,n.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[s,s,s]};let o=r.mode===">"?Mr.Scalar.BLOCK_FOLDED:Mr.Scalar.BLOCK_LITERAL,i=e.source?jp(e.source):[],a=i.length;for(let m=i.length-1;m>=0;--m){let h=i[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=r.chomp==="+"&&i.length>0?`
71
+ `.repeat(Math.max(1,i.length-1)):"",h=s+r.length;return e.source&&(h+=e.source.length),{value:m,type:o,comment:r.comment,range:[s,h,h]}}let c=e.indent+r.indent,l=e.offset+r.length,f=0;for(let m=0;m<a;++m){let[h,b]=i[m];if(b===""||b==="\r")r.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&t(l+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=h.length),f=m,c===0&&!n.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=h.length+b.length+1}for(let m=i.length-1;m>=a;--m)i[m][0].length>c&&(a=m+1);let u="",d="",p=!1;for(let m=0;m<f;++m)u+=i[m][0].slice(c)+`
72
+ `;for(let m=f;m<a;++m){let[h,b]=i[m];l+=h.length+b.length+1;let y=b[b.length-1]==="\r";if(y&&(b=b.slice(0,-1)),b&&h.length<c){let w=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(l-b.length-(y?2:1),"BAD_INDENT",w),h=""}o===Mr.Scalar.BLOCK_LITERAL?(u+=d+h.slice(c)+b,d=`
73
+ `):h.length>c||b[0]===" "?(d===" "?d=`
74
+ `:!p&&d===`
75
+ `&&(d=`
76
+
77
+ `),u+=d+h.slice(c)+b,d=`
78
+ `,p=!0):b===""?d===`
79
+ `?u+=`
80
+ `:d=`
81
+ `:(u+=d+b,d=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)u+=`
82
+ `+i[m][0].slice(c);u[u.length-1]!==`
83
+ `&&(u+=`
84
+ `);break;default:u+=`
85
+ `}let g=s+r.length+e.source.length;return{value:u,type:o,comment:r.comment,range:[s,g,g]}}function Up({offset:n,props:e},t,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],o=r[0],i=0,a="",c=-1;for(let d=1;d<r.length;++d){let p=r[d];if(!a&&(p==="-"||p==="+"))a=p;else{let g=Number(p);!i&&g?i=g:c===-1&&(c=n+d)}}c!==-1&&s(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let l=!1,f="",u=r.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&s(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":s(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let g=`Unexpected token in block scalar header: ${p.type}`;s(p,"UNEXPECTED_TOKEN",g);let m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:o,indent:i,chomp:a,comment:f,length:u}}function jp(n){let e=n.split(/\n( *)/),t=e[0],s=t.match(/^( *)/),o=[s?.[1]?[s[1],t.slice(s[1].length)]:["",t]];for(let i=1;i<e.length;i+=2)o.push([e[i],e[i+1]]);return o}ic.resolveBlockScalar=qp});var Dr=x(cc=>{"use strict";var Rr=R(),Fp=Be();function Bp(n,e,t){let{offset:s,type:r,source:o,end:i}=n,a,c,l=(d,p,g)=>t(s+d,p,g);switch(r){case"scalar":a=Rr.Scalar.PLAIN,c=Kp(o,l);break;case"single-quoted-scalar":a=Rr.Scalar.QUOTE_SINGLE,c=Gp(o,l);break;case"double-quoted-scalar":a=Rr.Scalar.QUOTE_DOUBLE,c=Jp(o,l);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[s,s+o.length,s+o.length]}}let f=s+o.length,u=Fp.resolveEnd(i,f,e,t);return{value:c,type:a,comment:u.comment,range:[s,f,u.offset]}}function Kp(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),ac(n)}function Gp(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),ac(n.slice(1,-1)).replace(/''/g,"'")}function ac(n){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
86
+ `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
87
+ `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(n);if(!s)return n;let r=s[1],o=" ",i=e.lastIndex;for(t.lastIndex=i;s=t.exec(n);)s[1]===""?o===`
88
+ `?r+=o:o=`
89
+ `:(r+=o+s[1],o=" "),i=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=i,s=a.exec(n),r+o+(s?.[1]??"")}function Jp(n,e){let t="";for(let s=1;s<n.length-1;++s){let r=n[s];if(!(r==="\r"&&n[s+1]===`
90
+ `))if(r===`
91
+ `){let{fold:o,offset:i}=Wp(n,s);t+=o,s=i}else if(r==="\\"){let o=n[++s],i=Hp[o];if(i)t+=i;else if(o===`
92
+ `)for(o=n[s+1];o===" "||o===" ";)o=n[++s+1];else if(o==="\r"&&n[s+1]===`
93
+ `)for(o=n[++s+1];o===" "||o===" ";)o=n[++s+1];else if(o==="x"||o==="u"||o==="U"){let a={x:2,u:4,U:8}[o];t+=Yp(n,s+1,a,e),s+=a}else{let a=n.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(r===" "||r===" "){let o=s,i=n[s+1];for(;i===" "||i===" ";)i=n[++s+1];i!==`
94
+ `&&!(i==="\r"&&n[s+2]===`
95
+ `)&&(t+=s>o?n.slice(o,s+1):r)}else t+=r}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function Wp(n,e){let t="",s=n[e+1];for(;(s===" "||s===" "||s===`
96
+ `||s==="\r")&&!(s==="\r"&&n[e+2]!==`
97
+ `);)s===`
98
+ `&&(t+=`
99
+ `),e+=1,s=n[e+1];return t||(t=" "),{fold:t,offset:e}}var Hp={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
100
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Yp(n,e,t,s){let r=n.substr(e,t),i=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;if(isNaN(i)){let a=n.substr(e-2,t+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(i)}cc.resolveFlowScalar=Bp});var fc=x(uc=>{"use strict";var Ae=I(),lc=R(),Vp=Lr(),zp=Dr();function Qp(n,e,t,s){let{value:r,type:o,comment:i,range:a}=e.type==="block-scalar"?Vp.resolveBlockScalar(n,e,s):zp.resolveFlowScalar(e,n.options.strict,s),c=t?n.directives.tagName(t.source,u=>s(t,"TAG_RESOLVE_FAILED",u)):null,l;n.options.stringKeys&&n.atKey?l=n.schema[Ae.SCALAR]:c?l=Xp(n.schema,r,c,t,s):e.type==="scalar"?l=Zp(n,r,e,s):l=n.schema[Ae.SCALAR];let f;try{let u=l.resolve(r,d=>s(t??e,"TAG_RESOLVE_FAILED",d),n.options);f=Ae.isScalar(u)?u:new lc.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);s(t??e,"TAG_RESOLVE_FAILED",d),f=new lc.Scalar(r)}return f.range=a,f.source=r,o&&(f.type=o),c&&(f.tag=c),l.format&&(f.format=l.format),i&&(f.comment=i),f}function Xp(n,e,t,s,r){if(t==="!")return n[Ae.SCALAR];let o=[];for(let a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(e))return a;let i=n.knownTags[t];return i&&!i.collection?(n.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[Ae.SCALAR])}function Zp({atKey:n,directives:e,schema:t},s,r,o){let i=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(s))||t[Ae.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(s))??t[Ae.SCALAR];if(i.tag!==a.tag){let c=e.tagString(i.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;o(r,"TAG_RESOLVE_FAILED",f,!0)}}return i}uc.composeScalar=Qp});var pc=x(dc=>{"use strict";function em(n,e,t){if(e){t??(t=e.length);for(let s=t-1;s>=0;--s){let r=e[s];switch(r.type){case"space":case"comment":case"newline":n-=r.source.length;continue}for(r=e[++s];r?.type==="space";)n+=r.source.length,r=e[++s];break}}return n}dc.emptyScalarPosition=em});var gc=x(Ur=>{"use strict";var tm=lt(),nm=I(),sm=oc(),mc=fc(),rm=Be(),om=pc(),im={composeNode:hc,composeEmptyNode:qr};function hc(n,e,t,s){let r=n.atKey,{spaceBefore:o,comment:i,anchor:a,tag:c}=t,l,f=!0;switch(e.type){case"alias":l=am(n,e,s),(a||c)&&s(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=mc.composeScalar(n,e,c,s),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=sm.composeCollection(im,n,e,t,s),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);s(e,"RESOURCE_EXHAUSTION",d)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;s(e,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=qr(n,e.offset,void 0,null,t,s)),a&&l.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&n.options.stringKeys&&(!nm.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&s(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(l.spaceBefore=!0),i&&(e.type==="scalar"&&e.source===""?l.comment=i:l.commentBefore=i),n.options.keepSourceTokens&&f&&(l.srcToken=e),l}function qr(n,e,t,s,{spaceBefore:r,comment:o,anchor:i,tag:a,end:c},l){let f={type:"scalar",offset:om.emptyScalarPosition(e,t,s),indent:-1,source:""},u=mc.composeScalar(n,f,a,l);return i&&(u.anchor=i.source.substring(1),u.anchor===""&&l(i,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),o&&(u.comment=o,u.range[2]=c),u}function am({options:n},{offset:e,source:t,end:s},r){let o=new tm.Alias(t.substring(1));o.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=e+t.length,a=rm.resolveEnd(s,i,n.strict,r);return o.range=[e,i,a.offset],a.comment&&(o.comment=a.comment),o}Ur.composeEmptyNode=qr;Ur.composeNode=hc});var bc=x(wc=>{"use strict";var cm=$t(),yc=gc(),lm=Be(),um=_t();function fm(n,e,{offset:t,start:s,value:r,end:o},i){let a=Object.assign({_directives:e},n),c=new cm.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=um.resolveProps(s,{indicator:"doc-start",next:r??o?.[0],offset:t,onError:i,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&i(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?yc.composeNode(l,r,f,i):yc.composeEmptyNode(l,f.end,s,null,f,i);let u=c.contents.range[2],d=lm.resolveEnd(o,u,!1,i);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}wc.composeDoc=fm});var Fr=x(kc=>{"use strict";var dm=Ut("process"),pm=$s(),mm=$t(),It=Nt(),Sc=I(),hm=bc(),gm=Be();function Ot(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function vc(n){let e="",t=!1,s=!1;for(let r=0;r<n.length;++r){let o=n[r];switch(o[0]){case"#":e+=(e===""?"":s?`
101
+
102
+ `:`
103
+ `)+(o.substring(1)||" "),t=!0,s=!1;break;case"%":n[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(s=!0),t=!1}}return{comment:e,afterEmptyLine:s}}var jr=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,s,r,o)=>{let i=Ot(t);o?this.warnings.push(new It.YAMLWarning(i,s,r)):this.errors.push(new It.YAMLParseError(i,s,r))},this.directives=new pm.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:s,afterEmptyLine:r}=vc(this.prelude);if(s){let o=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
+ ${s}`:s;else if(r||e.directives.docStart||!o)e.commentBefore=s;else if(Sc.isCollection(o)&&!o.flow&&o.items.length>0){let i=o.items[0];Sc.isPair(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${s}
105
+ ${a}`:s}else{let i=o.commentBefore;o.commentBefore=i?`${s}
106
+ ${i}`:s}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:vc(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,s=-1){for(let r of e)yield*this.next(r);yield*this.end(t,s)}*next(e){switch(dm.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,s,r)=>{let o=Ot(e);o[0]+=t,this.onError(o,"BAD_DIRECTIVE",s,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=hm.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,s=new It.YAMLParseError(Ot(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(s):this.doc.errors.push(s);break}case"doc-end":{if(!this.doc){let s="Unexpected doc-end without preceding document";this.errors.push(new It.YAMLParseError(Ot(e),"UNEXPECTED_TOKEN",s));break}this.doc.directives.docEnd=!0;let t=gm.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let s=this.doc.comment;this.doc.comment=s?`${s}
107
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new It.YAMLParseError(Ot(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 s=Object.assign({_directives:this.directives},this.options),r=new mm.Document(void 0,s);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}};kc.Composer=jr});var xc=x(Bn=>{"use strict";var ym=Lr(),wm=Dr(),bm=Nt(),Tc=mt();function Sm(n,e=!0,t){if(n){let s=(r,o,i)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,o,i);else throw new bm.YAMLParseError([a,a+1],o,i)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return wm.resolveFlowScalar(n,e,s);case"block-scalar":return ym.resolveBlockScalar({options:{strict:e}},n,s)}}return null}function vm(n,e){let{implicitKey:t=!1,indent:s,inFlow:r=!1,offset:o=-1,type:i="PLAIN"}=e,a=Tc.stringifyString({type:i,value:n},{implicitKey:t,indent:s>0?" ".repeat(s):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:s,source:`
108
+ `}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
109
+ `),f=a.substring(0,l),u=a.substring(l+1)+`
110
+ `,d=[{type:"block-scalar-header",offset:o,indent:s,source:f}];return Ac(d,c)||d.push({type:"newline",offset:-1,indent:s,source:`
111
+ `}),{type:"block-scalar",offset:o,indent:s,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:o,indent:s,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:s,source:a,end:c};default:return{type:"scalar",offset:o,indent:s,source:a,end:c}}}function km(n,e,t={}){let{afterKey:s=!1,implicitKey:r=!1,inFlow:o=!1,type:i}=t,a="indent"in n?n.indent:null;if(s&&typeof a=="number"&&(a+=2),!i)switch(n.type){case"single-quoted-scalar":i="QUOTE_SINGLE";break;case"double-quoted-scalar":i="QUOTE_DOUBLE";break;case"block-scalar":{let l=n.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:i="PLAIN"}let c=Tc.stringifyString({type:i,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Tm(n,c);break;case'"':Br(n,c,"double-quoted-scalar");break;case"'":Br(n,c,"single-quoted-scalar");break;default:Br(n,c,"scalar")}}function Tm(n,e){let t=e.indexOf(`
112
+ `),s=e.substring(0,t),r=e.substring(t+1)+`
113
+ `;if(n.type==="block-scalar"){let o=n.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=s,n.source=r}else{let{offset:o}=n,i="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:i,source:s}];Ac(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:i,source:`
114
+ `});for(let c of Object.keys(n))c!=="type"&&c!=="offset"&&delete n[c];Object.assign(n,{type:"block-scalar",indent:i,props:a,source:r})}}function Ac(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function Br(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let s=n.props.slice(1),r=e.length;n.props[0].type==="block-scalar-header"&&(r-=n.props[0].source.length);for(let o of s)o.offset+=r;delete n.props,Object.assign(n,{type:t,source:e,end:s});break}case"block-map":case"block-seq":{let r={type:"newline",offset:n.offset+e.length,indent:n.indent,source:`
115
+ `};delete n.items,Object.assign(n,{type:t,source:e,end:[r]});break}default:{let s="indent"in n?n.indent:-1,r="end"in n&&Array.isArray(n.end)?n.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(n))o!=="type"&&o!=="offset"&&delete n[o];Object.assign(n,{type:t,indent:s,source:e,end:r})}}}Bn.createScalarToken=vm;Bn.resolveAsScalar=Sm;Bn.setScalarValue=km});var Cc=x($c=>{"use strict";var Am=n=>"type"in n?Gn(n):Kn(n);function Gn(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=Gn(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=Kn(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=Kn(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=Kn(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function Kn({start:n,key:e,sep:t,value:s}){let r="";for(let o of n)r+=o.source;if(e&&(r+=Gn(e)),t)for(let o of t)r+=o.source;return s&&(r+=Gn(s)),r}$c.stringify=Am});var Ic=x(_c=>{"use strict";var Kr=Symbol("break visit"),xm=Symbol("skip children"),Ec=Symbol("remove item");function xe(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),Nc(Object.freeze([]),n,e)}xe.BREAK=Kr;xe.SKIP=xm;xe.REMOVE=Ec;xe.itemAtPath=(n,e)=>{let t=n;for(let[s,r]of e){let o=t?.[s];if(o&&"items"in o)t=o.items[r];else return}return t};xe.parentCollection=(n,e)=>{let t=xe.itemAtPath(n,e.slice(0,-1)),s=e[e.length-1][0],r=t?.[s];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Nc(n,e,t){let s=t(e,n);if(typeof s=="symbol")return s;for(let r of["key","value"]){let o=e[r];if(o&&"items"in o){for(let i=0;i<o.items.length;++i){let a=Nc(Object.freeze(n.concat([[r,i]])),o.items[i],t);if(typeof a=="number")i=a-1;else{if(a===Kr)return Kr;a===Ec&&(o.items.splice(i,1),i-=1)}}typeof s=="function"&&r==="key"&&(s=s(e,n))}}return typeof s=="function"?s(e,n):s}_c.visit=xe});var Jn=x(K=>{"use strict";var Gr=xc(),$m=Cc(),Cm=Ic(),Jr="\uFEFF",Wr="",Hr="",Yr="",Em=n=>!!n&&"items"in n,Nm=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar");function _m(n){switch(n){case Jr:return"<BOM>";case Wr:return"<DOC>";case Hr:return"<FLOW_END>";case Yr:return"<SCALAR>";default:return JSON.stringify(n)}}function Im(n){switch(n){case Jr:return"byte-order-mark";case Wr:return"doc-mode";case Hr:return"flow-error-end";case Yr:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
116
+ `:case`\r
117
+ `: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(n[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}K.createScalarToken=Gr.createScalarToken;K.resolveAsScalar=Gr.resolveAsScalar;K.setScalarValue=Gr.setScalarValue;K.stringify=$m.stringify;K.visit=Cm.visit;K.BOM=Jr;K.DOCUMENT=Wr;K.FLOW_END=Hr;K.SCALAR=Yr;K.isCollection=Em;K.isScalar=Nm;K.prettyToken=_m;K.tokenType=Im});var Qr=x(Pc=>{"use strict";var Pt=Jn();function Y(n){switch(n){case void 0:case" ":case`
118
+ `:case"\r":case" ":return!0;default:return!1}}var Oc=new Set("0123456789ABCDEFabcdef"),Om=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Wn=new Set(",[]{}"),Pm=new Set(` ,[]{}
119
+ \r `),Vr=n=>!n||Pm.has(n),zr=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 s=this.next??"stream";for(;s&&(t||this.hasChars(1));)s=yield*this.parseNext(s)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
120
+ `?!0:t==="\r"?this.buffer[e+1]===`
121
+ `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let s=0;for(;t===" ";)t=this.buffer[++s+e];if(t==="\r"){let r=this.buffer[s+e+1];if(r===`
122
+ `||!r&&!this.atEnd)return e+s+1}return t===`
123
+ `||s>=this.indentNext||!t&&!this.atEnd?e+s:-1}if(t==="-"||t==="."){let s=this.buffer.substr(e,3);if((s==="---"||s==="...")&&Y(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
124
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Pt.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,s=e.indexOf("#");for(;s!==-1;){let o=e[s-1];if(o===" "||o===" "){t=s-1;break}else s=e.indexOf("#",s+1)}for(;;){let o=e[t-1];if(o===" "||o===" ")t-=1;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Pt.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&Y(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Y(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Y(t)){let s=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=s,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Vr),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,s=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=s=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((s!==-1&&s<this.indentNext&&r[0]!=="#"||s===0&&(r.startsWith("---")||r.startsWith("..."))&&Y(r[3]))&&!(s===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Pt.FLOW_END,yield*this.parseLineStart();let o=0;for(;r[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),r[o]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Vr),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Y(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let o=0;for(;this.buffer[t-1-o]==="\\";)o+=1;if(o%2===0)break;t=this.buffer.indexOf('"',t+1)}let s=this.buffer.substring(0,t),r=s.indexOf(`
125
+ `,this.pos);if(r!==-1){for(;r!==-1;){let o=this.continueScalar(r+1);if(o===-1)break;r=s.indexOf(`
126
+ `,o)}r!==-1&&(t=r-(s[r-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Y(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,s;e:for(let o=this.pos;s=this.buffer[o];++o)switch(s){case" ":t+=1;break;case`
127
+ `:e=o,t=0;break;case"\r":{let i=this.buffer[o+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`
128
+ `)break}default:break e}if(!s&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(e+1);if(o===-1)break;e=this.buffer.indexOf(`
129
+ `,o)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(s=this.buffer[r];s===" ";)s=this.buffer[++r];if(s===" "){for(;s===" "||s===" "||s==="\r"||s===`
130
+ `;)s=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let o=e-1,i=this.buffer[o];i==="\r"&&(i=this.buffer[--o]);let a=o;for(;i===" ";)i=this.buffer[--o];if(i===`
131
+ `&&o>=this.pos&&o+1+t>a)e=o;else break}while(!0);return yield Pt.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,s=this.pos-1,r;for(;r=this.buffer[++s];)if(r===":"){let o=this.buffer[s+1];if(Y(o)||e&&Wn.has(o))break;t=s}else if(Y(r)){let o=this.buffer[s+1];if(r==="\r"&&(o===`
132
+ `?(s+=1,r=`
133
+ `,o=this.buffer[s+1]):t=s),o==="#"||e&&Wn.has(o))break;if(r===`
134
+ `){let i=this.continueScalar(s+1);if(i===-1)break;s=Math.max(s,i-2)}}else{if(e&&Wn.has(r))break;t=s}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Pt.SCALAR,yield*this.pushToIndex(t+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 s=this.buffer.slice(this.pos,e);return s?(yield s,this.pos+=s.length,s.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Vr))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(Y(t)||e&&Wn.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Y(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Om.has(t))t=this.buffer[++e];else if(t==="%"&&Oc.has(this.buffer[e+1])&&Oc.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===`
135
+ `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
136
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,s;do s=this.buffer[++t];while(s===" "||e&&s===" ");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,s=this.buffer[t];for(;!e(s);)s=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};Pc.Lexer=zr});var Zr=x(Mc=>{"use strict";var Xr=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,s=this.lineStarts.length;for(;t<s;){let o=t+s>>1;this.lineStarts[o]<e?t=o+1:s=o}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}}}};Mc.LineCounter=Xr});var to=x(Uc=>{"use strict";var Mm=Ut("process"),Lc=Jn(),Lm=Qr();function me(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}function Rc(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function qc(n){switch(n?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Hn(n){switch(n.type){case"document":return n.start;case"block-map":{let e=n.items[n.items.length-1];return e.sep??e.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}function Ke(n){if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}function Dc(n){if(n.start.type==="flow-seq-start")for(let e of n.items)e.sep&&!e.value&&!me(e.start,"explicit-key-ind")&&!me(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,qc(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var eo=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 Lm.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let s of this.lexer.lex(e,t))yield*this.next(s);t||(yield*this.end())}*next(e){if(this.source=e,Mm.env.LOG_TOKENS&&console.log("|",Lc.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Lc.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){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}else{let s=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:s,source:e}),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 s=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in s?s.indent:0:t.type==="flow-collection"&&s.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Dc(t),s.type){case"document":s.value=t;break;case"block-scalar":s.props.push(t);break;case"block-map":{let r=s.items[s.items.length-1];if(r.value){s.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=s.items[s.items.length-1];r.value?s.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{let r=s.items[s.items.length-1];!r||r.value?s.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((s.type==="document"||s.type==="block-map"||s.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Rc(r.start)===-1&&(t.indent===0||r.start.every(o=>o.type!=="comment"||o.indent<t.indent))&&(s.type==="document"?s.end=r.start:s.items.push({start:r.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":{Rc(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);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=Hn(this.peek(2)),s=Ke(t),r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];let o={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}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 t=this.source.indexOf(`
137
+ `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
138
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.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 r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let s=!this.onKeyLine&&this.indent===e.indent,r=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(r&&t.sep&&!t.value){let i=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(o=t.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(o.push(this.sourceToken),e.items.push({start:o}),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?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(me(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(qc(t.key)&&!me(t.sep,"newline")){let i=Ke(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(me(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let i=Ke(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:o,key:null,sep:[this.sourceToken]}):me(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 i=this.flowScalar(this.type);r||t.value?(e.items.push({start:o,key:i,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(i):(Object.assign(t,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!t.explicitKey&&t.sep&&!me(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 s&&e.items.push({start:o});this.stack.push(i);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 s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.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 r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.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||me(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let s;do yield*this.pop(),s=this.peek(1);while(s?.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 r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let s=this.startBlockValue(e);s?this.stack.push(s):(yield*this.pop(),yield*this.step())}else{let s=this.peek(2);if(s.type==="block-map"&&(this.type==="map-value-ind"&&s.indent===e.indent||this.type==="newline"&&!s.items[s.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&s.type!=="flow-collection"){let r=Hn(s),o=Ke(r);Dc(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:o,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
139
+ `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
140
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Hn(e),s=Ke(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Hn(e),s=Ke(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.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())}}};Uc.Parser=eo});var Gc=x(Lt=>{"use strict";var jc=Fr(),Rm=$t(),Mt=Nt(),Dm=Us(),qm=I(),Um=Zr(),Fc=to();function Bc(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new Um.LineCounter||null,prettyErrors:e}}function jm(n,e={}){let{lineCounter:t,prettyErrors:s}=Bc(e),r=new Fc.Parser(t?.addNewLine),o=new jc.Composer(e),i=Array.from(o.compose(r.parse(n)));if(s&&t)for(let a of i)a.errors.forEach(Mt.prettifyError(n,t)),a.warnings.forEach(Mt.prettifyError(n,t));return i.length>0?i:Object.assign([],{empty:!0},o.streamInfo())}function Kc(n,e={}){let{lineCounter:t,prettyErrors:s}=Bc(e),r=new Fc.Parser(t?.addNewLine),o=new jc.Composer(e),i=null;for(let a of o.compose(r.parse(n),!0,n.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Mt.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(i.errors.forEach(Mt.prettifyError(n,t)),i.warnings.forEach(Mt.prettifyError(n,t))),i}function Fm(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=Kc(n,t);if(!r)return null;if(r.warnings.forEach(o=>Dm.warn(r.options.logLevel,o)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:s},t))}function Bm(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(n===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return qm.isDocument(n)&&!s?n.toString(t):new Rm.Document(n,s,t).toString(t)}Lt.parse=Fm;Lt.parseAllDocuments=jm;Lt.parseDocument=Kc;Lt.stringify=Bm});var so=x(O=>{"use strict";var Km=Fr(),Gm=$t(),Jm=vr(),no=Nt(),Wm=lt(),he=I(),Hm=ue(),Ym=R(),Vm=de(),zm=pe(),Qm=Jn(),Xm=Qr(),Zm=Zr(),eh=to(),Yn=Gc(),Jc=ot();O.Composer=Km.Composer;O.Document=Gm.Document;O.Schema=Jm.Schema;O.YAMLError=no.YAMLError;O.YAMLParseError=no.YAMLParseError;O.YAMLWarning=no.YAMLWarning;O.Alias=Wm.Alias;O.isAlias=he.isAlias;O.isCollection=he.isCollection;O.isDocument=he.isDocument;O.isMap=he.isMap;O.isNode=he.isNode;O.isPair=he.isPair;O.isScalar=he.isScalar;O.isSeq=he.isSeq;O.Pair=Hm.Pair;O.Scalar=Ym.Scalar;O.YAMLMap=Vm.YAMLMap;O.YAMLSeq=zm.YAMLSeq;O.CST=Qm;O.Lexer=Xm.Lexer;O.LineCounter=Zm.LineCounter;O.Parser=eh.Parser;O.parse=Yn.parse;O.parseAllDocuments=Yn.parseAllDocuments;O.parseDocument=Yn.parseDocument;O.stringify=Yn.stringify;O.visit=Jc.visit;O.visitAsync=Jc.visitAsync});import{styleText as Dt}from"node:util";import{EventEmitter as Ro}from"node:events";import Do from"node:fs/promises";import{styleText as ms}from"node:util";import tu from"node:fs/promises";import Ft from"node:path";import fs from"node:os";import W from"node:path";import{fileURLToPath as Xl}from"node:url";var Zl=Xl(import.meta.url),Ee=W.dirname(W.dirname(Zl)),we=W.join(fs.homedir(),".config","plain-agent"),Ze=W.join(fs.homedir(),".cache","plain-agent"),eu=W.join(fs.homedir(),".local","share","plain-agent"),ds=W.join(eu,"usage.jsonl"),jt=W.join(Ze,"trusted-config-hashes"),q=".plain-agent",Ne=W.join(q,"memory"),et=W.join(q,"tmp"),_e=W.join(q,"claude-code-plugins"),ps=W.join(q,"messages.json"),ko=process.env.USER||"unknown";async function P(n){try{return await n()}catch(e){return e instanceof Error?e:new Error(`Non-Error thrown: ${e}`)}}function Ie(n){try{return n()}catch(e){return e instanceof Error?e:new Error(`Non-Error thrown: ${e}`)}}var tt="compact_context";function To(){let n=async()=>{throw new Error("Not implemented")};return{def:{name:tt,description:"Discard prior messages and reload task state from a memory file.",inputSchema:{type:"object",properties:{memoryPath:{type:"string",description:`Path to the memory file under ${Ne}/.`},reason:{type:"string",description:"The reason for compacting the context."}},required:["memoryPath","reason"]}},get impl(){return n},injectImpl(t){n=t}}}async function Ao(n){return await P(async()=>{let e=Ft.resolve(n.memoryPath),t=Ft.resolve(Ne),s=Ft.relative(t,e);if(s.startsWith("..")||Ft.isAbsolute(s))return new Error(`Access denied: memoryPath must be within ${Ne}`);let r=await tu.readFile(e,{encoding:"utf-8"});return["Context compacted. Prior conversation has been discarded.",`Reason: ${n.reason}`,`Memory file: ${n.memoryPath}`,"","Resume the task using the memory file contents below.","",r].join(`
141
+ `)})}function xo(n,e,t){let s=e.find(i=>i.toolName===tt);if(!s)return!1;let r=t.find(i=>i.toolUseId===s.toolUseId);if(!r||r.isError)return!1;let o=n.getMessageAt(0);return o?(n.setMessages([o]),n.appendMessages([{role:"user",content:r.content}]),!0):!1}function $o({callModel:n,stateManager:e,toolDefs:t,toolExecutor:s,agentEventEmitter:r,toolUseApprover:o,subagentManager:i,pauseSignal:a}){let c=nu({stateManager:e,toolExecutor:s,subagentManager:i,toolUseApprover:o});async function l(u){a.reset(),o.resetApprovalCount(),await c.handle(u),await f(),r.emit("turnEnd")}async function f(){let u=0,d=5;for(;;){if(a.isPaused()){a.reset();break}let p=await n({messages:e.getMessages(),tools:t,onPartialMessageContent:$=>{r.emit("partialMessageContent",$)}});if(p instanceof Error){r.emit("error",p);break}let{message:g,providerTokenUsage:m}=p;if(e.appendMessages([g]),m&&r.emit("providerTokenUsage",m),g.content.at(-1)?.type==="thinking"){if(u+=1,u>d)break;e.appendMessages([{role:"user",content:[{type:"text",text:"System: Continue"}]}]),console.error(ms("yellow",`
142
+ Model is thinking. Sending "System: Continue" (Loop: ${u}/${d})`));continue}let b=g.content.filter($=>$.type==="tool_use");if(b.length===0)break;let y=s.validateBatch(b);if(!y.isValid){e.appendMessages([{role:"user",content:y.toolResults}]),y.errorMessage&&console.error(ms("yellow",y.errorMessage));continue}let S=b.map(o.isAllowedToolUse);if(S.some($=>$.action==="deny")){let $=b.map((C,N)=>{let E=S[N],D=E.action==="deny"?`Tool call rejected. ${E.reason||""}`.trim():"Tool call rejected due to other denied tool calls";return{type:"tool_result",toolUseId:C.toolUseId,toolName:C.toolName,content:[{type:"text",text:D}],isError:!0}});e.appendMessages([{role:"user",content:$}]);continue}if(!S.every($=>$.action==="allow")){r.emit("toolUseRequest");break}let v=await s.executeBatch(b);if(!v.success){e.appendMessages([{role:"user",content:v.errors},{role:"user",content:[{type:"text",text:v.errorMessage}]}]),console.error(ms("yellow",v.errorMessage));continue}let T=v.results;if(xo(e,b,T))continue;let A=i.processToolResults(b,T,e.getMessages());e.setMessages(A.messages),A.newMessage?e.appendMessages([A.newMessage]):e.appendMessages([{role:"user",content:T}])}}return{handleUserInput:l}}function nu(n){let{stateManager:e,toolExecutor:t,subagentManager:s,toolUseApprover:r}=n;function o(l){return e.getMessageAt(-1)?.content.some(u=>u.type==="tool_use")?"toolApproval":l.length===1&&l[0].type==="text"&&l[0].text.toLowerCase()==="/resume"?"resume":"text"}async function i(l){let f=e.getMessageAt(-1);if(!f)return;let u=f.content.filter(p=>p.type==="tool_use");if(l.length===1&&l[0].type==="text"&&l[0].text.toLocaleLowerCase().match(/^(yes|y|y)$/i)){if(l[0].text.match(/^(YES|Y)$/))for(let h of u)r.allowToolUse(h);let p=await t.executeBatch(u);if(!p.success){e.appendMessages([{role:"user",content:p.errors}]);return}let g=p.results;if(xo(e,u,g))return;let m=s.processToolResults(u,g,e.getMessages());e.setMessages(m.messages),m.newMessage?e.appendMessages([m.newMessage]):e.appendMessages([{role:"user",content:g}])}else{let p=u.map(g=>({type:"tool_result",toolUseId:g.toolUseId,toolName:g.toolName,content:[{type:"text",text:"Tool call rejected"}],isError:!0}));e.appendMessages([{role:"user",content:p},{role:"user",content:l}])}}async function a(){}async function c(l){e.appendMessages([{role:"user",content:l}])}return{async handle(l){switch(o(l)){case"toolApproval":await i(l);break;case"resume":await a();break;case"text":await c(l);break}}}}function Co(n,e){let t=[...n];return{getMessages:()=>[...t],getMessageAt:s=>t.at(s),appendMessages:s=>{t=[...t,...s],e.onMessagesAppended(s)},setMessages:s=>{t=[...s]}}}function su(n){if(n===void 0)return;if(typeof n!="object"||n===null)throw new TypeError("CostConfig must be an object");let e=n;if(typeof e.currency!="string")throw new TypeError("CostConfig.currency must be a string");if(typeof e.unit!="string")throw new TypeError("CostConfig.unit must be a string");if(typeof e.costs!="object"||e.costs===null)throw new TypeError("CostConfig.costs must be an object");for(let[t,s]of Object.entries(e.costs))if(typeof s!="number")throw new TypeError(`CostConfig.costs["${t}"] must be a number, got ${typeof s}`)}function No(n){su(n);let e=[];function t(i){if(typeof i!="object"||i===null)throw new TypeError("usage must be a non-null object");e.push(i)}function s(){return Eo(e)}function r(){let i=Eo(e);return ru(i,n)}function o(){return e.length>0}return Object.freeze({recordUsage:t,getAggregatedUsage:s,calculateCost:r,hasUsage:o})}function Eo(n){let e={};for(let t of n)_o(t,[],e);return e}function _o(n,e,t){for(let[s,r]of Object.entries(n)){let o=[...e,s],i=o.join(".");typeof r=="number"?t[i]=(t[i]||0)+r:typeof r=="object"&&r!==null&&!Array.isArray(r)&&_o(r,o,t)}}function ru(n,e){let t={},s=0;for(let[r,o]of Object.entries(n)){if(t[r]=Object.freeze({tokens:o,cost:void 0}),!e?.costs?.[r])continue;let i=e.costs[r],a=ou(e.unit);if(typeof i!="number")throw new TypeError(`config.costs["${r}"] must be a number, got ${typeof i}`);let c=o*i/a;t[r]=Object.freeze({tokens:o,cost:c}),s+=c}return Object.freeze({currency:e?.currency??"USD",unit:e?.unit??"1M",breakdown:t,totalCost:e?.costs?s:void 0})}function ou(n){if(n==="1M")return 1e6;if(n==="1K")return 1e3;throw new Error(`Unknown cost unit: "${n}"`)}import iu from"node:fs/promises";import Kt from"node:path";function Io({username:n,modelName:e,sessionId:t,today:s,tmuxSessionId:r,workingDir:o,projectMetadataDir:i,agentRoles:a,skills:c}){let l=Array.from(a.entries()).map(([u,d])=>{let p=d.description.length>100?`${d.description.substring(0,100)}...`:d.description;return`- ${u}: ${p}`}).join(`
143
+ `);return`
144
+ # Communication Style
145
+
146
+ - Respond in the user's language.
147
+ - Address the user by their name, rather than "user".
148
+ - Use emojis sparingly to highlight key points.
149
+
150
+ # Memory Files
151
+
152
+ - Create/Update memory files after creating/updating a plan, completing milestones, encountering issues, or making decisions.
153
+ - Update existing task memory when continuing the same task.
154
+ - Write the memory content in the user's language.
155
+ - Ensure self-containment: The file must be standalone. A reader should fully understand the task context, logic and progress without any other references.
156
+
157
+ Memory files should include:
158
+ - Task overview: What the task is, why it's being done, requirements and constraints
159
+ - Context: Relevant documentation, source files, commands, and resources referenced
160
+ - Progress tracking: Completed milestones with evidence, current status, and next steps
161
+ - Decision records: Important decisions made, alternatives considered, and rationale
162
+ - Findings and learnings: Key discoveries, challenges encountered, and solutions applied
163
+ - Future considerations: Known limitations, potential improvements, and follow-up items
164
+
165
+ # Tools
166
+
167
+ Call multiple tools at once when they don't depend on each other's results.
168
+
169
+ ## exec_command
170
+
171
+ - Use relative paths.
172
+ - Avoid bash -c unless pipes (|) or redirection (>, <) are required.
173
+
174
+ Examples:
175
+ - List directories or find files: fd [".", "./", "--max-depth", "3", "--type", "d", "--hidden"]
176
+ - Search for strings: rg ["--heading", "--line-number", "pattern", "./"]
177
+ - Read specific line ranges (max 200 lines): sed ["-n", "1,200p", "file.txt"]
178
+ - Manage GitHub issues and PRs:
179
+ Get PR details: gh ["pr", "view", "123", "--json", "title,body,url"]
180
+ Get PR comment: gh ["api", "--method", "GET", "repos/<owner>/<repo>/pulls/comments/<id>", "--jq", "{user: .user.login, path: .path, line: .line, body: .body}"]
181
+
182
+ ## tmux_command
183
+
184
+ - Only use when the user explicitly requests it.
185
+ - Create a new session with the given tmux session id.
186
+ - Use relative paths.
187
+
188
+ Examples:
189
+ - Start session: new-session ["-d", "-s", "<tmux-session-id>"]
190
+ - Detect window number to send keys: list-windows ["-t", "<tmux-session-id>"]
191
+ - Get output of window before sending keys: capture-pane ["-p", "-t", "<tmux-session-id>:<window>"]
192
+ - Send key to session: send-keys ["-t", "<tmux-session-id>:<window>", "echo hello", "Enter"]
193
+ - Delete line: send-keys ["-t", "<tmux-session-id>:<window>", "C-a", "C-k"]
194
+
195
+ # Project Rules and Skills
196
+
197
+ Discover and apply project-specific rules and reusable skills.
198
+
199
+ ## AGENTS.md (falling back to CLAUDE.md if not found): Project-specific rules, conventions, and commands.
200
+
201
+ Find: fd ["^(AGENTS|CLAUDE)\\.md$", "./", "--hidden", "--max-depth", "5"]
202
+ Read from the project root to the directory you're working in: ./AGENTS.md \u2192 dir/AGENTS.md \u2192 dir/subdir/AGENTS.md
203
+ Apply rules when working in that directory
204
+
205
+ ## SKILL.md: Reusable workflows with specialized knowledge
206
+
207
+ If skill matches task: read full file and apply the workflow
208
+
209
+ ${c.map(u=>{let d=u.description.length>100?`${u.description.substring(0,100)}...`:u.description;return`- ${u.filePath}
210
+ ${d}`}).join(`
211
+ `)}
212
+
213
+ # Environment
214
+
215
+ - User name: ${n}
216
+ - Your model name: ${e}
217
+ - Current working directory: ${o}
218
+ - Today's date: ${s}
219
+ - Session id: ${t}
220
+ - Tmux session id: ${r}
221
+ - Memory file path: ${i}/memory/${t}--<kebab-case-title>.md
222
+
223
+ Available subagents:
224
+ ${l}
225
+ - custom:<role-name>: Use this for ad-hoc roles not listed above (e.g., custom:explore, custom:plan).
226
+ `.trim()}var Bt=`# Environment Constraints
227
+
228
+ - Use memory file to manage todo list.
229
+ - Subagents cannot run in parallel. Switch to them one at a time.
230
+ - Use AGENTS.md instead when CLAUDE.md is absent.
231
+ - If instructed to use "haiku agent", "sonnet agent", or "opus agent", use "worker" instead.`;var Oe="switch_to_main_agent";function Oo(){let n=async()=>{throw new Error("Not implemented")};return{def:{name:Oe,description:"Switch back to the main agent role and report the result.",inputSchema:{type:"object",properties:{memoryPath:{type:"string",description:"Path to the memory file containing the result of the subagent's task."}},required:["memoryPath"]}},get impl(){return n},injectImpl(t){n=t}}}function Po(n,e){let t=[],s=0;function r(l,f,u){if(t.length>0)return{success:!1,error:"Cannot call switch_to_subagent while already acting as a subagent."};let d=l.startsWith("custom:"),p=d?l.substring(7):l,g="";if(!d){let h=n.get(l);if(!h){let b=Array.from(n.keys()).sort().map(y=>` - ${y}`).join(`
232
+ `);return{success:!1,error:`Agent role "${l}" not found. Available agent roles:
233
+ ${b}
234
+
235
+ To use an ad-hoc role, prefix the name with "custom:" (e.g., "custom:researcher").`}}g=h.claudeOriginated?`${h.content}
236
+
237
+ ---
238
+
239
+ ${Bt}`:h.content}s++;let m=String(s).padStart(2,"0");return t.push({name:p,goal:f,switchMessageIndex:u}),e.onSubagentSwitched({name:p}),{success:!0,value:[`[SUBAGENT MODE ACTIVATED] You are now operating as the subagent "${p}".`,g?`Role: ${p}
240
+ ---
241
+ ${g}
242
+ ---`:`Role: ${p}`,`Your goal: ${f}`,`Memory file path format: ${q}/memory/<session-id>--${m}--${p.replace("/","-")}--<kebab-case-title>.md (Replace <kebab-case-title> with a short title describing your own goal)`,'When finished, call "switch_to_main_agent" with the memory file path. Start executing your goal now.'].join(`
243
+
244
+ `)}}async function o(l){if(t.length===0)return{success:!1,error:"Cannot call switch_to_main_agent from the main agent."};let f=Kt.resolve(l),u=Kt.resolve(q,"memory"),d=Kt.relative(u,f);if(d.startsWith("..")||Kt.isAbsolute(d))return{success:!1,error:`Access denied: memoryPath must be within ${q}/memory`};try{return{success:!0,memoryContent:await iu.readFile(f,{encoding:"utf-8"})}}catch(p){return{success:!1,error:`Failed to read memory file: ${p instanceof Error?p.message:String(p)}`}}}function i(l,f,u){let d=l.find(p=>p.toolName===Oe);if(d){let p=f.find(g=>g.toolUseId===d.toolUseId);return p?a(d,p,u):{messages:u,newMessage:null}}return{messages:u,newMessage:null}}function a(l,f,u){if(f.isError)return{messages:u,newMessage:null};let d=t.pop();if(!d)return{messages:u,newMessage:null};e.onSubagentSwitched(t.at(-1)??null);let p=u.slice(0,d.switchMessageIndex),g=f.content.map(b=>b.type==="text"?b.text:"").join(`
245
+
246
+ `),m=l.input,h={role:"user",content:[{type:"text",text:[`The subagent "${d.name}" has completed the task.`,`Goal: ${d.goal}`,`Memory file: ${m.memoryPath}`,`Result:
247
+ ${g}`].join(`
248
+
249
+ `)}]};return{messages:p,newMessage:h}}function c(){return t.length>0}return{switchToSubagent:r,switchToMainAgent:o,processToolResults:i,isSubagentActive:c}}function Mo(n,e={}){let{exclusiveToolNames:t=[]}=e;function s(a){let c=[];for(let f=0;f<a.length;f++){let u=a[f],d=n.get(u.toolName);if(!d){c.push({index:f,message:`Tool not found: ${u.toolName}`});continue}if(d.validateInput){let p=d.validateInput(u.input);p instanceof Error&&c.push({index:f,message:p.message})}}if(c.length>0)return{isValid:!1,errorMessage:c.map(f=>f.message).join("; "),toolResults:a.map((f,u)=>{let d=c.find(p=>p.index===u);return{type:"tool_result",toolUseId:f.toolUseId,toolName:f.toolName,content:[{type:"text",text:d?d.message:"Tool call rejected due to other tool validation error"}],isError:!0}})};let l=o(a);return l.isValid?{isValid:!0}:{isValid:!1,errorMessage:l.errorMessage,toolResults:a.map(f=>({type:"tool_result",toolUseId:f.toolUseId,toolName:f.toolName,content:[{type:"text",text:l.errorMessage}],isError:!0}))}}async function r(a){let c=s(a);if(!c.isValid)return{success:!1,errors:c.toolResults,errorMessage:c.errorMessage};let l=[];for(let f of a)l.push(await i(f));return{success:!0,results:l}}function o(a){let c=a.filter(l=>t.includes(l.toolName));return c.length>1?{isValid:!1,errorMessage:`System: ${c.map(f=>f.toolName).join(", ")} cannot be called together. Only one of these tools can be called at a time.`}:c.length===1&&a.length>1?{isValid:!1,errorMessage:`System: ${c[0].toolName} cannot be called with other tools. It must be called alone.`}:{isValid:!0}}async function i(a){let c=n.get(a.toolName);if(!c)return{type:"tool_result",toolUseId:a.toolUseId,toolName:a.toolName,content:[{type:"text",text:`Tool not found: ${a.toolName}`}],isError:!0};let l=await c.impl(a.input);return l instanceof Error?{type:"tool_result",toolUseId:a.toolUseId,toolName:a.toolName,content:[{type:"text",text:l.message}],isError:!0}:typeof l=="string"?{type:"tool_result",toolUseId:a.toolUseId,toolName:a.toolName,content:[{type:"text",text:l}]}:{type:"tool_result",toolUseId:a.toolUseId,toolName:a.toolName,content:l}}return{executeBatch:r,validateBatch:s}}var Gt="switch_to_subagent";function Lo(){let n=async()=>{throw new Error("Not implemented")};return{def:{name:Gt,description:"Switch to a subagent role within the same conversation, focusing on the specified goal. You inherit the current context.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Role or name of the subagent. Use 'custom:' prefix for ad-hoc roles."},goal:{type:"string",description:"The goal or task for the subagent to achieve."}},required:["name","goal"]}},get impl(){return n},injectImpl(t){n=t},maskApprovalInput:t=>{let{name:s}=t;return{name:s}}}}function qo({callModel:n,prompt:e,tools:t,toolUseApprover:s,agentRoles:r,modelCostConfig:o}){let i=new Ro,a=new Ro,c=No(o);a.on("providerTokenUsage",v=>{c.recordUsage(v)});let l=Co([{role:"system",content:[{type:"text",text:e}]}],{onMessagesAppended:v=>{let T=v.at(-1);T&&a.emit("message",T)}}),f=Po(r,{onSubagentSwitched:v=>{a.emit("subagentSwitched",v)}}),u=async v=>{let T=f.switchToSubagent(v.name,v.goal,l.getMessages().length-1);return T.success?T.value:new Error(T.error)},d=async v=>{let T=await f.switchToMainAgent(v.memoryPath);return T.success?T.memoryContent:new Error(T.error)},p=async v=>f.isSubagentActive()?new Error("compact_context cannot be used while running as a subagent. Call switch_to_main_agent to return to the main agent first."):await Ao(v),g=new Map;for(let v of t)v.def.name===Gt&&v.injectImpl&&v.injectImpl(u),v.def.name===Oe&&v.injectImpl&&v.injectImpl(d),v.def.name===tt&&v.injectImpl&&v.injectImpl(p),g.set(v.def.name,v);let m=t.map(({def:v})=>v),h=Mo(g,{exclusiveToolNames:[Gt,Oe]});async function b(){let v=ps;try{await Do.writeFile(v,JSON.stringify(l.getMessages(),null,2)),console.log(`Messages dumped to ${v}`)}catch(T){let A=T instanceof Error?T.message:String(T);console.error(`Error dumping messages: ${A}`)}}async function y(){let v=ps;try{let T=await Do.readFile(v,"utf-8"),A=JSON.parse(T);Array.isArray(A)?(l.setMessages([l.getMessageAt(0),...A.slice(1)]),console.log(`Messages loaded from ${v}`)):console.error("Error loading messages: Invalid format in file.")}catch(T){T instanceof Error&&console.error(`Error loading messages: ${T.message}`)}}let S=!1,k=$o({callModel:n,stateManager:l,toolDefs:m,toolExecutor:h,agentEventEmitter:a,toolUseApprover:s,subagentManager:f,pauseSignal:{isPaused:()=>S,reset:()=>{S=!1}}});return i.on("userInput",k.handleUserInput),{userEventEmitter:i,agentEventEmitter:a,agentCommands:{dumpMessages:b,loadMessages:y,getCostSummary:()=>c.calculateCost(),pauseAutoApprove:()=>{S=!0}}}}import{execFile as du}from"node:child_process";import Uo from"node:fs/promises";import jo from"node:path";import au from"node:crypto";import Wt from"node:fs/promises";import hs from"node:path";import cu from"node:readline";import{styleText as Jt}from"node:util";function nt(n){if(Array.isArray(n))return n.map(e=>nt(e));if(typeof n=="object"&&n!==null){if(Object.keys(n).length===1&&"$regex"in n&&typeof n.$regex=="string")return new RegExp(n.$regex);if(Object.keys(n).length===1&&"$env"in n&&typeof n.$env=="string"){let t=process.env[n.$env];if(t===void 0)throw new Error(`Environment variable '${n.$env}' is not defined`);return t}if(Object.keys(n).length===1&&"$env"in n&&typeof n.$env!="string")throw new Error(`The value of '$env' must be a string, got: ${typeof n.$env}`);if(Object.keys(n).length===1&&"$has"in n){let t=nt(n.$has);return s=>Array.isArray(s)?s.some(r=>typeof t=="string"?r===t:t instanceof RegExp?typeof r=="string"&&t.test(r):typeof t=="function"?t(r):!1):!1}let e={};for(let[t,s]of Object.entries(n))e[t]=nt(s);return e}return n}async function st(n={}){let{skipTrustCheck:e=!1,configFiles:t=[],skipUserConfig:s=!1}=n,r=[`${Ee}/config/config.predefined.json`];s||r.push(`${we}/config.json`,`${we}/config.local.json`,`${q}/config.json`,`${q}/config.local.json`),r.push(...t);let o=[],i={};for(let a of r){let c=await lu(hs.resolve(a),e);Object.keys(c).length&&o.push(a),i={model:c.model||i.model,models:[...c.models??[],...i.models??[]],platforms:[...c.platforms??[],...i.platforms??[]],autoApproval:{defaultAction:c.autoApproval?.defaultAction??i.autoApproval?.defaultAction,patterns:[...c.autoApproval?.patterns??[],...i.autoApproval?.patterns??[]],maxApprovals:c.autoApproval?.maxApprovals??i.autoApproval?.maxApprovals},sandbox:c.sandbox??i.sandbox,tools:{askWeb:c.tools?.askWeb?{...i.tools?.askWeb??{},...c.tools.askWeb}:i.tools?.askWeb,askURL:c.tools?.askURL?{...i.tools?.askURL??{},...c.tools.askURL}:i.tools?.askWeb},mcpServers:{...i.mcpServers??{},...c.mcpServers??{}},notifyCmd:c.notifyCmd??i.notifyCmd,claudeCodePlugins:[...i.claudeCodePlugins??[],...c.claudeCodePlugins??[]],voiceInput:c.voiceInput?{...i.voiceInput??{},...c.voiceInput}:i.voiceInput}}return{appConfig:i,loadedConfigPath:o}}async function lu(n,e=!1){let t;try{t=await Wt.readFile(n,"utf-8")}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return{};throw o}let s=au.createHash("sha256").update(t).digest("hex");if(!(e||await uu(s))){if(!process.stdout.isTTY)return console.warn(Jt("yellow",`WARNING: Config file found at '${n}' but cannot ask for approval without a TTY. Skipping.`)),{};let o=cu.createInterface({input:process.stdin,output:process.stdout});if((await new Promise(a=>{console.log(Jt("blue",`
250
+ Found a config file at ${n}`)),o.question(Jt("yellow","Do you want to load this file? (y/N) "),c=>{o.close(),a(c)})})).toLowerCase()!=="y")return console.log(Jt("yellow","Skipping local config file.")),{};await fu(s)}try{let o=t.replace(/^ *\/\/.+$/gm,""),i=JSON.parse(o);return nt(i)}catch(o){throw new Error(`Failed to parse JSON config at ${n}`,{cause:o})}}async function uu(n){try{return await Wt.access(hs.join(jt,n)),!0}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return!1;throw e}}async function fu(n){await Wt.mkdir(jt,{recursive:!0}),await Wt.writeFile(hs.join(jt,n),"")}function gs(n){if(!n)return[];let e=[];for(let t of n){let s=Bo(t.source);if(!s){console.warn(`Invalid source URL: ${t.source}`);continue}for(let r of t.plugins){let o;if(r.only)try{o=new RegExp(r.only)}catch(i){console.warn(`Invalid regex pattern "${r.only}" for plugin "${r.name}":`,i instanceof Error?i.message:String(i))}e.push({name:r.name,path:jo.join(_e,s,r.path),only:o})}}return e}async function Fo(){let{appConfig:n}=await st({skipTrustCheck:!0}),e=n.claudeCodePlugins??[];if(e.length===0){console.log("No plugins configured.");return}let t=0,s=0,r=0,o=[],i=[];await Uo.mkdir(_e,{recursive:!0});for(let a of e){let c=Bo(a.source);if(!c){console.error(`\u274C Invalid source URL: ${a.source}`),r++;continue}let l=jo.join(_e,c);if(await Uo.access(l).then(()=>!0).catch(()=>!1)){console.log(`\u23ED\uFE0F Skipping ${a.source} \u2192 ${l}: already installed`),i.push(l),s++;continue}console.log(`\u{1F4E5} Installing ${a.source}...`);try{await new Promise((u,d)=>{du("git",["clone","--depth","1",a.source,l],p=>{p?d(p):u(void 0)})}),console.log(`\u2705 Installed to ${l}`),o.push(l),t++}catch(u){console.error(`\u274C Failed to install: ${u instanceof Error?u.message:String(u)}`),r++}}if(console.log(`
251
+ \u{1F4CA} Summary: ${t} installed, ${s} skipped, ${r} failed`),o.length>0){console.log(`
252
+ Installed:`);for(let a of o)console.log(` \u2022 ${a}`)}if(i.length>0){console.log(`
253
+ Skipped:`);for(let a of i)console.log(` \u2022 ${a}`)}}function Bo(n){let e=n.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);return e?e[1]:null}function Ko(n){let e=n.slice(2),t=e[0];if(["-h","--help","help"].includes(t))return{subcommand:{type:"help"}};if(!t||t.startsWith("-")){let s=[],r=null;for(let o=0;o<e.length;o++)e[o]==="-m"||e[o]==="--model"?e[o+1]&&(r=e[o+1],o++):(e[o]==="-c"||e[o]==="--config")&&e[o+1]&&(s.push(e[o+1]),o++);return{subcommand:{type:"interactive",config:s,model:r}}}if(t==="batch"){let s=e.slice(1),r=null,o=null,i=[];for(let a=0;a<s.length;a++)s[a]==="-m"||s[a]==="--model"?s[a+1]&&(o=s[a+1],a++):s[a]==="-c"||s[a]==="--config"?s[a+1]&&(i.push(s[a+1]),a++):!s[a].startsWith("-")&&!r&&(r=s[a]);return{subcommand:{type:"batch",task:r||"",config:i,model:o}}}if(t==="list-models")return{subcommand:{type:"list-models"}};if(t==="install-claude-code-plugins")return{subcommand:{type:"install-claude-code-plugins"}};if(t==="cost"){let s=e.slice(1),r=null,o=null;for(let i=0;i<s.length;i++)s[i]==="--from"?s[i+1]&&(r=s[i+1],i++):s[i]==="--to"&&s[i+1]&&(o=s[i+1],i++);return{subcommand:{type:"cost",from:r,to:o}}}return{subcommand:{type:"help"}}}function Go(n=0){console.log(`
254
+ Usage: plain [options]
255
+ plain batch [options] <task>
256
+ plain cost [--from YYYY-MM-DD] [--to YYYY-MM-DD]
257
+ plain list-models
258
+ plain install-claude-code-plugins
259
+
260
+ Options:
261
+ -m, --model <model+variant> Model to use
262
+ -h, --help Show this help message
263
+ -c, --config <file> Config file to load (repeatable)
264
+
265
+ Subcommands:
266
+ batch <task> Run in batch mode with the given task instruction.
267
+ Config files are NOT auto-loaded in batch mode;
268
+ use -c to specify config files explicitly.
269
+ cost Show aggregated token cost per day for a period.
270
+ Defaults to the first day of the current month
271
+ through today.
272
+ list-models List available models
273
+ install-claude-code-plugins Install Claude Code plugins
274
+
275
+ Examples:
276
+ plain -m gpt-5.4+thinking-medium
277
+ plain batch \\
278
+ -c ~/.config/plain-agent/config.local.json \\
279
+ -c .plain-agent/config.json \\
280
+ "Add tests for ..."
281
+ `),process.exit(n)}import{styleText as M}from"node:util";var rt=class{diff(e,t,s={}){let r;typeof s=="function"?(r=s,s={}):"callback"in s&&(r=s.callback);let o=this.castInput(e,s),i=this.castInput(t,s),a=this.removeEmpty(this.tokenize(o,s)),c=this.removeEmpty(this.tokenize(i,s));return this.diffWithOptionsObj(a,c,s,r)}diffWithOptionsObj(e,t,s,r){var o;let i=y=>{if(y=this.postProcess(y,s),r){setTimeout(function(){r(y)},0);return}else return y},a=t.length,c=e.length,l=1,f=a+c;s.maxEditLength!=null&&(f=Math.min(f,s.maxEditLength));let u=(o=s.timeout)!==null&&o!==void 0?o:1/0,d=Date.now()+u,p=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(p[0],t,e,0,s);if(p[0].oldPos+1>=c&&g+1>=a)return i(this.buildValues(p[0].lastComponent,t,e));let m=-1/0,h=1/0,b=()=>{for(let y=Math.max(m,-l);y<=Math.min(h,l);y+=2){let S,w=p[y-1],k=p[y+1];w&&(p[y-1]=void 0);let v=!1;if(k){let A=k.oldPos-y;v=k&&0<=A&&A<a}let T=w&&w.oldPos+1<c;if(!v&&!T){p[y]=void 0;continue}if(!T||v&&w.oldPos<k.oldPos?S=this.addToPath(k,!0,!1,0,s):S=this.addToPath(w,!1,!0,1,s),g=this.extractCommon(S,t,e,y,s),S.oldPos+1>=c&&g+1>=a)return i(this.buildValues(S.lastComponent,t,e))||!0;p[y]=S,S.oldPos+1>=c&&(h=Math.min(h,y-1)),g+1>=a&&(m=Math.max(m,y+1))}l++};if(r)(function y(){setTimeout(function(){if(l>f||Date.now()>d)return r(void 0);b()||y()},0)})();else for(;l<=f&&Date.now()<=d;){let y=b();if(y)return y}}addToPath(e,t,s,r,o){let i=e.lastComponent;return i&&!o.oneChangePerToken&&i.added===t&&i.removed===s?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:s,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:s,previousComponent:i}}}extractCommon(e,t,s,r,o){let i=t.length,a=s.length,c=e.oldPos,l=c-r,f=0;for(;l+1<i&&c+1<a&&this.equals(s[c+1],t[l+1],o);)l++,c++,f++,o.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return f&&!o.oneChangePerToken&&(e.lastComponent={count:f,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=c,l}equals(e,t,s){return s.comparator?s.comparator(e,t):e===t||!!s.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let s=0;s<e.length;s++)e[s]&&t.push(e[s]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join("")}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,s){let r=[],o;for(;e;)r.push(e),o=e.previousComponent,delete e.previousComponent,e=o;r.reverse();let i=r.length,a=0,c=0,l=0;for(;a<i;a++){let f=r[a];if(f.removed)f.value=this.join(s.slice(l,l+f.count)),l+=f.count;else{if(!f.added&&this.useLongestToken){let u=t.slice(c,c+f.count);u=u.map(function(d,p){let g=s[l+p];return g.length>d.length?g:d}),f.value=this.join(u)}else f.value=this.join(t.slice(c,c+f.count));c+=f.count,f.added||(l+=f.count)}}return r}};var ys=class extends rt{constructor(){super(...arguments),this.tokenize=mu}equals(e,t,s){return s.ignoreWhitespace?((!s.newlineIsToken||!e.includes(`
282
+ `))&&(e=e.trim()),(!s.newlineIsToken||!t.includes(`
283
+ `))&&(t=t.trim())):s.ignoreNewlineAtEof&&!s.newlineIsToken&&(e.endsWith(`
284
+ `)&&(e=e.slice(0,-1)),t.endsWith(`
285
+ `)&&(t=t.slice(0,-1))),super.equals(e,t,s)}},pu=new ys;function ws(n,e,t){return pu.diff(n,e,t)}function mu(n,e){e.stripTrailingCr&&(n=n.replace(/\r\n/g,`
286
+ `));let t=[],s=n.split(/(\n|\r\n)/);s[s.length-1]||s.pop();for(let r=0;r<s.length;r++){let o=s[r];r%2&&!e.newlineIsToken?t[t.length-1]+=o:t.push(o)}return t}var Jo={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function bs(n,e,t,s,r,o,i){let a;i?typeof i=="function"?a={callback:i}:a=i:a={},typeof a.context>"u"&&(a.context=4);let c=a.context;if(a.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(a.callback){let{callback:f}=a;ws(t,s,Object.assign(Object.assign({},a),{callback:u=>{let d=l(u);f(d)}}))}else return l(ws(t,s,a));function l(f){if(!f)return;f.push({value:"",lines:[]});function u(y){return y.map(function(S){return" "+S})}let d=[],p=0,g=0,m=[],h=1,b=1;for(let y=0;y<f.length;y++){let S=f[y],w=S.lines||hu(S.value);if(S.lines=w,S.added||S.removed){if(!p){let k=f[y-1];p=h,g=b,k&&(m=c>0?u(k.lines.slice(-c)):[],p-=m.length,g-=m.length)}for(let k of w)m.push((S.added?"+":"-")+k);S.added?b+=w.length:h+=w.length}else{if(p)if(w.length<=c*2&&y<f.length-2)for(let k of u(w))m.push(k);else{let k=Math.min(w.length,c);for(let T of u(w.slice(0,k)))m.push(T);let v={oldStart:p,oldLines:h-p+k,newStart:g,newLines:b-g+k,lines:m};d.push(v),p=0,g=0,m=[]}h+=w.length,b+=w.length}}for(let y of d)for(let S=0;S<y.lines.length;S++)y.lines[S].endsWith(`
287
+ `)?y.lines[S]=y.lines[S].slice(0,-1):(y.lines.splice(S+1,0,"\"),S++);return{oldFileName:n,newFileName:e,oldHeader:r,newHeader:o,hunks:d}}}function Ht(n,e){if(e||(e=Jo),Array.isArray(n)){if(n.length>1&&!e.includeFileHeaders)throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");return n.map(s=>Ht(s,e)).join(`
288
+ `)}let t=[];e.includeIndex&&n.oldFileName==n.newFileName&&t.push("Index: "+n.oldFileName),e.includeUnderline&&t.push("==================================================================="),e.includeFileHeaders&&(t.push("--- "+n.oldFileName+(typeof n.oldHeader>"u"?"":" "+n.oldHeader)),t.push("+++ "+n.newFileName+(typeof n.newHeader>"u"?"":" "+n.newHeader)));for(let s=0;s<n.hunks.length;s++){let r=n.hunks[s];r.oldLines===0&&(r.oldStart-=1),r.newLines===0&&(r.newStart-=1),t.push("@@ -"+r.oldStart+","+r.oldLines+" +"+r.newStart+","+r.newLines+" @@");for(let o of r.lines)t.push(o)}return t.join(`
289
+ `)+`
290
+ `}function Wo(n,e,t,s,r,o,i){if(typeof i=="function"&&(i={callback:i}),i?.callback){let{callback:a}=i;bs(n,e,t,s,r,o,Object.assign(Object.assign({},i),{callback:c=>{a(c?Ht(c,i.headerOptions):void 0)}}))}else{let a=bs(n,e,t,s,r,o,i);return a?Ht(a,i?.headerOptions):void 0}}function Ss(n,e,t,s,r,o){return Wo(n,n,e,t,s,r,o)}function hu(n){let e=n.endsWith(`
291
+ `),t=n.split(`
292
+ `).map(s=>s+`
293
+ `);return e?t.pop():t.push(t.pop().slice(0,-1)),t}var Ho=60;function Yo(n){if(!Array.isArray(n)||n.length===0)return`args: ${JSON.stringify(n??[])}`;if(!n.some(s=>typeof s=="string"&&(s.includes(`
294
+ `)||s.length>Ho)))return`args: ${JSON.stringify(n)}`;let t=["args:"];for(let s of n)if(typeof s=="string"&&(s.includes(`
295
+ `)||s.length>Ho)){t.push(" - |");for(let r of s.split(`
296
+ `))t.push(` ${r}`)}else t.push(` - ${JSON.stringify(s)}`);return t.join(`
297
+ `)}function gu(n){let{toolName:e,input:t}=n;if(e==="exec_command"){let o=t;return[`tool: ${e}`,`command: ${JSON.stringify(o.command)}`,Yo(o.args)].join(`
298
+ `)}if(e==="write_file"){let o=t;return[`tool: ${e}`,`filePath: ${o.filePath}`,`content:
299
+ ${o.content}`].join(`
300
+ `)}if(e==="patch_file"){let o=t,i=o.diff||"",a=[],c=Array.from(i.matchAll(/<<< [0-9a-z]{3} <<< SEARCH\n(.*?)\n=== [0-9a-z]{3} ===\n(.*?)\n?>>> [0-9a-z]{3} >>> REPLACE/gs));for(let f of c){let[u,d,p]=f;a.push({search:d,replace:p})}let l=a.map(({search:f,replace:u})=>`${Ss(o.filePath||"",f,u).replace(/^-.+$/gm,d=>M("red",d)).replace(/^\+.+$/gm,d=>M("green",d)).replace(/^@@.+$/gm,d=>M("gray",d)).replace(/^\$/gm,d=>M("gray",d))}
301
+ -------
302
+ ${u}`).join(`
303
+
304
+ `);return[`tool: ${e}`,`path: ${o.filePath}`,`diff:
305
+ ${l}`].join(`
306
+ `)}if(e==="tmux_command"){let o=t;return[`tool: ${e}`,`command: ${o.command}`,Yo(o.args)].join(`
307
+ `)}if(e==="switch_to_subagent"){let o=t;return[`tool: ${e}`,`name: ${o.name}`,`goal: ${o.goal}`].join(`
308
+ `)}if(e==="compact_context"){let o=t;return[`tool: ${e}`,`memoryPath: ${o.memoryPath}`,`reason: ${o.reason}`].join(`
309
+ `)}if(e==="switch_to_main_agent"){let o=t;return[`tool: ${e}`,`memoryPath: ${o.memoryPath}`].join(`
310
+ `)}if(e==="ask_web"){let o=t;return[`tool: ${e}`,`question: ${o.question}`].join(`
311
+ `)}if(e==="ask_url"){let o=t;return[`tool: ${e}`,`question: ${o.question}`].join(`
312
+ `)}let{provider:s,...r}=n;return JSON.stringify(r,null,2)}var Vo=1024;function yu(n){let{content:e,isError:t}=n,s=[];for(let o of e)switch(o.type){case"text":s.push(o.text);break;case"image":s.push(`data:${o.mimeType};base64,${o.data.slice(0,20)}...`);break;default:console.log(`Unsupported content part: ${JSON.stringify(o)}`);break}let r=s.join(`
313
+
314
+ `);return t?M("red",r):n.toolName==="exec_command"?r.replace(/(^<stdout>|<\/stdout>$)/gm,M("blue","$1")).replace(/(<truncated_output.+?>|<\/truncated_output>)/g,M("yellow","$1")).replace(/(^<stderr>|<\/stderr>$)/gm,M("magenta","$1")).replace(/(^<error>|<\/error>$)/gm,M("red","$1")):n.toolName==="tmux_command"?r.replace(/(^<stdout>|<\/stdout>$)/gm,M("blue","$1")).replace(/(^<stderr>|<\/stderr>$)/gm,M("magenta","$1")).replace(/(^<error>|<\/error>$)/gm,M("red","$1")).replace(/(^<tmux:.*?>|<\/tmux:.*?>$)/gm,M("green","$1")):r.length>Vo?[r.slice(0,Vo),M("yellow","... (Output truncated for display)"),`
315
+ `].join(""):r}function zo(n){let e=[],t=[];for(let[r,o]of Object.entries(n))typeof o=="number"?t.push(`${r}: ${o}`):typeof o=="string"?t.push(`${r}: ${o}`):o&&e.push(`(${r}) ${Object.entries(o).filter(([i])=>!["audio_tokens","accepted_prediction_tokens","rejected_prediction_tokens"].includes(i)).map(([i,a])=>`${i}: ${JSON.stringify(a)}`).join(", ")}`);let s=[`
316
+ ${t.join(", ")}`];return e.length&&s.push(e.join(" / ")),M("gray",s.join(`
317
+ `))}function Yt(n){if(!n||Object.keys(n.breakdown).length===0)return M("gray","No token usage recorded yet.");let e=[];n.totalCost!==void 0?e.push(M("bold",`
318
+ Total: ${n.totalCost.toFixed(4)} ${n.currency}`)):e.push(M("yellow","Total: N/A (no cost configuration)")),e.push(M("bold",`
319
+ Tokens:`));for(let[t,{tokens:s,cost:r}]of Object.entries(n.breakdown)){let o=`${t}: ${s.toLocaleString()}`;if(r!==void 0){let i=`${r.toFixed(4)} ${n.currency}`;e.push(` ${o.padEnd(30)} ${M("cyan",i)}`)}else e.push(` ${o.padEnd(30)} ${M("gray","N/A")}`)}return e.join(`
320
+ `)}function Qo(n){if(!(!n||Object.keys(n.breakdown).length===0))return{total:n.totalCost,currency:n.currency,unit:n.unit,breakdown:Object.fromEntries(Object.entries(n.breakdown).map(([e,{tokens:t,cost:s}])=>[e,{tokens:t,cost:s}]))}}function Xo(n){switch(n.role){case"assistant":{for(let e of n.content)e.type==="tool_use"&&(console.log(M("bold",`
321
+ Tool call:`)),console.log(gu(e)));break}case"user":{for(let e of n.content)switch(e.type){case"tool_result":{console.log(M("bold",`
322
+ Tool result:`)),console.log(yu(e));break}case"text":{console.log(M("bold",`
323
+ User:`));let t=e.text.replace(/^(<context.+?>|<\/context>)/gm,M("green","$1"));console.log(t);break}case"image":break;default:console.log(M("bold",`
324
+ Unknown Message Format:`)),console.log(JSON.stringify(e,null,2))}break}default:console.log(M("bold",`
325
+ Unknown Message Format:`)),console.log(JSON.stringify(n,null,2))}}import vs from"node:fs/promises";import wu from"node:path";var Zo=3072;async function Vt(n,e={}){let t=e.path??ds,s=`${JSON.stringify(n)}
326
+ `,r=Buffer.byteLength(s,"utf8");if(r>Zo)throw new Error(`Usage record exceeds ${Zo} bytes (${r}); refusing to write to keep appends atomic.`);await vs.mkdir(wu.dirname(t),{recursive:!0}),await vs.appendFile(t,s,{encoding:"utf8"})}async function ei(n={}){let e=n.path??ds,t;try{t=await vs.readFile(e,"utf8")}catch(i){if(i instanceof Error&&i.code==="ENOENT")return{records:[],skipped:[]};throw i}let s=[],r=[],o=t.split(`
327
+ `);for(let i=0;i<o.length;i++){let a=o[i];if(a.length!==0)try{let c=JSON.parse(a);if(!bu(c)){r.push({line:i+1,reason:"invalid shape"});continue}s.push(c)}catch(c){let l=c instanceof Error?c.message:String(c);r.push({line:i+1,reason:l})}}return{records:s,skipped:r}}function zt({sessionId:n,mode:e,modelName:t,workingDir:s,costSummary:r,now:o}){let i={};for(let[c,l]of Object.entries(r.breakdown))i[c]=l.tokens;return Object.keys(i).length===0?null:{timestamp:(o??new Date).toISOString(),sessionId:n,mode:e,modelName:t,workingDir:s,currency:r.currency,unit:r.unit,totalCost:r.totalCost===void 0?null:r.totalCost,tokens:i}}function bu(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.timestamp=="string"&&typeof e.sessionId=="string"&&(e.mode==="interactive"||e.mode==="batch")&&typeof e.modelName=="string"&&typeof e.workingDir=="string"&&typeof e.currency=="string"&&typeof e.unit=="string"&&(e.totalCost===null||typeof e.totalCost=="number")&&typeof e.tokens=="object"&&e.tokens!==null}async function ti({userEventEmitter:n,agentEventEmitter:e,agentCommands:t,task:s,sessionId:r,modelName:o,sandbox:i,startTime:a,onStop:c}){vu(e,{sessionId:r,modelName:o,sandbox:i}),n.emit("userInput",[{type:"text",text:s}]),await new Promise(l=>{e.on("turnEnd",async()=>{let f=t.getCostSummary();be({type:"session_end",timestamp:new Date().toISOString(),cost:Qo(f)});try{let u=zt({sessionId:r,mode:"batch",modelName:o,workingDir:process.cwd(),costSummary:f,now:a});u&&await Vt(u)}catch(u){let d=u instanceof Error?u.message:String(u);be({type:"error",error:{message:`failed to record usage: ${d}`},timestamp:new Date().toISOString()})}await c(),l()})}),process.exit(0)}function vu(n,{sessionId:e,modelName:t,sandbox:s}){be({type:"session_start",sessionId:e,modelName:t,sandbox:s,timestamp:new Date().toISOString()}),n.on("message",r=>{be({type:"message",message:r,timestamp:new Date().toISOString()})}),n.on("error",r=>{be({type:"error",error:{message:r.message,stack:r.stack},timestamp:new Date().toISOString()}),process.exit(1)}),n.on("subagentSwitched",r=>{be({type:"subagent_switched",subagent:r,timestamp:new Date().toISOString()})}),n.on("providerTokenUsage",r=>{be({type:"token_usage",usage:r,timestamp:new Date().toISOString()})})}function be(n){console.log(JSON.stringify(n))}import{styleText as ku}from"node:util";function Tu(n=new Date){let e=n.getFullYear(),t=n.getMonth(),s=new Date(e,t,1);return{from:ks(s),to:ks(n)}}function ks(n){let e=n.getFullYear(),t=`${n.getMonth()+1}`.padStart(2,"0"),s=`${n.getDate()}`.padStart(2,"0");return`${e}-${t}-${s}`}function Qt(n){let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(!e)throw new Error(`Invalid date: "${n}" (expected YYYY-MM-DD)`);let[,t,s,r]=e,o=Number(t),i=Number(s),a=Number(r),c=new Date(o,i-1,a);if(c.getFullYear()!==o||c.getMonth()!==i-1||c.getDate()!==a)throw new Error(`Invalid date: "${n}"`);return c}function Au(n,e){let t=Qt(e.from),s=Qt(e.to);if(t.getTime()>s.getTime())throw new Error(`"from" (${e.from}) must be on or before "to" (${e.to}).`);let r=new Map,o=0,i=0;for(let c of n){if(c.timestamp==null){i++;continue}let l=new Date(c.timestamp);if(Number.isNaN(l.getTime())){i++;continue}let f=ks(l);if(f<e.from||f>e.to){i++;continue}if(c.totalCost===null){o++;continue}if(!c.currency||typeof c.currency!="string"){i++;continue}let u=r.get(c.currency)??new Map;r.set(c.currency,u);let d=u.get(f);d?(d.totalCost+=c.totalCost,d.sessionCount+=1):u.set(f,{date:f,totalCost:c.totalCost,sessionCount:1})}let a=[];for(let[c,l]of r){let f=Array.from(l.values()).sort((p,g)=>p.date.localeCompare(g.date)),u=0,d=0;for(let p of f)u+=p.totalCost,d+=p.sessionCount;a.push({currency:c,daily:f,totalCost:u,sessionCount:d})}return a.sort((c,l)=>c.currency.localeCompare(l.currency)),{period:e,byCurrency:a,noPricingSessionCount:o,excludedOutOfRange:i,totalRecords:n.length}}function ni(n){return`${n} session${n===1?"":"s"}`}function xu(n,e={}){let r=e.color??!0?ku:(i,a)=>a,o=[];if(o.push(r("bold",`Period: ${n.period.from} to ${n.period.to}`)),n.byCurrency.length===0)return o.push(""),o.push(r("gray","No usage recorded in this period.")),n.noPricingSessionCount>0&&o.push(r("gray",`(${n.noPricingSessionCount} session(s) had no pricing configuration)`)),o.join(`
328
+ `);for(let i of n.byCurrency){o.push(""),o.push(r("bold",`Daily cost (${i.currency}):`));for(let a of i.daily)o.push(` ${a.date} ${si(a.totalCost)} ${i.currency} (${ni(a.sessionCount)})`);o.push(""),o.push(r("bold",`Total: ${si(i.totalCost)} ${i.currency} (${ni(i.sessionCount)})`))}return n.noPricingSessionCount>0&&(o.push(""),o.push(r("gray",`Note: ${n.noPricingSessionCount} session(s) had no pricing configuration and are excluded from totals.`))),o.join(`
329
+ `)}function si(n){return n.toFixed(4)}async function ri(n,e={}){let t,s;try{({from:t,to:s}=$u(n))}catch(a){return a instanceof Error?console.error(`Error: ${a.message}`):console.error("Error: invalid period arguments"),1}let{records:r,skipped:o}=await(e.readUsageRecords??ei)();if(o.length>0){let a=o.slice(0,3).map(l=>`line ${l.line}: ${l.reason}`).join(", "),c=o.length>3?`, and ${o.length-3} more`:"";console.error(`Warning: skipped ${o.length} malformed line(s) in usage log (${a}${c}).`)}let i=Au(r,{from:t,to:s});return console.log(xu(i)),o.length>0?1:0}function $u(n){let e=Tu(),t=n.from??e.from,s=n.to??e.to;return Qt(t),Qt(s),{from:t,to:s}}import yl from"node:readline";import{styleText as L}from"node:util";import{execFileSync as Zc}from"node:child_process";import{styleText as V}from"node:util";var Wc=vo(so(),1);import th from"node:crypto";import Ge from"node:fs/promises";import te from"node:path";async function $e(n){let e=[{dir:te.resolve(Ee,"config","agents.predefined"),idPrefix:""},{dir:te.resolve(we,"agents"),idPrefix:""},{dir:te.resolve(q,"agents"),idPrefix:""},{dir:te.resolve(process.cwd(),".claude","agents"),idPrefix:"claude:"}];if(n)for(let r of n)e.push({dir:te.join(r.path,"agents"),idPrefix:`claude/${r.name}:`,only:r.only});let t=(await Promise.all(e.map(async({dir:r,idPrefix:o,only:i})=>(await Hc(r).catch(c=>(c.code!=="ENOENT"&&console.warn(`Failed to list agent roles in ${r}:`,c),[]))).map(c=>({dir:r,file:c,idPrefix:o,only:i}))))).flat().filter(({file:r,only:o})=>!(o&&!o.test(r))),s=(await Promise.all(t.map(async({dir:r,file:o,idPrefix:i})=>{let a=te.join(r,o),c=await Ge.readFile(a,"utf-8").catch(f=>(console.warn(`Failed to read agent role file ${a}:`,f),null));if(c===null)return null;let l=Yc(o,c,a,i);if(l.import)try{l=await nh(l,o,a)}catch(f){return console.warn(`Failed to import remote role ${l.id}:`,f),null}return l}))).filter(r=>r);return new Map(s.map(r=>[r.id,r]))}async function nh(n,e,t){let s=n.import;if(!s)return n;let r=await sh(s).catch(i=>(console.warn(`Failed to fetch agent role from ${s}:`,i),null));if(!r)return n;let o=Yc(e,r,t);return{...o,...n,content:`${o.content}
330
+
331
+ ---
332
+
333
+ ${n.content}`.trim(),description:n.description||o.description||""}}async function sh(n){let e=th.createHash("sha256").update(n).digest("hex"),t=te.join(Ze,"agents"),s=te.join(t,e),r=await Ge.readFile(s,"utf-8").catch(()=>null);if(r!==null)return r;let o=await rh(n);return Ge.mkdir(t,{recursive:!0}).then(()=>Ge.writeFile(s,o,"utf-8")).catch(i=>{console.warn(`Failed to write cache for ${n}:`,i)}),o}async function rh(n){let e=n.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\/([^/]+)\/(.+)$/);if(e){let[,s,r,o,i]=e,a=`repos/${s}/${r}/contents/${i}?ref=${o}`;try{let{execFileSync:c}=await import("node:child_process");return c("gh",["api","-H","Accept: application/vnd.github.v3.raw",a],{encoding:"utf-8"})}catch(c){throw new Error(`Failed to fetch from GitHub via gh CLI: ${c}`)}}let t=await fetch(n);if(!t.ok)throw new Error(`Failed to fetch agent role from ${n}: ${t.status} ${t.statusText}`);return t.text()}async function Hc(n,e=n){let t=await Ge.readdir(n,{withFileTypes:!0}),s=[];for(let r of t){let o=te.join(n,r.name),i=r.isDirectory(),a=r.isFile();if(r.isSymbolicLink()){let c=await Ge.stat(o).catch(()=>null);if(!c)continue;i=c.isDirectory(),a=c.isFile()}i?s.push(...await Hc(o,e)):a&&r.name.endsWith(".md")&&s.push(te.relative(e,o))}return s}function Yc(n,e,t,s=""){let r=n.replace(/\.md$/,""),o=s+r,i=s.startsWith("claude"),a=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!a)return{id:o,description:"",content:e.trim(),filePath:t,claudeOriginated:i};let c;try{c=(0,Wc.parse)(a[1])}catch{return{id:o,description:oh(a[1],"description")??"",content:e.trim(),filePath:t,claudeOriginated:i}}let l=a[2].trim();return{id:o,description:c.description??"",content:l,filePath:t,claudeOriginated:i,import:c.import}}function oh(n,e){let t=new RegExp(`^${e}:\\s*(.*)$`,"m"),s=n.match(t);return s?s[1].trim():void 0}var Vc=vo(so(),1);import{execFileSync as ih}from"node:child_process";import ah from"node:crypto";import Je from"node:fs/promises";import G from"node:path";async function ge(n){let e=[{dir:G.resolve(Ee,"config","prompts.predefined"),idPrefix:""},{dir:G.resolve(we,"prompts"),idPrefix:""},{dir:G.resolve(q,"prompts"),idPrefix:""},{dir:G.resolve(process.cwd(),".claude","commands"),idPrefix:"claude/commands:"},{dir:G.resolve(process.cwd(),".claude","skills"),idPrefix:"claude/skills:"}];if(n)for(let r of n)e.push({dir:G.join(r.path,"commands"),idPrefix:`claude/${r.name}/commands:`,only:r.only}),e.push({dir:G.join(r.path,"skills"),idPrefix:`claude/${r.name}/skills:`,only:r.only});let t=(await Promise.all(e.map(async({dir:r,idPrefix:o,only:i})=>(await zc(r).catch(c=>(c.code!=="ENOENT"&&console.warn(`Failed to list prompts in ${r}:`,c),[]))).map(c=>({dir:r,file:c,idPrefix:o,only:i}))))).flat().filter(({file:r,only:o})=>!(o&&!o.test(r))).filter(({file:r,dir:o})=>!(G.join(o,r).includes("/skills/")&&!r.endsWith("/SKILL.md"))),s=(await Promise.all(t.map(async({dir:r,file:o,idPrefix:i})=>{let a=G.join(r,o),c=await Je.readFile(a,"utf-8").catch(f=>(console.warn(`Failed to read prompt file ${a}:`,f),null));if(c===null)return null;let l=Qc(o,c,a,i);if(l.import)try{l=await ch(l,o,a)}catch(f){return console.warn(`Failed to import remote prompt ${l.id}:`,f),null}return l.userInvocable===!1?null:l}))).filter(r=>r);return new Map(s.map(r=>[r.id,r]))}async function ch(n,e,t){let s=n.import;if(!s)return n;let r=await lh(s).catch(i=>(console.warn(`Failed to fetch prompt from ${s}:`,i),null));if(!r)return n;let o=Qc(e,r,t);return{...o,...n,content:`${o.content}
334
+
335
+ ---
336
+
337
+ ${n.content}`.trim(),description:n.description||o.description||""}}async function lh(n){let e=ah.createHash("sha256").update(n).digest("hex"),t=G.join(Ze,"prompts"),s=G.join(t,e),r=await Je.readFile(s,"utf-8").catch(()=>null);if(r!==null)return r;let o=await uh(n);return Je.mkdir(t,{recursive:!0}).then(()=>Je.writeFile(s,o,"utf-8")).catch(i=>{console.warn(`Failed to write cache for ${n}:`,i)}),o}async function uh(n){let e=n.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\/([^/]+)\/(.+)$/);if(e){let[,s,r,o,i]=e,a=`repos/${s}/${r}/contents/${i}?ref=${o}`;try{return ih("gh",["api","-H","Accept: application/vnd.github.v3.raw",a],{encoding:"utf-8"})}catch(c){throw new Error(`Failed to fetch from GitHub via gh CLI: ${c}`)}}let t=await fetch(n);if(!t.ok)throw new Error(`Failed to fetch prompt from ${n}: ${t.status} ${t.statusText}`);return t.text()}async function zc(n,e=n){let t=await Je.readdir(n,{withFileTypes:!0}),s=[];for(let r of t){let o=G.join(n,r.name),i=r.isDirectory(),a=r.isFile();if(r.isSymbolicLink()){let c=await Je.stat(o).catch(()=>null);if(!c)continue;i=c.isDirectory(),a=c.isFile()}i?s.push(...await zc(o,e)):a&&r.name.endsWith(".md")&&s.push(G.relative(e,o))}return s}function Qc(n,e,t,s=""){let r=n.replace(/\/SKILL\.md$/,"").replace(/\.md$/,""),o=n.endsWith("SKILL.md"),i=r.startsWith("shortcuts/"),a=i?s+r.replace(/^shortcuts\//,""):s+r,c=s.startsWith("claude"),l=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!l)return{id:a,description:"",content:e.trim(),filePath:t,claudeOriginated:c,isShortcut:i,isSkill:o};let f=l[2].trim(),u;try{u=(0,Vc.parse)(l[1])}catch{return{id:a,description:ro(l[1],"description")??"",content:f,filePath:t,claudeOriginated:c,import:ro(l[1],"import"),userInvocable:ro(l[1],"user-invocable")==="true"||void 0,isShortcut:i,isSkill:o}}let d=u["user-invocable"];return{id:a,description:u.description??"",content:f,filePath:t,claudeOriginated:c,import:u.import,userInvocable:d??void 0,isShortcut:i,isSkill:n.endsWith("SKILL.md")}}function ro(n,e){let t=new RegExp(`^${e}:\\s*(.*)$`,"m"),s=n.match(t);return s?s[1].trim():void 0}import{readFile as dh}from"node:fs/promises";import We from"node:path";import{styleText as ph}from"node:util";function Vn(n){let e=n.match(/^([^:]+)(?::(\d+)(?:-(\d+))?)?$/);if(!e)return new Error("Invalid format. Use: path/to/file[:line] or path/to/file[:start-end]");let[,t,s,r]=e;return{filePath:t,startLine:s?Number.parseInt(s,10):void 0,endLine:r?Number.parseInt(r,10):void 0}}import fh from"node:fs/promises";async function zn({filePath:n,startLine:e,endLine:t}){let s;try{s=await fh.readFile(n,{encoding:"utf-8"})}catch(o){return new Error(`Error reading file: ${o instanceof Error?o.message:String(o)}`)}let r=s.split(`
338
+ `);if(e){let o=e,i=t||o;return 1<=o&&o<=i&&i<=r.length?r.slice(o-1,i).join(`
339
+ `):new Error(`Invalid line range. File ${n} has ${r.length} lines.`)}return s}var Xc=new Map([[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".webp","image/webp"]]);async function He(n){let e=process.cwd(),t=[],s=[],r=[],o=0;for(let i of n.matchAll(/(^|\s)@(?:'([^']+)'|((?:\\ |[^\s])+))/g)){o<i.index&&t.push(n.slice(o,i.index)),o=i.index+i[0].length;let[a,c,l,f]=i,u=l??f.replace(/\\ /g," "),d=We.extname(u).toLowerCase();if(Xc.has(d)){let g=await hh(u);if(g instanceof Error){Qn(`Failed to load image from ${u}: ${g.message}`),t.push(a);continue}r.push(g),t.push(`${c}[Image #${r.length}:${u}]`);continue}let p=await mh(u,e);p&&s.push(p),t.push(a)}return o<n.length&&t.push(n.slice(o)),[{type:"text",text:[t.join(""),...s].join(`
340
+
341
+ `)},...r]}async function mh(n,e){let t=Vn(n);if(t instanceof Error)return Qn(`Failed to parse context reference ${n}: ${t}`),null;let s=We.resolve(t.filePath),r=We.relative(e,s);if(r.startsWith("..")||We.isAbsolute(r))return Qn(`Refusing to load context from outside working directory: ${s}`),null;let o=await zn(t);return o instanceof Error?(Qn(`Failed to load context from ${n}: ${o}`),null):[`<context location="${n}">`,o,"</context>"].join(`
342
+ `)}async function hh(n){let e=We.resolve(n);return await P(async()=>({type:"image",data:(await dh(e)).toString("base64"),mimeType:gh(e)}))}function gh(n){let e=We.extname(n).toLowerCase(),t=Xc.get(e);if(!t)throw new Error(`Unsupported image extension: ${e} (file: ${n})`);return t}function Qn(n){console.warn(ph("yellow",n))}function el({agentCommands:n,userEventEmitter:e,claudeCodePlugins:t,helpMessage:s}){async function r(i,a){let f=(await $e(t)).get(i)?i:`custom:${i}`,[u,...d]=await He(a),p=u?.type==="text"?u.text:a,g=`Switch to "${f}" subagent with goal: ${p}`;return e.emit("userInput",[{type:"text",text:g},...d]),"continue"}async function o(i,a,c){let f=(await ge(t)).get(i);if(!f)return console.log(V("red",`
343
+ Prompt not found: ${i}`)),"prompt";let[u,...d]=a?await He(a):[],p=u?.type==="text"?u.text:a,g=`${c}${p?` ${p}`:""}`,m=f.claudeOriginated?`${f.content}
344
+
345
+ ---
346
+
347
+ ${Bt}`:f.content,h=f.isSkill?`System: This prompt was invoked as "${g}".
348
+ Prompt path: ${f.filePath}
349
+
350
+ ${m}`:`System: This prompt was invoked as "${g}".
351
+
352
+ ${m}`;return e.emit("userInput",[{type:"text",text:h},...d]),"continue"}return async function(a){if(["/help","help"].includes(a.toLowerCase()))return console.log(`
353
+ ${s}`),"prompt";if(a.startsWith("!")){let l=Vn(a.slice(1));if(l instanceof Error)return console.log(V("red",`
354
+ ${l.message}`)),"prompt";let f=await zn(l);if(f instanceof Error)return console.log(V("red",`
355
+ ${f.message}`)),"prompt";let u=await He(f);return e.emit("userInput",u),"continue"}if(a.toLowerCase()==="/dump")return await n.dumpMessages(),"prompt";if(a.toLowerCase()==="/load")return await n.loadMessages(),"prompt";if(a.toLowerCase()==="/cost"){let l=n.getCostSummary();return console.log(Yt(l)),"prompt"}if(a.toLowerCase()==="/compact"){let l=['System: This prompt was invoked as "/compact".',"","Compact the conversation context:","1. Update the memory file for the current task so it fully captures the task overview, progress, decisions, and next steps in a self-contained way.",'2. Then call the "compact_context" tool alone with that memory file path and a brief reason.'].join(`
356
+ `);return e.emit("userInput",[{type:"text",text:l}]),"continue"}if(a==="/agents"){let l=await $e(t);if(console.log(V("bold",`
357
+ Available Agent Roles:`)),l.size===0)console.log(" No agent roles found.");else for(let f of l.values()){let u=process.stdout.columns??100,d=` ${V("cyan",f.id.padEnd(20))} - ${f.description}`;console.log(d.length>u?`${d.slice(0,u)}...`:d)}return"prompt"}if(a.startsWith("/agents:")){let l=a.match(/^\/agents:([^ ]+)(?:\s+(.*))?$/s);return l?await r(l[1],l[2]||""):(console.log(V("red",`
358
+ Invalid agent invocation format.`)),"prompt")}if(a.startsWith("/prompts")){let l=await ge(t);if(a==="/prompts"){if(console.log(V("bold",`
359
+ Available Prompts:`)),l.size===0)console.log(" No prompts found.");else for(let f of l.values()){let u=process.stdout.columns??100,d=` ${V("cyan",f.id.padEnd(20))} - ${f.description}`;console.log(d.length>u?`${d.slice(0,u)}...`:d)}return"prompt"}if(a.startsWith("/prompts:")){let f=a.match(/^\/prompts:([^ ]+)(?:\s+(.*))?$/s);return f?await o(f[1],f[2]||"",`/prompts:${f[1]}`):(console.log(V("red",`
360
+ Invalid prompt invocation format.`)),"prompt")}}if(a.startsWith("/paste")){let l=a.slice(6).trim(),f;try{if(process.platform==="darwin")f=Zc("pbpaste",{encoding:"utf8"});else if(process.platform==="linux")f=Zc("xsel",["--clipboard","--output"],{encoding:"utf8"});else return console.log(V("red",`
361
+ Unsupported platform for /paste: ${process.platform}`)),"prompt"}catch(p){let g=p instanceof Error?p.message:String(p);return console.log(V("red",`
362
+ Failed to get clipboard content: ${g}`)),"prompt"}let u=l?`${l}
363
+
364
+ ${f}`:f,d=await He(u);return e.emit("userInput",d),"continue"}if(a.startsWith("/")){let l=a.match(/^\/([^ ]+)(?:\s+(.*))?$/);if(l){let f=l[1];if((await ge(t)).get(f)?.isShortcut)return await o(f,l[2]||"",`/${f}`)}}let c=await He(a);return e.emit("userInput",c),"continue"}}import{styleText as tl}from"node:util";var ao=[{name:"/help",description:"Display this help message"},{name:"/agents",description:"List available agent roles"},{name:"/agents:<id>",description:"Delegate to an agent with the given ID (e.g., /agents:code-simplifier)"},{name:"/prompts",description:"List available prompts"},{name:"/prompts:<id>",description:"Invoke a prompt with the given ID (e.g., /prompts:feature-dev)"},{name:"/<id>",description:"Shortcut for prompts in the shortcuts/ directory (e.g., /commit)"},{name:"/paste",description:"Paste content from clipboard"},{name:"/resume",description:"Resume conversation after an LLM provider error"},{name:"/dump",description:"Save current messages to a JSON file"},{name:"/load",description:"Load messages from a JSON file"},{name:"/cost",description:"Display session cost and token usage"},{name:"/compact",description:"Ask the agent to compact the context by reloading from a memory file"}];function oo(n,e,t){let s=e.slice(t),r=[],o=[];for(let i of n){let a=typeof i=="string"?i:i.name;a.startsWith(e)?r.push(i):s.length>0&&a.slice(t).includes(s)&&o.push(i)}return[...r,...o]}function yh(n){if(n.length===0)return"";let e=n[0];for(let t=1;t<n.length;t++)for(;!n[t].startsWith(e);)e=e.slice(0,-1);return e}function io(n,e,t,s){let r=e.map(i=>typeof i=="string"?i:i.name);if(e.length<=1){s(null,[r,t]);return}let o=yh(r);o.length>t.length?s(null,[[o],t]):s(null,[[],t]),setTimeout(()=>{let i=process.stdout.columns??100,a=e.map(c=>{if(typeof c=="string")return c;let l=c.name.padEnd(25),f=" - ",u=c.description,d=i-l.length-f.length-3,p=u.length>d&&d>0?`${u.slice(0,d)}...`:u,g=tl("cyan",l),m=tl("dim",p);return`${g}${f}${m}`}).join(`\r
365
+ `);process.stdout.write(`\r
366
+ ${a}\r
367
+ `),process.stdout.write(`${n.getPrompt()}${n.line}`)},0)}function nl(n,e){return(t,s)=>{(async()=>{try{let r=n(),o=await ge(e),i=await $e(e);if(t.startsWith("/agents:")){let a="/agents:",c=Array.from(i.values()).map(f=>({name:`${a}${f.id}`,description:f.description})),l=oo(c,t,a.length);io(r,l,t,s);return}if(t.startsWith("/prompts:")){let a="/prompts:",c=Array.from(o.values()).map(f=>({name:`${a}${f.id}`,description:f.description})),l=oo(c,t,a.length);io(r,l,t,s);return}if(t.startsWith("/")){let a=Array.from(o.values()).filter(f=>f.isShortcut).map(f=>({name:`/${f.id}`,description:f.description})),c=[...ao,...a].filter(f=>{let u=typeof f=="string"?f:f.name;return u!=="/<id>"&&(u==="/agents:"||!u.startsWith("/agents:"))&&(u==="/prompts:"||!u.startsWith("/prompts:"))}),l=oo(c,t,1);io(r,l,t,s);return}s(null,[[],t])}catch(r){let o=r instanceof Error?r:new Error(String(r));s(o,[[],t])}})()}}import{Transform as wh}from"node:stream";function sl({onCtrlC:n,onCtrlD:e,onVoiceToggle:t,voiceToggleByte:s=15}){let r=String.fromCharCode(s);return new wh({transform(o,i,a){let c=o.toString("utf8");if(c.includes("")){n(),a();return}if(c.includes("")){e(),a();return}if(t&&c.includes(r)){t(),a();return}this.push(o),a()}})}import{Transform as bh}from"node:stream";function rl({isMuted:n}){return new bh({transform(e,t,s){n()||this.push(e),s()}})}import{Transform as Sh}from"node:stream";var Xn="\x1B[200~",ol="\x1B[201~",vh=20;function kh(n){let e=0;for(let t=0;t<n.length;t++){let s=n.charCodeAt(t);e=(e<<5)-e+s,e=e&e}return Math.abs(e).toString(16).padStart(6,"0").slice(0,6)}function il(){let n=new Map,e="IDLE",t="",s=null,r,o=()=>{s&&(clearTimeout(s),s=null)},i=()=>{if(o(),t){let c=t.replace(/\n$/,"");if(c.includes(`
368
+ `)){let l=kh(t);n.set(l,t);let f=t.split(`
369
+ `).length;r.push(`[Pasted text #${l}, ${f} lines]`)}else r.push(c)}t="",e="IDLE"};return r=new Sh({transform(c,l,f){let u=c.toString("utf8");for(;u.length>0;)if(e==="PASTE"){let d=u.indexOf(ol);d===-1?(t+=u,u=""):(t+=u.slice(0,d),u=u.slice(d+ol.length),e="PENDING")}else if(e==="PENDING")u.startsWith(Xn)?(u=u.slice(Xn.length),o(),e="PASTE"):i();else{let d=u.indexOf(Xn);d===-1?(this.push(u),u=""):(this.push(u.slice(0,d)),u=u.slice(d+Xn.length),e="PASTE")}e==="PENDING"&&!s&&(s=setTimeout(()=>{s=null,i()},vh)),f()},flush(c){e==="PENDING"&&i(),c()}}),{transform:r,resolvePlaceholders:c=>{let l=[],f=c.replace(/\[Pasted text #([a-f0-9]{6}),/g,(u,d)=>{let p=n.get(d);return p!==void 0&&(n.delete(d),l.push(`<context id="pasted#${d}">
370
+ ${p}
371
+ </context>`)),u});return l.length>0?[f,...l].join(`
372
+
373
+ `):f}}}import{execFileSync as Th}from"node:child_process";function al(n){if(!n){process.stdout.write("\x07");return}return Ie(()=>{Th(n.command,n.args??[],{shell:!1,stdio:["ignore","inherit","pipe"],env:{PWD:process.env.PWD,PATH:process.env.PATH,HOME:process.env.HOME,DISPLAY:process.env.DISPLAY,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS},timeout:10*1e3})})}import{spawn as Ah,spawnSync as cl}from"node:child_process";var Zn=process.env.PLAIN_VOICE_DEBUG==="1";function ul(n){let e=String(n),t=process.platform==="darwin",s=[];t||s.push({command:"arecord",args:["-q","-f","S16_LE","-c","1","-r",e,"-t","raw"]}),s.push({command:"sox",args:["-q","-d","-b","16","-c","1","-r",e,"-e","signed-integer","-t","raw","-"]});let r=t?["-f","avfoundation","-i",":0"]:["-f","alsa","-i","default"];return s.push({command:"ffmpeg",args:["-hide_banner","-loglevel","error",...r,"-ac","1","-ar",e,"-f","s16le","-"]}),s}function fl(n){return n.find(e=>dl(e.command))??null}function dl(n){return process.platform==="win32"?cl("where",[n],{stdio:"ignore"}).status===0:cl("sh",["-c",`command -v ${n}`],{stdio:"ignore"}).status===0}function xh({recorder:n,onAudio:e,onError:t,onExit:s}){let r=Ah(n.command,n.args,{stdio:["ignore","pipe","pipe"]}),o=[];return r.stderr.on("data",i=>{o.push(i.toString("utf8"))}),r.on("error",i=>{let a=i.code==="ENOENT"?` (command "${n.command}" not found)`:"";t(new Error(`Recorder failed to start${a}: ${i.message}`))}),r.on("exit",(i,a)=>{if(i!==0&&a===null){let c=o.join("").trim();t(new Error(`Recorder "${n.command}" exited with code ${i}${c?`: ${c}`:""}`))}s()}),r.stdout.on("data",e),{stop(){try{r.kill("SIGTERM")}catch{}}}}function ts(n,e){return queueMicrotask(()=>{n.onError(e),n.onClose?.()}),{stop:async()=>{}}}function ns({hooks:n,config:e,callbacks:t}){let s=e.recorder??fl(ul(n.sampleRate));if(!s)return ts(t,new Error("No voice recorder found. Install arecord, sox, or ffmpeg (or set `voiceInput.recorder`)."));if(!dl(s.command))return ts(t,new Error(`Voice recorder command "${s.command}" not found on PATH.`));let r=!1,o=!1,i=!1,a=[],c=pl();function l(){o||(o=!0,t.onClose?.())}let f=n.buildWsUrl(e),u=n.buildWsOptions?.(e),d=WebSocket,p=new d(f,u);p.binaryType="arraybuffer";let g=xh({recorder:s,onAudio(b){r||(i&&p.readyState===WebSocket.OPEN?m(b):a.push(b))},onError(b){r||t.onError(b),h()},onExit(){h()}});function m(b){let y=n.buildAudioPayload(b,n.sampleRate);try{p.send(JSON.stringify(y))}catch(S){Zn&&process.stderr.write(`[voiceInput] sendAudio dropped: ${es(S)}
374
+ `)}}p.addEventListener("open",()=>{let b=n.buildSetupMessage(e);try{p.send(JSON.stringify(b))}catch(y){t.onError(new Error(`Failed to send setup message: ${es(y)}`)),h()}}),p.addEventListener("message",b=>{if(r)return;let y="",S;try{y=typeof b.data=="string"?b.data:Buffer.from(b.data).toString("utf8"),S=JSON.parse(y)}catch(v){t.onError(new Error(`Failed to parse server message: ${es(v)}`));return}if(!z(S))return;Zn&&process.stderr.write(`[voiceInput] <- ${y.slice(0,800)}
375
+ `);let w=n.extractError?.(S);if(w){t.onError(new Error(`${n.label} error: ${w}`));return}if(!i&&n.isReadyMessage(S)){i=!0;for(let v of a.splice(0))p.readyState===WebSocket.OPEN&&m(v);return}let k=n.extractTranscript(S);if(k&&k.length>0){let v=c.push(k);v.length>0&&t.onTranscript(v)}}),p.addEventListener("error",b=>{if(r)return;let y=b.message??"WebSocket error";t.onError(new Error(`${n.label} WebSocket error: ${y}`)),h()}),p.addEventListener("close",b=>{if(!r&&b.code!==1e3&&b.code!==1005){let y=b.reason?`: ${b.reason}`:"";t.onError(new Error(`${n.label} WebSocket closed (code ${b.code}${y})`))}r=!0,g.stop(),l()}),Zn&&process.stderr.write(`[voiceInput] driver=${n.label} recorder=${s.command} ${s.args.join(" ")}
376
+ `);async function h(){if(!r){if(r=!0,g.stop(),a.length=0,p.readyState===WebSocket.OPEN||p.readyState===WebSocket.CONNECTING)try{p.close(1e3,"client stop")}catch(b){Zn&&process.stderr.write(`[voiceInput] ws.close failed: ${es(b)}
377
+ `)}l()}}return{stop:h}}function pl(){let n="",e="";function t(s){return s===" "||s===" "||s==="\u3000"}return{push(s){let r="";for(let o of s){if(t(o)){e+=o;continue}e.length>0&&(ll(n)&&ll(o)||(r+=e),e=""),r+=o,n=o}return r},flush(){let s=e;return e="",n="",s}}}function ll(n){let e=n.codePointAt(0);return e===void 0?!1:e>=12288&&e<=13311||e>=13312&&e<=19903||e>=19968&&e<=40959||e>=44032&&e<=55215||e>=63744&&e<=64255||e>=65280&&e<=65519||e>=131072&&e<=196607}function z(n){return typeof n=="object"&&n!==null}function es(n){return n instanceof Error?n.message:String(n)}var $h="gemini-3.1-flash-live-preview",Ch="wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent",Eh=16e3,Nh="Gemini Live";function ml({config:n,callbacks:e}){return ns({hooks:{label:Nh,sampleRate:Eh,buildWsUrl(s){return`${s.baseURL??Ch}?key=${encodeURIComponent(s.apiKey)}`},buildSetupMessage(s){let r=s.model??$h,o={responseModalities:["AUDIO"],maxOutputTokens:1};r.includes("2.5")&&(o.thinkingConfig={thinkingBudget:0});let i={model:`models/${r}`,generationConfig:o,inputAudioTranscription:{}};return s.language&&(i.systemInstruction={parts:[{text:`The user is speaking in ${s.language}.`}]}),{setup:i}},isReadyMessage(s){return z(s)&&"setupComplete"in s},extractTranscript(s){if(!z(s))return;let r=s.serverContent;if(!z(r))return;let o=r.inputTranscription;if(z(o)&&typeof o.text=="string"&&o.text.length>0)return o.text},buildAudioPayload(s,r){return{realtimeInput:{audio:{data:s.toString("base64"),mimeType:`audio/pcm;rate=${r}`}}}}},config:n,callbacks:e})}var _h="gpt-4o-transcribe",Ih="wss://api.openai.com/v1/realtime",Oh=24e3,Ph="OpenAI Realtime";function hl({config:n,callbacks:e}){return ns({hooks:{label:Ph,sampleRate:Oh,buildWsUrl(s){return`${s.baseURL??Ih}?intent=transcription`},buildWsOptions(s){return{headers:{Authorization:`Bearer ${s.apiKey}`,"OpenAI-Beta":"realtime=v1"}}},buildSetupMessage(s){let o={model:s.model??_h};return s.language&&(o.language=s.language),{type:"transcription_session.update",session:{input_audio_format:"pcm16",input_audio_transcription:o,turn_detection:{type:"server_vad"}}}},isReadyMessage(s){return z(s)&&(s.type==="transcription_session.created"||s.type==="transcription_session.updated")},extractError(s){if(!z(s)||s.type!=="error")return;let r=s.error;if(z(r))return typeof r.message=="string"?r.message:JSON.stringify(r)},extractTranscript(s){if(z(s)&&s.type==="conversation.item.input_audio_transcription.delta"&&typeof s.delta=="string"&&s.delta.length>0)return s.delta},buildAudioPayload(s,r){return{type:"input_audio_buffer.append",audio:s.toString("base64")}}},config:n,callbacks:e})}var Mh=new Set([3,4,9,10,13,17,19]);function co(n){let e=(n??"ctrl-o").trim().toLowerCase(),t=/^ctrl-(.)$/.exec(e);if(!t)throw new Error(`Invalid voiceInput.toggleKey "${n}". Expected "ctrl-<char>".`);let s=t[1],r=s.charCodeAt(0),o;if(r>=97&&r<=122)o=r-96;else if(r>=91&&r<=95)o=r-64;else throw new Error(`Unsupported voiceInput.toggleKey "${n}". Use ctrl-<letter> or ctrl-<[ \\ ] ^ _>.`);if(Mh.has(o))throw new Error(`voiceInput.toggleKey "${n}" conflicts with a reserved terminal/readline key.`);return{byte:o,label:`Ctrl-${s.toUpperCase()}`}}function gl({config:n,callbacks:e}){if(n.provider==="openai")return hl({config:n,callbacks:e});if(n.provider==="gemini")return ml({config:n,callbacks:e});let t=n.provider;return ts(e,new Error(`Unsupported voiceInput.provider: ${t}`))}var Lh=["Commands:",...ao.map(n=>` ${n.name.padEnd(13)} - ${n.description}`),"","Multi-line Input Syntax:",' """ - Start/stop multi-line input mode',"","File Input Syntax:"," !path/to/file - Read content from a file"," !path/to/file:N - Read line N from a file"," !path/to/file:N-M - Read lines N to M from a file","","References (use within input content):"," @path/to/file - Reference content from another file"," @path/to/file:N - Reference line N from another file"," @path/to/file:N-M - Reference lines N to M from another file","","Image Attachments (use within input content):"," @path/to/image.png - Attach an image (png, jpg, jpeg, gif, webp)"," @'path/with spaces.png' - Quote paths that include spaces"," @path/with\\ spaces.png - Escape spaces with a backslash"].join(`
378
+ `).trim().replace(/^[^ ].*:/gm,n=>L("bold",n)).replace(/^ {2}\/.+?(?= - )/gm,n=>L("cyan",n)).replace(/^ {2}.+?(?= - )/gm,n=>L("blue",n));async function Rh(n,{sessionId:e,modelName:t,startTime:s}){try{let r=zt({sessionId:e,mode:"interactive",modelName:t,workingDir:process.cwd(),costSummary:n,now:s});if(!r)return;await Vt(r)}catch(r){let o=r instanceof Error?r.message:String(r);console.error(L("yellow",`Warning: failed to record usage: ${o}`))}}function wl({userEventEmitter:n,agentEventEmitter:e,agentCommands:t,sessionId:s,modelName:r,startTime:o,notifyCmd:i,sandbox:a,onStop:c,claudeCodePlugins:l,voiceInput:f}){let u={turn:!0,multiLineBuffer:null,subagentName:""},d=null,p=co(f?.toggleKey),g=(_="",Q="")=>["",L(["white","bgGray"],[..._?[`[${_}]`]:[],`session: ${s} | model: ${r} | sandbox: ${a?"on":"off"}`].join(" ")),...Q?[Q]:[],"> "].join(`
379
+ `),m=()=>{process.stdout.isTTY&&process.stdout.write("\x1B[?2004l")},h=!1,b=async()=>{if(h)return;h=!0,m();let _=t.getCostSummary();console.log(),console.log(Yt(_)),await Rh(_,{sessionId:s,modelName:r,startTime:o}),await c(),process.exit(0)},y=0,S=1500,w,k=()=>{u.multiLineBuffer!==null&&(u.multiLineBuffer=null,w.setPrompt(D)),w.write(null,{ctrl:!0,name:"a"}),w.write(null,{ctrl:!0,name:"k"}),w.prompt()},v=async()=>{if(!d)return;let _=d;d=null,await _.session.stop(),w.setPrompt(D),w._refreshLine?.()},C=sl({onCtrlC:()=>{if(d){v();return}if(!u.turn){t.pauseAutoApprove(),console.log(L("yellow",`
380
+
381
+ \u26A0\uFE0F Ctrl-C: Auto-approve paused. Finishing current tool...
382
+ Press Ctrl-D twice to exit.
383
+ `));return}w.line.length>0||u.multiLineBuffer!==null?k():(w.setPrompt(g(u.subagentName,L("yellow","Press Ctrl-D twice to exit"))),w.prompt()),y=0},onCtrlD:()=>{if(u.turn&&(w.line.length>0||u.multiLineBuffer!==null))return;let _=Date.now();if(_-y<S){b();return}y=_,u.turn?(w.setPrompt(g(u.subagentName,L("yellow","Press Ctrl-D again to exit."))),w.prompt()):console.log(L("yellow",`
384
+
385
+ \u26A0\uFE0F Press Ctrl-D again to exit.
386
+ `))},onVoiceToggle:()=>{if(!u.turn)return;if(d){v();return}if(!f){w.setPrompt(g(u.subagentName,L("yellow",`Voice input not configured. Set \`voiceInput\` in your config to enable ${p.label}.`))),w.prompt(!0);return}let _=w.cursor;d={session:gl({config:f,callbacks:{onTranscript:X=>{if(!d)return;let qt=d.startCursor+d.transcriptLength,Gl=w.line.slice(0,qt),Jl=w.line.slice(qt),bo=w;bo.line=Gl+X+Jl,bo.cursor=qt+X.length,d.transcriptLength+=X.length,w._refreshLine?.()},onError:X=>{d=null,w.setPrompt(g(u.subagentName,L("red",`Voice input error: ${X.message}`))),w.prompt(!0)},onClose:()=>{d&&(d=null,w.setPrompt(D),w._refreshLine?.())}}}),startCursor:_,transcriptLength:0},w.setPrompt(g(u.subagentName,L(["red","bold"],`\u25CF REC (${p.label} to stop)`))),w._refreshLine?.()},voiceToggleByte:p.byte}),N=rl({isMuted:()=>d!==null}),E=il();process.stdin.pipe(C).pipe(N).pipe(E.transform),process.stdout.isTTY&&process.stdout.write("\x1B[?2004h");let D=g();w=yl.createInterface({input:E.transform,output:process.stdout,prompt:D,completer:nl(()=>w,l)});let oe=w._refreshLine?.bind(w);oe&&(w._refreshLine=(..._)=>{u.turn&&oe(..._)}),yl.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),w.on("close",b);let us=el({agentCommands:t,userEventEmitter:n,claudeCodePlugins:l,helpMessage:Lh});async function wo(_){u.turn=!1;let X=E.resolvePlaceholders(_).trim();if(X.length===0){u.turn=!0,w.prompt();return}w.setPrompt(D),await us(X)==="prompt"&&(u.turn=!0,w.prompt())}w.on("line",async _=>{if(!u.turn){console.warn(L("yellow",`
387
+ Agent is working. Ignore input: ${_.trim()}`));return}if(_.trim()==='"""'){if(u.multiLineBuffer===null){u.multiLineBuffer=[],w.setPrompt(L("gray","... ")),w.prompt();return}let Q=u.multiLineBuffer.join(`
388
+ `);u.multiLineBuffer=null,w.setPrompt(D),await wo(Q);return}if(u.multiLineBuffer!==null){u.multiLineBuffer.push(_),w.prompt();return}await wo(_)}),e.on("partialMessageContent",_=>{if(_.position==="start"){let Q=u.subagentName?L("cyan",`[${u.subagentName}]
389
+ `):"",X=L("gray",`<${_.type}>`);console.log(`
390
+ ${Q}${X}`)}_.content&&(_.type==="tool_use"?process.stdout.write(L("gray",_.content)):process.stdout.write(_.content)),_.position==="stop"&&console.log(L("gray",`
391
+ </${_.type}>`))}),e.on("message",_=>{Xo(_)}),e.on("toolUseRequest",()=>{w.setPrompt(g(u.subagentName,L("yellow","Approve tool calls? (y = allow once, Y = allow in this session, or feedback)")))}),e.on("subagentSwitched",_=>{u.subagentName=_?.name??"",D=g(u.subagentName),w.setPrompt(D)}),e.on("providerTokenUsage",_=>{console.log(zo(_))}),e.on("error",_=>{console.log(L("red",`
392
+ Error: message=${_.message}, stack=${_.stack}`))}),e.on("turnEnd",async()=>{let _=al(i);_&&console.error(L("yellow",`
393
+ Notification error: ${_.message}`)),await new Promise(Q=>setTimeout(Q,0)),u.turn=!0,w.prompt()}),w.prompt(),process.on("exit",m),process.on("SIGTERM",m)}import{mkdir as Bh}from"node:fs/promises";import vl from"node:path";import{spawn as Dh}from"node:child_process";import{closeSync as qh,openSync as Uh}from"node:fs";import{createInterface as jh}from"node:readline";async function bl(n){let e=new uo(n.command,n.args,{env:n.env,stderr:n.stderr,onNotification:n.onNotification}),t=new lo(e);try{await t.initialize({protocolVersion:n.protocolVersion,clientInfo:n.clientInfo,capabilities:n.capabilities})}catch(s){throw await t.close().catch(()=>{}),s}return t}var lo=class{#e;#t=!1;constructor(e){this.#e=e}async initialize(e={}){if(this.#t)throw new Error("MCP client is closed");let t=await this.#e.request("initialize",{protocolVersion:e.protocolVersion??"2025-03-26",capabilities:e.capabilities??{},clientInfo:e.clientInfo??{name:"unknown",version:"0.0.0"}});return this.#e.notify("notifications/initialized"),t}async listTools(){if(this.#t)throw new Error("MCP client is closed");return this.#e.request("tools/list",{})}async callTool(e){if(this.#t)throw new Error("MCP client is closed");return this.#e.request("tools/call",e)}async close(){this.#t||(this.#t=!0,await this.#e.close())}},uo=class{#e;#t;#f=1;#n=new Map;#r=!1;#s;#i;#a;#c;#o;#u;constructor(e,t,s={}){let r={PWD:process.env.PWD||"",PATH:process.env.PATH||"",HOME:process.env.HOME||""},o="ignore";s.stderr==="inherit"||s.stderr==="ignore"||s.stderr==="pipe"?o=s.stderr:typeof s.stderr=="string"&&(this.#o=Uh(s.stderr,"a"),o=this.#o);let i=Dh(e,t||[],{env:{...r,...s.env},stdio:["pipe","pipe",o]});if(this.#e=i,this.#u=s.onNotification,!i.stdout)throw new Error("MCP server stdout is not available");this.#t=jh({input:i.stdout}),this.#i=a=>this.#d(a),this.#t.on("line",this.#i),this.#a=a=>this.#p(a),i.on("close",this.#a),this.#c=a=>this.#m(a),i.on("error",this.#c)}get process(){return this.#e}#d(e){if(e.trim())try{let t=JSON.parse(e);if(!("id"in t)){this.#u?.(t.method,t.params);return}if(this.#n.has(t.id)){let s=this.#n.get(t.id);if(!s)return;this.#n.delete(t.id),clearTimeout(s.timer),t.error?s.reject(new Error(t.error.message||JSON.stringify(t.error))):s.resolve(t.result)}}catch{}}#p(e){let t=new Error(`MCP server exited with code ${e}`);this.#s=t,this.#l(t)}#m(e){this.#s=e,this.#l(e)}#l(e){for(let[,{reject:t,timer:s}]of this.#n)clearTimeout(s),t(e);this.#n.clear()}request(e,t,s=3e4){if(this.#r)return Promise.reject(new Error("MCP client is closed"));if(this.#s)return Promise.reject(this.#s);let r=this.#f++;return new Promise((o,i)=>{let a=setTimeout(()=>{this.#n.delete(r),i(new Error(`Request ${e} timed out after ${s}ms`))},s);this.#n.set(r,{resolve:o,reject:i,timer:a});let c=JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t});this.#e.stdin?.write(`${c}
394
+ `,l=>{l&&(clearTimeout(a),this.#n.delete(r),i(l))})})}notify(e,t){if(this.#r||this.#s)return;let s=JSON.stringify(t?{jsonrpc:"2.0",method:e,params:t}:{jsonrpc:"2.0",method:e});this.#e.stdin?.write(`${s}
395
+ `,()=>{})}async close(e="SIGTERM",t=5e3){if(this.#r)return;this.#r=!0,this.#l(new Error("MCP client is closed")),this.#t.off("line",this.#i),this.#t.close(),this.#e.stdin?.end(),this.#e.off("close",this.#a),this.#e.off("error",this.#c);let s=new Promise(r=>{if(this.#e.exitCode!==null||this.#e.signalCode!==null){r(void 0);return}let o=setTimeout(()=>{this.#e.kill("SIGKILL"),r(void 0)},t);this.#e.once("close",()=>{clearTimeout(o),r(void 0)})});if(this.#e.kill(e),await s,this.#o!==void 0)try{qh(this.#o)}catch{}}};import Sl from"node:fs/promises";import Fh from"node:path";async function ss(n,e,t="txt"){let s=new Date().toISOString().slice(0,19).replace("T","-").replace(/:/g,""),r=Math.random().toString(36).substring(2,8),o=`${s}-${r}--${e}.${t}`,i=Fh.join(et,o);return await Sl.mkdir(et,{recursive:!0}),await Sl.writeFile(i,n,"utf8"),i}var Kh=1024*8;async function kl(n,e){let{options:t,...s}=e,r=vl.join(q,"logs");await Bh(r,{recursive:!0});let o=vl.join(r,`mcp--${n}.stderr`),i=await bl({...s,stderr:o});return{tools:(await Gh(n,i)).filter(c=>!t?.enabledTools||t.enabledTools.find(l=>c.def.name.endsWith(`__${l}`))),stderrLogPath:o,cleanup:async()=>{await i.close()}}}async function Gh(n,e){let{tools:t}=await e.listTools();return t.filter(r=>![""].includes(r.name)).map(r=>({def:{name:`mcp__${n}__${r.name}`,description:r.description||`${r.name} tool`,inputSchema:r.inputSchema},impl:async o=>P(async()=>{let i=await e.callTool({name:r.name,arguments:o}),a=JSON.stringify(i,null,2),c=[],l=[],f=!1;if(Array.isArray(i.content))for(let h of i.content)"text"in h&&typeof h.text=="string"?(c.push({type:"text",text:h.text}),l.push(h.text)):h.type==="image"&&typeof h.mimeType=="string"&&typeof h.data=="string"?(c.push({type:"image",data:h.data,mimeType:h.mimeType}),f=!0):console.error(`Unsupported content part from MCP: ${JSON.stringify(h)}`);if(f)return c;let u=l.join(`
396
+
397
+ `)||a,d=u,p="txt";try{let h=JSON.parse(u);d=JSON.stringify(h,null,2),p="json"}catch{}if(d.length<=Kh)return d;let g=await ss(d,r.name,p),m=d.split(`
398
+ `).length;return[`Content is large (${u.length} characters, ${m} lines) and saved to ${g}`,"Use exec_command tool to find relevant parts."].join(`
399
+ `)})}))}import{styleText as Vh}from"node:util";import{execFile as Jh}from"node:child_process";import{createHash as Wh,createHmac as xl}from"node:crypto";var Tl=new Map,Hh=60*1e3;async function Ye(n){let e=Tl.get(n);if(e&&Date.now()<e.expiration.getTime()-Hh)return e.credentials;let t=await new Promise((o,i)=>{Jh("aws",["configure","export-credentials","--profile",n],{shell:!1,timeout:30*1e3},(a,c,l)=>{if(a){i(a);return}o(c.trim())})}),s=JSON.parse(t);for(let o of["AccessKeyId","SecretAccessKey"])if(!s[o]||typeof s[o]!="string")throw new Error(`AWS credentials output missing ${o}. Raw output: ${t.slice(0,200)}`);let r={accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,...s.SessionToken&&{sessionToken:s.SessionToken}};if(s.Expiration){let o=new Date(s.Expiration);Number.isNaN(o.getTime())||Tl.set(n,{credentials:r,expiration:o})}return r}function Ve(n,e){let{method:t,hostname:s,path:r,headers:o,body:i}=n,{region:a,service:c,credentials:l}=e,u=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),d=u.slice(0,8),p={...o,host:s,"x-amz-date":u};l.sessionToken&&(p["x-amz-security-token"]=l.sessionToken);let g=Object.keys(p).map(E=>E.toLowerCase()).sort(),m=g.map(E=>{let D=Object.keys(p).find(oe=>oe.toLowerCase()===E);return`${E}:${p[D].trim()}`}).join(`
400
+ `),h=g.join(";"),b=Al(i||""),y=r.split("/").map(E=>encodeURIComponent(E)).join("/"),S=[t,y,"",`${m}
401
+ `,h,b].join(`
402
+ `),w=`${d}/${a}/${c}/aws4_request`,k=["AWS4-HMAC-SHA256",u,w,Al(S)].join(`
403
+ `),v=rs(`AWS4${l.secretAccessKey}`,d),T=rs(v,a),A=rs(T,c),$=rs(A,"aws4_request"),C=xl("sha256",$).update(k,"utf-8").digest("hex"),N=`AWS4-HMAC-SHA256 Credential=${l.accessKeyId}/${w}, SignedHeaders=${h}, Signature=${C}`;return{method:t,headers:{...p,Authorization:N},body:i}}function Al(n){return Wh("sha256").update(n,"utf-8").digest("hex")}function rs(n,e){return xl("sha256",n).update(e,"utf-8").digest()}import{styleText as $l}from"node:util";async function*ze(n){let e=new Uint8Array;for(;;){let{done:t,value:s}=await n.read();if(t)break;let r=new Uint8Array(e.length+s.length);for(r.set(e),r.set(s,e.length),e=r;e.length>=12;){let o=new DataView(e.buffer,e.byteOffset,e.byteLength),i=o.getUint32(0),a=o.getUint32(4);if(e.length<i)break;let c=12+a,l=i-a-16,f=e.slice(c,c+l),u=new TextDecoder().decode(f);try{let d=JSON.parse(u);if(d.bytes){let p=Buffer.from(d.bytes,"base64").toString("utf-8");yield JSON.parse(p)}else d.message?console.error($l("yellow",`Bedrock message received: ${JSON.stringify(d.message)}`)):yield d}catch(d){d instanceof Error&&console.error($l("red",`Error decoding payload: ${d.message}
404
+ Payload: ${u}`))}e=e.slice(i)}}}import{execFile as Yh}from"node:child_process";async function ne(n){let e=n?.endsWith(".iam.gserviceaccount.com")?["--impersonate-service-account",n]:n?[n]:[];return await new Promise((s,r)=>{Yh("gcloud",["auth","print-access-token",...e],{shell:!1,timeout:10*1e3},(o,i,a)=>{if(o){r(o);return}s(i.trim())})})}async function fo(n,e,t,s=0){return await P(async()=>{let r=zh(t.messages),o=tg(r),i=Qh(t.tools||[]),a=(()=>{let v=n.baseURL;switch(n.name){case"anthropic":return`${v}/v1/messages`;case"bedrock":return`${v}/model/${e.model}/invoke-with-response-stream`;case"vertex-ai":return`${v}/publishers/anthropic/models/${e.model}:streamRawPredict`;default:throw new Error(`Unsupported platform: ${n.name}`)}})(),c=await(async()=>{switch(n.name){case"anthropic":return{...n.customHeaders,"anthropic-version":"2023-06-01","x-api-key":`${n.apiKey}`};case"bedrock":return n.customHeaders??{};case"vertex-ai":return{...n.customHeaders,Authorization:`Bearer ${await ne()}`}}})(),{model:l,...f}=e,d={...(()=>{switch(n.name){case"anthropic":return{...e,stream:!0};case"bedrock":return{anthropic_version:"bedrock-2023-05-31",...f};case"vertex-ai":return{anthropic_version:"vertex-2023-10-16",stream:!0,...f}}})(),system:r.filter(v=>v.role==="system").flatMap(v=>v.content),messages:o.filter(v=>v.role!=="system"),tools:i.length?i:void 0},p=async()=>fetch(a,{method:"POST",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(480*1e3)}),g=async()=>{let v=a.match(/bedrock-runtime\.([\w-]+)\.amazonaws\.com/)?.[1]??"",T=new URL(a),{hostname:A,pathname:$}=T,C=await Ye(n.name==="bedrock"?n.awsProfile:""),N=Ve({method:"POST",hostname:A,path:$,headers:{host:A,"Content-Type":"application/json"},body:JSON.stringify(d)},{region:v,service:"bedrock",credentials:C});return fetch(a,{method:N.method,headers:N.headers,body:N.body,signal:AbortSignal.timeout(480*1e3)})},h=await(n.name==="bedrock"?g:p)();if(h.status===429||h.status>=500){let v=Math.min(2*2**s,16);return console.error(Vh("yellow",`Anthropic rate limit exceeded. Retry in ${v} seconds...`)),await new Promise(T=>setTimeout(T,v*1e3)),fo(n,e,t,s+1)}if(h.status!==200)return new Error(`Failed to call Anthropic model: status=${h.status}, body=${await h.text()}`);if(!h.body)throw new Error("Response body is empty");let b=h.body.getReader(),y=n.name==="bedrock"?ze:ng,S=[],w;for await(let v of y(b)){S.push(v);let T=eg(v,w);T&&(w=T),t.onPartialMessageContent&&T&&t.onPartialMessageContent(T)}let k=Zh(S);return{message:Xh(k),providerTokenUsage:k.usage}})}function zh(n){let e=[];for(let t of n)switch(t.role){case"system":{e.push({role:"system",content:t.content.map(s=>{if(s.type==="text")return{type:"text",text:s.text};throw new Error(`Unsupported content part: ${JSON.stringify(s)}`)})});break}case"user":{e.push({role:"user",content:t.content.map(s=>{if(s.type==="text")return{type:"text",text:s.text};if(s.type==="image")return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.data}};if(s.type==="tool_result")return{type:"tool_result",tool_use_id:s.toolUseId,content:s.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image",source:{type:"base64",media_type:r.mimeType,data:r.data}};default:throw new Error(`Unsupported content part: ${JSON.stringify(r)}`)}}),is_error:s.isError};throw new Error(`Unsupported content part: ${JSON.stringify(s)}`)})});break}case"assistant":{e.push({role:"assistant",content:t.content.map(s=>{if(s.type==="thinking"){let r=s.provider?.fields?.signature;return{type:"thinking",thinking:s.thinking,signature:r}}if(s.type==="redacted_thinking")return{type:"redacted_thinking",data:s.provider?.fields?.data};if(s.type==="text")return{type:"text",text:s.text};if(s.type==="tool_use")return{type:"tool_use",id:s.toolUseId,name:s.toolName,input:s.input};throw new Error(`Unknown message part type: ${s}`)})});break}}return e}function Qh(n){let e=[];for(let t of n)e.push({name:t.name,description:t.description,input_schema:t.inputSchema});return e}function Xh(n){let e=[];for(let t of n.content)t.type==="thinking"?e.push({type:"thinking",thinking:t.thinking,provider:{fields:{signature:t.signature}}}):t.type==="redacted_thinking"?e.push({type:"redacted_thinking",provider:{fields:{data:t.data}}}):t.type==="text"?e.push({type:"text",text:t.text}):t.type==="tool_use"&&e.push({type:"tool_use",toolUseId:t.id,toolName:t.name,input:t.input});return{role:"assistant",content:e}}function Zh(n){let e={},t=[];for(let s of n)if(s.type==="message_start")e=Object.assign(e,s.message);else if(s.type==="message_delta"){if(Object.assign(e,s.delta),s.usage?.output_tokens){let r=e.usage||{};r.output_tokens+=s.usage.output_tokens,e.usage=r}}else if(s.type==="content_block_start")e.content=e.content||[],e.content.push(s.content_block);else if(s.type==="content_block_delta"){let r=e.content?.at(-1);if(r)switch(s.delta.type){case"text_delta":{r.type==="text"&&(r.text=r.text+s.delta.text);break}case"thinking_delta":{r.type==="thinking"&&(r.thinking=r.thinking+s.delta.thinking);break}case"signature_delta":{r.type==="thinking"&&(r.signature=s.delta.signature);break}case"input_json_delta":{r.type==="tool_use"&&t.push(s.delta.partial_json);break}}else console.error(`Received content block delta without a content block: ${JSON.stringify(s)}`)}else if(s.type==="content_block_stop"){let r=e.content?.at(-1);r?.type==="tool_use"&&(r.input=JSON.parse(t.join("")||"{}"),t.length=0)}return e}function eg(n,e){switch(n.type){case"content_block_start":return{type:n.content_block.type,position:"start"};case"content_block_delta":switch(n.delta.type){case"text_delta":return{type:"text",content:n.delta.text,position:"delta"};case"thinking_delta":return{type:"thinking",content:n.delta.thinking,position:"delta"};case"input_json_delta":return{type:"tool_use",content:n.delta.partial_json,position:"delta"}}break;case"content_block_stop":return{type:e?.type||"unknown",position:"stop"}}}function tg(n){let e=[];for(let r=0;r<n.length;r++)n[r].role==="user"&&e.push(r);let t=[e.at(-1),e.at(-2)].filter(r=>r!==void 0);return n.map((r,o)=>o===0&&r.role==="system"||t.includes(o)?{...r,content:r.content.map((i,a)=>a===r.content.length-1?{...i,cache_control:{type:"ephemeral"}}:i)}:r)}async function*ng(n){let e=new Uint8Array;for(;;){let{done:t,value:s}=await n.read();if(t)break;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let o=10,i=[];for(let a=0;a<e.length-1;a++)e[a]===o&&e[a+1]===o&&i.push(a);for(let a=0;a<i.length;a++){let c=a===0?0:i[a-1]+2,l=i[a],f=e.slice(c,l),d=new TextDecoder().decode(f).split(`
405
+ `).at(-1);d?.startsWith("data: ")&&(yield JSON.parse(d.slice(6)))}i.length&&(e=e.slice(i[i.length-1]+2))}}import{styleText as po}from"node:util";async function mo(n,e,t,s=0){return await P(async()=>{let r=sg(t.messages),o=e.enablePromptCaching?ig(r):r,i=og(t.tools||[]),a=(()=>{let A=n.baseURL;if(n.name!=="bedrock")throw new Error(`Unsupported platform: ${n.name}`);return`${A}/model/${e.model}/converse-stream`})(),c=lg(n.baseURL),l={messages:o,...e.inferenceConfig&&{inferenceConfig:e.inferenceConfig},...e.additionalModelRequestFields&&{additionalModelRequestFields:e.additionalModelRequestFields}},f=rg(t.messages,e.enablePromptCaching);f.length>0&&(l.system=f),i.length>0&&(l.toolConfig={tools:i});let u=JSON.stringify(l),d=await Ye(n.awsProfile),p=new URL(a),{hostname:g,pathname:m}=p,h=Ve({method:"POST",hostname:g,path:m,headers:{host:g,"Content-Type":"application/json"},body:u},{region:c,service:"bedrock",credentials:d}),b=await fetch(a,{method:h.method,headers:h.headers,body:h.body,signal:AbortSignal.timeout(480*1e3)});if(b.status!==200){let A=await b.text();if(console.error(po("red",`Bedrock API error: ${b.status} ${A}`)),(b.status===429||b.status===502||b.status===503)&&s<3){let $=Math.min(2*2**s,16);return console.error(po("yellow",`Retrying in ${$} seconds... (attempt ${s+1})`)),await new Promise(C=>setTimeout(C,$*1e3)),mo(n,e,t,s+1)}throw new Error(`Bedrock API error: ${b.status} ${A}`)}if(!b.body)throw new Error("Response body is empty");let y=b.body.getReader(),S=[],w={},k;for await(let A of ze(y)){let $=A;if(t.onPartialMessageContent){let C=ag($,w);for(let N of C)t.onPartialMessageContent(N)}if("contentBlockIndex"in $&&"start"in $){let C=$.contentBlockIndex,N=$.start;N.toolUse&&(w[C]={toolUse:{toolUseId:N.toolUse.toolUseId||"",name:N.toolUse.name||"",input:{}}})}if("contentBlockIndex"in $&&"delta"in $){let C=$.contentBlockIndex,N=$.delta;w[C]||(N.text!==void 0?w[C]={text:""}:N.toolUse?w[C]={toolUse:{toolUseId:N.toolUse.toolUseId||"",name:N.toolUse.name||"",input:{}}}:N.reasoningContent&&(w[C]={reasoningContent:{text:void 0,signature:void 0,redactedContent:void 0}}));let E=w[C];E&&N.text!==void 0&&"text"in E?E.text+=N.text:E&&N.toolUse&&"toolUse"in E&&E.toolUse?(E._partialInput||(E._partialInput=""),E._partialInput+=N.toolUse.input||""):E&&N.reasoningContent&&"reasoningContent"in E&&E.reasoningContent&&(N.reasoningContent.text&&(E.reasoningContent.text=(E.reasoningContent.text||"")+N.reasoningContent.text),N.reasoningContent.signature&&(E.reasoningContent.signature=N.reasoningContent.signature),N.reasoningContent.redactedContent&&(E.reasoningContent.redactedContent=N.reasoningContent.redactedContent))}if("stopReason"in $)for(let[C,N]of Object.entries(w)){if(N&&"toolUse"in N&&N.toolUse&&N._partialInput){try{N.toolUse.input=JSON.parse(N._partialInput)}catch(E){console.error(po("red",`Failed to parse tool input JSON for tool "${N.toolUse.name}": ${N._partialInput}`)),N.toolUse.input={err:String(E),raw:N._partialInput}}delete N._partialInput}S.push(N)}"usage"in $&&"metrics"in $&&(k=$.usage)}let v=cg(S),T=k?{inputTokens:k.inputTokens,outputTokens:k.outputTokens,totalTokens:k.totalTokens,...k.cacheReadInputTokens&&{cacheReadInputTokens:k.cacheReadInputTokens},...k.cacheWriteInputTokens&&{cacheWriteInputTokens:k.cacheWriteInputTokens}}:{};return{message:v,providerTokenUsage:T}})}function sg(n){let e=[];for(let t of n)if(t.role!=="system"){if(t.role==="user"){let s=[];for(let r of t.content)if(r.type==="text"&&r.text)s.push({text:r.text});else if(r.type==="image")s.push({image:{format:r.mimeType.split("/")[1],source:{bytes:r.data}}});else if(r.type==="tool_result"){let o=[];for(let i of r.content)i.type==="text"?o.push({text:i.text}):i.type==="image"&&o.push({image:{format:i.mimeType.split("/")[1],source:{bytes:i.data}}});s.push({toolResult:{toolUseId:r.toolUseId,content:o,status:r.isError?"error":"success"}})}e.push({role:"user",content:s})}else if(t.role==="assistant"){let s=[];for(let r of t.content)if(r.type==="text")s.push({text:r.text});else if(r.type==="thinking"){let o=r.provider?.fields?.signature;o&&s.push({reasoningContent:{reasoningText:{text:r.thinking,signature:o}}})}else if(r.type==="redacted_thinking"){let o=r.provider?.fields?.data;o&&s.push({reasoningContent:{redactedContent:o}})}else r.type==="tool_use"&&s.push({toolUse:{toolUseId:r.toolUseId,name:r.toolName,input:r.input}});e.push({role:"assistant",content:s})}}return e}function rg(n,e=!1){let t=[];for(let s of n)if(s.role==="system")for(let r of s.content)t.push({text:r.text});return e&&t.length>0&&t.push({cachePoint:{type:"default"}}),t}function og(n){return n.map(e=>({toolSpec:{name:e.name,description:e.description,inputSchema:{json:e.inputSchema}}}))}function ig(n){let e=n.map((r,o)=>r.role==="user"?o:-1).filter(r=>r!==-1),t=[e.at(-1),e.at(-2)].filter(r=>r!==void 0);return n.map((r,o)=>{if(t.includes(o)){if(r.role==="user"){let i=[...r.content];if(!i.some(c=>"toolResult"in c&&c.toolResult))return i.push({cachePoint:{type:"default"}}),{...r,content:i}}if(r.role==="assistant"){let i=[...r.content];return i.push({cachePoint:{type:"default"}}),{...r,content:i}}}return r})}function ag(n,e){let t=[];if("contentBlockIndex"in n&&"start"in n){let s=n.contentBlockIndex,r=n.start;if(s>0&&e[s-1]){let o=e[s-1],i=o.text?"text":o.toolUse?"tool_use":o.reasoningContent?"thinking":"unknown";t.push({type:i,position:"stop"})}r.toolUse&&t.push({type:"tool_use",position:"start",content:JSON.stringify({toolUseId:r.toolUse.toolUseId,name:r.toolUse.name})})}if("contentBlockIndex"in n&&"delta"in n){let s=n.delta,r=n.contentBlockIndex;if(!e[r]&&r>0&&e[r-1]){let o=e[r-1],i=o.text?"text":o.toolUse?"tool_use":o.reasoningContent?"thinking":"unknown";t.push({type:i,position:"stop"})}s.text!==void 0?(e[r]||t.push({type:"text",position:"start",content:""}),t.push({type:"text",position:"delta",content:s.text})):s.toolUse||s.reasoningContent&&(e[r]||t.push({type:"thinking",position:"start",content:""}),s.reasoningContent.text&&t.push({type:"thinking",position:"delta",content:s.reasoningContent.text}))}if("stopReason"in n){let s=Object.values(e);if(s.length>0){let r=s[s.length-1],o=r&&"text"in r?"text":r&&"toolUse"in r?"tool_use":r&&"reasoningContent"in r?"thinking":"unknown";t.push({type:o,position:"stop"})}}return t}function cg(n){let e=[];for(let t of n)t.text?e.push({type:"text",text:t.text}):t.toolUse?e.push({type:"tool_use",toolUseId:t.toolUse.toolUseId||"",toolName:t.toolUse.name||"",input:t.toolUse.input??{}}):t.reasoningContent&&(t.reasoningContent.text?e.push({type:"thinking",thinking:t.reasoningContent.text,...t.reasoningContent.signature&&{provider:{fields:{signature:t.reasoningContent.signature}}}}):t.reasoningContent.redactedContent&&e.push({type:"redacted_thinking",provider:{fields:{data:t.reasoningContent.redactedContent}}}));return{role:"assistant",content:e}}function lg(n){let e=n.match(/bedrock-runtime\.([^.]+)\.amazonaws\.com/);if(!e)throw new Error(`Failed to extract region from baseURL: ${n}`);return e[1]}import{styleText as Qe}from"node:util";function Cl(n,e){let t=n.baseURL||"https://generativelanguage.googleapis.com/v1beta",s={cacheTTL:120,minCacheableTokenCount:2048},r={cache:void 0};async function o(a,c,l=0){return await P(async()=>{let f=ug(c.messages),u=fg(c.tools||[]),d={functionCallingConfig:{mode:"VALIDATED"}},p=f.find(C=>C.role==="system"),g=f.filter(C=>C.role!=="system");g.length<=(r.cache?.contentsLength??0)&&(r.cache=void 0);let m=(()=>{switch(n.name){case"gemini":return`${t}/models/${a.model}:streamGenerateContent?alt=sse`;case"vertex-ai":return`${t}/publishers/google/models/${a.model}:streamGenerateContent?alt=sse`;default:throw new Error(`Unsupported platform: ${n.name}`)}})(),h=await(async()=>{switch(n.name){case"gemini":return{...n.customHeaders,"x-goog-api-key":n.apiKey};case"vertex-ai":return{...n.customHeaders,Authorization:`Bearer ${await ne(n.account)}`}}})(),b={generationConfig:{temperature:0},safetySettings:[{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"}],...a.requestConfig},y=r.cache&&Date.now()<r.cache.expireTime.getTime()?{...b,cachedContent:r.cache.name,contents:g.slice(r.cache.contentsLength)}:{...b,system_instruction:p,contents:g,tools:u.length?u:void 0,toolConfig:d},S=await fetch(m,{method:"POST",headers:{...h,"Content-Type":"application/json"},body:JSON.stringify(y),signal:AbortSignal.timeout(480*1e3)});if(S.status===429||S.status>=500){let C=Math.min(2*2**l,16);return console.error(Qe("yellow",`Gemini rate limit exceeded. Retrying in ${C} seconds...`)),await new Promise(N=>setTimeout(N,C*1e3)),o(a,c,l+1)}if(S.status!==200)return new Error(`Failed to call Gemini model: status=${S.status}, body=${await S.text()}`);if(!S.body)throw new Error("Response body is empty");let w=S.body.getReader(),k=[],v;for await(let C of hg(w)){k.push(C);let N=mg(C,v);if(v=N.at(-1),c.onPartialMessageContent&&N.length)for(let E of N)c.onPartialMessageContent(E)}c.onPartialMessageContent&&v&&c.onPartialMessageContent({type:v.type,position:"stop"});let T=pg(k),A={promptTokenCount:T.usageMetadata.promptTokenCount,cachedContentTokenCount:T.usageMetadata.cachedContentTokenCount??0,candidatesTokenCount:T.usageMetadata.candidatesTokenCount??0,thoughtsTokenCount:T.usageMetadata.thoughtsTokenCount??0,totalTokenCount:T.usageMetadata.totalTokenCount},$=dg(T);if($ instanceof os||$ instanceof is){let C=Math.min(2*2**l,16);return console.error(Qe("yellow",`${$.name}: Retrying in ${C} seconds...`)),await new Promise(N=>setTimeout(N,C*1e3)),o(a,c,l+1)}return s.minCacheableTokenCount<T.usageMetadata.promptTokenCount&&await i({contentsWithoutSystem:[...g,T.candidates?.at(0)?.content],systemInstruction:p,tools:u,toolConfig:d,headers:h}),{message:$,providerTokenUsage:A}})}async function i({contentsWithoutSystem:a,systemInstruction:c,tools:l,toolConfig:f,headers:u}){let d=n.name==="vertex-ai"?`${t.match(/projects\/[^/]+\/locations\/[^/]+/)?.[0]||""}/publishers/google/models`:"models",p=`${t}/cachedContents`,g={model:`${d}/${e.model}`,ttl:`${s.cacheTTL}s`,system_instruction:c,contents:a,tools:l,toolConfig:f};await fetch(p,{method:"POST",headers:{...u,"Content-Type":"application/json"},body:JSON.stringify(g),signal:AbortSignal.timeout(480*1e3)}).then(async m=>{if(m.status!==200)console.error(Qe("yellow",`Failed to create Gemini context cache: status=${m.status}, body=${await m.text()}`));else{let h=await m.json();r.cache&&Date.now()<r.cache.expireTime.getTime()&&fetch(`${p}/${r.cache.name.replace(/.*cachedContents\//,"")}`,{method:"DELETE",headers:{...u,"Content-Type":"application/json"},signal:AbortSignal.timeout(120*1e3)}).then(async b=>{b.status!==200&&console.error(Qe("yellow",`Failed to delete Gemini context cache: status=${b.status}, body=${await b.text()}`))}).catch(b=>{console.error(Qe("yellow",`Failed to delete Gemini context cache: ${b}`))}),r.cache={name:h.name,contentsLength:a.length,expireTime:new Date(h.expireTime)}}}).catch(m=>{console.error(Qe("yellow",`Failed to create Gemini context cache: ${m}`))})}return o}function ug(n){let e=[];for(let t of n)switch(t.role){case"system":{e.push({role:"system",parts:t.content.map(s=>({text:s.text}))});break}case"user":{let s=t.content.filter(o=>o.type==="tool_result"),r=t.content.filter(o=>o.type==="text"||o.type==="image");s.length&&e.push({role:"user",parts:s.map(o=>({functionResponse:{name:o.toolName,response:{name:o.toolName,content:o.content.map(i=>{switch(i.type){case"text":return{text:i.text};case"image":return{inline_data:{mime_type:i.mimeType,data:i.data}};default:throw new Error(`Unsupported content part: ${JSON.stringify(i)}`)}})}}}))}),r.length&&e.push({role:"user",parts:r.map(o=>{if(o.type==="text")return{text:o.text};if(o.type==="image")return{inline_data:{mime_type:o.mimeType,data:o.data}};throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)})});break}case"assistant":{let s=[];for(let r of t.content)r.type==="thinking"?s.push({text:r.thinking,thought:!0,...r.provider?.fields||{}}):r.type==="text"?s.push({text:r.text,...r.provider?.fields||{}}):r.type==="tool_use"&&s.push({functionCall:{name:r.toolName,args:r.input},...r.provider?.fields||{}});e.push({role:"model",parts:s});break}}return e}function fg(n){let e=[];for(let t of n)e.push({name:t.name,description:t.description,parametersJsonSchema:t.inputSchema});return[{functionDeclarations:e}]}function dg(n){let e=n.candidates?.at(0);if(!e)return new os(`No candidates found: content=${JSON.stringify(n)}`);if(e.finishReason==="MALFORMED_FUNCTION_CALL")return new is(`Malformed function call: content=${JSON.stringify(n)}`);let t=[];for(let s of e.content.parts||[])"text"in s&&(s.thought?t.push({type:"thinking",thinking:s.text}):t.push({type:"text",text:s.text,provider:s.thoughtSignature?{fields:{thoughtSignature:s.thoughtSignature}}:void 0})),"functionCall"in s&&t.push({type:"tool_use",toolUseId:s.functionCall.name,toolName:s.functionCall.name,input:s.functionCall.args,provider:s.thoughtSignature?{fields:{thoughtSignature:s.thoughtSignature}}:void 0});return{role:"assistant",content:t}}function pg(n){let e=n.at(0);if(!e)throw new Error("No content found");let t={...e,candidates:(e.candidates||[]).map(s=>({...s,content:{...s.content,parts:[...s.content.parts||[]]}}))};for(let s=1;s<n.length;s++){let r=n[s];if(r.candidates?.length){let o=r.candidates.at(0);o?.content.parts?.length&&t.candidates?.[0].content.parts?.push(...o.content.parts),o?.finishReason&&t.candidates?.[0]&&(t.candidates[0].finishReason=o.finishReason),o?.finishMessage&&t.candidates?.[0]&&(t.candidates[0].finishMessage=o.finishMessage)}r.usageMetadata.totalTokenCount&&(t.usageMetadata=r.usageMetadata)}return t}function mg(n,e){let t=n.candidates?.at(0),s=[];if(t?.content.parts?.length){let r=e?.type;for(let o of t.content.parts){let i="text"in o?o.thought?"thinking":"text":"tool_use";r&&r!==i&&s.push({type:r,position:"stop"}),r!==i&&(r=i,s.push({type:i,position:"start"})),"text"in o&&(o.thought?s.push({type:"thinking",content:o.text,position:"delta"}):s.push({type:"text",content:o.text,position:"delta"})),"functionCall"in o&&(e?.type==="tool_use"&&s.push({type:"tool_use",content:`
406
+ `,position:"delta"}),s.push({type:"tool_use",content:o.functionCall.name,position:"delta"}))}}return s}var os=class extends Error{constructor(e){super(e),this.name="GeminiNoCandidateError"}},is=class extends Error{constructor(e){super(e),this.name="GeminiMalformedFunctionCallError"}};async function*hg(n){let e=new Uint8Array;for(;;){let{done:t,value:s}=await n.read();if(t)break;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let o=13,i=10,a=[];for(let c=0;c<e.length-3;c++)e[c]===o&&e[c+1]===i&&e[c+2]===o&&e[c+3]===i&&a.push(c);for(let c=0;c<a.length;c++){let l=c===0?0:a[c-1]+4,f=a[c],u=e.slice(l,f),d=new TextDecoder().decode(u);d.startsWith("data: {")&&(yield JSON.parse(d.slice(6)))}a.length&&(e=e.slice(a[a.length-1]+4))}}import{styleText as Nl}from"node:util";import{execFile as gg}from"node:child_process";async function El(n){return await new Promise((t,s)=>{gg("az",["account","get-access-token","--resource","https://cognitiveservices.azure.com","--query","accessToken","--output","tsv"],{shell:!1,timeout:1e4,env:n?{AZURE_CONFIG_DIR:n.azureConfigDir}:void 0},(r,o,i)=>{if(r){s(r);return}t(o.trim())})})}async function as(n,e,t,s=0){return await P(async()=>{let r=yg(t.messages),o=wg(t.tools||[]),{model:i,...a}=e,c={...a,model:i,input:r,tools:o.length?o:void 0,stream:!0},l=await(async()=>{switch(n.name){case"openai":case"openai-compatible":return n.apiKey;case"azure":return El(n.azureConfigDir?{azureConfigDir:n.azureConfigDir}:void 0);default:throw new Error(`Unsupported platform: ${n.name}`)}})(),f=await fetch(`${n.baseURL}/v1/responses`,{method:"POST",headers:{...n.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify(c),signal:AbortSignal.timeout(480*1e3)}),u=Math.min(2*2**s,16);if(f.status===429||f.status>=500)return console.error(Nl("yellow",`OpenAI rate limit exceeded. Retry in ${u} seconds...`)),await new Promise(m=>setTimeout(m,u*1e3)),as(n,e,t,s+1);if(f.status!==200)throw new Error(`Failed to call OpenAI model: status=${f.status}, body=${await f.text()}`);if(!f.body)throw new Error("Response body is empty");let d=f.body.getReader(),p=[];for await(let m of vg(d)){p.push(m);let h=Sg(m);t.onPartialMessageContent&&h&&t.onPartialMessageContent(h)}let g=p.at(-1);if(g?.type!=="response.completed"){let m=g?.type==="response.failed"?{type:g.type,response:{error:g.response.error}}:g;return console.error(Nl("yellow",`OpenAI stream did not complete: ${JSON.stringify(m)}. Retry in ${u} seconds...`)),await new Promise(h=>setTimeout(h,u*1e3)),as(n,e,t,s+1)}return{message:bg(g.response.output),providerTokenUsage:g.response.usage}})}function yg(n){let e=[];for(let t of n)switch(t.role){case"system":{e.push({role:"system",content:t.content.map(s=>({type:"input_text",text:s.text}))});break}case"user":{let s=t.content.filter(a=>a.type==="tool_result"),r=t.content.filter(a=>a.type==="text"||a.type==="image"),o=0;for(let a of s){let c=a.content.map(l=>{switch(l.type){case"text":return l.text;case"image":return o+=1,`(Image [${o}] omitted. See next message from user.)`;default:throw new Error(`Unsupported content part: ${JSON.stringify(l)}`)}}).join(`
407
+
408
+ `);e.push({type:"function_call_output",call_id:a.toolUseId,output:c})}let i=[];for(let a of s)for(let c of a.content)c.type==="image"&&i.push({type:"input_image",image_url:`data:${c.mimeType};base64,${c.data}`,detail:"auto"});i.length&&e.push({role:"user",content:i}),r.length&&e.push({role:"user",content:r.map(a=>{if(a.type==="text")return{type:"input_text",text:a.text};if(a.type==="image")return{type:"input_image",image_url:`data:${a.mimeType};base64,${a.data}`};throw new Error(`Unsupported content part: ${JSON.stringify(a)}`)})});break}case"assistant":for(let s of t.content)if(s.type==="thinking"&&e.push({type:"reasoning",...s.provider?.fields}),s.type==="tool_use"&&e.push({type:"function_call",name:s.toolName,arguments:JSON.stringify(s.input),call_id:s.toolUseId,...s.provider?.fields}),s.type==="text"){let r=s.provider?.fields?.id,o=e.find(i=>"id"in i&&i.id===r&&i.type==="message");o?o.content.push({type:"output_text",text:s.text}):e.push({type:"message",role:"assistant",content:[{type:"output_text",text:s.text}],...s.provider?.fields})}}return e}function wg(n){let e=[];for(let t of n)e.push({type:"function",name:t.name,description:t.description,parameters:t.inputSchema});return e}function bg(n){let e=[];for(let t of n){if(t.type==="reasoning"&&e.push({type:"thinking",thinking:t.summary.at(0)?.text??"",provider:{fields:{id:t.id,encrypted_content:t.encrypted_content,summary:t.summary}}}),t.type==="message")for(let s of t.content)s.type==="output_text"&&e.push({type:"text",text:s.text,provider:{fields:{id:t.id}}});t.type==="function_call"&&e.push({type:"tool_use",toolUseId:t.call_id,toolName:t.name,input:JSON.parse(t.arguments),provider:{fields:{id:t.id}}})}return{role:"assistant",content:e}}function Sg(n){if(n.type==="response.output_item.added"&&n.item.type==="reasoning")return{type:"thinking",position:"start"};if(n.type==="response.reasoning_summary_part.added")return{type:"thinking",position:"delta",content:n.part.text};if(n.type==="response.reasoning_summary_text.delta")return{type:"thinking",position:"delta",content:n.delta};if(n.type==="response.output_item.done"&&n.item.type==="reasoning")return{type:"thinking",position:"stop"};if(n.type==="response.content_part.added"){if(n.part.type==="output_text")return{type:"text",position:"start",content:n.part.text};if(n.part.type==="refusal")return{type:"refusal",position:"start",content:n.part.refusal}}if(n.type==="response.output_text.delta")return{type:"text",position:"delta",content:n.delta};if(n.type==="response.content_part.done"){if(n.part.type==="output_text")return{type:"text",position:"stop"};if(n.part.type==="refusal")return{type:"refusal",position:"stop"}}if(n.type==="response.output_item.added"&&n.item.type==="function_call")return{type:"tool_use",position:"start",content:n.item.arguments};if(n.type==="response.function_call_arguments.delta")return{type:"tool_use",position:"delta",content:n.delta};if(n.type==="response.output_item.done"&&n.item.type==="function_call")return{type:"tool_use",position:"stop"}}async function*vg(n){let e=new Uint8Array;for(;;){let{done:t,value:s}=await n.read();if(t)break;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let o=10,i=[];for(let a=0;a<e.length-1;a++)e[a]===o&&e[a+1]===o&&i.push(a);for(let a=0;a<i.length;a++){let c=a===0?0:i[a-1]+2,l=i[a],f=e.slice(c,l),u=new TextDecoder().decode(f);if(u.startsWith("event: ")){let d=u.split(`
409
+ `).slice(1).join(`
410
+ `);yield JSON.parse(d.slice(6))}}i.length&&(e=e.slice(i[i.length-1]+2))}}import{styleText as ho}from"node:util";async function _l(n,e){let t=0;for(;;)try{return t++,await n()}catch(s){if(t>=e.maxAttempt||!e.shouldRetry(s))throw s;let r=Math.min(e.initialInterval*e.multiplier**(t-1),e.maxInterval);e.beforeRetry&&await e.beforeRetry(s,r),await new Promise(o=>setTimeout(o,r))}}async function cs(n,e,t,s=0){let r=Math.min(2*2**s,16);return await P(async()=>{let o=kg(t.messages),i=Tg(t.tools||[]),a=(()=>{let T=n.baseURL;switch(n.name){case"openai":case"openai-compatible":return`${T}/v1/chat/completions`;case"bedrock":return`${T}/model/${e.model}/invoke-with-response-stream`;case"vertex-ai":return`${T}/endpoints/openapi/chat/completions`;default:throw new Error(`Unsupported platform: ${n.name}`)}})(),c=await(async()=>{switch(n.name){case"openai":case"openai-compatible":return{...n.customHeaders,Authorization:`Bearer ${n.apiKey}`};case"bedrock":return n.customHeaders??{};case"vertex-ai":return{...n.customHeaders,Authorization:`Bearer ${await ne()}`}}})(),{model:l,...f}=e,d={...(()=>{switch(n.name){case"openai":case"openai-compatible":return{...e,stream:!0};case"bedrock":return{...f};case"vertex-ai":return{...e,model:e.model,stream:!0}}})(),messages:o,tools:i.length?i:void 0,stream_options:{include_usage:!0}},p=async()=>fetch(a,{method:"POST",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(480*1e3)}),g=async()=>{let T=a.match(/bedrock-runtime\.([\w-]+)\.amazonaws\.com/)?.[1]??"",A=new URL(a),{hostname:$,pathname:C}=A,N=await Ye(n.name==="bedrock"?n.awsProfile:""),E=Ve({method:"POST",hostname:$,path:C,headers:{host:$,"Content-Type":"application/json"},body:JSON.stringify(d)},{region:T,service:"bedrock",credentials:N});return fetch(a,{method:E.method,headers:E.headers,body:E.body,signal:AbortSignal.timeout(480*1e3)})},m=n.name==="bedrock"?g:p,h=await _l(()=>m(),{shouldRetry:T=>T instanceof Error&&T.name==="TimeoutError",beforeRetry:(T,A)=>(console.error(ho("yellow",`Failed to call model: ${String(T)}; Retry in ${A} seconds...`)),Promise.resolve()),initialInterval:2,maxInterval:16,multiplier:2,maxAttempt:5});if(h.status===429||h.status>=500)return console.error(ho("yellow",`Model rate limit exceeded. Retry in ${r} seconds...`)),await new Promise(T=>setTimeout(T,r*1e3)),cs(n,e,t,s+1);if(h.status!==200)throw new Error(`Failed to call OpenAI compatible model: status=${h.status}, body=${await h.text()}`);if(!h.body)throw new Error("Response body is empty");let b=h.body.getReader(),y=n.name==="bedrock"?ze:Cg,S=[],w;for await(let T of y(b)){S.push(T);let A=$g(T,w);if(A.length&&(w=A.at(-1)),t.onPartialMessageContent)for(let $ of A)t.onPartialMessageContent($)}let k=xg(S);if(k instanceof Error)return console.error(ho("yellow",`Failed to process stream: ${k.message}; Retry in ${r} seconds...`)),await new Promise(T=>setTimeout(T,r*1e3)),cs(n,e,t,s+1);let v=k.choices[0].message;return{message:Ag(v),providerTokenUsage:k.usage}})}function kg(n){let e=[];for(let t of n)switch(t.role){case"system":{e.push({role:"system",content:t.content.map(s=>({type:"text",text:s.text}))});break}case"user":{let s=t.content.filter(a=>a.type==="tool_result"),r=t.content.filter(a=>a.type==="text"||a.type==="image"),o=0;for(let a of s){let c=a.content.map(l=>{switch(l.type){case"text":return l.text;case"image":return o+=1,`(Image [${o}] omitted. See next message from user.)`;default:throw new Error(`Unsupported content part: ${JSON.stringify(l)}`)}}).join(`
411
+
412
+ `);e.push({role:"tool",tool_call_id:a.toolUseId,content:c})}let i=[];for(let a of s)for(let c of a.content)c.type==="image"&&i.push({type:"image_url",image_url:{url:`data:${c.mimeType};base64,${c.data}`}});i.length&&e.push({role:"user",content:i}),r.length&&e.push({role:"user",content:r.map(a=>{if(a.type==="text")return{type:"text",text:a.text};if(a.type==="image")return{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}};throw new Error(`Unsupported content part: ${JSON.stringify(a)}`)})});break}case"assistant":{let s=t.content.filter(l=>l.type==="thinking");s.length>1&&console.error(`OpenAI Unsupported message format: ${JSON.stringify(t)}`);let r=s.map(l=>l.thinking).join(`
413
+ `),o=t.content.filter(l=>l.type==="text");o.length>1&&console.error(`OpenAI Unsupported message format: ${JSON.stringify(t)}`);let i=o.map(l=>l.text).join(`
414
+ `),c=t.content.filter(l=>l.type==="tool_use").map(l=>({id:l.toolUseId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}}));e.push({role:"assistant",reasoning_content:r||void 0,content:i||void 0,tool_calls:c.length?c:void 0})}}return e}function Tg(n){let e=[];for(let t of n)e.push({type:"function",function:{name:t.name,description:t.description,parameters:t.inputSchema}});return e}function Ag(n){let e=[];if(n.reasoning_content&&e.push({type:"thinking",thinking:n.reasoning_content}),n.content&&e.push({type:"text",text:n.content}),n.tool_calls)for(let t of n.tool_calls)if(t.type==="function"){let s;try{s=JSON.parse(t.function.arguments)}catch(r){s={err:String(r)}}e.push({type:"tool_use",toolUseId:t.id,toolName:t.function.name,input:s})}else throw new Error(`Unsupported tool call type: ${JSON.stringify(t)}`);return{role:"assistant",content:e}}function xg(n){let e=n.at(0);if(!e)return new Error("No data found in the stream");let t=e.choices.at(0);if(!t)return new Error("No choice found in the first data");let s=t.delta,r={...e,choices:[{index:t.index,message:s,finish_reason:t.finish_reason}]};for(let o=1;o<n.length;o++){let i=n[o],a=i?.choices.at(0);if(a){let c=a.delta;if(c.reasoning_content&&(s.reasoning_content=(s.reasoning_content??"")+c.reasoning_content),c.content&&(s.content=(s.content??"")+c.content),c.tool_calls)for(let l of c.tool_calls){let f=s.tool_calls?.at(l.index);f||(s.tool_calls||(s.tool_calls=[]),s.tool_calls.push(l)),f&&l.function&&(f.function.arguments=(f.function.arguments??"")+l.function.arguments)}a.finish_reason&&r.choices&&(r.choices[0].finish_reason=a.finish_reason)}i.usage&&(r.usage=i.usage)}return r}function $g(n,e){let t=[],s=n.choices.at(0);return s?.delta.reasoning_content&&t.push({type:"thinking",content:s?.delta.reasoning_content,position:e?.type==="thinking"?"delta":"start"}),s?.delta.content&&t.push({type:"text",content:s.delta.content,position:e?.type==="text"?"delta":"start"}),s?.delta.tool_calls&&t.push({type:"tool_use",content:[s.delta.tool_calls.at(0)?.function?.name,s.delta.tool_calls.at(0)?.function?.arguments].join(" "),position:e?.type==="tool_use"?"delta":"start"}),s?.finish_reason&&t.push({type:e?.type||"unknown",position:"stop"}),t.length&&e&&t[0].position!=="stop"&&t[0].type!==e.type&&t.unshift({type:e.type,position:"stop"}),t}async function*Cg(n){let e=new Uint8Array;for(;;){let{done:t,value:s}=await n.read();if(t)break;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let o=10,i=[];for(let a=0;a<e.length-1;a++)e[a]===o&&e[a+1]===o&&i.push(a);for(let a=0;a<i.length;a++){let c=a===0?0:i[a-1]+2,l=i[a],f=e.slice(c,l),u=new TextDecoder().decode(f);if(u==="data: [DONE]")break;u.startsWith("data: ")&&(yield JSON.parse(u.slice(6)))}i.length&&(e=e.slice(i[i.length-1]+2))}}function Il(n){let{platform:e,model:t}=n;switch(t.format){case"anthropic":return s=>fo(e,t.config,s);case"gemini":{let s=Cl(e,t.config);return r=>s(t.config,r)}case"openai-responses":return s=>as(e,t.config,s);case"openai-messages":return s=>cs(e,t.config,s);case"bedrock-converse":return s=>mo(e,t.config,s)}}import{styleText as Eg}from"node:util";function Ol(n){async function e(t,s=0){let r=n.model??"gemini-3-flash-preview",o=n.provider==="gemini-vertex-ai"?`${n.baseURL}/publishers/google/models/${n.model}:generateContent`:n.baseURL?`${n.baseURL}/models/${r}:generateContent`:`https://generativelanguage.googleapis.com/v1beta/models/${r}:generateContent`,i=n.provider==="gemini-vertex-ai"?{Authorization:`Bearer ${await ne(n.account)}`}:{"x-goog-api-key":n.apiKey??""},a={contents:[{role:"user",parts:[{text:`I need a comprehensive answer to this question. Please note that I don't have access to external URLs, so include all relevant facts, data, or explanations directly in your response. Avoid referencing links I can't open.
415
+
416
+ Question: ${t.question}`}]}],tools:[{url_context:{}}]},c=await fetch(o,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(120*1e3)});if(c.status===429||c.status>=500){let y=Math.min(2*2**s,16);return console.error(Eg("yellow",`Google API returned ${c.status}. Retrying in ${y} seconds...`)),await new Promise(S=>setTimeout(S,y*1e3)),e(t,s+1)}if(!c.ok)return new Error(`Failed to ask Web: status=${c.status}, body=${await c.text()}`);let l=await c.json(),f=l.candidates?.[0],u=f?.content?.parts?.[0]?.text,d=f?.groundingMetadata?.groundingSupports,p=f?.groundingMetadata?.groundingChunks;if(typeof u!="string")return new Error(`Unexpected response format from Google: ${JSON.stringify(l)}`);let g=(y,S,w)=>{let k=Buffer.from(y,"utf8"),v=Math.max(0,Math.min(S,k.length));return Buffer.concat([k.subarray(0,v),Buffer.from(w,"utf8"),k.subarray(v)]).toString("utf8")},m=d?.toSorted((y,S)=>(S.segment?.endIndex??0)-(y.segment?.endIndex??0)),h=u;for(let y of m??[]){let S=y.segment?.endIndex;typeof S!="number"||!y.groundingChunkIndices?.length||(h=g(h,S,` [${y.groundingChunkIndices.map(w=>w+1).join(", ")}] `))}let b=(p??[]).map((y,S)=>`- [${S+1} - ${y.web?.title}](${y.web?.uri})`).join(`
417
+ `);return[h,b].join(`
418
+
419
+ `)}return{def:{name:"ask_url",description:"Use one or more provided URLs to answer a question. Include the URLs in your question.",inputSchema:{type:"object",properties:{question:{type:"string",description:"The question to ask, including one or more URLs to use as context."}},required:["question"]}},impl:async t=>await P(async()=>e(t,0)),maskApprovalInput:t=>({})}}import{styleText as Ng}from"node:util";function Pl(n){async function e(t,s=0){let r=n.model??"gemini-3-flash-preview",o=n.provider==="gemini-vertex-ai"?`${n.baseURL}/publishers/google/models/${n.model}:generateContent`:n.baseURL?`${n.baseURL}/models/${r}:generateContent`:`https://generativelanguage.googleapis.com/v1beta/models/${r}:generateContent`,i=n.provider==="gemini-vertex-ai"?{Authorization:`Bearer ${await ne(n.account)}`}:{"x-goog-api-key":n.apiKey??""},a={contents:[{role:"user",parts:[{text:`I need a comprehensive answer to this question. Please note that I don't have access to external URLs, so include all relevant facts, data, or explanations directly in your response. Avoid referencing links I can't open.
420
+
421
+ Question: ${t.question}`}]}],tools:[{google_search:{}}]},c=await fetch(o,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(120*1e3)});if(c.status===429||c.status>=500){let y=Math.min(2*2**s,16);return console.error(Ng("yellow",`Google API returned ${c.status}. Retrying in ${y} seconds...`)),await new Promise(S=>setTimeout(S,y*1e3)),e(t,s+1)}if(!c.ok)return new Error(`Failed to ask Web: status=${c.status}, body=${await c.text()}`);let l=await c.json(),f=l.candidates?.[0],u=f?.content?.parts?.[0]?.text,d=f?.groundingMetadata?.groundingSupports,p=f?.groundingMetadata?.groundingChunks;if(typeof u!="string")return new Error(`Unexpected response format from Google: ${JSON.stringify(l)}`);let g=(y,S,w)=>{let k=Buffer.from(y,"utf8"),v=Math.max(0,Math.min(S,k.length));return Buffer.concat([k.subarray(0,v),Buffer.from(w,"utf8"),k.subarray(v)]).toString("utf8")},m=d?.toSorted((y,S)=>(S.segment?.endIndex??0)-(y.segment?.endIndex??0)),h=u;for(let y of m??[]){let S=y.segment?.endIndex;typeof S!="number"||!y.groundingChunkIndices?.length||(h=g(h,S,` [${y.groundingChunkIndices.map(w=>w+1).join(", ")}] `))}let b=(p??[]).map((y,S)=>`- [${S+1} - ${y.web?.title}](${y.web?.uri})`).join(`
422
+ `);return[h,b].join(`
423
+
424
+ `)}return{def:{name:"ask_web",description:"Use the web search to answer questions that need up-to-date information or supporting sources.",inputSchema:{type:"object",properties:{question:{type:"string",description:"The question to ask"}},required:["question"]}},impl:async t=>await P(async()=>e(t,0)),maskApprovalInput:t=>({})}}import{execFile as _g}from"node:child_process";function Xe(n,e){return typeof e=="string"?typeof n=="string"&&n===e:e instanceof RegExp?typeof n=="string"&&e.test(n):typeof e=="function"?e(n):Array.isArray(e)?Array.isArray(n)&&e.every((t,s)=>Xe(n[s],t)):typeof e=="object"?typeof n=="object"&&n!==null&&Object.entries(e).every(([t,s])=>Xe(n[t],s)):!1}var Ml=1024*8,Rt=1024*2;function Ll(n){return{def:{name:"exec_command",description:"Run a command without shell interpretation.",inputSchema:{type:"object",properties:{command:{description:"The executable name or path. e.g., rg",type:"string"},args:{description:"Array of arguments to pass to the command. Do not include the command name itself in this array.",type:"array",items:{type:"string"}}},required:["command"]}},validateInput:e=>{if(typeof e.command!="string")return new Error("command must be a string");if(e.command.match(/[<>]/))return new Error(`invalid tool use format: command=${JSON.stringify(e.command)}`);if(e.command.startsWith("-"))return new Error("command must not start with '-'");if(e.args&&!Array.isArray(e.args))return new Error("args must be an array of strings")},impl:async e=>await P(async()=>{let{command:t,args:s}=n?.sandbox?Ig(e,n.sandbox):e;return new Promise((r,o)=>{_g(t,s,{shell:!1,env:{PWD:process.env.PWD,PATH:process.env.PATH,HOME:process.env.HOME},timeout:3e5},async(a,c,l)=>{let f=async(g,m)=>{if(g.length<=Ml)return g;let h="txt";try{JSON.parse(g),h="json"}catch{}let b=`exec_command-${m}`,y=await ss(g,b,h),S=g.split(`
425
+ `).length,w=g.slice(0,Rt),k=g.slice(Math.max(g.length-Rt,0));return[`Content is too large (${g.length} characters, ${S} lines). Saved to ${y}.`,`<truncated_output part="start" length="${Rt}" total_length="${g.length}">
426
+ ${w}
427
+ </truncated_output>`,`<truncated_output part="end" length="${Rt}" total_length="${g.length}">
428
+ ${k}</truncated_output>
429
+ `].join(`
430
+
431
+ `)},u=await f(c,"stdout"),d=await f(l,"stderr"),p=[u?`<stdout>
432
+ ${u}</stdout>`:"<stdout></stdout>","",d?`<stderr>
433
+ ${d}</stderr>`:"<stderr></stderr>"];if(a&&![t,...s||[]].includes("rg")){let m=a.message.slice(0,Rt),h=a.message.length>Ml;p.push(`
434
+ <error>
435
+ ${a.name}: ${m}${h?"... (Message truncated)":""}</error>`)}return r(p.join(`
436
+ `))}).stdin?.end()})})}}function Ig(n,e){let t=(e.rules||[]).find(r=>Xe(n,r.pattern));if(t?.mode==="unsandboxed")return n;let s=[...e.args||[],...t?.additionalArgs||[]];return e.separator&&s.push(e.separator),s.push(n.command),n.args&&s.push(...n.args),{command:e.command,args:s}}import Rl from"node:fs/promises";function Dl(n=Math.random().toString(36).substring(2,5)){return{def:{name:"patch_file",description:"Modify a file by replacing specific content with new content.",inputSchema:{type:"object",properties:{filePath:{type:"string"},diff:{description:`
437
+ Format:
438
+ <<< ${n} <<< SEARCH
439
+ old content
440
+ === ${n} ===
441
+ new content
442
+ >>> ${n} >>> REPLACE
443
+
444
+ <<< ${n} <<< SEARCH
445
+ other old content
446
+ === ${n} ===
447
+ other new content
448
+ >>> ${n} >>> REPLACE
449
+
450
+ - Content is searched as an exact match including indentation and line breaks.
451
+ - The first match found will be replaced if there are multiple matches.
452
+ `.trim(),type:"string"}},required:["filePath","diff"]}},impl:async e=>await P(async()=>{let{filePath:t,diff:s}=e,r=`<<< ${n} <<< SEARCH`,o=`=== ${n} ===`,i=`>>> ${n} >>> REPLACE`,a=(g,m)=>g.split(m).length-1,c=a(s,r),l=a(s,o),f=a(s,i);if(c!==f)throw new Error(`Mismatched block markers: found ${c} "${r}" but ${f} "${i}". Did you accidentally include a marker in your search/replace content?`);if(l!==c)throw new Error(`Each diff block needs exactly one "${o}" separator, but found ${l} separators for ${c} block(s). Did you accidentally include the separator marker in your search/replace content?`);let u=await Rl.readFile(t,"utf8"),d=Array.from(s.matchAll(new RegExp(`<<< ${n} <<< SEARCH\\n(.*?)\\n=== ${n} ===\\n(.*?)\\n?>>> ${n} >>> REPLACE`,"gs")));if(d.length===0)throw new Error(`Invalid diff format. Each markers must include the nonce: <<< ${n} <<< SEARCH, === ${n} ===, >>> ${n} >>> REPLACE`);let p=u;for(let g of d){let[m,h,b]=g;if(!p.includes(h))throw new Error(JSON.stringify(`Search content not found: ${h}`));let y=b.replace(/\$/g,"$$$$");b===""&&p.includes(`${h}
453
+ `)?p=p.replace(`${h}
454
+ `,""):b===""&&p.includes(`
455
+ ${h}`)?p=p.replace(`
456
+ ${h}`,""):p=p.replace(h,y)}return await Rl.writeFile(t,p),`Patched file: ${t}`}),maskApprovalInput:e=>({filePath:e.filePath})}}import{execFile as go}from"node:child_process";var ye=1024*8;function ql(n){return{def:{name:"tmux_command",description:"Run a tmux command",inputSchema:{type:"object",properties:{command:{description:"The tmux command to run",type:"string"},args:{description:"Arguments to pass to the tmux command",type:"array",items:{type:"string"}}},required:["command"]}},impl:async e=>await P(async()=>{let{command:t}=e,s=e.args||[];if(t==="send-keys")for(let a=1;a<s.length;a++){let c=s[a];c.endsWith(";")&&!c.endsWith("\\;")&&(s[a]=`${c.slice(0,-1)}\\;`)}let r={shell:!1,env:{PWD:process.env.PWD,PATH:process.env.PATH,HOME:process.env.HOME}},o=({command:a,args:c})=>n?.sandbox?{command:n.sandbox.command,args:[...n.sandbox.args||[],a,...c]}:{command:a,args:c},i=o({command:"tmux",args:[t,...s]});return new Promise((a,c)=>{go(i.command,i.args,r,async(l,f,u)=>{let d=f.trim().slice(-ye),p=f.trim().length>ye,g=u.trim().slice(-ye),m=u.trim().length>ye,h=[d?`<stdout>
457
+ ${p?"(Output truncated) ...":""}${d}
458
+ </stdout>`:"<stdout></stdout>","",g?`<stderr>
459
+ ${m?"(Output truncated) ...":""}${g}
460
+ </stderr>`:"<stderr></stderr>"];if(l){let b=l.message.slice(0,ye),y=l.message.length>ye;h.push(`
461
+ <error>
462
+ ${l.name}: ${b}${y?"... (Message truncated)":""}</error>`)}if(["new-session","new","new-window"].includes(t)){let b=t.includes("window")?s.indexOf("-t")+1:s.indexOf("-s")+1,y=s[b],S=o({command:"tmux",args:["list-windows","-t",y]}),w=await new Promise((k,v)=>{go(S.command,S.args,r,(T,A,$)=>(T&&console.error(`Failed to list tmux windows: ${T.message}, stack=${T.stack}`),k(A)))});h.push(`
463
+ <tmux:list-windows>
464
+ ${w}</tmux:list-windows>`)}if(t==="send-keys"){await new Promise(T=>setTimeout(T,2e3));let b=s.indexOf("-t")+1,y=s[b],S=o({command:"tmux",args:["capture-pane","-p","-t",y]}),w=await new Promise((T,A)=>{go(S.command,S.args,r,($,C,N)=>($&&console.error(`Failed to capture tmux pane: ${$.message}, stack=${$.stack}`),T(C.trim())))}),k=w.slice(-ye),v=w.length>ye;h.push(`
465
+ <tmux:capture-pane target="${y}"">
466
+ ${v?"(Output truncated) ...":""}${k}
467
+ </tmux:capture-pane>`)}return a(h.join(`
468
+ `))})})})}}import Ul from"node:fs/promises";import jl from"node:path";var Fl={def:{name:"write_file",description:"Write a file",inputSchema:{type:"object",properties:{filePath:{type:"string"},content:{type:"string"}},required:["filePath","content"]}},impl:async n=>await P(async()=>{let{filePath:e,content:t}=n,s=jl.resolve(e),r=jl.dirname(s);return await Ul.mkdir(r,{recursive:!0}),await Ul.writeFile(s,t,"utf8"),`Wrote to file: ${e}`}),maskApprovalInput:n=>({filePath:n.filePath})};import{execFileSync as Og}from"node:child_process";import yo from"node:fs";import Ce from"node:path";function ls(n){return["number","boolean","undefined"].includes(typeof n)?!0:typeof n=="string"?Pg(n):Array.isArray(n)?n.every(e=>ls(e)):typeof n=="object"?n===null?!0:Object.values(n).every(e=>ls(e)):!1}function Pg(n){let e=process.cwd(),t=Ce.resolve(n),s=Mg(t,e);return!s||!Bl(s,e)||n.split(Ce.sep).includes("..")?!1:Lg(s)?!0:!Rg(s)}function Mg(n,e){let t=Ie(()=>yo.realpathSync(n));if(!(t instanceof Error))return t;let s=n,r=new Set,o=10;for(let i=0;i<o;i++){if(r.has(s))return null;r.add(s);let a=Ie(()=>yo.lstatSync(s));if(a instanceof Error||!a.isSymbolicLink())break;let c=Ie(()=>yo.readlinkSync(s));if(typeof c!="string")break;if(s=Ce.resolve(Ce.dirname(s),c),!Bl(s,e))return s}return r.size>=o?null:s}function Bl(n,e){return n===e||n.startsWith(`${e}${Ce.sep}`)}function Lg(n){let e=[Ne,et,_e];for(let t of e){let s=Ce.resolve(t);if(n===s||n.startsWith(`${s}${Ce.sep}`))return!0}return!1}function Rg(n){try{return Og("git",["check-ignore","--no-index","-q",n],{stdio:["ignore","ignore","ignore"]}),!0}catch(e){return!(e instanceof Error&&"status"in e&&typeof e.status=="number"&&e.status===1)}}function Kl({patterns:n,maxApprovals:e,defaultAction:t,maskApprovalInput:s}){let r={approvalCount:0,allowedToolUseInSession:[]};function o(){r.approvalCount=0}function i(c){let l={toolName:c.toolName,input:c.input};for(let f of[...n,...r.allowedToolUseInSession]){let u={toolName:f.toolName,...f.input!==void 0&&{input:f.input}};if(!Xe(l,u))continue;let d=f.action??t;if(!["allow","deny","ask"].includes(d))return{action:"ask"};if(d==="deny")return{action:"deny",reason:f.reason};if(d==="allow"){let p=s(c.toolName,c.input);return ls(p)?(r.approvalCount+=1,r.approvalCount<=e?{action:"allow"}:{action:"ask"}):{action:t}}return{action:d}}return{action:t}}function a(c){r.allowedToolUseInSession.push({toolName:c.toolName,input:s(c.toolName,c.input),action:"allow"})}return{isAllowedToolUse:i,allowToolUse:a,resetApprovalCount:o}}var F=Ko(process.argv);F.subcommand.type==="help"&&Go();if(F.subcommand.type==="list-models"){let{appConfig:n}=await st({skipTrustCheck:!0});(!n.models||n.models.length===0)&&(console.error("No models found in configuration."),process.exit(1));for(let e of n.models){let t=e.platform;console.log(`${e.name}+${e.variant} (platform: ${t.name}+${t.variant})`)}process.exit(0)}F.subcommand.type==="install-claude-code-plugins"&&(await Fo(),process.exit(0));if(F.subcommand.type==="cost")try{let n=await ri({from:F.subcommand.from,to:F.subcommand.to});process.exit(n)}catch(n){let e=n instanceof Error?n.message:String(n);console.error(e),process.exit(1)}(async()=>{let n=new Date,e=[`${n.getFullYear()}-${`0${n.getMonth()+1}`.slice(-2)}-${`0${n.getDate()}`.slice(-2)}`,`0${n.getHours()}`.slice(-2)+`0${n.getMinutes()}`.slice(-2)].join("-"),t=`agent-${e}`,s=F.subcommand.type==="batch",r=F.subcommand.type==="batch"||F.subcommand.type==="interactive"?F.subcommand.config:[],{appConfig:o,loadedConfigPath:i}=await st({skipUserConfig:s,skipTrustCheck:s,configFiles:r});if(!s)if(i.length>0&&(console.log(Dt("green",`
469
+ \u26A1 Loaded configuration files`)),console.log(i.map(C=>` \u2937 ${C}`).join(`
470
+ `))),o.sandbox){let C=[o.sandbox.command,...o.sandbox.args||[]].join(" ");console.log(Dt("green",`
471
+ \u{1F4E6} Sandbox: on`)),console.log(` \u2937 ${C}`)}else console.log(Dt("yellow",`
472
+ \u{1F4E6} Sandbox: off`));let a=[],c=[];if(o.mcpServers){let C=Object.entries(o.mcpServers);if(!s){console.log();for(let[E]of C)console.log(Dt("blue",`\u{1F50C} Connecting to MCP server: ${E}...`))}let N=await Promise.all(C.map(async([E,D])=>{let oe=await kl(E,D);return{serverName:E,...oe}}));for(let{serverName:E,tools:D,stderrLogPath:oe,cleanup:us}of N)c.push(...D),a.push(us),s||(console.log(Dt("green",`\u2705 Successfully connected to MCP server: ${E}`)),console.log(` \u2937 stderr log: ${oe}`))}let l=o.model||"",u=(F.subcommand.type==="batch"||F.subcommand.type==="interactive"?F.subcommand.model:null)||l,d=gs(o.claudeCodePlugins??[]),[p,g]=await Promise.all([ge(d),$e(d)]),m=Io({username:ko,modelName:u,workingDir:process.cwd(),today:new Date().toISOString().split("T")[0],sessionId:e,tmuxSessionId:t,projectMetadataDir:q,agentRoles:g,skills:Array.from(p.values()).filter(C=>C.isSkill)}),h=[Ll({sandbox:o.sandbox}),Fl,Dl(),ql({sandbox:o.sandbox}),To(),Lo(),Oo()];o.tools?.askWeb&&h.push(Pl(o.tools.askWeb)),o.tools?.askURL&&h.push(Ol(o.tools.askURL));let b=Kl({maxApprovals:o.autoApproval?.maxApprovals||50,defaultAction:o.autoApproval?.defaultAction||"ask",patterns:o.autoApproval?.patterns||[],maskApprovalInput:(C,N)=>{for(let E of h)if(E.def.name===C&&E.maskApprovalInput)return E.maskApprovalInput(N);return N}}),[y,S]=u.split("+"),w=(o.models??[]).find(C=>C.name===y&&C.variant===S);if(!w)throw new Error(`Model "${u}" not found in configuration.`);let k=(o.platforms??[]).find(C=>C.name===w.platform.name&&C.variant===w.platform.variant);if(!k)throw new Error(`Platform ${w.platform.name} variant=${w.platform.variant} not found in configuration.`);let{userEventEmitter:v,agentEventEmitter:T,agentCommands:A}=qo({callModel:Il({...w,platform:{...w.platform,...k}}),prompt:m,tools:[...h,...c],toolUseApprover:b,agentRoles:g,modelCostConfig:w.cost}),$={userEventEmitter:v,agentEventEmitter:T,agentCommands:A,sessionId:e,modelName:u,sandbox:!!o.sandbox,startTime:n,onStop:async()=>{for(let C of a)await C()}};if(F.subcommand.type==="batch"){let C=F.subcommand.task;if(!C)throw new Error("Batch task is required in batch mode");await ti({...$,task:C})}else wl({...$,notifyCmd:o.notifyCmd,claudeCodePlugins:gs(o.claudeCodePlugins??[]),voiceInput:o.voiceInput})})().catch(n=>{console.error(n),process.exit(1)});
473
+ //# sourceMappingURL=main.mjs.map