qlogicagent 2.24.7 → 2.24.9

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 (42) hide show
  1. package/dist/agent.js +10 -70
  2. package/dist/cli.js +7 -7
  3. package/dist/index.js +212 -272
  4. package/dist/orchestration.js +14 -14
  5. package/dist/types/agent/tool-loop/loop-helpers.d.ts +2 -34
  6. package/dist/types/agent/tool-loop.d.ts +7 -58
  7. package/dist/types/agent/types.d.ts +5 -17
  8. package/dist/types/cli/core-tools/agent-tool-service.d.ts +1 -2
  9. package/dist/types/cli/handlers/turn-handler.d.ts +1 -1
  10. package/dist/types/cli/mcp-bootstrap.d.ts +1 -1
  11. package/dist/types/cli/stdio-acp-protocol-coordinator.d.ts +1 -1
  12. package/dist/types/contracts/index.d.ts +1 -1
  13. package/dist/types/contracts/tool-execution-evidence.d.ts +0 -12
  14. package/dist/types/contracts/tool-name.d.ts +0 -5
  15. package/dist/types/contracts/turn-event.d.ts +7 -81
  16. package/dist/types/orchestration/tool-loop/tool-choice-policy.d.ts +0 -1
  17. package/dist/types/protocol/wire/notification-payloads.d.ts +2 -0
  18. package/dist/types/runtime/config/tunable-defaults.d.ts +0 -23
  19. package/dist/types/runtime/infra/agent-project-projection.d.ts +0 -1
  20. package/dist/types/runtime/infra/subagent-turn-snapshot.d.ts +0 -1
  21. package/dist/types/runtime/ports/agent-runtime-ports.d.ts +0 -1
  22. package/dist/types/runtime/prompt/system-prompt-sections.d.ts +1 -14
  23. package/dist/types/skills/tools/agent-tool.d.ts +0 -5
  24. package/dist/types/skills/tools/write-tool.d.ts +3 -11
  25. package/package.json +3 -4
  26. package/dist/types/agent/tool-loop/agent-argument-normalizer.d.ts +0 -12
  27. package/dist/types/agent/tool-loop/artifact-final-contract.d.ts +0 -171
  28. package/dist/types/agent/tool-loop/budget-continuation-policy.d.ts +0 -26
  29. package/dist/types/agent/tool-loop/completion-action-policy.d.ts +0 -48
  30. package/dist/types/agent/tool-loop/completion-stop-policy.d.ts +0 -19
  31. package/dist/types/agent/tool-loop/direct-response-contract.d.ts +0 -12
  32. package/dist/types/agent/tool-loop/final-status-stream-suppressor.d.ts +0 -22
  33. package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +0 -50
  34. package/dist/types/agent/tool-loop/tool-result-classification.d.ts +0 -10
  35. package/dist/types/agent/tool-loop.test-harness.d.ts +0 -20
  36. package/dist/types/cli/test-support/fs-cleanup.d.ts +0 -19
  37. package/dist/types/cli/test-support/tool-catalog-fixture.d.ts +0 -3
  38. package/dist/types/contracts/structured-planner.d.ts +0 -2
  39. package/dist/types/runtime/infra/token-budget.d.ts +0 -92
  40. package/dist/types/runtime/prompt/prompt-policy.d.ts +0 -12
  41. package/dist/types/test-support/global-home-setup.d.ts +0 -2
  42. package/dist/types/test-support/project-store-fixture.d.ts +0 -11
package/dist/agent.js CHANGED
@@ -1,74 +1,14 @@
1
- var th=Object.create;var fu=Object.defineProperty;var nh=Object.getOwnPropertyDescriptor;var oh=Object.getOwnPropertyNames;var rh=Object.getPrototypeOf,sh=Object.prototype.hasOwnProperty;var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ih=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of oh(t))!sh.call(e,r)&&r!==n&&fu(e,r,{get:()=>t[r],enumerable:!(o=nh(t,r))||o.enumerable});return e};var ah=(e,t,n)=>(n=e!=null?th(rh(e)):{},ih(t||!e||!e.__esModule?fu(n,"default",{value:e,enumerable:!0}):n,e));var oo=R(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.regexpCode=W.getEsmExportName=W.getProperty=W.safeStringify=W.stringify=W.strConcat=W.addCodeArg=W.str=W._=W.nil=W._Code=W.Name=W.IDENTIFIER=W._CodeOrName=void 0;var to=class{};W._CodeOrName=to;W.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var qt=class extends to{constructor(t){if(super(),!W.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};W.Name=qt;var Ue=class extends to{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((n,o)=>`${n}${o}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((n,o)=>(o instanceof qt&&(n[o.str]=(n[o.str]||0)+1),n),{})}};W._Code=Ue;W.nil=new Ue("");function Ju(e,...t){let n=[e[0]],o=0;for(;o<t.length;)xi(n,t[o]),n.push(e[++o]);return new Ue(n)}W._=Ju;var wi=new Ue("+");function Xu(e,...t){let n=[no(e[0])],o=0;for(;o<t.length;)n.push(wi),xi(n,t[o]),n.push(wi,no(e[++o]));return _y(n),new Ue(n)}W.str=Xu;function xi(e,t){t instanceof Ue?e.push(...t._items):t instanceof qt?e.push(t):e.push(ky(t))}W.addCodeArg=xi;function _y(e){let t=1;for(;t<e.length-1;){if(e[t]===wi){let n=vy(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function vy(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof qt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof qt))return`"${e}${t.slice(1)}`}function Ty(e,t){return t.emptyStr()?e:e.emptyStr()?t:Xu`${e}${t}`}W.strConcat=Ty;function ky(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:no(Array.isArray(e)?e.join(","):e)}function Cy(e){return new Ue(no(e))}W.stringify=Cy;function no(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}W.safeStringify=no;function Ry(e){return typeof e=="string"&&W.IDENTIFIER.test(e)?new Ue(`.${e}`):Ju`[${e}]`}W.getProperty=Ry;function wy(e){if(typeof e=="string"&&W.IDENTIFIER.test(e))return new Ue(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}W.getEsmExportName=wy;function xy(e){return new Ue(e.toString())}W.regexpCode=xy});var Ai=R(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var $e=oo(),Si=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},pr;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(pr||(Pe.UsedValueState=pr={}));Pe.varKinds={const:new $e.Name("const"),let:new $e.Name("let"),var:new $e.Name("var")};var mr=class{constructor({prefixes:t,parent:n}={}){this._names={},this._prefixes=t,this._parent=n}toName(t){return t instanceof $e.Name?t:this.name(t)}name(t){return new $e.Name(this._newName(t))}_newName(t){let n=this._names[t]||this._nameGroup(t);return`${t}${n.index++}`}_nameGroup(t){var n,o;if(!((o=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||o===void 0)&&o.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Pe.Scope=mr;var gr=class extends $e.Name{constructor(t,n){super(n),this.prefix=t}setValue(t,{property:n,itemIndex:o}){this.value=t,this.scopePath=(0,$e._)`.${new $e.Name(n)}[${o}]`}};Pe.ValueScopeName=gr;var Sy=(0,$e._)`\n`,Ei=class extends mr{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Sy:$e.nil}}get(){return this._scope}name(t){return new gr(t,this._newName(t))}value(t,n){var o;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let r=this.toName(t),{prefix:s}=r,i=(o=n.key)!==null&&o!==void 0?o:n.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,r);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=n.ref,r.setValue(n,{property:s,itemIndex:l}),r}getValue(t,n){let o=this._values[t];if(o)return o.get(n)}scopeRefs(t,n=this._values){return this._reduceValues(n,o=>{if(o.scopePath===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return(0,$e._)`${t}${o.scopePath}`})}scopeCode(t=this._values,n,o){return this._reduceValues(t,r=>{if(r.value===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return r.value.code},n,o)}_reduceValues(t,n,o={},r){let s=$e.nil;for(let i in t){let a=t[i];if(!a)continue;let c=o[i]=o[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,pr.Started);let d=n(l);if(d){let m=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;s=(0,$e._)`${s}${m} ${l} = ${d};${this.opts._n}`}else if(d=r?.(l))s=(0,$e._)`${s}${d}${this.opts._n}`;else throw new Si(l);c.set(l,pr.Completed)})}return s}};Pe.ValueScope=Ei});var F=R(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.or=D.and=D.not=D.CodeGen=D.operators=D.varKinds=D.ValueScopeName=D.ValueScope=D.Scope=D.Name=D.regexpCode=D.stringify=D.getProperty=D.nil=D.strConcat=D.str=D._=void 0;var V=oo(),Ze=Ai(),Ct=oo();Object.defineProperty(D,"_",{enumerable:!0,get:function(){return Ct._}});Object.defineProperty(D,"str",{enumerable:!0,get:function(){return Ct.str}});Object.defineProperty(D,"strConcat",{enumerable:!0,get:function(){return Ct.strConcat}});Object.defineProperty(D,"nil",{enumerable:!0,get:function(){return Ct.nil}});Object.defineProperty(D,"getProperty",{enumerable:!0,get:function(){return Ct.getProperty}});Object.defineProperty(D,"stringify",{enumerable:!0,get:function(){return Ct.stringify}});Object.defineProperty(D,"regexpCode",{enumerable:!0,get:function(){return Ct.regexpCode}});Object.defineProperty(D,"Name",{enumerable:!0,get:function(){return Ct.Name}});var _r=Ai();Object.defineProperty(D,"Scope",{enumerable:!0,get:function(){return _r.Scope}});Object.defineProperty(D,"ValueScope",{enumerable:!0,get:function(){return _r.ValueScope}});Object.defineProperty(D,"ValueScopeName",{enumerable:!0,get:function(){return _r.ValueScopeName}});Object.defineProperty(D,"varKinds",{enumerable:!0,get:function(){return _r.varKinds}});D.operators={GT:new V._Code(">"),GTE:new V._Code(">="),LT:new V._Code("<"),LTE:new V._Code("<="),EQ:new V._Code("==="),NEQ:new V._Code("!=="),NOT:new V._Code("!"),OR:new V._Code("||"),AND:new V._Code("&&"),ADD:new V._Code("+")};var pt=class{optimizeNodes(){return this}optimizeNames(t,n){return this}},$i=class extends pt{constructor(t,n,o){super(),this.varKind=t,this.name=n,this.rhs=o}render({es5:t,_n:n}){let o=t?Ze.varKinds.var:this.varKind,r=this.rhs===void 0?"":` = ${this.rhs}`;return`${o} ${this.name}${r};`+n}optimizeNames(t,n){if(t[this.name.str])return this.rhs&&(this.rhs=vn(this.rhs,t,n)),this}get names(){return this.rhs instanceof V._CodeOrName?this.rhs.names:{}}},hr=class extends pt{constructor(t,n,o){super(),this.lhs=t,this.rhs=n,this.sideEffects=o}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,n){if(!(this.lhs instanceof V.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=vn(this.rhs,t,n),this}get names(){let t=this.lhs instanceof V.Name?{}:{...this.lhs.names};return br(t,this.rhs)}},Pi=class extends hr{constructor(t,n,o,r){super(t,o,r),this.op=n}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Mi=class extends pt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Ii=class extends pt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Oi=class extends pt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Ni=class extends pt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,n){return this.code=vn(this.code,t,n),this}get names(){return this.code instanceof V._CodeOrName?this.code.names:{}}},ro=class extends pt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((n,o)=>n+o.render(t),"")}optimizeNodes(){let{nodes:t}=this,n=t.length;for(;n--;){let o=t[n].optimizeNodes();Array.isArray(o)?t.splice(n,1,...o):o?t[n]=o:t.splice(n,1)}return t.length>0?this:void 0}optimizeNames(t,n){let{nodes:o}=this,r=o.length;for(;r--;){let s=o[r];s.optimizeNames(t,n)||(Ey(t,s.names),o.splice(r,1))}return o.length>0?this:void 0}get names(){return this.nodes.reduce((t,n)=>Ht(t,n.names),{})}},mt=class extends ro{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Fi=class extends ro{},_n=class extends mt{};_n.kind="else";var Ut=class e extends mt{constructor(t,n){super(n),this.condition=t}render(t){let n=`if(${this.condition})`+super.render(t);return this.else&&(n+="else "+this.else.render(t)),n}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let o=n.optimizeNodes();n=this.else=Array.isArray(o)?new _n(o):o}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(Yu(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,n){var o;if(this.else=(o=this.else)===null||o===void 0?void 0:o.optimizeNames(t,n),!!(super.optimizeNames(t,n)||this.else))return this.condition=vn(this.condition,t,n),this}get names(){let t=super.names;return br(t,this.condition),this.else&&Ht(t,this.else.names),t}};Ut.kind="if";var zt=class extends mt{};zt.kind="for";var Li=class extends zt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,n){if(super.optimizeNames(t,n))return this.iteration=vn(this.iteration,t,n),this}get names(){return Ht(super.names,this.iteration.names)}},ji=class extends zt{constructor(t,n,o,r){super(),this.varKind=t,this.name=n,this.from=o,this.to=r}render(t){let n=t.es5?Ze.varKinds.var:this.varKind,{name:o,from:r,to:s}=this;return`for(${n} ${o}=${r}; ${o}<${s}; ${o}++)`+super.render(t)}get names(){let t=br(super.names,this.from);return br(t,this.to)}},yr=class extends zt{constructor(t,n,o,r){super(),this.loop=t,this.varKind=n,this.name=o,this.iterable=r}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,n){if(super.optimizeNames(t,n))return this.iterable=vn(this.iterable,t,n),this}get names(){return Ht(super.names,this.iterable.names)}},so=class extends mt{constructor(t,n,o){super(),this.name=t,this.args=n,this.async=o}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};so.kind="func";var io=class extends ro{render(t){return"return "+super.render(t)}};io.kind="return";var Di=class extends mt{render(t){let n="try"+super.render(t);return this.catch&&(n+=this.catch.render(t)),this.finally&&(n+=this.finally.render(t)),n}optimizeNodes(){var t,n;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(t,n){var o,r;return super.optimizeNames(t,n),(o=this.catch)===null||o===void 0||o.optimizeNames(t,n),(r=this.finally)===null||r===void 0||r.optimizeNames(t,n),this}get names(){let t=super.names;return this.catch&&Ht(t,this.catch.names),this.finally&&Ht(t,this.finally.names),t}},ao=class extends mt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};ao.kind="catch";var co=class extends mt{render(t){return"finally"+super.render(t)}};co.kind="finally";var Bi=class{constructor(t,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
2
- `:""},this._extScope=t,this._scope=new Ze.Scope({parent:t}),this._nodes=[new Fi]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,n){let o=this._extScope.value(t,n);return(this._values[o.prefix]||(this._values[o.prefix]=new Set)).add(o),o}getScopeValue(t,n){return this._extScope.getValue(t,n)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,n,o,r){let s=this._scope.toName(n);return o!==void 0&&r&&(this._constants[s.str]=o),this._leafNode(new $i(t,s,o)),s}const(t,n,o){return this._def(Ze.varKinds.const,t,n,o)}let(t,n,o){return this._def(Ze.varKinds.let,t,n,o)}var(t,n,o){return this._def(Ze.varKinds.var,t,n,o)}assign(t,n,o){return this._leafNode(new hr(t,n,o))}add(t,n){return this._leafNode(new Pi(t,D.operators.ADD,n))}code(t){return typeof t=="function"?t():t!==V.nil&&this._leafNode(new Ni(t)),this}object(...t){let n=["{"];for(let[o,r]of t)n.length>1&&n.push(","),n.push(o),(o!==r||this.opts.es5)&&(n.push(":"),(0,V.addCodeArg)(n,r));return n.push("}"),new V._Code(n)}if(t,n,o){if(this._blockNode(new Ut(t)),n&&o)this.code(n).else().code(o).endIf();else if(n)this.code(n).endIf();else if(o)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Ut(t))}else(){return this._elseNode(new _n)}endIf(){return this._endBlockNode(Ut,_n)}_for(t,n){return this._blockNode(t),n&&this.code(n).endFor(),this}for(t,n){return this._for(new Li(t),n)}forRange(t,n,o,r,s=this.opts.es5?Ze.varKinds.var:Ze.varKinds.let){let i=this._scope.toName(t);return this._for(new ji(s,i,n,o),()=>r(i))}forOf(t,n,o,r=Ze.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=n instanceof V.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,V._)`${i}.length`,a=>{this.var(s,(0,V._)`${i}[${a}]`),o(s)})}return this._for(new yr("of",r,s,n),()=>o(s))}forIn(t,n,o,r=this.opts.es5?Ze.varKinds.var:Ze.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,V._)`Object.keys(${n})`,o);let s=this._scope.toName(t);return this._for(new yr("in",r,s,n),()=>o(s))}endFor(){return this._endBlockNode(zt)}label(t){return this._leafNode(new Mi(t))}break(t){return this._leafNode(new Ii(t))}return(t){let n=new io;if(this._blockNode(n),this.code(t),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(io)}try(t,n,o){if(!n&&!o)throw new Error('CodeGen: "try" without "catch" and "finally"');let r=new Di;if(this._blockNode(r),this.code(t),n){let s=this.name("e");this._currNode=r.catch=new ao(s),n(s)}return o&&(this._currNode=r.finally=new co,this.code(o)),this._endBlockNode(ao,co)}throw(t){return this._leafNode(new Oi(t))}block(t,n){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(n),this}endBlock(t){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let o=this._nodes.length-n;if(o<0||t!==void 0&&o!==t)throw new Error(`CodeGen: wrong number of nodes: ${o} vs ${t} expected`);return this._nodes.length=n,this}func(t,n=V.nil,o,r){return this._blockNode(new so(t,n,o)),r&&this.code(r).endFunc(),this}endFunc(){return this._endBlockNode(so)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,n){let o=this._currNode;if(o instanceof t||n&&o instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${t.kind}/${n.kind}`:t.kind}"`)}_elseNode(t){let n=this._currNode;if(!(n instanceof Ut))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let n=this._nodes;n[n.length-1]=t}};D.CodeGen=Bi;function Ht(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function br(e,t){return t instanceof V._CodeOrName?Ht(e,t.names):e}function vn(e,t,n){if(e instanceof V.Name)return o(e);if(!r(e))return e;return new V._Code(e._items.reduce((s,i)=>(i instanceof V.Name&&(i=o(i)),i instanceof V._Code?s.push(...i._items):s.push(i),s),[]));function o(s){let i=n[s.str];return i===void 0||t[s.str]!==1?s:(delete t[s.str],i)}function r(s){return s instanceof V._Code&&s._items.some(i=>i instanceof V.Name&&t[i.str]===1&&n[i.str]!==void 0)}}function Ey(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function Yu(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,V._)`!${qi(e)}`}D.not=Yu;var Ay=Zu(D.operators.AND);function $y(...e){return e.reduce(Ay)}D.and=$y;var Py=Zu(D.operators.OR);function My(...e){return e.reduce(Py)}D.or=My;function Zu(e){return(t,n)=>t===V.nil?n:n===V.nil?t:(0,V._)`${qi(t)} ${e} ${qi(n)}`}function qi(e){return e instanceof V.Name?e:(0,V._)`(${e})`}});var U=R(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var Z=F(),Iy=oo();function Oy(e){let t={};for(let n of e)t[n]=!0;return t}q.toHash=Oy;function Ny(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(td(e,t),!nd(t,e.self.RULES.all))}q.alwaysValidSchema=Ny;function td(e,t=e.schema){let{opts:n,self:o}=e;if(!n.strictSchema||typeof t=="boolean")return;let r=o.RULES.keywords;for(let s in t)r[s]||sd(e,`unknown keyword: "${s}"`)}q.checkUnknownRules=td;function nd(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(t[n])return!0;return!1}q.schemaHasRules=nd;function Fy(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}q.schemaHasRulesButRef=Fy;function Ly({topSchemaRef:e,schemaPath:t},n,o,r){if(!r){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Z._)`${n}`}return(0,Z._)`${e}${t}${(0,Z.getProperty)(o)}`}q.schemaRefOrVal=Ly;function jy(e){return od(decodeURIComponent(e))}q.unescapeFragment=jy;function Dy(e){return encodeURIComponent(zi(e))}q.escapeFragment=Dy;function zi(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=zi;function od(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=od;function By(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}q.eachItem=By;function Qu({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:o}){return(r,s,i,a)=>{let c=i===void 0?s:i instanceof Z.Name?(s instanceof Z.Name?e(r,s,i):t(r,s,i),i):s instanceof Z.Name?(t(r,i,s),s):n(s,i);return a===Z.Name&&!(c instanceof Z.Name)?o(r,c):c}}q.mergeEvaluated={props:Qu({mergeNames:(e,t,n)=>e.if((0,Z._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,Z._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,Z._)`${n} || {}`).code((0,Z._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,Z._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,Z._)`${n} || {}`),Hi(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:rd}),items:Qu({mergeNames:(e,t,n)=>e.if((0,Z._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,Z._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,Z._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,Z._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function rd(e,t){if(t===!0)return e.var("props",!0);let n=e.var("props",(0,Z._)`{}`);return t!==void 0&&Hi(e,n,t),n}q.evaluatedPropsToName=rd;function Hi(e,t,n){Object.keys(n).forEach(o=>e.assign((0,Z._)`${t}${(0,Z.getProperty)(o)}`,!0))}q.setEvaluated=Hi;var ed={};function qy(e,t){return e.scopeValue("func",{ref:t,code:ed[t.code]||(ed[t.code]=new Iy._Code(t.code))})}q.useFunc=qy;var Ui;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ui||(q.Type=Ui={}));function Uy(e,t,n){if(e instanceof Z.Name){let o=t===Ui.Num;return n?o?(0,Z._)`"[" + ${e} + "]"`:(0,Z._)`"['" + ${e} + "']"`:o?(0,Z._)`"/" + ${e}`:(0,Z._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Z.getProperty)(e).toString():"/"+zi(e)}q.getErrorPath=Uy;function sd(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}q.checkStrictMode=sd});var ze=R(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});var _e=F(),zy={data:new _e.Name("data"),valCxt:new _e.Name("valCxt"),instancePath:new _e.Name("instancePath"),parentData:new _e.Name("parentData"),parentDataProperty:new _e.Name("parentDataProperty"),rootData:new _e.Name("rootData"),dynamicAnchors:new _e.Name("dynamicAnchors"),vErrors:new _e.Name("vErrors"),errors:new _e.Name("errors"),this:new _e.Name("this"),self:new _e.Name("self"),scope:new _e.Name("scope"),json:new _e.Name("json"),jsonPos:new _e.Name("jsonPos"),jsonLen:new _e.Name("jsonLen"),jsonPart:new _e.Name("jsonPart")};Vi.default=zy});var lo=R(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.extendErrors=ve.resetErrorsCount=ve.reportExtraError=ve.reportError=ve.keyword$DataError=ve.keywordError=void 0;var G=F(),vr=U(),Re=ze();ve.keywordError={message:({keyword:e})=>(0,G.str)`must pass "${e}" keyword validation`};ve.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,G.str)`"${e}" keyword must be ${t} ($data)`:(0,G.str)`"${e}" keyword is invalid ($data)`};function Hy(e,t=ve.keywordError,n,o){let{it:r}=e,{gen:s,compositeRule:i,allErrors:a}=r,c=cd(e,t,n);o??(i||a)?id(s,c):ad(r,(0,G._)`[${c}]`)}ve.reportError=Hy;function Vy(e,t=ve.keywordError,n){let{it:o}=e,{gen:r,compositeRule:s,allErrors:i}=o,a=cd(e,t,n);id(r,a),s||i||ad(o,Re.default.vErrors)}ve.reportExtraError=Vy;function Gy(e,t){e.assign(Re.default.errors,t),e.if((0,G._)`${Re.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,G._)`${Re.default.vErrors}.length`,t),()=>e.assign(Re.default.vErrors,null)))}ve.resetErrorsCount=Gy;function Wy({gen:e,keyword:t,schemaValue:n,data:o,errsCount:r,it:s}){if(r===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",r,Re.default.errors,a=>{e.const(i,(0,G._)`${Re.default.vErrors}[${a}]`),e.if((0,G._)`${i}.instancePath === undefined`,()=>e.assign((0,G._)`${i}.instancePath`,(0,G.strConcat)(Re.default.instancePath,s.errorPath))),e.assign((0,G._)`${i}.schemaPath`,(0,G.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,G._)`${i}.schema`,n),e.assign((0,G._)`${i}.data`,o))})}ve.extendErrors=Wy;function id(e,t){let n=e.const("err",t);e.if((0,G._)`${Re.default.vErrors} === null`,()=>e.assign(Re.default.vErrors,(0,G._)`[${n}]`),(0,G._)`${Re.default.vErrors}.push(${n})`),e.code((0,G._)`${Re.default.errors}++`)}function ad(e,t){let{gen:n,validateName:o,schemaEnv:r}=e;r.$async?n.throw((0,G._)`new ${e.ValidationError}(${t})`):(n.assign((0,G._)`${o}.errors`,t),n.return(!1))}var Vt={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function cd(e,t,n){let{createErrors:o}=e.it;return o===!1?(0,G._)`{}`:Ky(e,t,n)}function Ky(e,t,n={}){let{gen:o,it:r}=e,s=[Jy(r,n),Xy(e,n)];return Yy(e,t,s),o.object(...s)}function Jy({errorPath:e},{instancePath:t}){let n=t?(0,G.str)`${e}${(0,vr.getErrorPath)(t,vr.Type.Str)}`:e;return[Re.default.instancePath,(0,G.strConcat)(Re.default.instancePath,n)]}function Xy({keyword:e,it:{errSchemaPath:t}},{schemaPath:n,parentSchema:o}){let r=o?t:(0,G.str)`${t}/${e}`;return n&&(r=(0,G.str)`${r}${(0,vr.getErrorPath)(n,vr.Type.Str)}`),[Vt.schemaPath,r]}function Yy(e,{params:t,message:n},o){let{keyword:r,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:m}=a;o.push([Vt.keyword,r],[Vt.params,typeof t=="function"?t(e):t||(0,G._)`{}`]),c.messages&&o.push([Vt.message,typeof n=="function"?n(e):n]),c.verbose&&o.push([Vt.schema,i],[Vt.parentSchema,(0,G._)`${d}${m}`],[Re.default.data,s]),l&&o.push([Vt.propertyName,l])}});var ud=R(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.boolOrEmptySchema=Tn.topBoolOrEmptySchema=void 0;var Zy=lo(),Qy=F(),eb=ze(),tb={message:"boolean schema is false"};function nb(e){let{gen:t,schema:n,validateName:o}=e;n===!1?ld(e,!1):typeof n=="object"&&n.$async===!0?t.return(eb.default.data):(t.assign((0,Qy._)`${o}.errors`,null),t.return(!0))}Tn.topBoolOrEmptySchema=nb;function ob(e,t){let{gen:n,schema:o}=e;o===!1?(n.var(t,!1),ld(e)):n.var(t,!0)}Tn.boolOrEmptySchema=ob;function ld(e,t){let{gen:n,data:o}=e,r={gen:n,keyword:"false schema",data:o,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Zy.reportError)(r,tb,void 0,t)}});var Gi=R(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.getRules=kn.isJSONType=void 0;var rb=["string","number","integer","boolean","null","object","array"],sb=new Set(rb);function ib(e){return typeof e=="string"&&sb.has(e)}kn.isJSONType=ib;function ab(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}kn.getRules=ab});var Wi=R(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.shouldUseRule=Rt.shouldUseGroup=Rt.schemaHasRulesForType=void 0;function cb({schema:e,self:t},n){let o=t.RULES.types[n];return o&&o!==!0&&dd(e,o)}Rt.schemaHasRulesForType=cb;function dd(e,t){return t.rules.some(n=>fd(e,n))}Rt.shouldUseGroup=dd;function fd(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(o=>e[o]!==void 0))}Rt.shouldUseRule=fd});var uo=R(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.reportTypeError=Te.checkDataTypes=Te.checkDataType=Te.coerceAndCheckDataType=Te.getJSONTypes=Te.getSchemaTypes=Te.DataType=void 0;var lb=Gi(),ub=Wi(),db=lo(),L=F(),pd=U(),Cn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Cn||(Te.DataType=Cn={}));function fb(e){let t=md(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Te.getSchemaTypes=fb;function md(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(lb.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Te.getJSONTypes=md;function pb(e,t){let{gen:n,data:o,opts:r}=e,s=mb(t,r.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,ub.schemaHasRulesForType)(e,t[0]));if(i){let a=Ji(t,o,r.strictNumbers,Cn.Wrong);n.if(a,()=>{s.length?gb(e,t,s):Xi(e)})}return i}Te.coerceAndCheckDataType=pb;var gd=new Set(["string","number","integer","boolean","null"]);function mb(e,t){return t?e.filter(n=>gd.has(n)||t==="array"&&n==="array"):[]}function gb(e,t,n){let{gen:o,data:r,opts:s}=e,i=o.let("dataType",(0,L._)`typeof ${r}`),a=o.let("coerced",(0,L._)`undefined`);s.coerceTypes==="array"&&o.if((0,L._)`${i} == 'object' && Array.isArray(${r}) && ${r}.length == 1`,()=>o.assign(r,(0,L._)`${r}[0]`).assign(i,(0,L._)`typeof ${r}`).if(Ji(t,r,s.strictNumbers),()=>o.assign(a,r))),o.if((0,L._)`${a} !== undefined`);for(let l of n)(gd.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);o.else(),Xi(e),o.endIf(),o.if((0,L._)`${a} !== undefined`,()=>{o.assign(r,a),hb(e,a)});function c(l){switch(l){case"string":o.elseIf((0,L._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,L._)`"" + ${r}`).elseIf((0,L._)`${r} === null`).assign(a,(0,L._)`""`);return;case"number":o.elseIf((0,L._)`${i} == "boolean" || ${r} === null
3
- || (${i} == "string" && ${r} && ${r} == +${r})`).assign(a,(0,L._)`+${r}`);return;case"integer":o.elseIf((0,L._)`${i} === "boolean" || ${r} === null
4
- || (${i} === "string" && ${r} && ${r} == +${r} && !(${r} % 1))`).assign(a,(0,L._)`+${r}`);return;case"boolean":o.elseIf((0,L._)`${r} === "false" || ${r} === 0 || ${r} === null`).assign(a,!1).elseIf((0,L._)`${r} === "true" || ${r} === 1`).assign(a,!0);return;case"null":o.elseIf((0,L._)`${r} === "" || ${r} === 0 || ${r} === false`),o.assign(a,null);return;case"array":o.elseIf((0,L._)`${i} === "string" || ${i} === "number"
5
- || ${i} === "boolean" || ${r} === null`).assign(a,(0,L._)`[${r}]`)}}}function hb({gen:e,parentData:t,parentDataProperty:n},o){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${n}]`,o))}function Ki(e,t,n,o=Cn.Correct){let r=o===Cn.Correct?L.operators.EQ:L.operators.NEQ,s;switch(e){case"null":return(0,L._)`${t} ${r} null`;case"array":s=(0,L._)`Array.isArray(${t})`;break;case"object":s=(0,L._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,L._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,L._)`typeof ${t} ${r} ${e}`}return o===Cn.Correct?s:(0,L.not)(s);function i(a=L.nil){return(0,L.and)((0,L._)`typeof ${t} == "number"`,a,n?(0,L._)`isFinite(${t})`:L.nil)}}Te.checkDataType=Ki;function Ji(e,t,n,o){if(e.length===1)return Ki(e[0],t,n,o);let r,s=(0,pd.toHash)(e);if(s.array&&s.object){let i=(0,L._)`typeof ${t} != "object"`;r=s.null?i:(0,L._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else r=L.nil;s.number&&delete s.integer;for(let i in s)r=(0,L.and)(r,Ki(i,t,n,o));return r}Te.checkDataTypes=Ji;var yb={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function Xi(e){let t=bb(e);(0,db.reportError)(t,yb)}Te.reportTypeError=Xi;function bb(e){let{gen:t,data:n,schema:o}=e,r=(0,pd.schemaRefOrVal)(e,o,"type");return{gen:t,keyword:"type",data:n,schema:o.type,schemaCode:r,schemaValue:r,parentSchema:o,params:{},it:e}}});var yd=R(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.assignDefaults=void 0;var Rn=F(),_b=U();function vb(e,t){let{properties:n,items:o}=e.schema;if(t==="object"&&n)for(let r in n)hd(e,r,n[r].default);else t==="array"&&Array.isArray(o)&&o.forEach((r,s)=>hd(e,s,r.default))}Tr.assignDefaults=vb;function hd(e,t,n){let{gen:o,compositeRule:r,data:s,opts:i}=e;if(n===void 0)return;let a=(0,Rn._)`${s}${(0,Rn.getProperty)(t)}`;if(r){(0,_b.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Rn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Rn._)`${c} || ${a} === null || ${a} === ""`),o.if(c,(0,Rn._)`${a} = ${(0,Rn.stringify)(n)}`)}});var He=R(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.validateUnion=X.validateArray=X.usePattern=X.callValidateCode=X.schemaProperties=X.allSchemaProperties=X.noPropertyInData=X.propertyInData=X.isOwnProperty=X.hasPropFunc=X.reportMissingProp=X.checkMissingProp=X.checkReportMissingProp=void 0;var te=F(),Yi=U(),wt=ze(),Tb=U();function kb(e,t){let{gen:n,data:o,it:r}=e;n.if(Qi(n,o,t,r.opts.ownProperties),()=>{e.setParams({missingProperty:(0,te._)`${t}`},!0),e.error()})}X.checkReportMissingProp=kb;function Cb({gen:e,data:t,it:{opts:n}},o,r){return(0,te.or)(...o.map(s=>(0,te.and)(Qi(e,t,s,n.ownProperties),(0,te._)`${r} = ${s}`)))}X.checkMissingProp=Cb;function Rb(e,t){e.setParams({missingProperty:t},!0),e.error()}X.reportMissingProp=Rb;function bd(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,te._)`Object.prototype.hasOwnProperty`})}X.hasPropFunc=bd;function Zi(e,t,n){return(0,te._)`${bd(e)}.call(${t}, ${n})`}X.isOwnProperty=Zi;function wb(e,t,n,o){let r=(0,te._)`${t}${(0,te.getProperty)(n)} !== undefined`;return o?(0,te._)`${r} && ${Zi(e,t,n)}`:r}X.propertyInData=wb;function Qi(e,t,n,o){let r=(0,te._)`${t}${(0,te.getProperty)(n)} === undefined`;return o?(0,te.or)(r,(0,te.not)(Zi(e,t,n))):r}X.noPropertyInData=Qi;function _d(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}X.allSchemaProperties=_d;function xb(e,t){return _d(t).filter(n=>!(0,Yi.alwaysValidSchema)(e,t[n]))}X.schemaProperties=xb;function Sb({schemaCode:e,data:t,it:{gen:n,topSchemaRef:o,schemaPath:r,errorPath:s},it:i},a,c,l){let d=l?(0,te._)`${e}, ${t}, ${o}${r}`:t,m=[[wt.default.instancePath,(0,te.strConcat)(wt.default.instancePath,s)],[wt.default.parentData,i.parentData],[wt.default.parentDataProperty,i.parentDataProperty],[wt.default.rootData,wt.default.rootData]];i.opts.dynamicRef&&m.push([wt.default.dynamicAnchors,wt.default.dynamicAnchors]);let y=(0,te._)`${d}, ${n.object(...m)}`;return c!==te.nil?(0,te._)`${a}.call(${c}, ${y})`:(0,te._)`${a}(${y})`}X.callValidateCode=Sb;var Eb=(0,te._)`new RegExp`;function Ab({gen:e,it:{opts:t}},n){let o=t.unicodeRegExp?"u":"",{regExp:r}=t.code,s=r(n,o);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,te._)`${r.code==="new RegExp"?Eb:(0,Tb.useFunc)(e,r)}(${n}, ${o})`})}X.usePattern=Ab;function $b(e){let{gen:t,data:n,keyword:o,it:r}=e,s=t.name("valid");if(r.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let c=t.const("len",(0,te._)`${n}.length`);t.forRange("i",0,c,l=>{e.subschema({keyword:o,dataProp:l,dataPropType:Yi.Type.Num},s),t.if((0,te.not)(s),a)})}}X.validateArray=$b;function Pb(e){let{gen:t,schema:n,keyword:o,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Yi.alwaysValidSchema)(r,c))&&!r.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>n.forEach((c,l)=>{let d=e.subschema({keyword:o,schemaProp:l,compositeRule:!0},a);t.assign(i,(0,te._)`${i} || ${a}`),e.mergeValidEvaluated(d,a)||t.if((0,te.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}X.validateUnion=Pb});var kd=R(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.validateKeywordUsage=it.validSchemaType=it.funcKeywordCode=it.macroKeywordCode=void 0;var we=F(),Gt=ze(),Mb=He(),Ib=lo();function Ob(e,t){let{gen:n,keyword:o,schema:r,parentSchema:s,it:i}=e,a=t.macro.call(i.self,r,s,i),c=Td(n,o,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=n.name("valid");e.subschema({schema:a,schemaPath:we.nil,errSchemaPath:`${i.errSchemaPath}/${o}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}it.macroKeywordCode=Ob;function Nb(e,t){var n;let{gen:o,keyword:r,schema:s,parentSchema:i,$data:a,it:c}=e;Lb(c,t);let l=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,d=Td(o,r,l),m=o.let("valid");e.block$data(m,y),e.ok((n=t.valid)!==null&&n!==void 0?n:m);function y(){if(t.errors===!1)v(),t.modifying&&vd(e),k(()=>e.error());else{let C=t.async?_():h();t.modifying&&vd(e),k(()=>Fb(e,C))}}function _(){let C=o.let("ruleErrs",null);return o.try(()=>v((0,we._)`await `),E=>o.assign(m,!1).if((0,we._)`${E} instanceof ${c.ValidationError}`,()=>o.assign(C,(0,we._)`${E}.errors`),()=>o.throw(E))),C}function h(){let C=(0,we._)`${d}.errors`;return o.assign(C,null),v(we.nil),C}function v(C=t.async?(0,we._)`await `:we.nil){let E=c.opts.passContext?Gt.default.this:Gt.default.self,O=!("compile"in t&&!a||t.schema===!1);o.assign(m,(0,we._)`${C}${(0,Mb.callValidateCode)(e,d,E,O)}`,t.modifying)}function k(C){var E;o.if((0,we.not)((E=t.valid)!==null&&E!==void 0?E:m),C)}}it.funcKeywordCode=Nb;function vd(e){let{gen:t,data:n,it:o}=e;t.if(o.parentData,()=>t.assign(n,(0,we._)`${o.parentData}[${o.parentDataProperty}]`))}function Fb(e,t){let{gen:n}=e;n.if((0,we._)`Array.isArray(${t})`,()=>{n.assign(Gt.default.vErrors,(0,we._)`${Gt.default.vErrors} === null ? ${t} : ${Gt.default.vErrors}.concat(${t})`).assign(Gt.default.errors,(0,we._)`${Gt.default.vErrors}.length`),(0,Ib.extendErrors)(e)},()=>e.error())}function Lb({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Td(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,we.stringify)(n)})}function jb(e,t,n=!1){return!t.length||t.some(o=>o==="array"?Array.isArray(e):o==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==o||n&&typeof e>"u")}it.validSchemaType=jb;function Db({schema:e,opts:t,self:n,errSchemaPath:o},r,s){if(Array.isArray(r.keyword)?!r.keyword.includes(s):r.keyword!==s)throw new Error("ajv implementation error");let i=r.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(r.validateSchema&&!r.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${o}": `+n.errorsText(r.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}it.validateKeywordUsage=Db});var Rd=R(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.extendSubschemaMode=xt.extendSubschemaData=xt.getSubschema=void 0;var at=F(),Cd=U();function Bb(e,{keyword:t,schemaProp:n,schema:o,schemaPath:r,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&o!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return n===void 0?{schema:a,schemaPath:(0,at._)`${e.schemaPath}${(0,at.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,at._)`${e.schemaPath}${(0,at.getProperty)(t)}${(0,at.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Cd.escapeFragment)(n)}`}}if(o!==void 0){if(r===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:r,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}xt.getSubschema=Bb;function qb(e,t,{dataProp:n,dataPropType:o,data:r,dataTypes:s,propertyName:i}){if(r!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(n!==void 0){let{errorPath:l,dataPathArr:d,opts:m}=t,y=a.let("data",(0,at._)`${t.data}${(0,at.getProperty)(n)}`,!0);c(y),e.errorPath=(0,at.str)`${l}${(0,Cd.getErrorPath)(n,o,m.jsPropertySyntax)}`,e.parentDataProperty=(0,at._)`${n}`,e.dataPathArr=[...d,e.parentDataProperty]}if(r!==void 0){let l=r instanceof at.Name?r:a.let("data",r,!0);c(l),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}xt.extendSubschemaData=qb;function Ub(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:o,createErrors:r,allErrors:s}){o!==void 0&&(e.compositeRule=o),r!==void 0&&(e.createErrors=r),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}xt.extendSubschemaMode=Ub});var ea=R((wE,wd)=>{"use strict";wd.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var o,r,s;if(Array.isArray(t)){if(o=t.length,o!=n.length)return!1;for(r=o;r--!==0;)if(!e(t[r],n[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),o=s.length,o!==Object.keys(n).length)return!1;for(r=o;r--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[r]))return!1;for(r=o;r--!==0;){var i=s[r];if(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n}});var Sd=R((xE,xd)=>{"use strict";var St=xd.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var o=typeof n=="function"?n:n.pre||function(){},r=n.post||function(){};kr(t,o,r,e,"",e)};St.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};St.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};St.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};St.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function kr(e,t,n,o,r,s,i,a,c,l){if(o&&typeof o=="object"&&!Array.isArray(o)){t(o,r,s,i,a,c,l);for(var d in o){var m=o[d];if(Array.isArray(m)){if(d in St.arrayKeywords)for(var y=0;y<m.length;y++)kr(e,t,n,m[y],r+"/"+d+"/"+y,s,r,d,o,y)}else if(d in St.propsKeywords){if(m&&typeof m=="object")for(var _ in m)kr(e,t,n,m[_],r+"/"+d+"/"+zb(_),s,r,d,o,_)}else(d in St.keywords||e.allKeys&&!(d in St.skipKeywords))&&kr(e,t,n,m,r+"/"+d,s,r,d,o)}n(o,r,s,i,a,c,l)}}function zb(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var fo=R(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.getSchemaRefs=Me.resolveUrl=Me.normalizeId=Me._getFullPath=Me.getFullPath=Me.inlineRef=void 0;var Hb=U(),Vb=ea(),Gb=Sd(),Wb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Kb(e,t=!0){return typeof e=="boolean"?!0:t===!0?!ta(e):t?Ed(e)<=t:!1}Me.inlineRef=Kb;var Jb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ta(e){for(let t in e){if(Jb.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(ta)||typeof n=="object"&&ta(n))return!0}return!1}function Ed(e){let t=0;for(let n in e){if(n==="$ref")return 1/0;if(t++,!Wb.has(n)&&(typeof e[n]=="object"&&(0,Hb.eachItem)(e[n],o=>t+=Ed(o)),t===1/0))return 1/0}return t}function Ad(e,t="",n){n!==!1&&(t=wn(t));let o=e.parse(t);return $d(e,o)}Me.getFullPath=Ad;function $d(e,t){return e.serialize(t).split("#")[0]+"#"}Me._getFullPath=$d;var Xb=/#\/?$/;function wn(e){return e?e.replace(Xb,""):""}Me.normalizeId=wn;function Yb(e,t,n){return n=wn(n),e.resolve(t,n)}Me.resolveUrl=Yb;var Zb=/^[a-z_][-a-z0-9._]*$/i;function Qb(e,t){if(typeof e=="boolean")return{};let{schemaId:n,uriResolver:o}=this.opts,r=wn(e[n]||t),s={"":r},i=Ad(o,r,!1),a={},c=new Set;return Gb(e,{allKeys:!0},(m,y,_,h)=>{if(h===void 0)return;let v=i+y,k=s[h];typeof m[n]=="string"&&(k=C.call(this,m[n])),E.call(this,m.$anchor),E.call(this,m.$dynamicAnchor),s[y]=k;function C(O){let z=this.opts.uriResolver.resolve;if(O=wn(k?z(k,O):O),c.has(O))throw d(O);c.add(O);let M=this.refs[O];return typeof M=="string"&&(M=this.refs[M]),typeof M=="object"?l(m,M.schema,O):O!==wn(v)&&(O[0]==="#"?(l(m,a[O],O),a[O]=m):this.refs[O]=v),O}function E(O){if(typeof O=="string"){if(!Zb.test(O))throw new Error(`invalid anchor "${O}"`);C.call(this,`#${O}`)}}}),a;function l(m,y,_){if(y!==void 0&&!Vb(m,y))throw d(_)}function d(m){return new Error(`reference "${m}" resolves to more than one schema`)}}Me.getSchemaRefs=Qb});var go=R(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.getData=Et.KeywordCxt=Et.validateFunctionCode=void 0;var Nd=ud(),Pd=uo(),oa=Wi(),Cr=uo(),e_=yd(),mo=kd(),na=Rd(),A=F(),N=ze(),t_=fo(),gt=U(),po=lo();function n_(e){if(jd(e)&&(Dd(e),Ld(e))){s_(e);return}Fd(e,()=>(0,Nd.topBoolOrEmptySchema)(e))}Et.validateFunctionCode=n_;function Fd({gen:e,validateName:t,schema:n,schemaEnv:o,opts:r},s){r.code.es5?e.func(t,(0,A._)`${N.default.data}, ${N.default.valCxt}`,o.$async,()=>{e.code((0,A._)`"use strict"; ${Md(n,r)}`),r_(e,r),e.code(s)}):e.func(t,(0,A._)`${N.default.data}, ${o_(r)}`,o.$async,()=>e.code(Md(n,r)).code(s))}function o_(e){return(0,A._)`{${N.default.instancePath}="", ${N.default.parentData}, ${N.default.parentDataProperty}, ${N.default.rootData}=${N.default.data}${e.dynamicRef?(0,A._)`, ${N.default.dynamicAnchors}={}`:A.nil}}={}`}function r_(e,t){e.if(N.default.valCxt,()=>{e.var(N.default.instancePath,(0,A._)`${N.default.valCxt}.${N.default.instancePath}`),e.var(N.default.parentData,(0,A._)`${N.default.valCxt}.${N.default.parentData}`),e.var(N.default.parentDataProperty,(0,A._)`${N.default.valCxt}.${N.default.parentDataProperty}`),e.var(N.default.rootData,(0,A._)`${N.default.valCxt}.${N.default.rootData}`),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,A._)`${N.default.valCxt}.${N.default.dynamicAnchors}`)},()=>{e.var(N.default.instancePath,(0,A._)`""`),e.var(N.default.parentData,(0,A._)`undefined`),e.var(N.default.parentDataProperty,(0,A._)`undefined`),e.var(N.default.rootData,N.default.data),t.dynamicRef&&e.var(N.default.dynamicAnchors,(0,A._)`{}`)})}function s_(e){let{schema:t,opts:n,gen:o}=e;Fd(e,()=>{n.$comment&&t.$comment&&qd(e),u_(e),o.let(N.default.vErrors,null),o.let(N.default.errors,0),n.unevaluated&&i_(e),Bd(e),p_(e)})}function i_(e){let{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,A._)`${n}.evaluated`),t.if((0,A._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,A._)`${e.evaluated}.props`,(0,A._)`undefined`)),t.if((0,A._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,A._)`${e.evaluated}.items`,(0,A._)`undefined`))}function Md(e,t){let n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,A._)`/*# sourceURL=${n} */`:A.nil}function a_(e,t){if(jd(e)&&(Dd(e),Ld(e))){c_(e,t);return}(0,Nd.boolOrEmptySchema)(e,t)}function Ld({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function jd(e){return typeof e.schema!="boolean"}function c_(e,t){let{schema:n,gen:o,opts:r}=e;r.$comment&&n.$comment&&qd(e),d_(e),f_(e);let s=o.const("_errs",N.default.errors);Bd(e,s),o.var(t,(0,A._)`${s} === ${N.default.errors}`)}function Dd(e){(0,gt.checkUnknownRules)(e),l_(e)}function Bd(e,t){if(e.opts.jtd)return Id(e,[],!1,t);let n=(0,Pd.getSchemaTypes)(e.schema),o=(0,Pd.coerceAndCheckDataType)(e,n);Id(e,n,!o,t)}function l_(e){let{schema:t,errSchemaPath:n,opts:o,self:r}=e;t.$ref&&o.ignoreKeywordsWithRef&&(0,gt.schemaHasRulesButRef)(t,r.RULES)&&r.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function u_(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,gt.checkStrictMode)(e,"default is ignored in the schema root")}function d_(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,t_.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function f_(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function qd({gen:e,schemaEnv:t,schema:n,errSchemaPath:o,opts:r}){let s=n.$comment;if(r.$comment===!0)e.code((0,A._)`${N.default.self}.logger.log(${s})`);else if(typeof r.$comment=="function"){let i=(0,A.str)`${o}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,A._)`${N.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function p_(e){let{gen:t,schemaEnv:n,validateName:o,ValidationError:r,opts:s}=e;n.$async?t.if((0,A._)`${N.default.errors} === 0`,()=>t.return(N.default.data),()=>t.throw((0,A._)`new ${r}(${N.default.vErrors})`)):(t.assign((0,A._)`${o}.errors`,N.default.vErrors),s.unevaluated&&m_(e),t.return((0,A._)`${N.default.errors} === 0`))}function m_({gen:e,evaluated:t,props:n,items:o}){n instanceof A.Name&&e.assign((0,A._)`${t}.props`,n),o instanceof A.Name&&e.assign((0,A._)`${t}.items`,o)}function Id(e,t,n,o){let{gen:r,schema:s,data:i,allErrors:a,opts:c,self:l}=e,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,gt.schemaHasRulesButRef)(s,d))){r.block(()=>zd(e,"$ref",d.all.$ref.definition));return}c.jtd||g_(e,t),r.block(()=>{for(let y of d.rules)m(y);m(d.post)});function m(y){(0,oa.shouldUseGroup)(s,y)&&(y.type?(r.if((0,Cr.checkDataType)(y.type,i,c.strictNumbers)),Od(e,y),t.length===1&&t[0]===y.type&&n&&(r.else(),(0,Cr.reportTypeError)(e)),r.endIf()):Od(e,y),a||r.if((0,A._)`${N.default.errors} === ${o||0}`))}}function Od(e,t){let{gen:n,schema:o,opts:{useDefaults:r}}=e;r&&(0,e_.assignDefaults)(e,t.type),n.block(()=>{for(let s of t.rules)(0,oa.shouldUseRule)(o,s)&&zd(e,s.keyword,s.definition,t.type)})}function g_(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(h_(e,t),e.opts.allowUnionTypes||y_(e,t),b_(e,e.dataTypes))}function h_(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{Ud(e.dataTypes,n)||ra(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),v_(e,t)}}function y_(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&ra(e,"use allowUnionTypes to allow union type keyword")}function b_(e,t){let n=e.self.RULES.all;for(let o in n){let r=n[o];if(typeof r=="object"&&(0,oa.shouldUseRule)(e.schema,r)){let{type:s}=r.definition;s.length&&!s.some(i=>__(t,i))&&ra(e,`missing type "${s.join(",")}" for keyword "${o}"`)}}}function __(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Ud(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function v_(e,t){let n=[];for(let o of e.dataTypes)Ud(t,o)?n.push(o):t.includes("integer")&&o==="number"&&n.push("integer");e.dataTypes=n}function ra(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,gt.checkStrictMode)(e,t,e.opts.strictTypes)}var Rr=class{constructor(t,n,o){if((0,mo.validateKeywordUsage)(t,n,o),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=o,this.data=t.data,this.schema=t.schema[o],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,gt.schemaRefOrVal)(t,this.schema,o,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",Hd(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,mo.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${o} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=t.gen.const("_errs",N.default.errors))}result(t,n,o){this.failResult((0,A.not)(t),n,o)}failResult(t,n,o){this.gen.if(t),o?o():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,A.not)(t),void 0,n)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:n}=this;this.fail((0,A._)`${n} !== undefined && (${(0,A.or)(this.invalid$data(),t)})`)}error(t,n,o){if(n){this.setParams(n),this._error(t,o),this.setParams({});return}this._error(t,o)}_error(t,n){(t?po.reportExtraError:po.reportError)(this,this.def.error,n)}$dataError(){(0,po.reportError)(this,this.def.$dataError||po.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,po.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,o=A.nil){this.gen.block(()=>{this.check$data(t,o),n()})}check$data(t=A.nil,n=A.nil){if(!this.$data)return;let{gen:o,schemaCode:r,schemaType:s,def:i}=this;o.if((0,A.or)((0,A._)`${r} === undefined`,n)),t!==A.nil&&o.assign(t,!0),(s.length||i.validateSchema)&&(o.elseIf(this.invalid$data()),this.$dataError(),t!==A.nil&&o.assign(t,!1)),o.else()}invalid$data(){let{gen:t,schemaCode:n,schemaType:o,def:r,it:s}=this;return(0,A.or)(i(),a());function i(){if(o.length){if(!(n instanceof A.Name))throw new Error("ajv implementation error");let c=Array.isArray(o)?o:[o];return(0,A._)`${(0,Cr.checkDataTypes)(c,n,s.opts.strictNumbers,Cr.DataType.Wrong)}`}return A.nil}function a(){if(r.validateSchema){let c=t.scopeValue("validate$data",{ref:r.validateSchema});return(0,A._)`!${c}(${n})`}return A.nil}}subschema(t,n){let o=(0,na.getSubschema)(this.it,t);(0,na.extendSubschemaData)(o,this.it,t),(0,na.extendSubschemaMode)(o,t);let r={...this.it,...o,items:void 0,props:void 0};return a_(r,n),r}mergeEvaluated(t,n){let{it:o,gen:r}=this;o.opts.unevaluated&&(o.props!==!0&&t.props!==void 0&&(o.props=gt.mergeEvaluated.props(r,t.props,o.props,n)),o.items!==!0&&t.items!==void 0&&(o.items=gt.mergeEvaluated.items(r,t.items,o.items,n)))}mergeValidEvaluated(t,n){let{it:o,gen:r}=this;if(o.opts.unevaluated&&(o.props!==!0||o.items!==!0))return r.if(n,()=>this.mergeEvaluated(t,A.Name)),!0}};Et.KeywordCxt=Rr;function zd(e,t,n,o){let r=new Rr(e,n,t);"code"in n?n.code(r,o):r.$data&&n.validate?(0,mo.funcKeywordCode)(r,n):"macro"in n?(0,mo.macroKeywordCode)(r,n):(n.compile||n.validate)&&(0,mo.funcKeywordCode)(r,n)}var T_=/^\/(?:[^~]|~0|~1)*$/,k_=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Hd(e,{dataLevel:t,dataNames:n,dataPathArr:o}){let r,s;if(e==="")return N.default.rootData;if(e[0]==="/"){if(!T_.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);r=e,s=N.default.rootData}else{let l=k_.exec(e);if(!l)throw new Error(`Invalid JSON-pointer: ${e}`);let d=+l[1];if(r=l[2],r==="#"){if(d>=t)throw new Error(c("property/index",d));return o[t-d]}if(d>t)throw new Error(c("data",d));if(s=n[t-d],!r)return s}let i=s,a=r.split("/");for(let l of a)l&&(s=(0,A._)`${s}${(0,A.getProperty)((0,gt.unescapeJsonPointer)(l))}`,i=(0,A._)`${i} && ${s}`);return i;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${t}`}}Et.getData=Hd});var wr=R(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});var sa=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};ia.default=sa});var ho=R(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});var aa=fo(),ca=class extends Error{constructor(t,n,o,r){super(r||`can't resolve reference ${o} from id ${n}`),this.missingRef=(0,aa.resolveUrl)(t,n,o),this.missingSchema=(0,aa.normalizeId)((0,aa.getFullPath)(t,this.missingRef))}};la.default=ca});var yo=R(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.resolveSchema=Ve.getCompilingSchema=Ve.resolveRef=Ve.compileSchema=Ve.SchemaEnv=void 0;var Qe=F(),C_=wr(),Wt=ze(),et=fo(),Vd=U(),R_=go(),xn=class{constructor(t){var n;this.refs={},this.dynamicAnchors={};let o;typeof t.schema=="object"&&(o=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,et.normalizeId)(o?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=o?.$async,this.refs={}}};Ve.SchemaEnv=xn;function da(e){let t=Gd.call(this,e);if(t)return t;let n=(0,et.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:o,lines:r}=this.opts.code,{ownProperties:s}=this.opts,i=new Qe.CodeGen(this.scope,{es5:o,lines:r,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:C_.default,code:(0,Qe._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");e.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Wt.default.data,parentData:Wt.default.parentData,parentDataProperty:Wt.default.parentDataProperty,dataNames:[Wt.default.data],dataPathArr:[Qe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Qe.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Qe.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qe._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(e),(0,R_.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let m=i.toString();d=`${i.scopeRefs(Wt.default.scope)}return ${m}`,this.opts.code.process&&(d=this.opts.code.process(d,e));let _=new Function(`${Wt.default.self}`,`${Wt.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:_}),_.errors=null,_.schema=e.schema,_.schemaEnv=e,e.$async&&(_.$async=!0),this.opts.code.source===!0&&(_.source={validateName:c,validateCode:m,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:v}=l;_.evaluated={props:h instanceof Qe.Name?void 0:h,items:v instanceof Qe.Name?void 0:v,dynamicProps:h instanceof Qe.Name,dynamicItems:v instanceof Qe.Name},_.source&&(_.source.evaluated=(0,Qe.stringify)(_.evaluated))}return e.validate=_,e}catch(m){throw delete e.validate,delete e.validateName,d&&this.logger.error("Error compiling schema, function code:",d),m}finally{this._compilations.delete(e)}}Ve.compileSchema=da;function w_(e,t,n){var o;n=(0,et.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let s=E_.call(this,e,n);if(s===void 0){let i=(o=e.localRefs)===null||o===void 0?void 0:o[n],{schemaId:a}=this.opts;i&&(s=new xn({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=x_.call(this,s)}Ve.resolveRef=w_;function x_(e){return(0,et.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:da.call(this,e)}function Gd(e){for(let t of this._compilations)if(S_(t,e))return t}Ve.getCompilingSchema=Gd;function S_(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function E_(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||xr.call(this,e,t)}function xr(e,t){let n=this.opts.uriResolver.parse(t),o=(0,et._getFullPath)(this.opts.uriResolver,n),r=(0,et.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&o===r)return ua.call(this,n,e);let s=(0,et.normalizeId)(o),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=xr.call(this,e,i);return typeof a?.schema!="object"?void 0:ua.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||da.call(this,i),s===(0,et.normalizeId)(t)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(r=(0,et.resolveUrl)(this.opts.uriResolver,r,l)),new xn({schema:a,schemaId:c,root:e,baseId:r})}return ua.call(this,n,i)}}Ve.resolveSchema=xr;var A_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ua(e,{baseId:t,schema:n,root:o}){var r;if(((r=e.fragment)===null||r===void 0?void 0:r[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,Vd.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!A_.has(a)&&l&&(t=(0,et.resolveUrl)(this.opts.uriResolver,t,l))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Vd.schemaHasRulesButRef)(n,this.RULES)){let a=(0,et.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=xr.call(this,o,a)}let{schemaId:i}=this.opts;if(s=s||new xn({schema:n,schemaId:i,root:o,baseId:t}),s.schema!==s.root.schema)return s}});var Wd=R((ME,$_)=>{$_.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var ma=R((IE,Qd)=>{"use strict";var P_=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Jd=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),fa=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Xd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),M_=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function pa(e){let t="",n=0,o=0;for(o=0;o<e.length;o++)if(n=e[o].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[o];break}for(o+=1;o<e.length;o++){if(n=e[o].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[o]}return t}var I_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Kd(e){return e.length=0,!0}function O_(e,t,n){if(e.length){let o=pa(e);if(o!=="")t.push(o);else return n.error=!0,!1;e.length=0}return!0}function N_(e){let t=0,n={error:!1,address:"",zone:""},o=[],r=[],s=!1,i=!1,a=O_;for(let c=0;c<e.length;c++){let l=e[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(r,o,n))break;if(++t>7){n.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),o.push(":");continue}else if(l==="%"){if(!a(r,o,n))break;a=Kd}else{r.push(l);continue}}return r.length&&(a===Kd?n.zone=r.join(""):i?o.push(r.join("")):o.push(pa(r))),n.address=o.join(""),n}function Yd(e){if(F_(e,":")<2)return{host:e,isIPV6:!1};let t=N_(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,o=t.address;return t.zone&&(n+="%"+t.zone,o+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:o}}}function F_(e,t){let n=0;for(let o=0;o<e.length;o++)e[o]===t&&n++;return n}function L_(e){let t=e,n=[],o=-1,r=0;for(;r=t.length;){if(r===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(r===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(r===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((o=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,o)),t=t.slice(o)}return n.join("")}var j_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},D_=/[@/?#:]/g,B_=/[@/?#]/g;function Zd(e,t){let n=t?B_:D_;return n.lastIndex=0,e.replace(n,o=>j_[o])}function q_(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let o=0;o<e.length;o++){if(e[o]==="%"&&o+2<e.length){let r=e.slice(o+1,o+3);if(fa(r)){let s=r.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Xd(i)?n+=i:n+="%"+s,o+=2;continue}}n+=e[o]}return n}function U_(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(fa(o)){let r=o.toUpperCase(),s=String.fromCharCode(parseInt(r,16));s!=="."&&Xd(s)?t+=s:t+="%"+r,n+=2;continue}}M_(e[n])?t+=e[n]:t+=escape(e[n])}return t}function z_(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(fa(o)){t+="%"+o.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function H_(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!Jd(n)){let o=Yd(n);o.isIPV6===!0?n=`[${o.escapedHost}]`:n=Zd(n,!1)}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}Qd.exports={nonSimpleDomain:I_,recomposeAuthority:H_,reescapeHostDelimiters:Zd,normalizePercentEncoding:q_,normalizePathEncoding:U_,escapePreservingEscapes:z_,removeDotSegments:L_,isIPv4:Jd,isUUID:P_,normalizeIPv6:Yd,stringArrayToHexStripped:pa}});var rf=R((OE,of)=>{"use strict";var{isUUID:V_}=ma(),G_=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,W_=["http","https","ws","wss","urn","urn:uuid"];function K_(e){return W_.indexOf(e)!==-1}function ga(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function ef(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function tf(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function J_(e){return e.secure=ga(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function X_(e){if((e.port===(ga(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function Y_(e,t){if(!e.path)return e.error="URN can not be parsed",e;let n=e.path.match(G_);if(n){let o=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];let r=`${o}:${t.nid||e.nid}`,s=ha(r);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Z_(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=t.scheme||e.scheme||"urn",o=e.nid.toLowerCase(),r=`${n}:${t.nid||o}`,s=ha(r);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${o||t.nid}:${a}`,t.skipEscape=!0,i}function Q_(e,t){let n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!V_(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function ev(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var nf={scheme:"http",domainHost:!0,parse:ef,serialize:tf},tv={scheme:"https",domainHost:nf.domainHost,parse:ef,serialize:tf},Sr={scheme:"ws",domainHost:!0,parse:J_,serialize:X_},nv={scheme:"wss",domainHost:Sr.domainHost,parse:Sr.parse,serialize:Sr.serialize},ov={scheme:"urn",parse:Y_,serialize:Z_,skipNormalize:!0},rv={scheme:"urn:uuid",parse:Q_,serialize:ev,skipNormalize:!0},Er={http:nf,https:tv,ws:Sr,wss:nv,urn:ov,"urn:uuid":rv};Object.setPrototypeOf(Er,null);function ha(e){return e&&(Er[e]||Er[e.toLowerCase()])||void 0}of.exports={wsIsSecure:ga,SCHEMES:Er,isValidSchemeName:K_,getSchemeHandler:ha}});var df=R((NE,Ar)=>{"use strict";var{normalizeIPv6:sv,removeDotSegments:bo,recomposeAuthority:iv,normalizePercentEncoding:av,normalizePathEncoding:cv,escapePreservingEscapes:lv,reescapeHostDelimiters:uv,isIPv4:dv,nonSimpleDomain:fv}=ma(),{SCHEMES:pv,getSchemeHandler:af}=rf();function mv(e,t){return typeof e=="string"?e=_v(e,t):typeof e=="object"&&(e=Sn(Kt(e,t),t)),e}function gv(e,t,n){let o=n?Object.assign({scheme:"null"},n):{scheme:"null"},r=cf(Sn(e,o),Sn(t,o),o,!0);return o.skipEscape=!0,Kt(r,o)}function cf(e,t,n,o){let r={};return o||(e=Sn(Kt(e,n),n),t=Sn(Kt(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(r.scheme=t.scheme,r.userinfo=t.userinfo,r.host=t.host,r.port=t.port,r.path=bo(t.path||""),r.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(r.userinfo=t.userinfo,r.host=t.host,r.port=t.port,r.path=bo(t.path||""),r.query=t.query):(t.path?(t.path[0]==="/"?r.path=bo(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?r.path="/"+t.path:e.path?r.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:r.path=t.path,r.path=bo(r.path)),r.query=t.query):(r.path=e.path,t.query!==void 0?r.query=t.query:r.query=e.query),r.userinfo=e.userinfo,r.host=e.host,r.port=e.port),r.scheme=e.scheme),r.fragment=t.fragment,r}function hv(e,t,n){let o=sf(e,n),r=sf(t,n);return o!==void 0&&r!==void 0&&o.toLowerCase()===r.toLowerCase()}function Kt(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},o=Object.assign({},t),r=[],s=af(o.scheme||n.scheme);s&&s.serialize&&s.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=av(n.path):(n.path=lv(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),o.reference!=="suffix"&&n.scheme&&r.push(n.scheme,":");let i=iv(n);if(i!==void 0&&(o.reference!=="suffix"&&r.push("//"),r.push(i),n.path&&n.path[0]!=="/"&&r.push("/")),n.path!==void 0){let a=n.path;!o.absolutePath&&(!s||!s.absolutePath)&&(a=bo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),r.push(a)}return n.query!==void 0&&r.push("?",n.query),n.fragment!==void 0&&r.push("#",n.fragment),r.join("")}var yv=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function bv(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function lf(e,t){let n=Object.assign({},t),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=!1,s=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);let i=e.match(yv);if(i){o.scheme=i[1],o.userinfo=i[3],o.host=i[4],o.port=parseInt(i[5],10),o.path=i[6]||"",o.query=i[7],o.fragment=i[8],isNaN(o.port)&&(o.port=i[5]);let a=bv(o,i);if(a!==void 0&&(o.error=o.error||a,r=!0),o.host)if(dv(o.host)===!1){let d=sv(o.host);o.host=d.host.toLowerCase(),s=d.isIPV6}else s=!0;o.scheme===void 0&&o.userinfo===void 0&&o.host===void 0&&o.port===void 0&&o.query===void 0&&!o.path?o.reference="same-document":o.scheme===void 0?o.reference="relative":o.fragment===void 0?o.reference="absolute":o.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==o.reference&&(o.error=o.error||"URI is not a "+n.reference+" reference.");let c=af(n.scheme||o.scheme);if(!n.unicodeSupport&&(!c||!c.unicodeSupport)&&o.host&&(n.domainHost||c&&c.domainHost)&&s===!1&&fv(o.host))try{o.host=URL.domainToASCII(o.host.toLowerCase())}catch(l){o.error=o.error||"Host's domain name can not be converted to ASCII: "+l}if((!c||c&&!c.skipNormalize)&&(e.indexOf("%")!==-1&&(o.scheme!==void 0&&(o.scheme=unescape(o.scheme)),o.host!==void 0&&(o.host=uv(unescape(o.host),s))),o.path&&(o.path=cv(o.path)),o.fragment))try{o.fragment=encodeURI(decodeURIComponent(o.fragment))}catch{o.error=o.error||"URI malformed"}c&&c.parse&&c.parse(o,n)}else o.error=o.error||"URI can not be parsed.";return{parsed:o,malformedAuthorityOrPort:r}}function Sn(e,t){return lf(e,t).parsed}function _v(e,t){return uf(e,t).normalized}function uf(e,t){let{parsed:n,malformedAuthorityOrPort:o}=lf(e,t);return{normalized:o?e:Kt(n,t),malformedAuthorityOrPort:o}}function sf(e,t){if(typeof e=="string"){let{normalized:n,malformedAuthorityOrPort:o}=uf(e,t);return o?void 0:n}if(typeof e=="object")return Kt(e,t)}var ya={SCHEMES:pv,normalize:mv,resolve:gv,resolveComponent:cf,equal:hv,serialize:Kt,parse:Sn};Ar.exports=ya;Ar.exports.default=ya;Ar.exports.fastUri=ya});var pf=R(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});var ff=df();ff.code='require("ajv/dist/runtime/uri").default';ba.default=ff});var Tf=R(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=void 0;var vv=go();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return vv.KeywordCxt}});var En=F();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return En._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return En.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return En.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return En.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return En.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return En.CodeGen}});var Tv=wr(),bf=ho(),kv=Gi(),_o=yo(),Cv=F(),vo=fo(),$r=uo(),va=U(),mf=Wd(),Rv=pf(),_f=(e,t)=>new RegExp(e,t);_f.code="new RegExp";var wv=["removeAdditional","useDefaults","coerceTypes"],xv=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Sv={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Ev={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},gf=200;function Av(e){var t,n,o,r,s,i,a,c,l,d,m,y,_,h,v,k,C,E,O,z,M,ee,Ne,Q,Ke;let nt=e.strict,an=(t=e.code)===null||t===void 0?void 0:t.optimize,lt=an===!0||an===void 0?1:an||0,Fe=(o=(n=e.code)===null||n===void 0?void 0:n.regExp)!==null&&o!==void 0?o:_f,ut=(r=e.uriResolver)!==null&&r!==void 0?r:Rv.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:nt)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:nt)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=e.strictTypes)!==null&&l!==void 0?l:nt)!==null&&d!==void 0?d:"log",strictTuples:(y=(m=e.strictTuples)!==null&&m!==void 0?m:nt)!==null&&y!==void 0?y:"log",strictRequired:(h=(_=e.strictRequired)!==null&&_!==void 0?_:nt)!==null&&h!==void 0?h:!1,code:e.code?{...e.code,optimize:lt,regExp:Fe}:{optimize:lt,regExp:Fe},loopRequired:(v=e.loopRequired)!==null&&v!==void 0?v:gf,loopEnum:(k=e.loopEnum)!==null&&k!==void 0?k:gf,meta:(C=e.meta)!==null&&C!==void 0?C:!0,messages:(E=e.messages)!==null&&E!==void 0?E:!0,inlineRefs:(O=e.inlineRefs)!==null&&O!==void 0?O:!0,schemaId:(z=e.schemaId)!==null&&z!==void 0?z:"$id",addUsedSchema:(M=e.addUsedSchema)!==null&&M!==void 0?M:!0,validateSchema:(ee=e.validateSchema)!==null&&ee!==void 0?ee:!0,validateFormats:(Ne=e.validateFormats)!==null&&Ne!==void 0?Ne:!0,unicodeRegExp:(Q=e.unicodeRegExp)!==null&&Q!==void 0?Q:!0,int32range:(Ke=e.int32range)!==null&&Ke!==void 0?Ke:!0,uriResolver:ut}}var To=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...Av(t)};let{es5:n,lines:o}=this.opts.code;this.scope=new Cv.ValueScope({scope:{},prefixes:xv,es5:n,lines:o}),this.logger=Nv(t.logger);let r=t.validateFormats;t.validateFormats=!1,this.RULES=(0,kv.getRules)(),hf.call(this,Sv,t,"NOT SUPPORTED"),hf.call(this,Ev,t,"DEPRECATED","warn"),this._metaOpts=Iv.call(this),t.formats&&Pv.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Mv.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),$v.call(this),t.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:n,schemaId:o}=this.opts,r=mf;o==="id"&&(r={...mf},r.id=r.$id,delete r.$id),n&&t&&this.addMetaSchema(r,r[o],!1)}defaultMeta(){let{meta:t,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[n]||t:void 0}validate(t,n){let o;if(typeof t=="string"){if(o=this.getSchema(t),!o)throw new Error(`no schema with key or ref "${t}"`)}else o=this.compile(t);let r=o(n);return"$async"in o||(this.errors=o.errors),r}compile(t,n){let o=this._addSchema(t,n);return o.validate||this._compileSchemaEnv(o)}compileAsync(t,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:o}=this.opts;return r.call(this,t,n);async function r(d,m){await s.call(this,d.$schema);let y=this._addSchema(d,m);return y.validate||i.call(this,y)}async function s(d){d&&!this.getSchema(d)&&await r.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(m){if(!(m instanceof bf.default))throw m;return a.call(this,m),await c.call(this,m.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:m}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${m} cannot be resolved`)}async function c(d){let m=await l.call(this,d);this.refs[d]||await s.call(this,m.$schema),this.refs[d]||this.addSchema(m,d,n)}async function l(d){let m=this._loading[d];if(m)return m;try{return await(this._loading[d]=o(d))}finally{delete this._loading[d]}}}addSchema(t,n,o,r=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,o,r);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return n=(0,vo.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(t,o,n,r,!0),this}addMetaSchema(t,n,o=this.opts.validateSchema){return this.addSchema(t,n,!0,o),this}validateSchema(t,n){if(typeof t=="boolean")return!0;let o;if(o=t.$schema,o!==void 0&&typeof o!="string")throw new Error("$schema must be a string");if(o=o||this.opts.defaultMeta||this.defaultMeta(),!o)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let r=this.validate(o,t);if(!r&&n){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return r}getSchema(t){let n;for(;typeof(n=yf.call(this,t))=="string";)t=n;if(n===void 0){let{schemaId:o}=this.opts,r=new _o.SchemaEnv({schema:{},schemaId:o});if(n=_o.resolveSchema.call(this,r,t),!n)return;this.refs[t]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=yf.call(this,t);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let n=t;this._cache.delete(n);let o=t[this.opts.schemaId];return o&&(o=(0,vo.normalizeId)(o),delete this.schemas[o],delete this.refs[o]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let n of t)this.addKeyword(n);return this}addKeyword(t,n){let o;if(typeof t=="string")o=t,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=o);else if(typeof t=="object"&&n===void 0){if(n=t,o=n.keyword,Array.isArray(o)&&!o.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Lv.call(this,o,n),!n)return(0,va.eachItem)(o,s=>_a.call(this,s)),this;Dv.call(this,n);let r={...n,type:(0,$r.getJSONTypes)(n.type),schemaType:(0,$r.getJSONTypes)(n.schemaType)};return(0,va.eachItem)(o,r.type.length===0?s=>_a.call(this,s,r):s=>r.type.forEach(i=>_a.call(this,s,r,i))),this}getKeyword(t){let n=this.RULES.all[t];return typeof n=="object"?n.definition:!!n}removeKeyword(t){let{RULES:n}=this;delete n.keywords[t],delete n.all[t];for(let o of n.rules){let r=o.rules.findIndex(s=>s.keyword===t);r>=0&&o.rules.splice(r,1)}return this}addFormat(t,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[t]=n,this}errorsText(t=this.errors,{separator:n=", ",dataVar:o="data"}={}){return!t||t.length===0?"No errors":t.map(r=>`${o}${r.instancePath} ${r.message}`).reduce((r,s)=>r+n+s)}$dataMetaSchema(t,n){let o=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let r of n){let s=r.split("/").slice(1),i=t;for(let a of s)i=i[a];for(let a in o){let c=o[a];if(typeof c!="object")continue;let{$data:l}=c.definition,d=i[a];l&&d&&(i[a]=vf(d))}}return t}_removeAllSchemas(t,n){for(let o in t){let r=t[o];(!n||n.test(o))&&(typeof r=="string"?delete t[o]:r&&!r.meta&&(this._cache.delete(r.schema),delete t[o]))}}_addSchema(t,n,o,r=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;o=(0,vo.normalizeId)(i||o);let l=vo.getSchemaRefs.call(this,t,o);return c=new _o.SchemaEnv({schema:t,schemaId:a,meta:n,baseId:o,localRefs:l}),this._cache.set(c.schema,c),s&&!o.startsWith("#")&&(o&&this._checkUnique(o),this.refs[o]=c),r&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):_o.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let n=this.opts;this.opts=this._metaOpts;try{_o.compileSchema.call(this,t)}finally{this.opts=n}}};To.ValidationError=Tv.default;To.MissingRefError=bf.default;ge.default=To;function hf(e,t,n,o="error"){for(let r in e){let s=r;s in t&&this.logger[o](`${n}: option ${r}. ${e[s]}`)}}function yf(e){return e=(0,vo.normalizeId)(e),this.schemas[e]||this.refs[e]}function $v(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function Pv(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Mv(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}function Iv(){let e={...this.opts};for(let t of wv)delete e[t];return e}var Ov={log(){},warn(){},error(){}};function Nv(e){if(e===!1)return Ov;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var Fv=/^[a-z_$][a-z0-9_$:-]*$/i;function Lv(e,t){let{RULES:n}=this;if((0,va.eachItem)(e,o=>{if(n.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!Fv.test(o))throw new Error(`Keyword ${o} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function _a(e,t,n){var o;let r=t?.post;if(n&&r)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=r?s.post:s.rules.find(({type:c})=>c===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,$r.getJSONTypes)(t.type),schemaType:(0,$r.getJSONTypes)(t.schemaType)}};t.before?jv.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(o=t.implements)===null||o===void 0||o.forEach(c=>this.addKeyword(c))}function jv(e,t,n){let o=e.rules.findIndex(r=>r.keyword===n);o>=0?e.rules.splice(o,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function Dv(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=vf(t)),e.validateSchema=this.compile(t,!0))}var Bv={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function vf(e){return{anyOf:[e,Bv]}}});var kf=R(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});var qv={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ta.default=qv});var Ir=R(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.callRef=Jt.getValidate=void 0;var Uv=ho(),Cf=He(),Ie=F(),An=ze(),Rf=yo(),Pr=U(),zv={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:n,it:o}=e,{baseId:r,schemaEnv:s,validateName:i,opts:a,self:c}=o,{root:l}=s;if((n==="#"||n==="#/")&&r===l.baseId)return m();let d=Rf.resolveRef.call(c,l,r,n);if(d===void 0)throw new Uv.default(o.opts.uriResolver,r,n);if(d instanceof Rf.SchemaEnv)return y(d);return _(d);function m(){if(s===l)return Mr(e,i,s,s.$async);let h=t.scopeValue("root",{ref:l});return Mr(e,(0,Ie._)`${h}.validate`,l,l.$async)}function y(h){let v=wf(e,h);Mr(e,v,h,h.$async)}function _(h){let v=t.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Ie.stringify)(h)}:{ref:h}),k=t.name("valid"),C=e.subschema({schema:h,dataTypes:[],schemaPath:Ie.nil,topSchemaRef:v,errSchemaPath:n},k);e.mergeEvaluated(C),e.ok(k)}}};function wf(e,t){let{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,Ie._)`${n.scopeValue("wrapper",{ref:t})}.validate`}Jt.getValidate=wf;function Mr(e,t,n,o){let{gen:r,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?An.default.this:Ie.nil;o?d():m();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=r.let("valid");r.try(()=>{r.code((0,Ie._)`await ${(0,Cf.callValidateCode)(e,t,l)}`),_(t),i||r.assign(h,!0)},v=>{r.if((0,Ie._)`!(${v} instanceof ${s.ValidationError})`,()=>r.throw(v)),y(v),i||r.assign(h,!1)}),e.ok(h)}function m(){e.result((0,Cf.callValidateCode)(e,t,l),()=>_(t),()=>y(t))}function y(h){let v=(0,Ie._)`${h}.errors`;r.assign(An.default.vErrors,(0,Ie._)`${An.default.vErrors} === null ? ${v} : ${An.default.vErrors}.concat(${v})`),r.assign(An.default.errors,(0,Ie._)`${An.default.vErrors}.length`)}function _(h){var v;if(!s.opts.unevaluated)return;let k=(v=n?.validate)===null||v===void 0?void 0:v.evaluated;if(s.props!==!0)if(k&&!k.dynamicProps)k.props!==void 0&&(s.props=Pr.mergeEvaluated.props(r,k.props,s.props));else{let C=r.var("props",(0,Ie._)`${h}.evaluated.props`);s.props=Pr.mergeEvaluated.props(r,C,s.props,Ie.Name)}if(s.items!==!0)if(k&&!k.dynamicItems)k.items!==void 0&&(s.items=Pr.mergeEvaluated.items(r,k.items,s.items));else{let C=r.var("items",(0,Ie._)`${h}.evaluated.items`);s.items=Pr.mergeEvaluated.items(r,C,s.items,Ie.Name)}}}Jt.callRef=Mr;Jt.default=zv});var xf=R(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});var Hv=kf(),Vv=Ir(),Gv=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Hv.default,Vv.default];ka.default=Gv});var Sf=R(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});var Or=F(),At=Or.operators,Nr={maximum:{okStr:"<=",ok:At.LTE,fail:At.GT},minimum:{okStr:">=",ok:At.GTE,fail:At.LT},exclusiveMaximum:{okStr:"<",ok:At.LT,fail:At.GTE},exclusiveMinimum:{okStr:">",ok:At.GT,fail:At.LTE}},Wv={message:({keyword:e,schemaCode:t})=>(0,Or.str)`must be ${Nr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Or._)`{comparison: ${Nr[e].okStr}, limit: ${t}}`},Kv={keyword:Object.keys(Nr),type:"number",schemaType:"number",$data:!0,error:Wv,code(e){let{keyword:t,data:n,schemaCode:o}=e;e.fail$data((0,Or._)`${n} ${Nr[t].fail} ${o} || isNaN(${n})`)}};Ca.default=Kv});var Ef=R(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});var ko=F(),Jv={message:({schemaCode:e})=>(0,ko.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,ko._)`{multipleOf: ${e}}`},Xv={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Jv,code(e){let{gen:t,data:n,schemaCode:o,it:r}=e,s=r.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,ko._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ko._)`${i} !== parseInt(${i})`;e.fail$data((0,ko._)`(${o} === 0 || (${i} = ${n}/${o}, ${a}))`)}};Ra.default=Xv});var $f=R(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});function Af(e){let t=e.length,n=0,o=0,r;for(;o<t;)n++,r=e.charCodeAt(o++),r>=55296&&r<=56319&&o<t&&(r=e.charCodeAt(o),(r&64512)===56320&&o++);return n}wa.default=Af;Af.code='require("ajv/dist/runtime/ucs2length").default'});var Pf=R(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});var Xt=F(),Yv=U(),Zv=$f(),Qv={message({keyword:e,schemaCode:t}){let n=e==="maxLength"?"more":"fewer";return(0,Xt.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,Xt._)`{limit: ${e}}`},eT={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Qv,code(e){let{keyword:t,data:n,schemaCode:o,it:r}=e,s=t==="maxLength"?Xt.operators.GT:Xt.operators.LT,i=r.opts.unicode===!1?(0,Xt._)`${n}.length`:(0,Xt._)`${(0,Yv.useFunc)(e.gen,Zv.default)}(${n})`;e.fail$data((0,Xt._)`${i} ${s} ${o}`)}};xa.default=eT});var Mf=R(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});var tT=He(),nT=U(),$n=F(),oT={message:({schemaCode:e})=>(0,$n.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,$n._)`{pattern: ${e}}`},rT={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:oT,code(e){let{gen:t,data:n,$data:o,schema:r,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(o){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,$n._)`new RegExp`:(0,nT.useFunc)(t,c),d=t.let("valid");t.try(()=>t.assign(d,(0,$n._)`${l}(${s}, ${a}).test(${n})`),()=>t.assign(d,!1)),e.fail$data((0,$n._)`!${d}`)}else{let c=(0,tT.usePattern)(e,r);e.fail$data((0,$n._)`!${c}.test(${n})`)}}};Sa.default=rT});var If=R(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});var Co=F(),sT={message({keyword:e,schemaCode:t}){let n=e==="maxProperties"?"more":"fewer";return(0,Co.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,Co._)`{limit: ${e}}`},iT={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:sT,code(e){let{keyword:t,data:n,schemaCode:o}=e,r=t==="maxProperties"?Co.operators.GT:Co.operators.LT;e.fail$data((0,Co._)`Object.keys(${n}).length ${r} ${o}`)}};Ea.default=iT});var Of=R(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});var Ro=He(),wo=F(),aT=U(),cT={message:({params:{missingProperty:e}})=>(0,wo.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,wo._)`{missingProperty: ${e}}`},lT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:cT,code(e){let{gen:t,schema:n,schemaCode:o,data:r,$data:s,it:i}=e,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?l():d(),a.strictRequired){let _=e.parentSchema.properties,{definedProperties:h}=e.it;for(let v of n)if(_?.[v]===void 0&&!h.has(v)){let k=i.schemaEnv.baseId+i.errSchemaPath,C=`required property "${v}" is not defined at "${k}" (strictRequired)`;(0,aT.checkStrictMode)(i,C,i.opts.strictRequired)}}function l(){if(c||s)e.block$data(wo.nil,m);else for(let _ of n)(0,Ro.checkReportMissingProp)(e,_)}function d(){let _=t.let("missing");if(c||s){let h=t.let("valid",!0);e.block$data(h,()=>y(_,h)),e.ok(h)}else t.if((0,Ro.checkMissingProp)(e,n,_)),(0,Ro.reportMissingProp)(e,_),t.else()}function m(){t.forOf("prop",o,_=>{e.setParams({missingProperty:_}),t.if((0,Ro.noPropertyInData)(t,r,_,a.ownProperties),()=>e.error())})}function y(_,h){e.setParams({missingProperty:_}),t.forOf(_,o,()=>{t.assign(h,(0,Ro.propertyInData)(t,r,_,a.ownProperties)),t.if((0,wo.not)(h),()=>{e.error(),t.break()})},wo.nil)}}};Aa.default=lT});var Nf=R($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});var xo=F(),uT={message({keyword:e,schemaCode:t}){let n=e==="maxItems"?"more":"fewer";return(0,xo.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,xo._)`{limit: ${e}}`},dT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:uT,code(e){let{keyword:t,data:n,schemaCode:o}=e,r=t==="maxItems"?xo.operators.GT:xo.operators.LT;e.fail$data((0,xo._)`${n}.length ${r} ${o}`)}};$a.default=dT});var Fr=R(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});var Ff=ea();Ff.code='require("ajv/dist/runtime/equal").default';Pa.default=Ff});var Lf=R(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});var Ma=uo(),he=F(),fT=U(),pT=Fr(),mT={message:({params:{i:e,j:t}})=>(0,he.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,he._)`{i: ${e}, j: ${t}}`},gT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:mT,code(e){let{gen:t,data:n,$data:o,schema:r,parentSchema:s,schemaCode:i,it:a}=e;if(!o&&!r)return;let c=t.let("valid"),l=s.items?(0,Ma.getSchemaTypes)(s.items):[];e.block$data(c,d,(0,he._)`${i} === false`),e.ok(c);function d(){let h=t.let("i",(0,he._)`${n}.length`),v=t.let("j");e.setParams({i:h,j:v}),t.assign(c,!0),t.if((0,he._)`${h} > 1`,()=>(m()?y:_)(h,v))}function m(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function y(h,v){let k=t.name("item"),C=(0,Ma.checkDataTypes)(l,k,a.opts.strictNumbers,Ma.DataType.Wrong),E=t.const("indices",(0,he._)`{}`);t.for((0,he._)`;${h}--;`,()=>{t.let(k,(0,he._)`${n}[${h}]`),t.if(C,(0,he._)`continue`),l.length>1&&t.if((0,he._)`typeof ${k} == "string"`,(0,he._)`${k} += "_"`),t.if((0,he._)`typeof ${E}[${k}] == "number"`,()=>{t.assign(v,(0,he._)`${E}[${k}]`),e.error(),t.assign(c,!1).break()}).code((0,he._)`${E}[${k}] = ${h}`)})}function _(h,v){let k=(0,fT.useFunc)(t,pT.default),C=t.name("outer");t.label(C).for((0,he._)`;${h}--;`,()=>t.for((0,he._)`${v} = ${h}; ${v}--;`,()=>t.if((0,he._)`${k}(${n}[${h}], ${n}[${v}])`,()=>{e.error(),t.assign(c,!1).break(C)})))}}};Ia.default=gT});var jf=R(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});var Oa=F(),hT=U(),yT=Fr(),bT={message:"must be equal to constant",params:({schemaCode:e})=>(0,Oa._)`{allowedValue: ${e}}`},_T={keyword:"const",$data:!0,error:bT,code(e){let{gen:t,data:n,$data:o,schemaCode:r,schema:s}=e;o||s&&typeof s=="object"?e.fail$data((0,Oa._)`!${(0,hT.useFunc)(t,yT.default)}(${n}, ${r})`):e.fail((0,Oa._)`${s} !== ${n}`)}};Na.default=_T});var Df=R(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var So=F(),vT=U(),TT=Fr(),kT={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,So._)`{allowedValues: ${e}}`},CT={keyword:"enum",schemaType:"array",$data:!0,error:kT,code(e){let{gen:t,data:n,$data:o,schema:r,schemaCode:s,it:i}=e;if(!o&&r.length===0)throw new Error("enum must have non-empty array");let a=r.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,vT.useFunc)(t,TT.default)),d;if(a||o)d=t.let("valid"),e.block$data(d,m);else{if(!Array.isArray(r))throw new Error("ajv implementation error");let _=t.const("vSchema",s);d=(0,So.or)(...r.map((h,v)=>y(_,v)))}e.pass(d);function m(){t.assign(d,!1),t.forOf("v",s,_=>t.if((0,So._)`${l()}(${n}, ${_})`,()=>t.assign(d,!0).break()))}function y(_,h){let v=r[h];return typeof v=="object"&&v!==null?(0,So._)`${l()}(${n}, ${_}[${h}])`:(0,So._)`${n} === ${v}`}}};Fa.default=CT});var Bf=R(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});var RT=Sf(),wT=Ef(),xT=Pf(),ST=Mf(),ET=If(),AT=Of(),$T=Nf(),PT=Lf(),MT=jf(),IT=Df(),OT=[RT.default,wT.default,xT.default,ST.default,ET.default,AT.default,$T.default,PT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},MT.default,IT.default];La.default=OT});var Da=R(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.validateAdditionalItems=void 0;var Yt=F(),ja=U(),NT={message:({params:{len:e}})=>(0,Yt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Yt._)`{limit: ${e}}`},FT={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:NT,code(e){let{parentSchema:t,it:n}=e,{items:o}=t;if(!Array.isArray(o)){(0,ja.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}qf(e,o)}};function qf(e,t){let{gen:n,schema:o,data:r,keyword:s,it:i}=e;i.items=!0;let a=n.const("len",(0,Yt._)`${r}.length`);if(o===!1)e.setParams({len:t.length}),e.pass((0,Yt._)`${a} <= ${t.length}`);else if(typeof o=="object"&&!(0,ja.alwaysValidSchema)(i,o)){let l=n.var("valid",(0,Yt._)`${a} <= ${t.length}`);n.if((0,Yt.not)(l),()=>c(l)),e.ok(l)}function c(l){n.forRange("i",t.length,a,d=>{e.subschema({keyword:s,dataProp:d,dataPropType:ja.Type.Num},l),i.allErrors||n.if((0,Yt.not)(l),()=>n.break())})}}Eo.validateAdditionalItems=qf;Eo.default=FT});var Ba=R(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.validateTuple=void 0;var Uf=F(),Lr=U(),LT=He(),jT={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:n}=e;if(Array.isArray(t))return zf(e,"additionalItems",t);n.items=!0,!(0,Lr.alwaysValidSchema)(n,t)&&e.ok((0,LT.validateArray)(e))}};function zf(e,t,n=e.schema){let{gen:o,parentSchema:r,data:s,keyword:i,it:a}=e;d(r),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Lr.mergeEvaluated.items(o,n.length,a.items));let c=o.name("valid"),l=o.const("len",(0,Uf._)`${s}.length`);n.forEach((m,y)=>{(0,Lr.alwaysValidSchema)(a,m)||(o.if((0,Uf._)`${l} > ${y}`,()=>e.subschema({keyword:i,schemaProp:y,dataProp:y},c)),e.ok(c))});function d(m){let{opts:y,errSchemaPath:_}=a,h=n.length,v=h===m.minItems&&(h===m.maxItems||m[t]===!1);if(y.strictTuples&&!v){let k=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${_}"`;(0,Lr.checkStrictMode)(a,k,y.strictTuples)}}}Ao.validateTuple=zf;Ao.default=jT});var Hf=R(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});var DT=Ba(),BT={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,DT.validateTuple)(e,"items")};qa.default=BT});var Gf=R(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});var Vf=F(),qT=U(),UT=He(),zT=Da(),HT={message:({params:{len:e}})=>(0,Vf.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Vf._)`{limit: ${e}}`},VT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:HT,code(e){let{schema:t,parentSchema:n,it:o}=e,{prefixItems:r}=n;o.items=!0,!(0,qT.alwaysValidSchema)(o,t)&&(r?(0,zT.validateAdditionalItems)(e,r):e.ok((0,UT.validateArray)(e)))}};Ua.default=VT});var Wf=R(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var Ge=F(),jr=U(),GT={message:({params:{min:e,max:t}})=>t===void 0?(0,Ge.str)`must contain at least ${e} valid item(s)`:(0,Ge.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ge._)`{minContains: ${e}}`:(0,Ge._)`{minContains: ${e}, maxContains: ${t}}`},WT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:GT,code(e){let{gen:t,schema:n,parentSchema:o,data:r,it:s}=e,i,a,{minContains:c,maxContains:l}=o;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let d=t.const("len",(0,Ge._)`${r}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,jr.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,jr.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,jr.alwaysValidSchema)(s,n)){let v=(0,Ge._)`${d} >= ${i}`;a!==void 0&&(v=(0,Ge._)`${v} && ${d} <= ${a}`),e.pass(v);return}s.items=!0;let m=t.name("valid");a===void 0&&i===1?_(m,()=>t.if(m,()=>t.break())):i===0?(t.let(m,!0),a!==void 0&&t.if((0,Ge._)`${r}.length > 0`,y)):(t.let(m,!1),y()),e.result(m,()=>e.reset());function y(){let v=t.name("_valid"),k=t.let("count",0);_(v,()=>t.if(v,()=>h(k)))}function _(v,k){t.forRange("i",0,d,C=>{e.subschema({keyword:"contains",dataProp:C,dataPropType:jr.Type.Num,compositeRule:!0},v),k()})}function h(v){t.code((0,Ge._)`${v}++`),a===void 0?t.if((0,Ge._)`${v} >= ${i}`,()=>t.assign(m,!0).break()):(t.if((0,Ge._)`${v} > ${a}`,()=>t.assign(m,!1).break()),i===1?t.assign(m,!0):t.if((0,Ge._)`${v} >= ${i}`,()=>t.assign(m,!0)))}}};za.default=WT});var Dr=R(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.validateSchemaDeps=ct.validatePropertyDeps=ct.error=void 0;var Ha=F(),KT=U(),$o=He();ct.error={message:({params:{property:e,depsCount:t,deps:n}})=>{let o=t===1?"property":"properties";return(0,Ha.str)`must have ${o} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:n,missingProperty:o}})=>(0,Ha._)`{property: ${e},
6
- missingProperty: ${o},
1
+ var Fu=Object.create;var Ni=Object.defineProperty;var Uu=Object.getOwnPropertyDescriptor;var Bu=Object.getOwnPropertyNames;var zu=Object.getPrototypeOf,Vu=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ku=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Bu(t))!Vu.call(e,o)&&o!==n&&Ni(e,o,{get:()=>t[o],enumerable:!(r=Uu(t,o))||r.enumerable});return e};var Gu=(e,t,n)=>(n=e!=null?Fu(zu(e)):{},Ku(t||!e||!e.__esModule?Ni(n,"default",{value:e,enumerable:!0}):n,e));var Wt=v(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.regexpCode=L.getEsmExportName=L.getProperty=L.safeStringify=L.stringify=L.strConcat=L.addCodeArg=L.str=L._=L.nil=L._Code=L.Name=L.IDENTIFIER=L._CodeOrName=void 0;var Gt=class{};L._CodeOrName=Gt;L.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var et=class extends Gt{constructor(t){if(super(),!L.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};L.Name=et;var fe=class extends Gt{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((n,r)=>(r instanceof et&&(n[r.str]=(n[r.str]||0)+1),n),{})}};L._Code=fe;L.nil=new fe("");function ca(e,...t){let n=[e[0]],r=0;for(;r<t.length;)ao(n,t[r]),n.push(e[++r]);return new fe(n)}L._=ca;var io=new fe("+");function ua(e,...t){let n=[Ht(e[0])],r=0;for(;r<t.length;)n.push(io),ao(n,t[r]),n.push(io,Ht(e[++r]));return Wd(n),new fe(n)}L.str=ua;function ao(e,t){t instanceof fe?e.push(...t._items):t instanceof et?e.push(t):e.push(Xd(t))}L.addCodeArg=ao;function Wd(e){let t=1;for(;t<e.length-1;){if(e[t]===io){let n=Jd(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function Jd(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof et||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof et))return`"${e}${t.slice(1)}`}function Yd(e,t){return t.emptyStr()?e:e.emptyStr()?t:ua`${e}${t}`}L.strConcat=Yd;function Xd(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Ht(Array.isArray(e)?e.join(","):e)}function Qd(e){return new fe(Ht(e))}L.stringify=Qd;function Ht(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}L.safeStringify=Ht;function Zd(e){return typeof e=="string"&&L.IDENTIFIER.test(e)?new fe(`.${e}`):ca`[${e}]`}L.getProperty=Zd;function ef(e){if(typeof e=="string"&&L.IDENTIFIER.test(e))return new fe(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}L.getEsmExportName=ef;function tf(e){return new fe(e.toString())}L.regexpCode=tf});var uo=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.ValueScope=ie.ValueScopeName=ie.Scope=ie.varKinds=ie.UsedValueState=void 0;var se=Wt(),lo=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Bn;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Bn||(ie.UsedValueState=Bn={}));ie.varKinds={const:new se.Name("const"),let:new se.Name("let"),var:new se.Name("var")};var zn=class{constructor({prefixes:t,parent:n}={}){this._names={},this._prefixes=t,this._parent=n}toName(t){return t instanceof se.Name?t:this.name(t)}name(t){return new se.Name(this._newName(t))}_newName(t){let n=this._names[t]||this._nameGroup(t);return`${t}${n.index++}`}_nameGroup(t){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};ie.Scope=zn;var Vn=class extends se.Name{constructor(t,n){super(n),this.prefix=t}setValue(t,{property:n,itemIndex:r}){this.value=t,this.scopePath=(0,se._)`.${new se.Name(n)}[${r}]`}};ie.ValueScopeName=Vn;var nf=(0,se._)`\n`,co=class extends zn{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?nf:se.nil}}get(){return this._scope}name(t){return new Vn(t,this._newName(t))}value(t,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.ref,l=this._values[s];if(l){let u=l.get(i);if(u)return u}else l=this._values[s]=new Map;l.set(i,o);let a=this._scope[s]||(this._scope[s]=[]),c=a.length;return a[c]=n.ref,o.setValue(n,{property:s,itemIndex:c}),o}getValue(t,n){let r=this._values[t];if(r)return r.get(n)}scopeRefs(t,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,se._)`${t}${r.scopePath}`})}scopeCode(t=this._values,n,r){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(t,n,r={},o){let s=se.nil;for(let i in t){let l=t[i];if(!l)continue;let a=r[i]=r[i]||new Map;l.forEach(c=>{if(a.has(c))return;a.set(c,Bn.Started);let u=n(c);if(u){let d=this.opts.es5?ie.varKinds.var:ie.varKinds.const;s=(0,se._)`${s}${d} ${c} = ${u};${this.opts._n}`}else if(u=o?.(c))s=(0,se._)`${s}${u}${this.opts._n}`;else throw new lo(c);a.set(c,Bn.Completed)})}return s}};ie.ValueScope=co});var S=v(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.or=P.and=P.not=P.CodeGen=P.operators=P.varKinds=P.ValueScopeName=P.ValueScope=P.Scope=P.Name=P.regexpCode=P.stringify=P.getProperty=P.nil=P.strConcat=P.str=P._=void 0;var O=Wt(),ke=uo(),Fe=Wt();Object.defineProperty(P,"_",{enumerable:!0,get:function(){return Fe._}});Object.defineProperty(P,"str",{enumerable:!0,get:function(){return Fe.str}});Object.defineProperty(P,"strConcat",{enumerable:!0,get:function(){return Fe.strConcat}});Object.defineProperty(P,"nil",{enumerable:!0,get:function(){return Fe.nil}});Object.defineProperty(P,"getProperty",{enumerable:!0,get:function(){return Fe.getProperty}});Object.defineProperty(P,"stringify",{enumerable:!0,get:function(){return Fe.stringify}});Object.defineProperty(P,"regexpCode",{enumerable:!0,get:function(){return Fe.regexpCode}});Object.defineProperty(P,"Name",{enumerable:!0,get:function(){return Fe.Name}});var Wn=uo();Object.defineProperty(P,"Scope",{enumerable:!0,get:function(){return Wn.Scope}});Object.defineProperty(P,"ValueScope",{enumerable:!0,get:function(){return Wn.ValueScope}});Object.defineProperty(P,"ValueScopeName",{enumerable:!0,get:function(){return Wn.ValueScopeName}});Object.defineProperty(P,"varKinds",{enumerable:!0,get:function(){return Wn.varKinds}});P.operators={GT:new O._Code(">"),GTE:new O._Code(">="),LT:new O._Code("<"),LTE:new O._Code("<="),EQ:new O._Code("==="),NEQ:new O._Code("!=="),NOT:new O._Code("!"),OR:new O._Code("||"),AND:new O._Code("&&"),ADD:new O._Code("+")};var Ne=class{optimizeNodes(){return this}optimizeNames(t,n){return this}},fo=class extends Ne{constructor(t,n,r){super(),this.varKind=t,this.name=n,this.rhs=r}render({es5:t,_n:n}){let r=t?ke.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(t,n){if(t[this.name.str])return this.rhs&&(this.rhs=bt(this.rhs,t,n)),this}get names(){return this.rhs instanceof O._CodeOrName?this.rhs.names:{}}},Kn=class extends Ne{constructor(t,n,r){super(),this.lhs=t,this.rhs=n,this.sideEffects=r}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,n){if(!(this.lhs instanceof O.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=bt(this.rhs,t,n),this}get names(){let t=this.lhs instanceof O.Name?{}:{...this.lhs.names};return Hn(t,this.rhs)}},po=class extends Kn{constructor(t,n,r,o){super(t,r,o),this.op=n}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},mo=class extends Ne{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ho=class extends Ne{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},go=class extends Ne{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},yo=class extends Ne{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,n){return this.code=bt(this.code,t,n),this}get names(){return this.code instanceof O._CodeOrName?this.code.names:{}}},Jt=class extends Ne{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((n,r)=>n+r.render(t),"")}optimizeNodes(){let{nodes:t}=this,n=t.length;for(;n--;){let r=t[n].optimizeNodes();Array.isArray(r)?t.splice(n,1,...r):r?t[n]=r:t.splice(n,1)}return t.length>0?this:void 0}optimizeNames(t,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(t,n)||(rf(t,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((t,n)=>rt(t,n.names),{})}},je=class extends Jt{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},_o=class extends Jt{},vt=class extends je{};vt.kind="else";var tt=class e extends je{constructor(t,n){super(n),this.condition=t}render(t){let n=`if(${this.condition})`+super.render(t);return this.else&&(n+="else "+this.else.render(t)),n}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new vt(r):r}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(da(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(t,n),!!(super.optimizeNames(t,n)||this.else))return this.condition=bt(this.condition,t,n),this}get names(){let t=super.names;return Hn(t,this.condition),this.else&&rt(t,this.else.names),t}};tt.kind="if";var nt=class extends je{};nt.kind="for";var To=class extends nt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,n){if(super.optimizeNames(t,n))return this.iteration=bt(this.iteration,t,n),this}get names(){return rt(super.names,this.iteration.names)}},vo=class extends nt{constructor(t,n,r,o){super(),this.varKind=t,this.name=n,this.from=r,this.to=o}render(t){let n=t.es5?ke.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(t)}get names(){let t=Hn(super.names,this.from);return Hn(t,this.to)}},Gn=class extends nt{constructor(t,n,r,o){super(),this.loop=t,this.varKind=n,this.name=r,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,n){if(super.optimizeNames(t,n))return this.iterable=bt(this.iterable,t,n),this}get names(){return rt(super.names,this.iterable.names)}},Yt=class extends je{constructor(t,n,r){super(),this.name=t,this.args=n,this.async=r}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Yt.kind="func";var Xt=class extends Jt{render(t){return"return "+super.render(t)}};Xt.kind="return";var bo=class extends je{render(t){let n="try"+super.render(t);return this.catch&&(n+=this.catch.render(t)),this.finally&&(n+=this.finally.render(t)),n}optimizeNodes(){var t,n;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(t,n){var r,o;return super.optimizeNames(t,n),(r=this.catch)===null||r===void 0||r.optimizeNames(t,n),(o=this.finally)===null||o===void 0||o.optimizeNames(t,n),this}get names(){let t=super.names;return this.catch&&rt(t,this.catch.names),this.finally&&rt(t,this.finally.names),t}},Qt=class extends je{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Qt.kind="catch";var Zt=class extends je{render(t){return"finally"+super.render(t)}};Zt.kind="finally";var ko=class{constructor(t,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
2
+ `:""},this._extScope=t,this._scope=new ke.Scope({parent:t}),this._nodes=[new _o]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,n){let r=this._extScope.value(t,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(t,n){return this._extScope.getValue(t,n)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new fo(t,s,r)),s}const(t,n,r){return this._def(ke.varKinds.const,t,n,r)}let(t,n,r){return this._def(ke.varKinds.let,t,n,r)}var(t,n,r){return this._def(ke.varKinds.var,t,n,r)}assign(t,n,r){return this._leafNode(new Kn(t,n,r))}add(t,n){return this._leafNode(new po(t,P.operators.ADD,n))}code(t){return typeof t=="function"?t():t!==O.nil&&this._leafNode(new yo(t)),this}object(...t){let n=["{"];for(let[r,o]of t)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,O.addCodeArg)(n,o));return n.push("}"),new O._Code(n)}if(t,n,r){if(this._blockNode(new tt(t)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new tt(t))}else(){return this._elseNode(new vt)}endIf(){return this._endBlockNode(tt,vt)}_for(t,n){return this._blockNode(t),n&&this.code(n).endFor(),this}for(t,n){return this._for(new To(t),n)}forRange(t,n,r,o,s=this.opts.es5?ke.varKinds.var:ke.varKinds.let){let i=this._scope.toName(t);return this._for(new vo(s,i,n,r),()=>o(i))}forOf(t,n,r,o=ke.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let i=n instanceof O.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,O._)`${i}.length`,l=>{this.var(s,(0,O._)`${i}[${l}]`),r(s)})}return this._for(new Gn("of",o,s,n),()=>r(s))}forIn(t,n,r,o=this.opts.es5?ke.varKinds.var:ke.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,O._)`Object.keys(${n})`,r);let s=this._scope.toName(t);return this._for(new Gn("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(nt)}label(t){return this._leafNode(new mo(t))}break(t){return this._leafNode(new ho(t))}return(t){let n=new Xt;if(this._blockNode(n),this.code(t),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Xt)}try(t,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new bo;if(this._blockNode(o),this.code(t),n){let s=this.name("e");this._currNode=o.catch=new Qt(s),n(s)}return r&&(this._currNode=o.finally=new Zt,this.code(r)),this._endBlockNode(Qt,Zt)}throw(t){return this._leafNode(new go(t))}block(t,n){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(n),this}endBlock(t){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||t!==void 0&&r!==t)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${t} expected`);return this._nodes.length=n,this}func(t,n=O.nil,r,o){return this._blockNode(new Yt(t,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Yt)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,n){let r=this._currNode;if(r instanceof t||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${t.kind}/${n.kind}`:t.kind}"`)}_elseNode(t){let n=this._currNode;if(!(n instanceof tt))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let n=this._nodes;n[n.length-1]=t}};P.CodeGen=ko;function rt(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function Hn(e,t){return t instanceof O._CodeOrName?rt(e,t.names):e}function bt(e,t,n){if(e instanceof O.Name)return r(e);if(!o(e))return e;return new O._Code(e._items.reduce((s,i)=>(i instanceof O.Name&&(i=r(i)),i instanceof O._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[s.str];return i===void 0||t[s.str]!==1?s:(delete t[s.str],i)}function o(s){return s instanceof O._Code&&s._items.some(i=>i instanceof O.Name&&t[i.str]===1&&n[i.str]!==void 0)}}function rf(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function da(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,O._)`!${Co(e)}`}P.not=da;var of=fa(P.operators.AND);function sf(...e){return e.reduce(of)}P.and=sf;var af=fa(P.operators.OR);function lf(...e){return e.reduce(af)}P.or=lf;function fa(e){return(t,n)=>t===O.nil?n:n===O.nil?t:(0,O._)`${Co(t)} ${e} ${Co(n)}`}function Co(e){return e instanceof O.Name?e:(0,O._)`(${e})`}});var M=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.checkStrictMode=A.getErrorPath=A.Type=A.useFunc=A.setEvaluated=A.evaluatedPropsToName=A.mergeEvaluated=A.eachItem=A.unescapeJsonPointer=A.escapeJsonPointer=A.escapeFragment=A.unescapeFragment=A.schemaRefOrVal=A.schemaHasRulesButRef=A.schemaHasRules=A.checkUnknownRules=A.alwaysValidSchema=A.toHash=void 0;var z=S(),cf=Wt();function uf(e){let t={};for(let n of e)t[n]=!0;return t}A.toHash=uf;function df(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(ha(e,t),!ga(t,e.self.RULES.all))}A.alwaysValidSchema=df;function ha(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;let o=r.RULES.keywords;for(let s in t)o[s]||Ta(e,`unknown keyword: "${s}"`)}A.checkUnknownRules=ha;function ga(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(t[n])return!0;return!1}A.schemaHasRules=ga;function ff(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}A.schemaHasRulesButRef=ff;function pf({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,z._)`${n}`}return(0,z._)`${e}${t}${(0,z.getProperty)(r)}`}A.schemaRefOrVal=pf;function mf(e){return ya(decodeURIComponent(e))}A.unescapeFragment=mf;function hf(e){return encodeURIComponent(Eo(e))}A.escapeFragment=hf;function Eo(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}A.escapeJsonPointer=Eo;function ya(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}A.unescapeJsonPointer=ya;function gf(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}A.eachItem=gf;function pa({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,l)=>{let a=i===void 0?s:i instanceof z.Name?(s instanceof z.Name?e(o,s,i):t(o,s,i),i):s instanceof z.Name?(t(o,i,s),s):n(s,i);return l===z.Name&&!(a instanceof z.Name)?r(o,a):a}}A.mergeEvaluated={props:pa({mergeNames:(e,t,n)=>e.if((0,z._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,z._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,z._)`${n} || {}`).code((0,z._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,z._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,z._)`${n} || {}`),wo(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:_a}),items:pa({mergeNames:(e,t,n)=>e.if((0,z._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,z._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,z._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,z._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function _a(e,t){if(t===!0)return e.var("props",!0);let n=e.var("props",(0,z._)`{}`);return t!==void 0&&wo(e,n,t),n}A.evaluatedPropsToName=_a;function wo(e,t,n){Object.keys(n).forEach(r=>e.assign((0,z._)`${t}${(0,z.getProperty)(r)}`,!0))}A.setEvaluated=wo;var ma={};function yf(e,t){return e.scopeValue("func",{ref:t,code:ma[t.code]||(ma[t.code]=new cf._Code(t.code))})}A.useFunc=yf;var Ro;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ro||(A.Type=Ro={}));function _f(e,t,n){if(e instanceof z.Name){let r=t===Ro.Num;return n?r?(0,z._)`"[" + ${e} + "]"`:(0,z._)`"['" + ${e} + "']"`:r?(0,z._)`"/" + ${e}`:(0,z._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,z.getProperty)(e).toString():"/"+Eo(e)}A.getErrorPath=_f;function Ta(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}A.checkStrictMode=Ta});var pe=v($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});var Z=S(),Tf={data:new Z.Name("data"),valCxt:new Z.Name("valCxt"),instancePath:new Z.Name("instancePath"),parentData:new Z.Name("parentData"),parentDataProperty:new Z.Name("parentDataProperty"),rootData:new Z.Name("rootData"),dynamicAnchors:new Z.Name("dynamicAnchors"),vErrors:new Z.Name("vErrors"),errors:new Z.Name("errors"),this:new Z.Name("this"),self:new Z.Name("self"),scope:new Z.Name("scope"),json:new Z.Name("json"),jsonPos:new Z.Name("jsonPos"),jsonLen:new Z.Name("jsonLen"),jsonPart:new Z.Name("jsonPart")};$o.default=Tf});var en=v(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.extendErrors=ee.resetErrorsCount=ee.reportExtraError=ee.reportError=ee.keyword$DataError=ee.keywordError=void 0;var N=S(),Jn=M(),ne=pe();ee.keywordError={message:({keyword:e})=>(0,N.str)`must pass "${e}" keyword validation`};ee.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,N.str)`"${e}" keyword must be ${t} ($data)`:(0,N.str)`"${e}" keyword is invalid ($data)`};function vf(e,t=ee.keywordError,n,r){let{it:o}=e,{gen:s,compositeRule:i,allErrors:l}=o,a=ka(e,t,n);r??(i||l)?va(s,a):ba(o,(0,N._)`[${a}]`)}ee.reportError=vf;function bf(e,t=ee.keywordError,n){let{it:r}=e,{gen:o,compositeRule:s,allErrors:i}=r,l=ka(e,t,n);va(o,l),s||i||ba(r,ne.default.vErrors)}ee.reportExtraError=bf;function kf(e,t){e.assign(ne.default.errors,t),e.if((0,N._)`${ne.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,N._)`${ne.default.vErrors}.length`,t),()=>e.assign(ne.default.vErrors,null)))}ee.resetErrorsCount=kf;function Cf({gen:e,keyword:t,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,ne.default.errors,l=>{e.const(i,(0,N._)`${ne.default.vErrors}[${l}]`),e.if((0,N._)`${i}.instancePath === undefined`,()=>e.assign((0,N._)`${i}.instancePath`,(0,N.strConcat)(ne.default.instancePath,s.errorPath))),e.assign((0,N._)`${i}.schemaPath`,(0,N.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,N._)`${i}.schema`,n),e.assign((0,N._)`${i}.data`,r))})}ee.extendErrors=Cf;function va(e,t){let n=e.const("err",t);e.if((0,N._)`${ne.default.vErrors} === null`,()=>e.assign(ne.default.vErrors,(0,N._)`[${n}]`),(0,N._)`${ne.default.vErrors}.push(${n})`),e.code((0,N._)`${ne.default.errors}++`)}function ba(e,t){let{gen:n,validateName:r,schemaEnv:o}=e;o.$async?n.throw((0,N._)`new ${e.ValidationError}(${t})`):(n.assign((0,N._)`${r}.errors`,t),n.return(!1))}var ot={keyword:new N.Name("keyword"),schemaPath:new N.Name("schemaPath"),params:new N.Name("params"),propertyName:new N.Name("propertyName"),message:new N.Name("message"),schema:new N.Name("schema"),parentSchema:new N.Name("parentSchema")};function ka(e,t,n){let{createErrors:r}=e.it;return r===!1?(0,N._)`{}`:Rf(e,t,n)}function Rf(e,t,n={}){let{gen:r,it:o}=e,s=[Ef(o,n),wf(e,n)];return $f(e,t,s),r.object(...s)}function Ef({errorPath:e},{instancePath:t}){let n=t?(0,N.str)`${e}${(0,Jn.getErrorPath)(t,Jn.Type.Str)}`:e;return[ne.default.instancePath,(0,N.strConcat)(ne.default.instancePath,n)]}function wf({keyword:e,it:{errSchemaPath:t}},{schemaPath:n,parentSchema:r}){let o=r?t:(0,N.str)`${t}/${e}`;return n&&(o=(0,N.str)`${o}${(0,Jn.getErrorPath)(n,Jn.Type.Str)}`),[ot.schemaPath,o]}function $f(e,{params:t,message:n},r){let{keyword:o,data:s,schemaValue:i,it:l}=e,{opts:a,propertyName:c,topSchemaRef:u,schemaPath:d}=l;r.push([ot.keyword,o],[ot.params,typeof t=="function"?t(e):t||(0,N._)`{}`]),a.messages&&r.push([ot.message,typeof n=="function"?n(e):n]),a.verbose&&r.push([ot.schema,i],[ot.parentSchema,(0,N._)`${u}${d}`],[ne.default.data,s]),c&&r.push([ot.propertyName,c])}});var Ra=v(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.boolOrEmptySchema=kt.topBoolOrEmptySchema=void 0;var Sf=en(),xf=S(),Pf=pe(),Af={message:"boolean schema is false"};function Mf(e){let{gen:t,schema:n,validateName:r}=e;n===!1?Ca(e,!1):typeof n=="object"&&n.$async===!0?t.return(Pf.default.data):(t.assign((0,xf._)`${r}.errors`,null),t.return(!0))}kt.topBoolOrEmptySchema=Mf;function Of(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),Ca(e)):n.var(t,!0)}kt.boolOrEmptySchema=Of;function Ca(e,t){let{gen:n,data:r}=e,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Sf.reportError)(o,Af,void 0,t)}});var So=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.getRules=Ct.isJSONType=void 0;var If=["string","number","integer","boolean","null","object","array"],Nf=new Set(If);function jf(e){return typeof e=="string"&&Nf.has(e)}Ct.isJSONType=jf;function Lf(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Ct.getRules=Lf});var xo=v(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.shouldUseRule=Ue.shouldUseGroup=Ue.schemaHasRulesForType=void 0;function qf({schema:e,self:t},n){let r=t.RULES.types[n];return r&&r!==!0&&Ea(e,r)}Ue.schemaHasRulesForType=qf;function Ea(e,t){return t.rules.some(n=>wa(e,n))}Ue.shouldUseGroup=Ea;function wa(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}Ue.shouldUseRule=wa});var tn=v(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.reportTypeError=te.checkDataTypes=te.checkDataType=te.coerceAndCheckDataType=te.getJSONTypes=te.getSchemaTypes=te.DataType=void 0;var Df=So(),Ff=xo(),Uf=en(),x=S(),$a=M(),Rt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Rt||(te.DataType=Rt={}));function Bf(e){let t=Sa(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}te.getSchemaTypes=Bf;function Sa(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Df.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}te.getJSONTypes=Sa;function zf(e,t){let{gen:n,data:r,opts:o}=e,s=Vf(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Ff.schemaHasRulesForType)(e,t[0]));if(i){let l=Ao(t,r,o.strictNumbers,Rt.Wrong);n.if(l,()=>{s.length?Kf(e,t,s):Mo(e)})}return i}te.coerceAndCheckDataType=zf;var xa=new Set(["string","number","integer","boolean","null"]);function Vf(e,t){return t?e.filter(n=>xa.has(n)||t==="array"&&n==="array"):[]}function Kf(e,t,n){let{gen:r,data:o,opts:s}=e,i=r.let("dataType",(0,x._)`typeof ${o}`),l=r.let("coerced",(0,x._)`undefined`);s.coerceTypes==="array"&&r.if((0,x._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,x._)`${o}[0]`).assign(i,(0,x._)`typeof ${o}`).if(Ao(t,o,s.strictNumbers),()=>r.assign(l,o))),r.if((0,x._)`${l} !== undefined`);for(let c of n)(xa.has(c)||c==="array"&&s.coerceTypes==="array")&&a(c);r.else(),Mo(e),r.endIf(),r.if((0,x._)`${l} !== undefined`,()=>{r.assign(o,l),Gf(e,l)});function a(c){switch(c){case"string":r.elseIf((0,x._)`${i} == "number" || ${i} == "boolean"`).assign(l,(0,x._)`"" + ${o}`).elseIf((0,x._)`${o} === null`).assign(l,(0,x._)`""`);return;case"number":r.elseIf((0,x._)`${i} == "boolean" || ${o} === null
3
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(l,(0,x._)`+${o}`);return;case"integer":r.elseIf((0,x._)`${i} === "boolean" || ${o} === null
4
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(l,(0,x._)`+${o}`);return;case"boolean":r.elseIf((0,x._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(l,!1).elseIf((0,x._)`${o} === "true" || ${o} === 1`).assign(l,!0);return;case"null":r.elseIf((0,x._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(l,null);return;case"array":r.elseIf((0,x._)`${i} === "string" || ${i} === "number"
5
+ || ${i} === "boolean" || ${o} === null`).assign(l,(0,x._)`[${o}]`)}}}function Gf({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,x._)`${t} !== undefined`,()=>e.assign((0,x._)`${t}[${n}]`,r))}function Po(e,t,n,r=Rt.Correct){let o=r===Rt.Correct?x.operators.EQ:x.operators.NEQ,s;switch(e){case"null":return(0,x._)`${t} ${o} null`;case"array":s=(0,x._)`Array.isArray(${t})`;break;case"object":s=(0,x._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,x._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,x._)`typeof ${t} ${o} ${e}`}return r===Rt.Correct?s:(0,x.not)(s);function i(l=x.nil){return(0,x.and)((0,x._)`typeof ${t} == "number"`,l,n?(0,x._)`isFinite(${t})`:x.nil)}}te.checkDataType=Po;function Ao(e,t,n,r){if(e.length===1)return Po(e[0],t,n,r);let o,s=(0,$a.toHash)(e);if(s.array&&s.object){let i=(0,x._)`typeof ${t} != "object"`;o=s.null?i:(0,x._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=x.nil;s.number&&delete s.integer;for(let i in s)o=(0,x.and)(o,Po(i,t,n,r));return o}te.checkDataTypes=Ao;var Hf={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,x._)`{type: ${e}}`:(0,x._)`{type: ${t}}`};function Mo(e){let t=Wf(e);(0,Uf.reportError)(t,Hf)}te.reportTypeError=Mo;function Wf(e){let{gen:t,data:n,schema:r}=e,o=(0,$a.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}});var Aa=v(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.assignDefaults=void 0;var Et=S(),Jf=M();function Yf(e,t){let{properties:n,items:r}=e.schema;if(t==="object"&&n)for(let o in n)Pa(e,o,n[o].default);else t==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Pa(e,s,o.default))}Yn.assignDefaults=Yf;function Pa(e,t,n){let{gen:r,compositeRule:o,data:s,opts:i}=e;if(n===void 0)return;let l=(0,Et._)`${s}${(0,Et.getProperty)(t)}`;if(o){(0,Jf.checkStrictMode)(e,`default is ignored for: ${l}`);return}let a=(0,Et._)`${l} === undefined`;i.useDefaults==="empty"&&(a=(0,Et._)`${a} || ${l} === null || ${l} === ""`),r.if(a,(0,Et._)`${l} = ${(0,Et.stringify)(n)}`)}});var me=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.validateUnion=B.validateArray=B.usePattern=B.callValidateCode=B.schemaProperties=B.allSchemaProperties=B.noPropertyInData=B.propertyInData=B.isOwnProperty=B.hasPropFunc=B.reportMissingProp=B.checkMissingProp=B.checkReportMissingProp=void 0;var V=S(),Oo=M(),Be=pe(),Xf=M();function Qf(e,t){let{gen:n,data:r,it:o}=e;n.if(No(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,V._)`${t}`},!0),e.error()})}B.checkReportMissingProp=Qf;function Zf({gen:e,data:t,it:{opts:n}},r,o){return(0,V.or)(...r.map(s=>(0,V.and)(No(e,t,s,n.ownProperties),(0,V._)`${o} = ${s}`)))}B.checkMissingProp=Zf;function ep(e,t){e.setParams({missingProperty:t},!0),e.error()}B.reportMissingProp=ep;function Ma(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,V._)`Object.prototype.hasOwnProperty`})}B.hasPropFunc=Ma;function Io(e,t,n){return(0,V._)`${Ma(e)}.call(${t}, ${n})`}B.isOwnProperty=Io;function tp(e,t,n,r){let o=(0,V._)`${t}${(0,V.getProperty)(n)} !== undefined`;return r?(0,V._)`${o} && ${Io(e,t,n)}`:o}B.propertyInData=tp;function No(e,t,n,r){let o=(0,V._)`${t}${(0,V.getProperty)(n)} === undefined`;return r?(0,V.or)(o,(0,V.not)(Io(e,t,n))):o}B.noPropertyInData=No;function Oa(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}B.allSchemaProperties=Oa;function np(e,t){return Oa(t).filter(n=>!(0,Oo.alwaysValidSchema)(e,t[n]))}B.schemaProperties=np;function rp({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},l,a,c){let u=c?(0,V._)`${e}, ${t}, ${r}${o}`:t,d=[[Be.default.instancePath,(0,V.strConcat)(Be.default.instancePath,s)],[Be.default.parentData,i.parentData],[Be.default.parentDataProperty,i.parentDataProperty],[Be.default.rootData,Be.default.rootData]];i.opts.dynamicRef&&d.push([Be.default.dynamicAnchors,Be.default.dynamicAnchors]);let h=(0,V._)`${u}, ${n.object(...d)}`;return a!==V.nil?(0,V._)`${l}.call(${a}, ${h})`:(0,V._)`${l}(${h})`}B.callValidateCode=rp;var op=(0,V._)`new RegExp`;function sp({gen:e,it:{opts:t}},n){let r=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(n,r);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,V._)`${o.code==="new RegExp"?op:(0,Xf.useFunc)(e,o)}(${n}, ${r})`})}B.usePattern=sp;function ip(e){let{gen:t,data:n,keyword:r,it:o}=e,s=t.name("valid");if(o.allErrors){let l=t.let("valid",!0);return i(()=>t.assign(l,!1)),l}return t.var(s,!0),i(()=>t.break()),s;function i(l){let a=t.const("len",(0,V._)`${n}.length`);t.forRange("i",0,a,c=>{e.subschema({keyword:r,dataProp:c,dataPropType:Oo.Type.Num},s),t.if((0,V.not)(s),l)})}}B.validateArray=ip;function ap(e){let{gen:t,schema:n,keyword:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,Oo.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),l=t.name("_valid");t.block(()=>n.forEach((a,c)=>{let u=e.subschema({keyword:r,schemaProp:c,compositeRule:!0},l);t.assign(i,(0,V._)`${i} || ${l}`),e.mergeValidEvaluated(u,l)||t.if((0,V.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}B.validateUnion=ap});var ja=v(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.validateKeywordUsage=Ae.validSchemaType=Ae.funcKeywordCode=Ae.macroKeywordCode=void 0;var re=S(),st=pe(),lp=me(),cp=en();function up(e,t){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=e,l=t.macro.call(i.self,o,s,i),a=Na(n,r,l);i.opts.validateSchema!==!1&&i.self.validateSchema(l,!0);let c=n.name("valid");e.subschema({schema:l,schemaPath:re.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:a,compositeRule:!0},c),e.pass(c,()=>e.error(!0))}Ae.macroKeywordCode=up;function dp(e,t){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:l,it:a}=e;pp(a,t);let c=!l&&t.compile?t.compile.call(a.self,s,i,a):t.validate,u=Na(r,o,c),d=r.let("valid");e.block$data(d,h),e.ok((n=t.valid)!==null&&n!==void 0?n:d);function h(){if(t.errors===!1)f(),t.modifying&&Ia(e),m(()=>e.error());else{let _=t.async?T():p();t.modifying&&Ia(e),m(()=>fp(e,_))}}function T(){let _=r.let("ruleErrs",null);return r.try(()=>f((0,re._)`await `),E=>r.assign(d,!1).if((0,re._)`${E} instanceof ${a.ValidationError}`,()=>r.assign(_,(0,re._)`${E}.errors`),()=>r.throw(E))),_}function p(){let _=(0,re._)`${u}.errors`;return r.assign(_,null),f(re.nil),_}function f(_=t.async?(0,re._)`await `:re.nil){let E=a.opts.passContext?st.default.this:st.default.self,w=!("compile"in t&&!l||t.schema===!1);r.assign(d,(0,re._)`${_}${(0,lp.callValidateCode)(e,u,E,w)}`,t.modifying)}function m(_){var E;r.if((0,re.not)((E=t.valid)!==null&&E!==void 0?E:d),_)}}Ae.funcKeywordCode=dp;function Ia(e){let{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,re._)`${r.parentData}[${r.parentDataProperty}]`))}function fp(e,t){let{gen:n}=e;n.if((0,re._)`Array.isArray(${t})`,()=>{n.assign(st.default.vErrors,(0,re._)`${st.default.vErrors} === null ? ${t} : ${st.default.vErrors}.concat(${t})`).assign(st.default.errors,(0,re._)`${st.default.vErrors}.length`),(0,cp.extendErrors)(e)},()=>e.error())}function pp({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Na(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,re.stringify)(n)})}function mp(e,t,n=!1){return!t.length||t.some(r=>r==="array"?Array.isArray(e):r==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==r||n&&typeof e>"u")}Ae.validSchemaType=mp;function hp({schema:e,opts:t,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(l=>!Object.prototype.hasOwnProperty.call(e,l)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){let a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}Ae.validateKeywordUsage=hp});var qa=v(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendSubschemaMode=ze.extendSubschemaData=ze.getSubschema=void 0;var Me=S(),La=M();function gp(e,{keyword:t,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let l=e.schema[t];return n===void 0?{schema:l,schemaPath:(0,Me._)`${e.schemaPath}${(0,Me.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:l[n],schemaPath:(0,Me._)`${e.schemaPath}${(0,Me.getProperty)(t)}${(0,Me.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,La.escapeFragment)(n)}`}}if(r!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}ze.getSubschema=gp;function yp(e,t,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:l}=t;if(n!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=t,h=l.let("data",(0,Me._)`${t.data}${(0,Me.getProperty)(n)}`,!0);a(h),e.errorPath=(0,Me.str)`${c}${(0,La.getErrorPath)(n,r,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Me._)`${n}`,e.dataPathArr=[...u,e.parentDataProperty]}if(o!==void 0){let c=o instanceof Me.Name?o:l.let("data",o,!0);a(c),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function a(c){e.data=c,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,c]}}ze.extendSubschemaData=yp;function _p(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(e.compositeRule=r),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}ze.extendSubschemaMode=_p});var jo=v((rb,Da)=>{"use strict";Da.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n}});var Ua=v((ob,Fa)=>{"use strict";var Ve=Fa.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};Xn(t,r,o,e,"",e)};Ve.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ve.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ve.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ve.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Xn(e,t,n,r,o,s,i,l,a,c){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,o,s,i,l,a,c);for(var u in r){var d=r[u];if(Array.isArray(d)){if(u in Ve.arrayKeywords)for(var h=0;h<d.length;h++)Xn(e,t,n,d[h],o+"/"+u+"/"+h,s,o,u,r,h)}else if(u in Ve.propsKeywords){if(d&&typeof d=="object")for(var T in d)Xn(e,t,n,d[T],o+"/"+u+"/"+Tp(T),s,o,u,r,T)}else(u in Ve.keywords||e.allKeys&&!(u in Ve.skipKeywords))&&Xn(e,t,n,d,o+"/"+u,s,o,u,r)}n(r,o,s,i,l,a,c)}}function Tp(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var nn=v(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.getSchemaRefs=ae.resolveUrl=ae.normalizeId=ae._getFullPath=ae.getFullPath=ae.inlineRef=void 0;var vp=M(),bp=jo(),kp=Ua(),Cp=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Rp(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Lo(e):t?Ba(e)<=t:!1}ae.inlineRef=Rp;var Ep=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Lo(e){for(let t in e){if(Ep.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(Lo)||typeof n=="object"&&Lo(n))return!0}return!1}function Ba(e){let t=0;for(let n in e){if(n==="$ref")return 1/0;if(t++,!Cp.has(n)&&(typeof e[n]=="object"&&(0,vp.eachItem)(e[n],r=>t+=Ba(r)),t===1/0))return 1/0}return t}function za(e,t="",n){n!==!1&&(t=wt(t));let r=e.parse(t);return Va(e,r)}ae.getFullPath=za;function Va(e,t){return e.serialize(t).split("#")[0]+"#"}ae._getFullPath=Va;var wp=/#\/?$/;function wt(e){return e?e.replace(wp,""):""}ae.normalizeId=wt;function $p(e,t,n){return n=wt(n),e.resolve(t,n)}ae.resolveUrl=$p;var Sp=/^[a-z_][-a-z0-9._]*$/i;function xp(e,t){if(typeof e=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=wt(e[n]||t),s={"":o},i=za(r,o,!1),l={},a=new Set;return kp(e,{allKeys:!0},(d,h,T,p)=>{if(p===void 0)return;let f=i+h,m=s[p];typeof d[n]=="string"&&(m=_.call(this,d[n])),E.call(this,d.$anchor),E.call(this,d.$dynamicAnchor),s[h]=m;function _(w){let q=this.opts.uriResolver.resolve;if(w=wt(m?q(m,w):w),a.has(w))throw u(w);a.add(w);let R=this.refs[w];return typeof R=="string"&&(R=this.refs[R]),typeof R=="object"?c(d,R.schema,w):w!==wt(f)&&(w[0]==="#"?(c(d,l[w],w),l[w]=d):this.refs[w]=f),w}function E(w){if(typeof w=="string"){if(!Sp.test(w))throw new Error(`invalid anchor "${w}"`);_.call(this,`#${w}`)}}}),l;function c(d,h,T){if(h!==void 0&&!bp(d,h))throw u(T)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ae.getSchemaRefs=xp});var sn=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.getData=Ke.KeywordCxt=Ke.validateFunctionCode=void 0;var Ja=Ra(),Ka=tn(),Do=xo(),Qn=tn(),Pp=Aa(),on=ja(),qo=qa(),C=S(),$=pe(),Ap=nn(),Le=M(),rn=en();function Mp(e){if(Qa(e)&&(Za(e),Xa(e))){Np(e);return}Ya(e,()=>(0,Ja.topBoolOrEmptySchema)(e))}Ke.validateFunctionCode=Mp;function Ya({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},s){o.code.es5?e.func(t,(0,C._)`${$.default.data}, ${$.default.valCxt}`,r.$async,()=>{e.code((0,C._)`"use strict"; ${Ga(n,o)}`),Ip(e,o),e.code(s)}):e.func(t,(0,C._)`${$.default.data}, ${Op(o)}`,r.$async,()=>e.code(Ga(n,o)).code(s))}function Op(e){return(0,C._)`{${$.default.instancePath}="", ${$.default.parentData}, ${$.default.parentDataProperty}, ${$.default.rootData}=${$.default.data}${e.dynamicRef?(0,C._)`, ${$.default.dynamicAnchors}={}`:C.nil}}={}`}function Ip(e,t){e.if($.default.valCxt,()=>{e.var($.default.instancePath,(0,C._)`${$.default.valCxt}.${$.default.instancePath}`),e.var($.default.parentData,(0,C._)`${$.default.valCxt}.${$.default.parentData}`),e.var($.default.parentDataProperty,(0,C._)`${$.default.valCxt}.${$.default.parentDataProperty}`),e.var($.default.rootData,(0,C._)`${$.default.valCxt}.${$.default.rootData}`),t.dynamicRef&&e.var($.default.dynamicAnchors,(0,C._)`${$.default.valCxt}.${$.default.dynamicAnchors}`)},()=>{e.var($.default.instancePath,(0,C._)`""`),e.var($.default.parentData,(0,C._)`undefined`),e.var($.default.parentDataProperty,(0,C._)`undefined`),e.var($.default.rootData,$.default.data),t.dynamicRef&&e.var($.default.dynamicAnchors,(0,C._)`{}`)})}function Np(e){let{schema:t,opts:n,gen:r}=e;Ya(e,()=>{n.$comment&&t.$comment&&tl(e),Fp(e),r.let($.default.vErrors,null),r.let($.default.errors,0),n.unevaluated&&jp(e),el(e),zp(e)})}function jp(e){let{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,C._)`${n}.evaluated`),t.if((0,C._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,C._)`${e.evaluated}.props`,(0,C._)`undefined`)),t.if((0,C._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,C._)`${e.evaluated}.items`,(0,C._)`undefined`))}function Ga(e,t){let n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,C._)`/*# sourceURL=${n} */`:C.nil}function Lp(e,t){if(Qa(e)&&(Za(e),Xa(e))){qp(e,t);return}(0,Ja.boolOrEmptySchema)(e,t)}function Xa({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function Qa(e){return typeof e.schema!="boolean"}function qp(e,t){let{schema:n,gen:r,opts:o}=e;o.$comment&&n.$comment&&tl(e),Up(e),Bp(e);let s=r.const("_errs",$.default.errors);el(e,s),r.var(t,(0,C._)`${s} === ${$.default.errors}`)}function Za(e){(0,Le.checkUnknownRules)(e),Dp(e)}function el(e,t){if(e.opts.jtd)return Ha(e,[],!1,t);let n=(0,Ka.getSchemaTypes)(e.schema),r=(0,Ka.coerceAndCheckDataType)(e,n);Ha(e,n,!r,t)}function Dp(e){let{schema:t,errSchemaPath:n,opts:r,self:o}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,Le.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Fp(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Le.checkStrictMode)(e,"default is ignored in the schema root")}function Up(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Ap.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function Bp(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function tl({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:o}){let s=n.$comment;if(o.$comment===!0)e.code((0,C._)`${$.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,C.str)`${r}/$comment`,l=e.scopeValue("root",{ref:t.root});e.code((0,C._)`${$.default.self}.opts.$comment(${s}, ${i}, ${l}.schema)`)}}function zp(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=e;n.$async?t.if((0,C._)`${$.default.errors} === 0`,()=>t.return($.default.data),()=>t.throw((0,C._)`new ${o}(${$.default.vErrors})`)):(t.assign((0,C._)`${r}.errors`,$.default.vErrors),s.unevaluated&&Vp(e),t.return((0,C._)`${$.default.errors} === 0`))}function Vp({gen:e,evaluated:t,props:n,items:r}){n instanceof C.Name&&e.assign((0,C._)`${t}.props`,n),r instanceof C.Name&&e.assign((0,C._)`${t}.items`,r)}function Ha(e,t,n,r){let{gen:o,schema:s,data:i,allErrors:l,opts:a,self:c}=e,{RULES:u}=c;if(s.$ref&&(a.ignoreKeywordsWithRef||!(0,Le.schemaHasRulesButRef)(s,u))){o.block(()=>rl(e,"$ref",u.all.$ref.definition));return}a.jtd||Kp(e,t),o.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,Do.shouldUseGroup)(s,h)&&(h.type?(o.if((0,Qn.checkDataType)(h.type,i,a.strictNumbers)),Wa(e,h),t.length===1&&t[0]===h.type&&n&&(o.else(),(0,Qn.reportTypeError)(e)),o.endIf()):Wa(e,h),l||o.if((0,C._)`${$.default.errors} === ${r||0}`))}}function Wa(e,t){let{gen:n,schema:r,opts:{useDefaults:o}}=e;o&&(0,Pp.assignDefaults)(e,t.type),n.block(()=>{for(let s of t.rules)(0,Do.shouldUseRule)(r,s)&&rl(e,s.keyword,s.definition,t.type)})}function Kp(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Gp(e,t),e.opts.allowUnionTypes||Hp(e,t),Wp(e,e.dataTypes))}function Gp(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{nl(e.dataTypes,n)||Fo(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),Yp(e,t)}}function Hp(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Fo(e,"use allowUnionTypes to allow union type keyword")}function Wp(e,t){let n=e.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Do.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Jp(t,i))&&Fo(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function Jp(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function nl(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function Yp(e,t){let n=[];for(let r of e.dataTypes)nl(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function Fo(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,Le.checkStrictMode)(e,t,e.opts.strictTypes)}var Zn=class{constructor(t,n,r){if((0,on.validateKeywordUsage)(t,n,r),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=r,this.data=t.data,this.schema=t.schema[r],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Le.schemaRefOrVal)(t,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",ol(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,on.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=t.gen.const("_errs",$.default.errors))}result(t,n,r){this.failResult((0,C.not)(t),n,r)}failResult(t,n,r){this.gen.if(t),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,C.not)(t),void 0,n)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:n}=this;this.fail((0,C._)`${n} !== undefined && (${(0,C.or)(this.invalid$data(),t)})`)}error(t,n,r){if(n){this.setParams(n),this._error(t,r),this.setParams({});return}this._error(t,r)}_error(t,n){(t?rn.reportExtraError:rn.reportError)(this,this.def.error,n)}$dataError(){(0,rn.reportError)(this,this.def.$dataError||rn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,rn.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,r=C.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=C.nil,n=C.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,C.or)((0,C._)`${o} === undefined`,n)),t!==C.nil&&r.assign(t,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==C.nil&&r.assign(t,!1)),r.else()}invalid$data(){let{gen:t,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,C.or)(i(),l());function i(){if(r.length){if(!(n instanceof C.Name))throw new Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return(0,C._)`${(0,Qn.checkDataTypes)(a,n,s.opts.strictNumbers,Qn.DataType.Wrong)}`}return C.nil}function l(){if(o.validateSchema){let a=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,C._)`!${a}(${n})`}return C.nil}}subschema(t,n){let r=(0,qo.getSubschema)(this.it,t);(0,qo.extendSubschemaData)(r,this.it,t),(0,qo.extendSubschemaMode)(r,t);let o={...this.it,...r,items:void 0,props:void 0};return Lp(o,n),o}mergeEvaluated(t,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=Le.mergeEvaluated.props(o,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=Le.mergeEvaluated.items(o,t.items,r.items,n)))}mergeValidEvaluated(t,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(t,C.Name)),!0}};Ke.KeywordCxt=Zn;function rl(e,t,n,r){let o=new Zn(e,n,t);"code"in n?n.code(o,r):o.$data&&n.validate?(0,on.funcKeywordCode)(o,n):"macro"in n?(0,on.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,on.funcKeywordCode)(o,n)}var Xp=/^\/(?:[^~]|~0|~1)*$/,Qp=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ol(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let o,s;if(e==="")return $.default.rootData;if(e[0]==="/"){if(!Xp.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=$.default.rootData}else{let c=Qp.exec(e);if(!c)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+c[1];if(o=c[2],o==="#"){if(u>=t)throw new Error(a("property/index",u));return r[t-u]}if(u>t)throw new Error(a("data",u));if(s=n[t-u],!o)return s}let i=s,l=o.split("/");for(let c of l)c&&(s=(0,C._)`${s}${(0,C.getProperty)((0,Le.unescapeJsonPointer)(c))}`,i=(0,C._)`${i} && ${s}`);return i;function a(c,u){return`Cannot access ${c} ${u} levels up, current level is ${t}`}}Ke.getData=ol});var er=v(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});var Uo=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Bo.default=Uo});var an=v(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});var zo=nn(),Vo=class extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,zo.resolveUrl)(t,n,r),this.missingSchema=(0,zo.normalizeId)((0,zo.getFullPath)(t,this.missingRef))}};Ko.default=Vo});var ln=v(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.resolveSchema=he.getCompilingSchema=he.resolveRef=he.compileSchema=he.SchemaEnv=void 0;var Ce=S(),Zp=er(),it=pe(),Re=nn(),sl=M(),em=sn(),$t=class{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Re.normalizeId)(r?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r?.$async,this.refs={}}};he.SchemaEnv=$t;function Ho(e){let t=il.call(this,e);if(t)return t;let n=(0,Re.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ce.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),l;e.$async&&(l=i.scopeValue("Error",{ref:Zp.default,code:(0,Ce._)`require("ajv/dist/runtime/validation_error").default`}));let a=i.scopeName("validate");e.validateName=a;let c={gen:i,allErrors:this.opts.allErrors,data:it.default.data,parentData:it.default.parentData,parentDataProperty:it.default.parentDataProperty,dataNames:[it.default.data],dataPathArr:[Ce.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ce.stringify)(e.schema)}:{ref:e.schema}),validateName:a,ValidationError:l,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ce.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ce._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,em.validateFunctionCode)(c),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(it.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let T=new Function(`${it.default.self}`,`${it.default.scope}`,u)(this,this.scope.get());if(this.scope.value(a,{ref:T}),T.errors=null,T.schema=e.schema,T.schemaEnv=e,e.$async&&(T.$async=!0),this.opts.code.source===!0&&(T.source={validateName:a,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:f}=c;T.evaluated={props:p instanceof Ce.Name?void 0:p,items:f instanceof Ce.Name?void 0:f,dynamicProps:p instanceof Ce.Name,dynamicItems:f instanceof Ce.Name},T.source&&(T.source.evaluated=(0,Ce.stringify)(T.evaluated))}return e.validate=T,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e)}}he.compileSchema=Ho;function tm(e,t,n){var r;n=(0,Re.resolveUrl)(this.opts.uriResolver,t,n);let o=e.refs[n];if(o)return o;let s=om.call(this,e,n);if(s===void 0){let i=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:l}=this.opts;i&&(s=new $t({schema:i,schemaId:l,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=nm.call(this,s)}he.resolveRef=tm;function nm(e){return(0,Re.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Ho.call(this,e)}function il(e){for(let t of this._compilations)if(rm(t,e))return t}he.getCompilingSchema=il;function rm(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function om(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||tr.call(this,e,t)}function tr(e,t){let n=this.opts.uriResolver.parse(t),r=(0,Re._getFullPath)(this.opts.uriResolver,n),o=(0,Re.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return Go.call(this,n,e);let s=(0,Re.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let l=tr.call(this,e,i);return typeof l?.schema!="object"?void 0:Go.call(this,n,l)}if(typeof i?.schema=="object"){if(i.validate||Ho.call(this,i),s===(0,Re.normalizeId)(t)){let{schema:l}=i,{schemaId:a}=this.opts,c=l[a];return c&&(o=(0,Re.resolveUrl)(this.opts.uriResolver,o,c)),new $t({schema:l,schemaId:a,root:e,baseId:o})}return Go.call(this,n,i)}}he.resolveSchema=tr;var sm=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Go(e,{baseId:t,schema:n,root:r}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let l of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let a=n[(0,sl.unescapeFragment)(l)];if(a===void 0)return;n=a;let c=typeof n=="object"&&n[this.opts.schemaId];!sm.has(l)&&c&&(t=(0,Re.resolveUrl)(this.opts.uriResolver,t,c))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,sl.schemaHasRulesButRef)(n,this.RULES)){let l=(0,Re.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=tr.call(this,r,l)}let{schemaId:i}=this.opts;if(s=s||new $t({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}});var al=v((ub,im)=>{im.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Yo=v((db,pl)=>{"use strict";var am=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),cl=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Wo=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ul=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),lm=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Jo(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}var cm=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ll(e){return e.length=0,!0}function um(e,t,n){if(e.length){let r=Jo(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function dm(e){let t=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,l=um;for(let a=0;a<e.length;a++){let c=e[a];if(!(c==="["||c==="]"))if(c===":"){if(s===!0&&(i=!0),!l(o,r,n))break;if(++t>7){n.error=!0;break}a>0&&e[a-1]===":"&&(s=!0),r.push(":");continue}else if(c==="%"){if(!l(o,r,n))break;l=ll}else{o.push(c);continue}}return o.length&&(l===ll?n.zone=o.join(""):i?r.push(o.join("")):r.push(Jo(o))),n.address=r.join(""),n}function dl(e){if(fm(e,":")<2)return{host:e,isIPV6:!1};let t=dm(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,r=t.address;return t.zone&&(n+="%"+t.zone,r+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:r}}}function fm(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function pm(e){let t=e,n=[],r=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(o===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")}var mm={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},hm=/[@/?#:]/g,gm=/[@/?#]/g;function fl(e,t){let n=t?gm:hm;return n.lastIndex=0,e.replace(n,r=>mm[r])}function ym(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let o=e.slice(r+1,r+3);if(Wo(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&ul(i)?n+=i:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function _m(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let r=e.slice(n+1,n+3);if(Wo(r)){let o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&ul(s)?t+=s:t+="%"+o,n+=2;continue}}lm(e[n])?t+=e[n]:t+=escape(e[n])}return t}function Tm(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let r=e.slice(n+1,n+3);if(Wo(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function vm(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!cl(n)){let r=dl(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=fl(n,!1)}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}pl.exports={nonSimpleDomain:cm,recomposeAuthority:vm,reescapeHostDelimiters:fl,normalizePercentEncoding:ym,normalizePathEncoding:_m,escapePreservingEscapes:Tm,removeDotSegments:pm,isIPv4:cl,isUUID:am,normalizeIPv6:dl,stringArrayToHexStripped:Jo}});var _l=v((fb,yl)=>{"use strict";var{isUUID:bm}=Yo(),km=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Cm=["http","https","ws","wss","urn","urn:uuid"];function Rm(e){return Cm.indexOf(e)!==-1}function Xo(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function ml(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function hl(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function Em(e){return e.secure=Xo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function wm(e){if((e.port===(Xo(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function $m(e,t){if(!e.path)return e.error="URN can not be parsed",e;let n=e.path.match(km);if(n){let r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];let o=`${r}:${t.nid||e.nid}`,s=Qo(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Sm(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),o=`${n}:${t.nid||r}`,s=Qo(o);s&&(e=s.serialize(e,t));let i=e,l=e.nss;return i.path=`${r||t.nid}:${l}`,t.skipEscape=!0,i}function xm(e,t){let n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!bm(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Pm(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var gl={scheme:"http",domainHost:!0,parse:ml,serialize:hl},Am={scheme:"https",domainHost:gl.domainHost,parse:ml,serialize:hl},nr={scheme:"ws",domainHost:!0,parse:Em,serialize:wm},Mm={scheme:"wss",domainHost:nr.domainHost,parse:nr.parse,serialize:nr.serialize},Om={scheme:"urn",parse:$m,serialize:Sm,skipNormalize:!0},Im={scheme:"urn:uuid",parse:xm,serialize:Pm,skipNormalize:!0},rr={http:gl,https:Am,ws:nr,wss:Mm,urn:Om,"urn:uuid":Im};Object.setPrototypeOf(rr,null);function Qo(e){return e&&(rr[e]||rr[e.toLowerCase()])||void 0}yl.exports={wsIsSecure:Xo,SCHEMES:rr,isValidSchemeName:Rm,getSchemeHandler:Qo}});var Rl=v((pb,or)=>{"use strict";var{normalizeIPv6:Nm,removeDotSegments:cn,recomposeAuthority:jm,normalizePercentEncoding:Lm,normalizePathEncoding:qm,escapePreservingEscapes:Dm,reescapeHostDelimiters:Fm,isIPv4:Um,nonSimpleDomain:Bm}=Yo(),{SCHEMES:zm,getSchemeHandler:vl}=_l();function Vm(e,t){return typeof e=="string"?e=Jm(e,t):typeof e=="object"&&(e=St(at(e,t),t)),e}function Km(e,t,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=bl(St(e,r),St(t,r),r,!0);return r.skipEscape=!0,at(o,r)}function bl(e,t,n,r){let o={};return r||(e=St(at(e,n),n),t=St(at(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=cn(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=cn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=cn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=cn(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function Gm(e,t,n){let r=Tl(e,n),o=Tl(t,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function at(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},r=Object.assign({},t),o=[],s=vl(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=Lm(n.path):(n.path=Dm(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let i=jm(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let l=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(l=cn(l)),i===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),o.push(l)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var Hm=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Wm(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function kl(e,t){let n=Object.assign({},t),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);let i=e.match(Hm);if(i){r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]);let l=Wm(r,i);if(l!==void 0&&(r.error=r.error||l,o=!0),r.host)if(Um(r.host)===!1){let u=Nm(r.host);r.host=u.host.toLowerCase(),s=u.isIPV6}else s=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let a=vl(n.scheme||r.scheme);if(!n.unicodeSupport&&(!a||!a.unicodeSupport)&&r.host&&(n.domainHost||a&&a.domainHost)&&s===!1&&Bm(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(c){r.error=r.error||"Host's domain name can not be converted to ASCII: "+c}if((!a||a&&!a.skipNormalize)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Fm(unescape(r.host),s))),r.path&&(r.path=qm(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}a&&a.parse&&a.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function St(e,t){return kl(e,t).parsed}function Jm(e,t){return Cl(e,t).normalized}function Cl(e,t){let{parsed:n,malformedAuthorityOrPort:r}=kl(e,t);return{normalized:r?e:at(n,t),malformedAuthorityOrPort:r}}function Tl(e,t){if(typeof e=="string"){let{normalized:n,malformedAuthorityOrPort:r}=Cl(e,t);return r?void 0:n}if(typeof e=="object")return at(e,t)}var Zo={SCHEMES:zm,normalize:Vm,resolve:Km,resolveComponent:bl,equal:Gm,serialize:at,parse:St};or.exports=Zo;or.exports.default=Zo;or.exports.fastUri=Zo});var wl=v(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var El=Rl();El.code='require("ajv/dist/runtime/uri").default';es.default=El});var Il=v(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.CodeGen=Y.Name=Y.nil=Y.stringify=Y.str=Y._=Y.KeywordCxt=void 0;var Ym=sn();Object.defineProperty(Y,"KeywordCxt",{enumerable:!0,get:function(){return Ym.KeywordCxt}});var xt=S();Object.defineProperty(Y,"_",{enumerable:!0,get:function(){return xt._}});Object.defineProperty(Y,"str",{enumerable:!0,get:function(){return xt.str}});Object.defineProperty(Y,"stringify",{enumerable:!0,get:function(){return xt.stringify}});Object.defineProperty(Y,"nil",{enumerable:!0,get:function(){return xt.nil}});Object.defineProperty(Y,"Name",{enumerable:!0,get:function(){return xt.Name}});Object.defineProperty(Y,"CodeGen",{enumerable:!0,get:function(){return xt.CodeGen}});var Xm=er(),Al=an(),Qm=So(),un=ln(),Zm=S(),dn=nn(),sr=tn(),ns=M(),$l=al(),eh=wl(),Ml=(e,t)=>new RegExp(e,t);Ml.code="new RegExp";var th=["removeAdditional","useDefaults","coerceTypes"],nh=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),rh={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},oh={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Sl=200;function sh(e){var t,n,r,o,s,i,l,a,c,u,d,h,T,p,f,m,_,E,w,q,R,Q,W,we,$e;let ye=e.strict,Se=(t=e.code)===null||t===void 0?void 0:t.optimize,We=Se===!0||Se===void 0?1:Se||0,ft=(r=(n=e.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Ml,Rn=(o=e.uriResolver)!==null&&o!==void 0?o:eh.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:ye)!==null&&i!==void 0?i:!0,strictNumbers:(a=(l=e.strictNumbers)!==null&&l!==void 0?l:ye)!==null&&a!==void 0?a:!0,strictTypes:(u=(c=e.strictTypes)!==null&&c!==void 0?c:ye)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=e.strictTuples)!==null&&d!==void 0?d:ye)!==null&&h!==void 0?h:"log",strictRequired:(p=(T=e.strictRequired)!==null&&T!==void 0?T:ye)!==null&&p!==void 0?p:!1,code:e.code?{...e.code,optimize:We,regExp:ft}:{optimize:We,regExp:ft},loopRequired:(f=e.loopRequired)!==null&&f!==void 0?f:Sl,loopEnum:(m=e.loopEnum)!==null&&m!==void 0?m:Sl,meta:(_=e.meta)!==null&&_!==void 0?_:!0,messages:(E=e.messages)!==null&&E!==void 0?E:!0,inlineRefs:(w=e.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(q=e.schemaId)!==null&&q!==void 0?q:"$id",addUsedSchema:(R=e.addUsedSchema)!==null&&R!==void 0?R:!0,validateSchema:(Q=e.validateSchema)!==null&&Q!==void 0?Q:!0,validateFormats:(W=e.validateFormats)!==null&&W!==void 0?W:!0,unicodeRegExp:(we=e.unicodeRegExp)!==null&&we!==void 0?we:!0,int32range:($e=e.int32range)!==null&&$e!==void 0?$e:!0,uriResolver:Rn}}var fn=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...sh(t)};let{es5:n,lines:r}=this.opts.code;this.scope=new Zm.ValueScope({scope:{},prefixes:nh,es5:n,lines:r}),this.logger=dh(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,Qm.getRules)(),xl.call(this,rh,t,"NOT SUPPORTED"),xl.call(this,oh,t,"DEPRECATED","warn"),this._metaOpts=ch.call(this),t.formats&&ah.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&lh.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),ih.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:n,schemaId:r}=this.opts,o=$l;r==="id"&&(o={...$l},o.id=o.$id,delete o.$id),n&&t&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:t,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[n]||t:void 0}validate(t,n){let r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error(`no schema with key or ref "${t}"`)}else r=this.compile(t);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(t,n){let r=this._addSchema(t,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(t,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,t,n);async function o(u,d){await s.call(this,u.$schema);let h=this._addSchema(u,d);return h.validate||i.call(this,h)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Al.default))throw d;return l.call(this,d),await a.call(this,d.missingSchema),i.call(this,u)}}function l({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function a(u){let d=await c.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,n)}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(t,n,r,o=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,r,o);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return n=(0,dn.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(t,r,n,o,!0),this}addMetaSchema(t,n,r=this.opts.validateSchema){return this.addSchema(t,n,!0,r),this}validateSchema(t,n){if(typeof t=="boolean")return!0;let r;if(r=t.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,t);if(!o&&n){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(t){let n;for(;typeof(n=Pl.call(this,t))=="string";)t=n;if(n===void 0){let{schemaId:r}=this.opts,o=new un.SchemaEnv({schema:{},schemaId:r});if(n=un.resolveSchema.call(this,o,t),!n)return;this.refs[t]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=Pl.call(this,t);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let n=t;this._cache.delete(n);let r=t[this.opts.schemaId];return r&&(r=(0,dn.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let n of t)this.addKeyword(n);return this}addKeyword(t,n){let r;if(typeof t=="string")r=t,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof t=="object"&&n===void 0){if(n=t,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(ph.call(this,r,n),!n)return(0,ns.eachItem)(r,s=>ts.call(this,s)),this;hh.call(this,n);let o={...n,type:(0,sr.getJSONTypes)(n.type),schemaType:(0,sr.getJSONTypes)(n.schemaType)};return(0,ns.eachItem)(r,o.type.length===0?s=>ts.call(this,s,o):s=>o.type.forEach(i=>ts.call(this,s,o,i))),this}getKeyword(t){let n=this.RULES.all[t];return typeof n=="object"?n.definition:!!n}removeKeyword(t){let{RULES:n}=this;delete n.keywords[t],delete n.all[t];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===t);o>=0&&r.rules.splice(o,1)}return this}addFormat(t,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[t]=n,this}errorsText(t=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!t||t.length===0?"No errors":t.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(t,n){let r=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of n){let s=o.split("/").slice(1),i=t;for(let l of s)i=i[l];for(let l in r){let a=r[l];if(typeof a!="object")continue;let{$data:c}=a.definition,u=i[l];c&&u&&(i[l]=Ol(u))}}return t}_removeAllSchemas(t,n){for(let r in t){let o=t[r];(!n||n.test(r))&&(typeof o=="string"?delete t[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[r]))}}_addSchema(t,n,r,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:l}=this.opts;if(typeof t=="object")i=t[l];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let a=this._cache.get(t);if(a!==void 0)return a;r=(0,dn.normalizeId)(i||r);let c=dn.getSchemaRefs.call(this,t,r);return a=new un.SchemaEnv({schema:t,schemaId:l,meta:n,baseId:r,localRefs:c}),this._cache.set(a.schema,a),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=a),o&&this.validateSchema(t,!0),a}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):un.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let n=this.opts;this.opts=this._metaOpts;try{un.compileSchema.call(this,t)}finally{this.opts=n}}};fn.ValidationError=Xm.default;fn.MissingRefError=Al.default;Y.default=fn;function xl(e,t,n,r="error"){for(let o in e){let s=o;s in t&&this.logger[r](`${n}: option ${o}. ${e[s]}`)}}function Pl(e){return e=(0,dn.normalizeId)(e),this.schemas[e]||this.refs[e]}function ih(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function ah(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function lh(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}function ch(){let e={...this.opts};for(let t of th)delete e[t];return e}var uh={log(){},warn(){},error(){}};function dh(e){if(e===!1)return uh;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var fh=/^[a-z_$][a-z0-9_$:-]*$/i;function ph(e,t){let{RULES:n}=this;if((0,ns.eachItem)(e,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!fh.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function ts(e,t,n){var r;let o=t?.post;if(n&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:a})=>a===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[e]=!0,!t)return;let l={keyword:e,definition:{...t,type:(0,sr.getJSONTypes)(t.type),schemaType:(0,sr.getJSONTypes)(t.schemaType)}};t.before?mh.call(this,i,l,t.before):i.rules.push(l),s.all[e]=l,(r=t.implements)===null||r===void 0||r.forEach(a=>this.addKeyword(a))}function mh(e,t,n){let r=e.rules.findIndex(o=>o.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function hh(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Ol(t)),e.validateSchema=this.compile(t,!0))}var gh={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ol(e){return{anyOf:[e,gh]}}});var Nl=v(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var yh={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};rs.default=yh});var lr=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.callRef=lt.getValidate=void 0;var _h=an(),jl=me(),le=S(),Pt=pe(),Ll=ln(),ir=M(),Th={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:s,validateName:i,opts:l,self:a}=r,{root:c}=s;if((n==="#"||n==="#/")&&o===c.baseId)return d();let u=Ll.resolveRef.call(a,c,o,n);if(u===void 0)throw new _h.default(r.opts.uriResolver,o,n);if(u instanceof Ll.SchemaEnv)return h(u);return T(u);function d(){if(s===c)return ar(e,i,s,s.$async);let p=t.scopeValue("root",{ref:c});return ar(e,(0,le._)`${p}.validate`,c,c.$async)}function h(p){let f=ql(e,p);ar(e,f,p,p.$async)}function T(p){let f=t.scopeValue("schema",l.code.source===!0?{ref:p,code:(0,le.stringify)(p)}:{ref:p}),m=t.name("valid"),_=e.subschema({schema:p,dataTypes:[],schemaPath:le.nil,topSchemaRef:f,errSchemaPath:n},m);e.mergeEvaluated(_),e.ok(m)}}};function ql(e,t){let{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,le._)`${n.scopeValue("wrapper",{ref:t})}.validate`}lt.getValidate=ql;function ar(e,t,n,r){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:l,opts:a}=s,c=a.passContext?Pt.default.this:le.nil;r?u():d();function u(){if(!l.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,le._)`await ${(0,jl.callValidateCode)(e,t,c)}`),T(t),i||o.assign(p,!0)},f=>{o.if((0,le._)`!(${f} instanceof ${s.ValidationError})`,()=>o.throw(f)),h(f),i||o.assign(p,!1)}),e.ok(p)}function d(){e.result((0,jl.callValidateCode)(e,t,c),()=>T(t),()=>h(t))}function h(p){let f=(0,le._)`${p}.errors`;o.assign(Pt.default.vErrors,(0,le._)`${Pt.default.vErrors} === null ? ${f} : ${Pt.default.vErrors}.concat(${f})`),o.assign(Pt.default.errors,(0,le._)`${Pt.default.vErrors}.length`)}function T(p){var f;if(!s.opts.unevaluated)return;let m=(f=n?.validate)===null||f===void 0?void 0:f.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=ir.mergeEvaluated.props(o,m.props,s.props));else{let _=o.var("props",(0,le._)`${p}.evaluated.props`);s.props=ir.mergeEvaluated.props(o,_,s.props,le.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=ir.mergeEvaluated.items(o,m.items,s.items));else{let _=o.var("items",(0,le._)`${p}.evaluated.items`);s.items=ir.mergeEvaluated.items(o,_,s.items,le.Name)}}}lt.callRef=ar;lt.default=Th});var Dl=v(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});var vh=Nl(),bh=lr(),kh=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",vh.default,bh.default];os.default=kh});var Fl=v(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});var cr=S(),Ge=cr.operators,ur={maximum:{okStr:"<=",ok:Ge.LTE,fail:Ge.GT},minimum:{okStr:">=",ok:Ge.GTE,fail:Ge.LT},exclusiveMaximum:{okStr:"<",ok:Ge.LT,fail:Ge.GTE},exclusiveMinimum:{okStr:">",ok:Ge.GT,fail:Ge.LTE}},Ch={message:({keyword:e,schemaCode:t})=>(0,cr.str)`must be ${ur[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,cr._)`{comparison: ${ur[e].okStr}, limit: ${t}}`},Rh={keyword:Object.keys(ur),type:"number",schemaType:"number",$data:!0,error:Ch,code(e){let{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,cr._)`${n} ${ur[t].fail} ${r} || isNaN(${n})`)}};ss.default=Rh});var Ul=v(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});var pn=S(),Eh={message:({schemaCode:e})=>(0,pn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,pn._)`{multipleOf: ${e}}`},wh={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Eh,code(e){let{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),l=s?(0,pn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,pn._)`${i} !== parseInt(${i})`;e.fail$data((0,pn._)`(${r} === 0 || (${i} = ${n}/${r}, ${l}))`)}};is.default=wh});var zl=v(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});function Bl(e){let t=e.length,n=0,r=0,o;for(;r<t;)n++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<t&&(o=e.charCodeAt(r),(o&64512)===56320&&r++);return n}as.default=Bl;Bl.code='require("ajv/dist/runtime/ucs2length").default'});var Vl=v(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});var ct=S(),$h=M(),Sh=zl(),xh={message({keyword:e,schemaCode:t}){let n=e==="maxLength"?"more":"fewer";return(0,ct.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,ct._)`{limit: ${e}}`},Ph={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xh,code(e){let{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?ct.operators.GT:ct.operators.LT,i=o.opts.unicode===!1?(0,ct._)`${n}.length`:(0,ct._)`${(0,$h.useFunc)(e.gen,Sh.default)}(${n})`;e.fail$data((0,ct._)`${i} ${s} ${r}`)}};ls.default=Ph});var Kl=v(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var Ah=me(),Mh=M(),At=S(),Oh={message:({schemaCode:e})=>(0,At.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,At._)`{pattern: ${e}}`},Ih={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Oh,code(e){let{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e,l=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:a}=i.opts.code,c=a.code==="new RegExp"?(0,At._)`new RegExp`:(0,Mh.useFunc)(t,a),u=t.let("valid");t.try(()=>t.assign(u,(0,At._)`${c}(${s}, ${l}).test(${n})`),()=>t.assign(u,!1)),e.fail$data((0,At._)`!${u}`)}else{let a=(0,Ah.usePattern)(e,o);e.fail$data((0,At._)`!${a}.test(${n})`)}}};cs.default=Ih});var Gl=v(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});var mn=S(),Nh={message({keyword:e,schemaCode:t}){let n=e==="maxProperties"?"more":"fewer";return(0,mn.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,mn._)`{limit: ${e}}`},jh={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Nh,code(e){let{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?mn.operators.GT:mn.operators.LT;e.fail$data((0,mn._)`Object.keys(${n}).length ${o} ${r}`)}};us.default=jh});var Hl=v(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var hn=me(),gn=S(),Lh=M(),qh={message:({params:{missingProperty:e}})=>(0,gn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,gn._)`{missingProperty: ${e}}`},Dh={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qh,code(e){let{gen:t,schema:n,schemaCode:r,data:o,$data:s,it:i}=e,{opts:l}=i;if(!s&&n.length===0)return;let a=n.length>=l.loopRequired;if(i.allErrors?c():u(),l.strictRequired){let T=e.parentSchema.properties,{definedProperties:p}=e.it;for(let f of n)if(T?.[f]===void 0&&!p.has(f)){let m=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${f}" is not defined at "${m}" (strictRequired)`;(0,Lh.checkStrictMode)(i,_,i.opts.strictRequired)}}function c(){if(a||s)e.block$data(gn.nil,d);else for(let T of n)(0,hn.checkReportMissingProp)(e,T)}function u(){let T=t.let("missing");if(a||s){let p=t.let("valid",!0);e.block$data(p,()=>h(T,p)),e.ok(p)}else t.if((0,hn.checkMissingProp)(e,n,T)),(0,hn.reportMissingProp)(e,T),t.else()}function d(){t.forOf("prop",r,T=>{e.setParams({missingProperty:T}),t.if((0,hn.noPropertyInData)(t,o,T,l.ownProperties),()=>e.error())})}function h(T,p){e.setParams({missingProperty:T}),t.forOf(T,r,()=>{t.assign(p,(0,hn.propertyInData)(t,o,T,l.ownProperties)),t.if((0,gn.not)(p),()=>{e.error(),t.break()})},gn.nil)}}};ds.default=Dh});var Wl=v(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});var yn=S(),Fh={message({keyword:e,schemaCode:t}){let n=e==="maxItems"?"more":"fewer";return(0,yn.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,yn._)`{limit: ${e}}`},Uh={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Fh,code(e){let{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?yn.operators.GT:yn.operators.LT;e.fail$data((0,yn._)`${n}.length ${o} ${r}`)}};fs.default=Uh});var dr=v(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var Jl=jo();Jl.code='require("ajv/dist/runtime/equal").default';ps.default=Jl});var Yl=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var ms=tn(),X=S(),Bh=M(),zh=dr(),Vh={message:({params:{i:e,j:t}})=>(0,X.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,X._)`{i: ${e}, j: ${t}}`},Kh={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Vh,code(e){let{gen:t,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:l}=e;if(!r&&!o)return;let a=t.let("valid"),c=s.items?(0,ms.getSchemaTypes)(s.items):[];e.block$data(a,u,(0,X._)`${i} === false`),e.ok(a);function u(){let p=t.let("i",(0,X._)`${n}.length`),f=t.let("j");e.setParams({i:p,j:f}),t.assign(a,!0),t.if((0,X._)`${p} > 1`,()=>(d()?h:T)(p,f))}function d(){return c.length>0&&!c.some(p=>p==="object"||p==="array")}function h(p,f){let m=t.name("item"),_=(0,ms.checkDataTypes)(c,m,l.opts.strictNumbers,ms.DataType.Wrong),E=t.const("indices",(0,X._)`{}`);t.for((0,X._)`;${p}--;`,()=>{t.let(m,(0,X._)`${n}[${p}]`),t.if(_,(0,X._)`continue`),c.length>1&&t.if((0,X._)`typeof ${m} == "string"`,(0,X._)`${m} += "_"`),t.if((0,X._)`typeof ${E}[${m}] == "number"`,()=>{t.assign(f,(0,X._)`${E}[${m}]`),e.error(),t.assign(a,!1).break()}).code((0,X._)`${E}[${m}] = ${p}`)})}function T(p,f){let m=(0,Bh.useFunc)(t,zh.default),_=t.name("outer");t.label(_).for((0,X._)`;${p}--;`,()=>t.for((0,X._)`${f} = ${p}; ${f}--;`,()=>t.if((0,X._)`${m}(${n}[${p}], ${n}[${f}])`,()=>{e.error(),t.assign(a,!1).break(_)})))}}};hs.default=Kh});var Xl=v(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var gs=S(),Gh=M(),Hh=dr(),Wh={message:"must be equal to constant",params:({schemaCode:e})=>(0,gs._)`{allowedValue: ${e}}`},Jh={keyword:"const",$data:!0,error:Wh,code(e){let{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,gs._)`!${(0,Gh.useFunc)(t,Hh.default)}(${n}, ${o})`):e.fail((0,gs._)`${s} !== ${n}`)}};ys.default=Jh});var Ql=v(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var _n=S(),Yh=M(),Xh=dr(),Qh={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,_n._)`{allowedValues: ${e}}`},Zh={keyword:"enum",schemaType:"array",$data:!0,error:Qh,code(e){let{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let l=o.length>=i.opts.loopEnum,a,c=()=>a??(a=(0,Yh.useFunc)(t,Xh.default)),u;if(l||r)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let T=t.const("vSchema",s);u=(0,_n.or)(...o.map((p,f)=>h(T,f)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",s,T=>t.if((0,_n._)`${c()}(${n}, ${T})`,()=>t.assign(u,!0).break()))}function h(T,p){let f=o[p];return typeof f=="object"&&f!==null?(0,_n._)`${c()}(${n}, ${T}[${p}])`:(0,_n._)`${n} === ${f}`}}};_s.default=Zh});var Zl=v(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var eg=Fl(),tg=Ul(),ng=Vl(),rg=Kl(),og=Gl(),sg=Hl(),ig=Wl(),ag=Yl(),lg=Xl(),cg=Ql(),ug=[eg.default,tg.default,ng.default,rg.default,og.default,sg.default,ig.default,ag.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},lg.default,cg.default];Ts.default=ug});var bs=v(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.validateAdditionalItems=void 0;var ut=S(),vs=M(),dg={message:({params:{len:e}})=>(0,ut.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ut._)`{limit: ${e}}`},fg={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:dg,code(e){let{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,vs.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}ec(e,r)}};function ec(e,t){let{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;let l=n.const("len",(0,ut._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,ut._)`${l} <= ${t.length}`);else if(typeof r=="object"&&!(0,vs.alwaysValidSchema)(i,r)){let c=n.var("valid",(0,ut._)`${l} <= ${t.length}`);n.if((0,ut.not)(c),()=>a(c)),e.ok(c)}function a(c){n.forRange("i",t.length,l,u=>{e.subschema({keyword:s,dataProp:u,dataPropType:vs.Type.Num},c),i.allErrors||n.if((0,ut.not)(c),()=>n.break())})}}Tn.validateAdditionalItems=ec;Tn.default=fg});var ks=v(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.validateTuple=void 0;var tc=S(),fr=M(),pg=me(),mg={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:n}=e;if(Array.isArray(t))return nc(e,"additionalItems",t);n.items=!0,!(0,fr.alwaysValidSchema)(n,t)&&e.ok((0,pg.validateArray)(e))}};function nc(e,t,n=e.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:l}=e;u(o),l.opts.unevaluated&&n.length&&l.items!==!0&&(l.items=fr.mergeEvaluated.items(r,n.length,l.items));let a=r.name("valid"),c=r.const("len",(0,tc._)`${s}.length`);n.forEach((d,h)=>{(0,fr.alwaysValidSchema)(l,d)||(r.if((0,tc._)`${c} > ${h}`,()=>e.subschema({keyword:i,schemaProp:h,dataProp:h},a)),e.ok(a))});function u(d){let{opts:h,errSchemaPath:T}=l,p=n.length,f=p===d.minItems&&(p===d.maxItems||d[t]===!1);if(h.strictTuples&&!f){let m=`"${i}" is ${p}-tuple, but minItems or maxItems/${t} are not specified or different at path "${T}"`;(0,fr.checkStrictMode)(l,m,h.strictTuples)}}}vn.validateTuple=nc;vn.default=mg});var rc=v(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var hg=ks(),gg={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,hg.validateTuple)(e,"items")};Cs.default=gg});var sc=v(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var oc=S(),yg=M(),_g=me(),Tg=bs(),vg={message:({params:{len:e}})=>(0,oc.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,oc._)`{limit: ${e}}`},bg={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:vg,code(e){let{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,yg.alwaysValidSchema)(r,t)&&(o?(0,Tg.validateAdditionalItems)(e,o):e.ok((0,_g.validateArray)(e)))}};Rs.default=bg});var ic=v(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var ge=S(),pr=M(),kg={message:({params:{min:e,max:t}})=>t===void 0?(0,ge.str)`must contain at least ${e} valid item(s)`:(0,ge.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,ge._)`{minContains: ${e}}`:(0,ge._)`{minContains: ${e}, maxContains: ${t}}`},Cg={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:kg,code(e){let{gen:t,schema:n,parentSchema:r,data:o,it:s}=e,i,l,{minContains:a,maxContains:c}=r;s.opts.next?(i=a===void 0?1:a,l=c):i=1;let u=t.const("len",(0,ge._)`${o}.length`);if(e.setParams({min:i,max:l}),l===void 0&&i===0){(0,pr.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(l!==void 0&&i>l){(0,pr.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,pr.alwaysValidSchema)(s,n)){let f=(0,ge._)`${u} >= ${i}`;l!==void 0&&(f=(0,ge._)`${f} && ${u} <= ${l}`),e.pass(f);return}s.items=!0;let d=t.name("valid");l===void 0&&i===1?T(d,()=>t.if(d,()=>t.break())):i===0?(t.let(d,!0),l!==void 0&&t.if((0,ge._)`${o}.length > 0`,h)):(t.let(d,!1),h()),e.result(d,()=>e.reset());function h(){let f=t.name("_valid"),m=t.let("count",0);T(f,()=>t.if(f,()=>p(m)))}function T(f,m){t.forRange("i",0,u,_=>{e.subschema({keyword:"contains",dataProp:_,dataPropType:pr.Type.Num,compositeRule:!0},f),m()})}function p(f){t.code((0,ge._)`${f}++`),l===void 0?t.if((0,ge._)`${f} >= ${i}`,()=>t.assign(d,!0).break()):(t.if((0,ge._)`${f} > ${l}`,()=>t.assign(d,!1).break()),i===1?t.assign(d,!0):t.if((0,ge._)`${f} >= ${i}`,()=>t.assign(d,!0)))}}};Es.default=Cg});var mr=v(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.validateSchemaDeps=Oe.validatePropertyDeps=Oe.error=void 0;var ws=S(),Rg=M(),bn=me();Oe.error={message:({params:{property:e,depsCount:t,deps:n}})=>{let r=t===1?"property":"properties";return(0,ws.str)`must have ${r} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:n,missingProperty:r}})=>(0,ws._)`{property: ${e},
6
+ missingProperty: ${r},
7
7
  depsCount: ${t},
8
- deps: ${n}}`};var JT={keyword:"dependencies",type:"object",schemaType:"object",error:ct.error,code(e){let[t,n]=XT(e);Kf(e,t),Jf(e,n)}};function XT({schema:e}){let t={},n={};for(let o in e){if(o==="__proto__")continue;let r=Array.isArray(e[o])?t:n;r[o]=e[o]}return[t,n]}function Kf(e,t=e.schema){let{gen:n,data:o,it:r}=e;if(Object.keys(t).length===0)return;let s=n.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let c=(0,$o.propertyInData)(n,o,i,r.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),r.allErrors?n.if(c,()=>{for(let l of a)(0,$o.checkReportMissingProp)(e,l)}):(n.if((0,Ha._)`${c} && (${(0,$o.checkMissingProp)(e,a,s)})`),(0,$o.reportMissingProp)(e,s),n.else())}}ct.validatePropertyDeps=Kf;function Jf(e,t=e.schema){let{gen:n,data:o,keyword:r,it:s}=e,i=n.name("valid");for(let a in t)(0,KT.alwaysValidSchema)(s,t[a])||(n.if((0,$o.propertyInData)(n,o,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:r,schemaProp:a},i);e.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),e.ok(i))}ct.validateSchemaDeps=Jf;ct.default=JT});var Yf=R(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var Xf=F(),YT=U(),ZT={message:"property name must be valid",params:({params:e})=>(0,Xf._)`{propertyName: ${e.propertyName}}`},QT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ZT,code(e){let{gen:t,schema:n,data:o,it:r}=e;if((0,YT.alwaysValidSchema)(r,n))return;let s=t.name("valid");t.forIn("key",o,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,Xf.not)(s),()=>{e.error(!0),r.allErrors||t.break()})}),e.ok(s)}};Va.default=QT});var Wa=R(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Br=He(),tt=F(),ek=ze(),qr=U(),tk={message:"must NOT have additional properties",params:({params:e})=>(0,tt._)`{additionalProperty: ${e.additionalProperty}}`},nk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:tk,code(e){let{gen:t,schema:n,parentSchema:o,data:r,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,qr.alwaysValidSchema)(i,n))return;let l=(0,Br.allSchemaProperties)(o.properties),d=(0,Br.allSchemaProperties)(o.patternProperties);m(),e.ok((0,tt._)`${s} === ${ek.default.errors}`);function m(){t.forIn("key",r,k=>{!l.length&&!d.length?h(k):t.if(y(k),()=>h(k))})}function y(k){let C;if(l.length>8){let E=(0,qr.schemaRefOrVal)(i,o.properties,"properties");C=(0,Br.isOwnProperty)(t,E,k)}else l.length?C=(0,tt.or)(...l.map(E=>(0,tt._)`${k} === ${E}`)):C=tt.nil;return d.length&&(C=(0,tt.or)(C,...d.map(E=>(0,tt._)`${(0,Br.usePattern)(e,E)}.test(${k})`))),(0,tt.not)(C)}function _(k){t.code((0,tt._)`delete ${r}[${k}]`)}function h(k){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){_(k);return}if(n===!1){e.setParams({additionalProperty:k}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,qr.alwaysValidSchema)(i,n)){let C=t.name("valid");c.removeAdditional==="failing"?(v(k,C,!1),t.if((0,tt.not)(C),()=>{e.reset(),_(k)})):(v(k,C),a||t.if((0,tt.not)(C),()=>t.break()))}}function v(k,C,E){let O={keyword:"additionalProperties",dataProp:k,dataPropType:qr.Type.Str};E===!1&&Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(O,C)}}};Ga.default=nk});var ep=R(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var ok=go(),Zf=He(),Ka=U(),Qf=Wa(),rk={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,parentSchema:o,data:r,it:s}=e;s.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&Qf.default.code(new ok.KeywordCxt(s,Qf.default,"additionalProperties"));let i=(0,Zf.allSchemaProperties)(n);for(let m of i)s.definedProperties.add(m);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Ka.mergeEvaluated.props(t,(0,Ka.toHash)(i),s.props));let a=i.filter(m=>!(0,Ka.alwaysValidSchema)(s,n[m]));if(a.length===0)return;let c=t.name("valid");for(let m of a)l(m)?d(m):(t.if((0,Zf.propertyInData)(t,r,m,s.opts.ownProperties)),d(m),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(m),e.ok(c);function l(m){return s.opts.useDefaults&&!s.compositeRule&&n[m].default!==void 0}function d(m){e.subschema({keyword:"properties",schemaProp:m,dataProp:m},c)}}};Ja.default=rk});var rp=R(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var tp=He(),Ur=F(),np=U(),op=U(),sk={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,data:o,parentSchema:r,it:s}=e,{opts:i}=s,a=(0,tp.allSchemaProperties)(n),c=a.filter(v=>(0,np.alwaysValidSchema)(s,n[v]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&r.properties,d=t.name("valid");s.props!==!0&&!(s.props instanceof Ur.Name)&&(s.props=(0,op.evaluatedPropsToName)(t,s.props));let{props:m}=s;y();function y(){for(let v of a)l&&_(v),s.allErrors?h(v):(t.var(d,!0),h(v),t.if(d))}function _(v){for(let k in l)new RegExp(v).test(k)&&(0,np.checkStrictMode)(s,`property ${k} matches pattern ${v} (use allowMatchingProperties)`)}function h(v){t.forIn("key",o,k=>{t.if((0,Ur._)`${(0,tp.usePattern)(e,v)}.test(${k})`,()=>{let C=c.includes(v);C||e.subschema({keyword:"patternProperties",schemaProp:v,dataProp:k,dataPropType:op.Type.Str},d),s.opts.unevaluated&&m!==!0?t.assign((0,Ur._)`${m}[${k}]`,!0):!C&&!s.allErrors&&t.if((0,Ur.not)(d),()=>t.break())})})}}};Xa.default=sk});var sp=R(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var ik=U(),ak={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:n,it:o}=e;if((0,ik.alwaysValidSchema)(o,n)){e.fail();return}let r=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},r),e.failResult(r,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ya.default=ak});var ip=R(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});var ck=He(),lk={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ck.validateUnion,error:{message:"must match a schema in anyOf"}};Za.default=lk});var ap=R(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var zr=F(),uk=U(),dk={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,zr._)`{passingSchemas: ${e.passing}}`},fk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:dk,code(e){let{gen:t,schema:n,parentSchema:o,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(r.opts.discriminator&&o.discriminator)return;let s=n,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(i,()=>e.reset(),()=>e.error(!0));function l(){s.forEach((d,m)=>{let y;(0,uk.alwaysValidSchema)(r,d)?t.var(c,!0):y=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},c),m>0&&t.if((0,zr._)`${c} && ${i}`).assign(i,!1).assign(a,(0,zr._)`[${a}, ${m}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,m),y&&e.mergeEvaluated(y,zr.Name)})})}}};Qa.default=fk});var cp=R(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var pk=U(),mk={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:n,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");let r=t.name("valid");n.forEach((s,i)=>{if((0,pk.alwaysValidSchema)(o,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},r);e.ok(r),e.mergeEvaluated(a)})}};ec.default=mk});var dp=R(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Hr=F(),up=U(),gk={message:({params:e})=>(0,Hr.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Hr._)`{failingKeyword: ${e.ifClause}}`},hk={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:gk,code(e){let{gen:t,parentSchema:n,it:o}=e;n.then===void 0&&n.else===void 0&&(0,up.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let r=lp(o,"then"),s=lp(o,"else");if(!r&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),r&&s){let d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,l("then",d),l("else",d))}else r?t.if(a,l("then")):t.if((0,Hr.not)(a),l("else"));e.pass(i,()=>e.error(!0));function c(){let d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function l(d,m){return()=>{let y=e.subschema({keyword:d},a);t.assign(i,a),e.mergeValidEvaluated(y,i),m?t.assign(m,(0,Hr._)`${d}`):e.setParams({ifClause:d})}}}};function lp(e,t){let n=e.schema[t];return n!==void 0&&!(0,up.alwaysValidSchema)(e,n)}tc.default=hk});var fp=R(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var yk=U(),bk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,yk.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};nc.default=bk});var pp=R(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var _k=Da(),vk=Hf(),Tk=Ba(),kk=Gf(),Ck=Wf(),Rk=Dr(),wk=Yf(),xk=Wa(),Sk=ep(),Ek=rp(),Ak=sp(),$k=ip(),Pk=ap(),Mk=cp(),Ik=dp(),Ok=fp();function Nk(e=!1){let t=[Ak.default,$k.default,Pk.default,Mk.default,Ik.default,Ok.default,wk.default,xk.default,Rk.default,Sk.default,Ek.default];return e?t.push(vk.default,kk.default):t.push(_k.default,Tk.default),t.push(Ck.default),t}oc.default=Nk});var sc=R(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.dynamicAnchor=void 0;var rc=F(),Fk=ze(),mp=yo(),Lk=Ir(),jk={keyword:"$dynamicAnchor",schemaType:"string",code:e=>gp(e,e.schema)};function gp(e,t){let{gen:n,it:o}=e;o.schemaEnv.root.dynamicAnchors[t]=!0;let r=(0,rc._)`${Fk.default.dynamicAnchors}${(0,rc.getProperty)(t)}`,s=o.errSchemaPath==="#"?o.validateName:Dk(e);n.if((0,rc._)`!${r}`,()=>n.assign(r,s))}Po.dynamicAnchor=gp;function Dk(e){let{schemaEnv:t,schema:n,self:o}=e.it,{root:r,baseId:s,localRefs:i,meta:a}=t.root,{schemaId:c}=o.opts,l=new mp.SchemaEnv({schema:n,schemaId:c,root:r,baseId:s,localRefs:i,meta:a});return mp.compileSchema.call(o,l),(0,Lk.getValidate)(e,l)}Po.default=jk});var ic=R(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.dynamicRef=void 0;var hp=F(),Bk=ze(),yp=Ir(),qk={keyword:"$dynamicRef",schemaType:"string",code:e=>bp(e,e.schema)};function bp(e,t){let{gen:n,keyword:o,it:r}=e;if(t[0]!=="#")throw new Error(`"${o}" only supports hash fragment reference`);let s=t.slice(1);if(r.allErrors)i();else{let c=n.let("valid",!1);i(c),e.ok(c)}function i(c){if(r.schemaEnv.root.dynamicAnchors[s]){let l=n.let("_v",(0,hp._)`${Bk.default.dynamicAnchors}${(0,hp.getProperty)(s)}`);n.if(l,a(l,c),a(r.validateName,c))}else a(r.validateName,c)()}function a(c,l){return l?()=>n.block(()=>{(0,yp.callRef)(e,c),n.let(l,!0)}):()=>(0,yp.callRef)(e,c)}}Mo.dynamicRef=bp;Mo.default=qk});var _p=R(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var Uk=sc(),zk=U(),Hk={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,Uk.dynamicAnchor)(e,""):(0,zk.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};ac.default=Hk});var vp=R(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var Vk=ic(),Gk={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,Vk.dynamicRef)(e,e.schema)};cc.default=Gk});var Tp=R(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var Wk=sc(),Kk=ic(),Jk=_p(),Xk=vp(),Yk=[Wk.default,Kk.default,Jk.default,Xk.default];lc.default=Yk});var Cp=R(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var kp=Dr(),Zk={keyword:"dependentRequired",type:"object",schemaType:"object",error:kp.error,code:e=>(0,kp.validatePropertyDeps)(e)};uc.default=Zk});var Rp=R(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var Qk=Dr(),eC={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,Qk.validateSchemaDeps)(e)};dc.default=eC});var wp=R(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var tC=U(),nC={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){t.contains===void 0&&(0,tC.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};fc.default=nC});var xp=R(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var oC=Cp(),rC=Rp(),sC=wp(),iC=[oC.default,rC.default,sC.default];pc.default=iC});var Ep=R(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var $t=F(),Sp=U(),aC=ze(),cC={message:"must NOT have unevaluated properties",params:({params:e})=>(0,$t._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},lC={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:cC,code(e){let{gen:t,schema:n,data:o,errsCount:r,it:s}=e;if(!r)throw new Error("ajv implementation error");let{allErrors:i,props:a}=s;a instanceof $t.Name?t.if((0,$t._)`${a} !== true`,()=>t.forIn("key",o,m=>t.if(l(a,m),()=>c(m)))):a!==!0&&t.forIn("key",o,m=>a===void 0?c(m):t.if(d(a,m),()=>c(m))),s.props=!0,e.ok((0,$t._)`${r} === ${aC.default.errors}`);function c(m){if(n===!1){e.setParams({unevaluatedProperty:m}),e.error(),i||t.break();return}if(!(0,Sp.alwaysValidSchema)(s,n)){let y=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:m,dataPropType:Sp.Type.Str},y),i||t.if((0,$t.not)(y),()=>t.break())}}function l(m,y){return(0,$t._)`!${m} || !${m}[${y}]`}function d(m,y){let _=[];for(let h in m)m[h]===!0&&_.push((0,$t._)`${y} !== ${h}`);return(0,$t.and)(..._)}}};mc.default=lC});var $p=R(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var Zt=F(),Ap=U(),uC={message:({params:{len:e}})=>(0,Zt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Zt._)`{limit: ${e}}`},dC={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:uC,code(e){let{gen:t,schema:n,data:o,it:r}=e,s=r.items||0;if(s===!0)return;let i=t.const("len",(0,Zt._)`${o}.length`);if(n===!1)e.setParams({len:s}),e.fail((0,Zt._)`${i} > ${s}`);else if(typeof n=="object"&&!(0,Ap.alwaysValidSchema)(r,n)){let c=t.var("valid",(0,Zt._)`${i} <= ${s}`);t.if((0,Zt.not)(c),()=>a(c,s)),e.ok(c)}r.items=!0;function a(c,l){t.forRange("i",l,i,d=>{e.subschema({keyword:"unevaluatedItems",dataProp:d,dataPropType:Ap.Type.Num},c),r.allErrors||t.if((0,Zt.not)(c),()=>t.break())})}}};gc.default=dC});var Pp=R(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var fC=Ep(),pC=$p(),mC=[fC.default,pC.default];hc.default=mC});var Mp=R(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var se=F(),gC={message:({schemaCode:e})=>(0,se.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,se._)`{format: ${e}}`},hC={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:gC,code(e,t){let{gen:n,data:o,$data:r,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:d,self:m}=a;if(!c.validateFormats)return;r?y():_();function y(){let h=n.scopeValue("formats",{ref:m.formats,code:c.code.formats}),v=n.const("fDef",(0,se._)`${h}[${i}]`),k=n.let("fType"),C=n.let("format");n.if((0,se._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>n.assign(k,(0,se._)`${v}.type || "string"`).assign(C,(0,se._)`${v}.validate`),()=>n.assign(k,(0,se._)`"string"`).assign(C,v)),e.fail$data((0,se.or)(E(),O()));function E(){return c.strictSchema===!1?se.nil:(0,se._)`${i} && !${C}`}function O(){let z=d.$async?(0,se._)`(${v}.async ? await ${C}(${o}) : ${C}(${o}))`:(0,se._)`${C}(${o})`,M=(0,se._)`(typeof ${C} == "function" ? ${z} : ${C}.test(${o}))`;return(0,se._)`${C} && ${C} !== true && ${k} === ${t} && !${M}`}}function _(){let h=m.formats[s];if(!h){E();return}if(h===!0)return;let[v,k,C]=O(h);v===t&&e.pass(z());function E(){if(c.strictSchema===!1){m.logger.warn(M());return}throw new Error(M());function M(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function O(M){let ee=M instanceof RegExp?(0,se.regexpCode)(M):c.code.formats?(0,se._)`${c.code.formats}${(0,se.getProperty)(s)}`:void 0,Ne=n.scopeValue("formats",{key:s,ref:M,code:ee});return typeof M=="object"&&!(M instanceof RegExp)?[M.type||"string",M.validate,(0,se._)`${Ne}.validate`]:["string",M,Ne]}function z(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,se._)`await ${C}(${o})`}return typeof k=="function"?(0,se._)`${C}(${o})`:(0,se._)`${C}.test(${o})`}}}};yc.default=hC});var Ip=R(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var yC=Mp(),bC=[yC.default];bc.default=bC});var Op=R(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.contentVocabulary=Pn.metadataVocabulary=void 0;Pn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Pn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Fp=R(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var _C=xf(),vC=Bf(),TC=pp(),kC=Tp(),CC=xp(),RC=Pp(),wC=Ip(),Np=Op(),xC=[kC.default,_C.default,vC.default,(0,TC.default)(!0),wC.default,Np.metadataVocabulary,Np.contentVocabulary,CC.default,RC.default];_c.default=xC});var jp=R(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.DiscrError=void 0;var Lp;(function(e){e.Tag="tag",e.Mapping="mapping"})(Lp||(Vr.DiscrError=Lp={}))});var Bp=R(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Mn=F(),vc=jp(),Dp=yo(),SC=ho(),EC=U(),AC={message:({params:{discrError:e,tagName:t}})=>e===vc.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Mn._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},$C={keyword:"discriminator",type:"object",schemaType:"object",error:AC,code(e){let{gen:t,data:n,schema:o,parentSchema:r,it:s}=e,{oneOf:i}=r;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=o.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,Mn._)`${n}${(0,Mn.getProperty)(a)}`);t.if((0,Mn._)`typeof ${l} == "string"`,()=>d(),()=>e.error(!1,{discrError:vc.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function d(){let _=y();t.if(!1);for(let h in _)t.elseIf((0,Mn._)`${l} === ${h}`),t.assign(c,m(_[h]));t.else(),e.error(!1,{discrError:vc.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function m(_){let h=t.name("valid"),v=e.subschema({keyword:"oneOf",schemaProp:_},h);return e.mergeEvaluated(v,Mn.Name),h}function y(){var _;let h={},v=C(r),k=!0;for(let z=0;z<i.length;z++){let M=i[z];if(M?.$ref&&!(0,EC.schemaHasRulesButRef)(M,s.self.RULES)){let Ne=M.$ref;if(M=Dp.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ne),M instanceof Dp.SchemaEnv&&(M=M.schema),M===void 0)throw new SC.default(s.opts.uriResolver,s.baseId,Ne)}let ee=(_=M?.properties)===null||_===void 0?void 0:_[a];if(typeof ee!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);k=k&&(v||C(M)),E(ee,z)}if(!k)throw new Error(`discriminator: "${a}" must be required`);return h;function C({required:z}){return Array.isArray(z)&&z.includes(a)}function E(z,M){if(z.const)O(z.const,M);else if(z.enum)for(let ee of z.enum)O(ee,M);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function O(z,M){if(typeof z!="string"||z in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[z]=M}}}};Tc.default=$C});var qp=R((NA,PC)=>{PC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var Up=R((FA,MC)=>{MC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var zp=R((LA,IC)=>{IC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var Hp=R((jA,OC)=>{OC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var Vp=R((DA,NC)=>{NC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var Gp=R((BA,FC)=>{FC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var Wp=R((qA,LC)=>{LC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var Kp=R((UA,jC)=>{jC.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var Jp=R(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var DC=qp(),BC=Up(),qC=zp(),UC=Hp(),zC=Vp(),HC=Gp(),VC=Wp(),GC=Kp(),WC=["/properties"];function KC(e){return[DC,BC,qC,UC,zC,t(this,HC),VC,t(this,GC)].forEach(n=>this.addMetaSchema(n,void 0,!1)),this;function t(n,o){return e?n.$dataMetaSchema(o,WC):o}}kc.default=KC});var Xp=R((ne,Rc)=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.MissingRefError=ne.ValidationError=ne.CodeGen=ne.Name=ne.nil=ne.stringify=ne.str=ne._=ne.KeywordCxt=ne.Ajv2020=void 0;var JC=Tf(),XC=Fp(),YC=Bp(),ZC=Jp(),Cc="https://json-schema.org/draft/2020-12/schema",In=class extends JC.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),XC.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(YC.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:n}=this.opts;n&&(ZC.default.call(this,t),this.refs["http://json-schema.org/schema"]=Cc)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Cc)?Cc:void 0)}};ne.Ajv2020=In;Rc.exports=ne=In;Rc.exports.Ajv2020=In;Object.defineProperty(ne,"__esModule",{value:!0});ne.default=In;var QC=go();Object.defineProperty(ne,"KeywordCxt",{enumerable:!0,get:function(){return QC.KeywordCxt}});var On=F();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return On._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return On.str}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return On.stringify}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return On.nil}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return On.Name}});Object.defineProperty(ne,"CodeGen",{enumerable:!0,get:function(){return On.CodeGen}});var eR=wr();Object.defineProperty(ne,"ValidationError",{enumerable:!0,get:function(){return eR.default}});var tR=ho();Object.defineProperty(ne,"MissingRefError",{enumerable:!0,get:function(){return tR.default}})});function Qs(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function be(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var ch=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,jt={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},lh=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,uh=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,dh=512,fh=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var ph=new Set([500,502,503,504,521,522,523,524,529]),mh=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],gh=["upgrade your plan","upgrade plan","current plan","subscription"],hh=["daily","weekly","monthly"],yh=["try again","retry","temporary","cooldown"],bh=["usage limit","rate limit","organization usage"],_h=["organization","workspace"],vh=["billing period","exceeded","reached","exhausted"],Th=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,kh=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function Dt(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Ch(e){return Dt(e,jt.format)}function pu(e){return Dt(e,jt.rateLimit)}function Rh(e){return Dt(e,jt.timeout)}function wh(e){return ch.test(e)}function ei(e){let t=e.toLowerCase();return t?e.length>dh?uh.test(t):Dt(t,jt.billing)?!0:lh.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function mu(e){return Dt(e,jt.authPermanent)}function xh(e){return Dt(e,jt.auth)}function gu(e){return Dt(e,jt.overloaded)}function Lt(e,t){return t.some(n=>e.includes(n))}function Sh(e){return Lt(e,mh)||Lt(e,gh)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Eh(e){let t=Lt(e,hh),n=e.includes("spend limit")||e.includes("spending limit"),o=Lt(e,_h);return Lt(e,yh)&&Lt(e,bh)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||Lt(e,vh))}function Ah(e){return e.trim().toLowerCase().replace(kh,"").trim()}function hu(e){let t=Ah(e);return!t||Sh(t)?"billing":pu(t)||Eh(t)?"rate_limit":"billing"}function $h(e){return Th.test(e)?hu(e):null}function yu(e){let t=e.match(fh);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Ph(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Mh(e){let t=e.trim();if(!t)return!1;let n=yu(t);return n?ph.has(n.code):!1}function bu(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?hu(t):"billing":e===429?"rate_limit":e===401||e===403?t&&mu(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&gu(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&ei(t)?"billing":"format":null}function Ih(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Oh(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function _u(e){if(Oh(e))return"session_expired";if(Ih(e))return"model_not_found";let t=$h(e);return t||(wh(e)?ei(e)?"billing":"rate_limit":pu(e)?"rate_limit":gu(e)?"overloaded":Mh(e)?yu(e.trim())?.code===529?"overloaded":"timeout":Ph(e)?"timeout":Ch(e)?"format":ei(e)?"billing":Rh(e)?"timeout":mu(e)?"auth_permanent":xh(e)?"auth":null)}var Nh=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function sr(e){return Nh.has(e)}var Fh={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function yn(e,t){let n=bu(e,t)??(t?_u(t):null);return n?Fh[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function vu(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Lh=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]);function jh(e){let t=e;for(let n=0;n<3;n+=1){if(!t||typeof t!="object"||Array.isArray(t))return;let o=t,r=o.outcome??o.status;if(r==="committed"||r==="not-applied"||r==="indeterminate")return r;t=o.structuredContent}}var Xn=class{constructor(t=20,n=vu){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let c of t){let l=c.tool_calls;if(Array.isArray(l))for(let d of l)d?.id&&d.function?.name&&o.set(d.id,d.function.name)}let r=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((c,l)=>{if(l>=r||c.role!=="tool"||typeof c.content!="string")return c;let d=c.name??o.get(c.tool_call_id??""),m=jh(c.structuredContent);if(!m&&(!d||!Lh.has(d)))return c;let y=c.structuredContent?JSON.stringify(c.structuredContent).length:0;if(c.content.length<=200&&y<=200)return c;let _=this.estimateTokens(c);return i+=_,s++,{...c,content:`[result cleared \u2014 ${c.content.length+y} chars]`,...m?{structuredContent:{status:m,outcome:m}}:{}}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function ti(e,t,n=vu){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let c=a.tool_call_id??"";if(c&&t.has(c)){o+=n(a),r++,t.delete(c);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function ni(){return{stages:[]}}function oi(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=Tu(e,t),i=Dh(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=Tu(e,t),{messages:s,stagedCount:i.length}}function ri(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ku(e,t),committed:n}}function Tu(e,t){return t.stages.filter(o=>o.committed).length===0?e:ku(e,t)}function ku(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),c={role:"system",content:r.summary};o.splice(s,a-s,c)}return o}function Dh(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<o;c++){let l=e[c];if(l.role==="tool"||l.role==="assistant"&&typeof l.content=="string"&&l.content==="")i<0&&(i=c),a++;else{if(a>=3){let m=`${i}-${i+a}`;s.has(m)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let c=`${i}-${i+a}`;s.has(c)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}function Bh(e){return[...new Set(e.map(ir).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Cu(e){let t=Bh(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function qh(e){let t=[...new Set(e.map(ir).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Cu(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function ir(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Uh(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function zh(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Hh(e){if(!e.eligibility?.length)return[...e.tools];let t=zh(e.eligibility);return e.tools.filter(n=>{let o=ir(n);if(!o)return!1;let r=t.get(o);return!r||Uh(r.status)})}function Vh(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function si(e){let t=Vh({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Hh({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Cu(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:qh(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(c=>ir(c)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Gh=["stop","aborted","timeout","cancelled","interrupted","error"],Wh=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Ru(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Kh(e,t){return{...e,content:[...Ru(e.content),...Ru(t.content)]}}function Jh(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Xh(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=Jh(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Yh(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Zh(e){return new Set((e??Gh).map(t=>t.trim().toLowerCase()))}function Qh(e,t){return e?Zh(t).has(e.trim().toLowerCase()):!1}function ii(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(c=>{if(c.role==="assistant"&&Array.isArray(c.tool_calls)){let l=c.tool_calls.filter(d=>Yh(d));return{...c,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...c}}),n=new Set;for(let c of t)if(!(c.role!=="assistant"||!Array.isArray(c.tool_calls)))for(let l of c.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(c=>c.role!=="tool"?!0:!!(c.tool_call_id&&n.has(c.tool_call_id))),r=new Set;for(let c of o)c.role==="tool"&&typeof c.tool_call_id=="string"&&c.tool_call_id&&r.add(c.tool_call_id);let s=[];for(let c of o){if(c.role==="assistant"&&Array.isArray(c.tool_calls)&&c.tool_calls.length>0){let l=c.tool_calls.filter(d=>typeof d.id=="string"&&r.has(d.id));if(l.length===0){let{tool_calls:d,...m}=c;m.content!=null&&m.content!==""&&s.push(m);continue}if(l.length<c.tool_calls.length){s.push({...c,tool_calls:l});continue}}s.push(c)}let i=Xh(s),a=[];for(let c of i){let l=a.length>0?a[a.length-1]:void 0;if(c.role==="user"&&l?.role==="user"){a[a.length-1]=Kh(l,c);continue}a.push(c)}return a}function ai(e,t){return Qh(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Wh)delete o[r];return o}):[...e]}function ci(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function li(e,t){let n=ii(e),o=ai(n,t);return ci(o,t)}function ey(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function ty(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function ny(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function ui(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function ar(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function cr(e){let t=[],n=ii(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=ai(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=ci(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:ny({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:ey(r),completedToolCallIds:ty(r)}),recoveryActions:t}}var oy=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function di(e){return e?oy.has(e):!0}function fi(e){return e===429||e===529}function lr(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var $x={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function ur(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Yn=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var wu=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),xu=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Su=3,bn=2,dr=2,Eu=128e3,Au=13e3,$u=16384,Pu=65536,Mu=3;var pi=500,Iu=3;var Ou=3e4,Nu=3,Bt=2;var Mx=50*1024,Ix=500*1024,Ox=500*1024*1024,Nx=50*1024*1024;function mi(e){let t=Number.isFinite(e.totalPromptTokens)&&(e.totalPromptTokens??0)>0?Math.floor(e.totalPromptTokens):0,n=Number.isFinite(e.promptTokens)&&e.promptTokens>0?Math.floor(e.promptTokens):0,o=Number.isFinite(e.cacheReadTokens)&&(e.cacheReadTokens??0)>0?Math.floor(e.cacheReadTokens):0,r=Number.isFinite(e.cacheCreationTokens)&&(e.cacheCreationTokens??0)>0?Math.floor(e.cacheCreationTokens):0,s=o+r,i=s>n?n+s:n;return Math.max(t,i)}function gi(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function hi(e,t){let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return o>=85?{level:"warning",usagePercent:o,remainingTokens:Math.max(0,n-e.promptTokens)}:{level:"ok"}}function yi(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function bi(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function _i(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function vi(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Zn(e){return!e.attemptedThisTurn}import{createHash as ls}from"node:crypto";import{existsSync as sn,readFileSync as ms,statSync as Yw}from"node:fs";function Ti(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}var sy=new Set(["agent","ask_user","edit","exec","patch","read","search","task","tool_schema_load","write"]);function Fu(e,t){return t?.owner==="agent"&&t.family==="builtin"?!0:sy.has(e)}function Ae(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?e:e.slice(t+2)}function Lu(e){let t=e.indexOf("__");if(!(t<=0||t+2>=e.length))return e.slice(0,t)}function ki(e,t){return Ae(e)===t}var Ci="tool_schema_load";function ju(e){return e?.type!=="tool_schema_load"||!Array.isArray(e.requestedToolNames)?[]:[...new Set(e.requestedToolNames.filter(t=>typeof t=="string"&&t.trim().length>0))]}function ue(e,t,n,o){e?.invoke(t,n).catch(r=>{let s=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${s}`)})}var iy=new Set(["skill_search","skill_load","skill_resource_read","project_instructions","capability_inventory","prompt_read","tool_schema_load"]);function fr(e){return e.identity.family!=="skill"&&!iy.has(e.identity.logicalName)}function Du(e){return e.some(t=>t.status==="succeeded"&&fr(t))}function Bu(e){if(e.blocked)return"policy_blocked";let t=typeof e.details?.error=="string"?e.details.error:"",n=`${t} ${e.error??""}`;return t==="semantic_quality_failed"?"semantic_quality_failed":/MCP_START_FAILED/iu.test(n)?"mcp_start_failed":/mcp_not_connected|mcp_unavailable/iu.test(n)?"mcp_unavailable":/\bTIMEOUT\b|timed out/iu.test(n)?"timeout":"tool_execution_failed"}function Qn(e,t,n=[]){let o=t.filter(c=>c.status==="succeeded").map(c=>c.callId),r=new Set(n),s=e?t.filter(c=>c.status==="succeeded"&&fr(c)&&(r.size===0||r.has(c.identity.logicalName))).map(c=>c.callId):o,i=t.filter(c=>c.status==="failed"||c.status==="running").map(c=>c.callId),a=t.filter(c=>c.status==="blocked").map(c=>c.callId);return e?s.length>0?{schemaVersion:1,requirement:"fresh-tool-evidence",disposition:"grounded",successfulCallIds:s,failedCallIds:i,blockedCallIds:a,reason:r.size>0?"at least one Skill-required execution call succeeded":"at least one required evidence call succeeded"}:{schemaVersion:1,requirement:"fresh-tool-evidence",disposition:t.length===0?"blocked-no-tool-evidence":"blocked-no-successful-evidence",successfulCallIds:s,failedCallIds:i,blockedCallIds:a,reason:t.length===0?"fresh evidence was required but no tool call completed":r.size>0&&o.length>0?`fresh evidence required a successful Skill execution call from: ${[...r].join(", ")}`:o.length>0?"fresh evidence was required but successful calls were instruction or capability discovery only":"fresh evidence was required but every tool call failed or was blocked"}:{schemaVersion:1,requirement:"not-required",disposition:"not-required",successfulCallIds:s,failedCallIds:i,blockedCallIds:a,reason:"the turn did not require fresh tool evidence"}}function qu(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function Uu(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=[],r=Array.isArray(n.inlineImageUrls)?n.inlineImageUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[];for(let s of r)o.push(ay(e,"image",s,n));return o}function ay(e,t,n,o){return{type:"media_result",turnId:e,mediaType:t,url:n,model:typeof o.model=="string"?o.model:void 0,provider:typeof o.provider=="string"?o.provider:void 0,durationSeconds:typeof o.durationMs=="number"?o.durationMs/1e3:void 0,...typeof o.mimeType=="string"?{mimeType:o.mimeType}:{},...typeof o.filename=="string"?{filename:o.filename}:{},...typeof o.size=="number"?{size:o.size}:{},taskId:typeof o.taskId=="string"?o.taskId:void 0}}var cy=[/<||DSML||tool_calls>/u,/<\|DSML\|>tool_calls/u,/<tool_calls?>[\s\S]*?<\/tool_calls?>/iu,/<function_calls?>[\s\S]*?<\/function_calls?>/iu],zu=["<\uFF5C\uFF5Cdsml\uFF5C\uFF5Ctool_calls>","<|dsml|>tool_calls","<tool_call","<function_call"];function Hu(e){return cy.some(t=>t.test(e))}function Vu(){let e="",t=!1,n=!1;return{push(o){if(!o||n)return"";if(t)return o;e+=o;let r=e.trimStart().toLowerCase();if(zu.some(i=>r.startsWith(i)))return e="",n=!0,"";if(zu.some(i=>i.startsWith(r)))return"";t=!0;let s=e;return e="",s},flush(){if(n)return"";let o=e;return e="",t=!0,o}}}var ly=new Set(["write","edit","patch"]);function Gu(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(a=>a.id===n.callId);if(!r)return[];let s=[],i=uy(r.function.arguments);if(!i)return s;if(ly.has(n.toolName)){let a=dy(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:fy(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:py(a)})}return s}function uy(e){try{return JSON.parse(e)}catch{return null}}function dy(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function fy(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function py(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}var my={general:"general",generalist:"general",explore:"explore",explorer:"explore",plan:"plan",planner:"plan",planning:"plan",code:"code",coder:"code",coding:"code",research:"research",researcher:"research",verify:"verify",verifier:"verify",verification:"verify"},gy=["type","role","specialization","agentType","agent_type"],hy=["task","objective","instruction","instructions","request","query"],yy=["async","runInBackground","run_in_background"];function by(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function eo(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Wu(e){let t=e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-agent$/,"");return my[t]??t}function Ri(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e===1?!0:e===0?!1:void 0;if(typeof e=="string")switch(e.trim().toLowerCase()){case"true":case"yes":case"1":case"background":case"async":return!0;case"false":case"no":case"0":case"foreground":case"sync":return!1;default:return}}function Ku(e,t){if(e!=="agent")return{rawArguments:t,corrections:[]};let n;try{n=JSON.parse(t)}catch{return{rawArguments:t,corrections:[]}}let o=by(n);if(!o)return{rawArguments:t,corrections:[]};let r=[],s=eo(o.agent);if(s){let a=Wu(s);a!==s&&(o.agent=a,r.push("agent-value"))}else for(let a of gy){let c=eo(o[a]);if(c){o.agent=Wu(c),delete o[a],r.push(`${a}->agent`);break}}if(!eo(o.prompt)){let a;for(let c of hy){let l=eo(o[c]);if(l){o.prompt=l,delete o[c],a=c;break}}if(a)r.push(`${a}->prompt`);else{let c=eo(o.description);c&&(o.prompt=c,r.push("description->prompt"))}}let i=Ri(o.background);if(o.background!==void 0&&i!==void 0)o.background!==i&&(o.background=i,r.push("background-value"));else if(o.background===void 0){let a;for(let c of yy){let l=Ri(o[c]);if(l!==void 0){o.background=l,delete o[c],a=c;break}}if(a)r.push(`${a}->background`);else{let c=Ri(o.foreground);c!==void 0&&(o.background=!c,delete o.foreground,r.push("foreground->background"))}}return r.length>0?{rawArguments:JSON.stringify(o),corrections:r}:{rawArguments:t,corrections:r}}var Zp=ah(Xp(),1),nR=new Zp.Ajv2020({allErrors:!0,allowUnionTypes:!0,strict:!1,validateFormats:!1}),Yp=new WeakMap;function oR(e){let t=Yp.get(e);if(t)return t;let n=nR.compile(e);return Yp.set(e,n),n}function rR(e){return e.instancePath?`arguments${e.instancePath}`:e.keyword==="required"&&typeof e.params.missingProperty=="string"?`arguments/${e.params.missingProperty}`:"arguments"}function sR(e){return(e??[]).slice(0,4).map(t=>`${rR(t)} ${t.message??`violates ${t.keyword}`}`).join("; ")}function Qp(e,t,n){let o;try{o=JSON.parse(n)}catch{return{ok:!1,error:`Tool "${e}" arguments must be valid JSON.`}}if(!o||typeof o!="object"||Array.isArray(o))return{ok:!1,error:`Tool "${e}" arguments must be a JSON object.`};if(!t)return{ok:!0};try{let r=oR(t);return r(o)?{ok:!0}:{ok:!1,error:`Tool "${e}" arguments do not match the offered schema: ${sR(r.errors)}.`}}catch(r){return{ok:!1,error:`Tool "${e}" has an invalid offered JSON Schema: ${r instanceof Error?r.message:String(r)}.`}}}var iR=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,aR=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Gr(e){if(!aR.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?cR(e.message.content).trim():"";return t.length>0&&t.length<200&&iR.test(t)}function cR(e){return e.match(/<untrusted_tool_result\b[^>]*>\s*([\s\S]*?)\s*<\/untrusted_tool_result>/i)?.[1]??e}var lR=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,uR=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])((?:[A-Za-z0-9._-]+[\\/])+[A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,dR=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,wc=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|产出|导出|自检)/i;function Kr(e,t,n){for(let o=e.length-1;o>=0;o--){let r=e[o];if(!r||r.role!=="tool")continue;let s=typeof r.content=="string"?r.content:"";if(s.startsWith("Error: ")){if(t){let i=typeof r.tool_call_id=="string"?r.tool_call_id:"",a=!1;for(let c=o-1;c>=0&&i;c--){let l=e[c];if(!l||l.role!=="assistant"||!Array.isArray(l.tool_calls))continue;let d=l.tool_calls.find(y=>y?.id===i);if(!d)continue;let m=d.function;a=m?.name===t&&(n===void 0||m.arguments===n);break}if(!a)continue}return s.slice(7).trim()}}}var fR=/(?:^|[,。!?;:、,.!?;:()()"'「」『』])(?:我们?)?(?:目前|暂时|现在|当前)?(?:无法|不能|没有办法|做不到|不具备|暂不支持|不支持)[^。.!?!?\n]{0,24}(?:能力|权限|功能|工具|截图|截屏|访问|操作)|我们?(?:目前|暂时|现在)?没有[^。.!?!?\n]{0,24}(?:能力|权限|功能|工具|截图|截屏|访问|操作)/,pR=/\b(?:i\s+(?:can(?:no|')t|cannot|am unable to|don['’]?t have|do not have|lack))\b[^.!?\n]{0,60}\b(?:ability|capability|permission|access|tool|feature|screenshot|support)\b|\bno such (?:tool|capability)\b/i;function em(e){let t=e.trim();return t.length===0||t.length>600?!1:fR.test(t)||pR.test(t)}function Jr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.round(e):0}function tm(e){if(!e)return 0;let t=new Set,n=new Set,o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&n.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(lR))o(i[0]);if(wc.test(s)){for(let i of s.matchAll(uR)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let c=a.replace(/\\/g,"/").split("/").pop();c&&n.add(c)}for(let i of s.matchAll(dR)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function Xr(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1){let t=Math.round(e);return t>100&&console.error(`[tool-loop] requested per-round maxToolCalls ${t} exceeds the provider cap ${100} \u2014 clamped to ${100}`),Math.min(t,100)}return wu}function nm(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function xc(e,t){let n=[];for(let o=e.length-1;o>=0;o--){let r=e[o];if(r.role==="tool"&&typeof r.content=="string")n.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return n.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${n.length} tool result(s)`),n.join(`
9
-
10
- `)):""}function Sc(e,t){let n=Kr(e,"")?.slice(0,600).trim(),o=`\u5DF2\u505C\u6B62\u672C\u8F6E\uFF1A\u5DE5\u5177\u8FDE\u7EED ${t} \u8F6E\u8C03\u7528\u5931\u8D25\uFF0C\u7EE7\u7EED\u91CD\u8BD5\u6CA1\u6709\u610F\u4E49\u3002`;return n?`${o}
11
-
12
- \u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
13
- ${n}
14
-
15
- \u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${o}
16
-
17
- \u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function om(e,t){let n,o;for(let i=e.length-1;i>=0;i--){let a=e[i];if(a?.role==="tool"&&typeof a.content=="string"&&a.content.startsWith("Error: ")){n=a.content.slice(7,807).trim(),o=typeof a.tool_call_id=="string"?a.tool_call_id:void 0;break}}if(!n)return null;let r;if(o)for(let i of e){let a=i.tool_calls;if(Array.isArray(a))for(let c of a){let l=c;if(l.id!==o)continue;let d=l.function;typeof d?.arguments=="string"&&(r=Ec(d.arguments)??d.arguments.slice(0,200))}}let s=(()=>{switch(t){case"semantic_quality_failed":return"\u641C\u7D22\u7ED3\u679C\u4E0E\u8BF7\u6C42\u5B9E\u4F53\u4E0D\u5339\u914D\u3002\u4E0D\u8981\u91CD\u590D\u539F\u67E5\u8BE2\uFF1B\u4F7F\u7528\u660E\u786E\u7684\u4EA7\u54C1\u540D\u3001\u7248\u672C\u53F7\u3001\u6807\u51C6\u7F16\u53F7\u6216\u6743\u5A01\u57DF\u540D\u91CD\u5199\u67E5\u8BE2\uFF0C\u5E76\u4EC5\u4F9D\u636E\u65B0\u53D6\u5F97\u7684\u76F8\u5173\u7ED3\u679C\u56DE\u7B54\u3002";case"timeout":return"\u5DE5\u5177\u8D85\u65F6\u3002\u6700\u591A\u518D\u5C1D\u8BD5\u4E00\u6B21\uFF1A\u7F29\u5C0F\u8BF7\u6C42\u8303\u56F4\uFF0C\u6216\u6539\u7528\u8DEF\u7531\u5668\u5DF2\u7ECF\u66B4\u9732\u7684\u7B49\u4EF7\u7C7B\u578B\u5316\u5DE5\u5177\uFF1B\u4E0D\u8981\u6539\u7528 shell \u5B89\u88C5\u6216\u4E34\u65F6\u811A\u672C\u7ED5\u8FC7\u3002";case"mcp_start_failed":case"mcp_unavailable":return"\u6240\u9009 MCP \u5F53\u524D\u4E0D\u53EF\u7528\u3002\u4E0D\u8981\u91CD\u590D\u542F\u52A8\u540C\u4E00\u8FDE\u63A5\u5668\uFF1B\u53EA\u6709\u5728\u8DEF\u7531\u5668\u5DF2\u66B4\u9732\u53E6\u4E00\u7B49\u4EF7\u7C7B\u578B\u5316\u8FDE\u63A5\u5668\u65F6\u624D\u5207\u6362\uFF0C\u5426\u5219\u5982\u5B9E\u62A5\u544A\u4E0D\u53EF\u7528\u3002";case"policy_blocked":return"\u8C03\u7528\u88AB\u7B56\u7565\u963B\u6B62\u3002\u4E0D\u5F97\u7528 exec\u3001PowerShell \u6216\u4E34\u65F6\u811A\u672C\u7ED5\u8FC7\uFF1B\u6539\u7528\u7B56\u7565\u5141\u8BB8\u7684\u4E13\u7528\u5DE5\u5177\uFF0C\u82E5\u4E0D\u5B58\u5728\u5219\u5982\u5B9E\u505C\u6B62\u3002";default:return"\u6839\u636E\u9519\u8BEF\u4FEE\u6B63\u53C2\u6570\u540E\u518D\u8BD5\u4E00\u6B21\u3002\u547D\u4EE4\u578B\u4E13\u7528\u5DE5\u5177\u5E94\u5148\u67E5\u770B\u5176\u5185\u7F6E help \u6765\u786E\u8BA4\u5B50\u547D\u4EE4\u548C\u8BED\u6CD5\uFF1B\u4E0D\u5F97\u91CD\u590D\u540C\u4E00\u5931\u8D25\u8C03\u7528\uFF0C\u4E5F\u4E0D\u5F97\u7528\u901A\u7528 shell \u53D6\u4EE3\u5DF2\u6709\u4E13\u7528\u5DE5\u5177\u3002"}})();return{role:"user",content:`\u6700\u8FD1\u4E00\u8F6E\u5DE5\u5177\u8C03\u7528\u8FDE\u7EED\u5931\u8D25\u3002\u5148\u7EA0\u6B63\u5931\u8D25\u539F\u56E0\uFF0C\u4E0D\u8981\u91CD\u590D\u76F8\u540C\u8C03\u7528\u3002
18
-
19
- `+(r?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${r}
20
- `:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
21
- ${n}
22
-
23
- `+s}}function Io(e){let t=e.replace(/\s+/g," ").trim().split(" "),n=(t[0]??"").replace(/^.*[\\/]/,"").toLowerCase(),o=(t[1]??"").replace(/^.*[\\/]/,"").toLowerCase(),r=/^[a-z][\w.-]*$/i.test(o)?o:"";return[n,r].filter(Boolean).join(" ")}var mR=/^(?:npx )?(?:vitest|jest|mocha|playwright|pytest|tsc|eslint|oxlint)\b|^(?:pnpm|npm|yarn) (?:test|run|build|lint|check)\b|^(?:go|cargo) (?:test|build|check)\b|^git (?:status|diff|log|add|commit)\b/;function rm(e){return mR.test(e)}var gR=/^(?:pip3?|pipx|uv|conda|npm|pnpm|yarn|apt(?:-get)?|brew|choco|winget)(?:\.\w+)?$/i,hR=/^(?:[^\s]*[\\/])?(?:python[\d.]*|py)(?:\.exe)?(?:\s+-\S+)?\s+-m\s+pip\s+(?:install|download)\b/i,yR=/^(?:[^\s]*[\\/])?uv(?:\.exe)?\s+pip\s+(?:install|sync)\b/i;function sm(e){if(!e)return!1;let t=e.replace(/\s+/g," ").trim();if(hR.test(t)||yR.test(t))return!0;let n=Io(e),[o,r]=n.split(" ");return!o||!gR.test(o)?!1:r==="install"||r==="add"}function Ec(e){try{let t=JSON.parse(e),o=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(s=>typeof s=="string"&&s.trim().length>0);if(typeof o=="string")return o.trim().slice(0,240);let r=Object.keys(t);return r.length>0?r.slice(0,5).join(" / "):void 0}catch{return}}function Ac(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function $c(e){return e==="length"||e==="max_tokens"}function Pc(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function im(e){let t=e.headers;if(!t)return null;let n=t["retry-after"]??t["Retry-After"];if(!n)return null;let o=parseInt(n,10);return!isNaN(o)&&o>0?o*1e3:null}function am(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let n=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(n)||isNaN(o))return null;let r=o-n-1e3;return r>=3e3?r:null}async function*cm(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:c,sessionId:l,currentModel:d,log:m,recovery:y,onAutocompact:_}=e,h;{let v=await i.enforceToolResultBudget(t,n,l);if(h=v.messages,v.newlyReplacedCount>0){let k=v.newlyPersistedBytes??0,C=k>0?` (~${Math.max(1,Math.round(k/1024))} KB)`:"";m.info(`tool-result-budget: persisted ${v.newlyReplacedCount} oversized tool results${C}`),yield y("tool_result_budget",`${v.newlyReplacedCount} persisted${C}`)}}{let v=ti(h,o);if(h=v.messages,v.removedCount>0){if(v.boundaryMessage){let k=h,C=0;for(;C<k.length&&k[C]?.role==="system";)C++;h=[...k.slice(0,C),v.boundaryMessage,...k.slice(C)]}m.info(`snip: removed ${v.removedCount} messages, freed ~${v.tokensFreed} tokens`),yield y("snip",`${v.removedCount} messages`)}}{let k=new Xn().compress(h,0);k.droppedCount>0&&(h=k.messages,m.info(`microcompact: cleared ${k.droppedCount} old tool results`),yield y("microcompact",`${k.droppedCount} old tool results cleared`))}if(h=oi(h,r).messages,s.contextWindowTokens>0){let v=s.contextWindowTokens*.75,k=i.getActiveContextCompressionEngine(),C;k?C=await k.compressAsync(h,v,{model:d,sessionId:l}):C=i.compressMessages(h,{budget:v,model:d}),C.droppedCount>0&&(h=C.messages,m.info(`autocompact: ${C.strategy}, dropped ${C.droppedCount}`),yield y("autocompact",`${C.strategy}: ${C.droppedCount} dropped`),yield{type:"lifecycle",turnId:c.turnId,kind:"context_compression",status:"completed",detail:`${C.strategy}: ${C.droppedCount} dropped`},_(),ue(a,"context.after_compact",{...c,removedCount:C.droppedCount},m))}if(i.restoreRequiredContextMessages){let v=i.restoreRequiredContextMessages(t,h,n);h=v.messages,v.recoveredCount>0&&(m.info(`typed-context-budget: recovered ${v.recoveredCount} required skill context message(s)`),yield y("typed_context_recovery",`${v.recoveredCount} required skill context message(s)`))}return h=nm(h),h}async function*lm(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:a,log:c,emitRecovery:l}=t;if(e instanceof Yn&&r)return c.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield l("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let d=e instanceof Error?e.message:String(e),m=typeof e?.status=="number"?e.status:void 0;if(!m&&d&&(d.includes("ECONNRESET")||d.includes("EPIPE"))){let _=(n.consecutiveApiRetries??0)+1;return _>Bt?(c.info(`stale connection retry limit reached (${Bt}), aborting`),yield{type:"error",turnId:a,error:d,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(c.info(`stale connection (${d.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield l("stale_connection_retry",d.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:_,transition:void 0}})}let y=am({status:m,message:d});if(y!==null)return c.info(`max_tokens overflow: adjusting to ${y}`),o.currentMaxOutputTokens=y,{kind:"continue",patch:{maxOutputTokensOverride:y,transition:void 0}};if(fi(m)){n.consecutive529Errors++;let _=2,h=r&&n.currentModel!==r;if(n.consecutive529Errors>_&&!h&&!ur())return c.info(`transient ${m} \xD7 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${n.consecutive529Errors} consecutive ${m} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=Nu&&r&&n.currentModel!==r)return c.info(`529 \xD7 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield l("model_fallback",`529 \xD7 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(ur()){let v=lr(n.consecutive529Errors);c.info(`persistent retry: waiting ${v}ms (attempt ${n.consecutive529Errors})`);let k=v;for(;k>0;){if(s?.aborted)return yield{type:"error",turnId:a,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:a,message:`Retrying in ${Math.ceil(k/1e3)}s (${m})`};let C=Math.min(k,Ou);await new Promise(E=>setTimeout(E,C)),k-=C}return{kind:"continue",patch:{transition:void 0}}}if(di(i)){let k=im({status:m,message:d})??lr(n.consecutive529Errors);return c.info(`transient ${m}: retry in ${k}ms`),yield l("retry",`${m} retry in ${k}ms`),await new Promise(C=>setTimeout(C,k)),{kind:"continue",patch:{transition:void 0}}}c.info(`background source ${i}: not retrying ${m}`)}return{kind:"streamError",streamError:{status:m,message:d}}}import{readdirSync as hm,statSync as Oo}from"node:fs";import{tmpdir as bR}from"node:os";function um(e){let t=[],n=[],o=a=>{let c=Mc(a?.trim()??"");c&&t.push(c)},r=e.split(`
24
- `),s=!1,i=null;for(let a of r){let c=a.trimEnd();if(c.startsWith("*** Add File: "))s=!0,o(c.slice(14));else if(c.startsWith("*** Update File: "))s=!0,o(c.slice(17));else if(c.startsWith("*** Delete File: ")){s=!0;let l=c.slice(17).trim();l&&(t.push(l),n.push(l))}else if(c.startsWith("*** Move to: "))s=!0,o(c.slice(13));else if(c.startsWith("*** Move File: ")){s=!0;let l=c.slice(15).trim(),[d,m]=l.split(" -> ");o(d),o(m)}else if(c.startsWith("--- ")){s=!0;let l=Mc(c.slice(4).trim());i=l||null,l&&l!=="/dev/null"&&t.push(l)}else if(c.startsWith("+++ ")){s=!0;let l=Mc(c.slice(4).trim());l&&l!=="/dev/null"&&t.push(l),l==="/dev/null"&&i&&i!=="/dev/null"&&n.push(i),i=null}}if(!s&&e.includes("<<<< SEARCH")){let c=(e.split(/^(<<<< SEARCH)$/m)[0]??"").trim().split(`
25
- `).pop()?.trim();o(c)}return{paths:t,deletes:n}}function Mc(e){let t=e.trim();if(!t||t==="/dev/null")return t;let n=t.indexOf(" ");n!==-1&&(t=t.slice(0,n));let o=t.search(/\s+\d{4}-\d{2}-\d{2}/);return o!==-1&&(t=t.slice(0,o)),t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1)),t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t}var _R=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|generate\s+(?:a\s+)?file|new\s+file/i,vR=/\bfix\b|implement|modify|update|repair/i,No=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,dm=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,TR=/\b(?:in|into|under|to|at|output(?:\s+to)?|save(?:\s+to)?|saved?\s+under)\s+([A-Za-z]:[\\/][^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+)/gi,kR=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},.;:\uFF0C\u3001\uFF1B\u3002])/gi,CR=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},.;:\uFF0C\u3001\uFF1B\u3002])/gi,RR=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+)[\\/]?(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,wR=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,Ic=/(?:do\s*not|don'?t|never|不要|不能|别|勿|禁止|不准|不得)[^.。;;\n]{0,14}(?:create|write|make|produce|generate|生成|创建|写入|写出|建立|新建)/i;function re(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function ym(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function fm(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function pm(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
26
- `,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(o,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+n.length);return new RegExp(`\\bno\\s+${km(n)}\\b`,"i").test(s)}function Qr(e){return e.replace(/https?:\/\/\S+/gu," ")}var xR=/\b(?:read|analy[sz]e|inspect|review|open|load|parse|consume|input|source)\b|读取|阅读|分析|检查|查看|打开|载入|输入|源文件/gi,SR=/\b(?:write|create|generate|save|output|produce|deliver|export|update|modify|edit)\b|写入|创建|生成|保存|输出|交付|导出|更新|修改|编辑/gi;function mm(e,t){let n=-1;for(let o of e.matchAll(t))n=o.index??n;return n}function ER(e){let t=new Set;for(let n of e){if(n.role!=="user"||typeof n.content!="string")continue;let o=Qr(n.content);for(let r of o.matchAll(No)){let s=r[0],i=o.slice(0,r.index??0),a=mm(i,xR),c=mm(i,SR);a>c&&t.add(re(s))}}return t}function es(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=re(s);t.has(i)||(t.add(i),n.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Qr(r.content);for(let i of s.matchAll(No)){let a=i[0],c=(i.index??0)+a.length;if(s[c]==="/"||s[c]==="\\")continue;o(a);let l=a.replace(/\\/g,"/"),d=l.lastIndexOf("/");if(d>=0){let m=l.slice(0,d+1);dm.lastIndex=c;let y;for(;(y=dm.exec(s))!==null;)o(`${m}${y[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Qr(r.content);if(!wc.test(s))continue;let i=Array.from(s.matchAll(TR)).map(d=>ym(d[1]??"")).filter(d=>d&&!fm(d));if(i.length===0)continue;let a=i[i.length-1],c=Array.from(s.matchAll(No)).map(d=>({start:d.index??0,end:(d.index??0)+d[0].length})),l=d=>c.some(m=>d>=m.start&&d<m.end);for(let d of s.matchAll(kR)){let m=d[1];if(!m)continue;let y=(d.index??0)+d[0].indexOf(m);l(y)||pm(s,d.index??0,m)||o(`${a}/${m}`)}for(let d of s.matchAll(CR)){let m=d[1];if(!m)continue;let y=(d.index??0)+d[0].indexOf(m);l(y)||pm(s,d.index??0,m)||o(`${a}/${m}`)}for(let d of s.matchAll(RR)){let m=d[1];m&&(fm(m)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(m)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${a}/${m}/*`))}wR.test(s)&&o(`${a}/previews/*`)}return n}function tn(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function AR(e){if(!tn(e))return!1;let t=typeof e.content=="string"?e.content:"";return!/^\s*Error:/i.test(t)&&!/(?:^|\n)\s*Errors:\s*(?:\n|$)/i.test(t)&&!/^\s*No changes applied\.\s*$/i.test(t)}function bm(e){let t=new Set;for(let o of e){let r=o;AR(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=[];for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.function;if(c?.name!=="patch"||typeof a.id!="string"||!t.has(a.id)||typeof c.arguments!="string")continue;let l=nn(c.arguments);typeof l?.input=="string"&&n.push(...um(l.input).paths)}}return n}function Oc(e){let t=new Set,n=new Map,o=[...bm(e)];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let c=a,l=c.id,d=c.function;typeof l=="string"&&typeof d?.name=="string"&&n.set(l,d.name)}}for(let r of e){let s=r;if(tn(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?n.get(i):void 0)==="exec"&&typeof s.content=="string"&&o.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let c=a,l=c.id;if(typeof l!="string"||!t.has(l))continue;let d=c.function;if(!(typeof d?.name!="string"||typeof d.arguments!="string"))try{let m=JSON.parse(d.arguments);if(d.name==="write"||d.name==="edit"){for(let y of["path","filePath","file_path"]){let _=m[y];typeof _=="string"&&o.push(_)}continue}if(d.name==="exec"){let y=m.command;typeof y=="string"&&o.push(y)}}catch{d.name==="exec"&&o.push(d.arguments)}}}return o.join(`
27
- `).replace(/\\/g,"/").toLowerCase()}function ts(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return hm(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return Oo(`${n}/${r.name}`).size>0}catch{return!1}})}let t=Oo(e);return t.isFile()&&t.size>0}catch{return!1}}function $R(e,t){let n=re(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function _m(e){let t=new Set;for(let n of e){let o=n,r=Array.isArray(o.tool_calls)?o.tool_calls:[];for(let s of r){let i=s,a=i.id,c=i.function;typeof a=="string"&&c?.name==="agent"&&t.add(a)}}for(let n of e){let o=n,r=o.tool_call_id;if(typeof r=="string"&&t.has(r)&&tn(o))return!0}return!1}function PR(e){let t=Tm(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function MR(e){let t=ym(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function IR(e){if(e.length===0)return"";let t=e.map(o=>MR(o).split("/")),n=[];for(let o=0;o<t[0].length;o++){let r=t[0][o];if(t.every(s=>s[o]?.toLowerCase()===r.toLowerCase()))n.push(r);else break}return n.join("/")}function OR(e,t){let n=re(e);return t.some(o=>{let r=re(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function Nc(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,l=a.function;if(typeof c!="string"||l?.name!=="write"&&l?.name!=="edit"||typeof l.arguments!="string")continue;let d=nn(l.arguments);if(!d)continue;let m=Fo(d);m&&n.set(c,m)}}for(let o of e){let r=o;if(!tn(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...n.entries()].filter(([o])=>t.has(o)).map(([,o])=>o)}function NR(e){return/\bartifact[-_\s]?index\b/i.test(e)&&(/\b(?:evidence|status|failed|partial|passed|verified)\b/i.test(e)||/\bGoal\s+\d+\b/i.test(e))}function FR(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function LR(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,l=a.function;if(typeof c!="string"||l?.name!=="write"&&l?.name!=="edit"||typeof l.arguments!="string")continue;let d=nn(l.arguments);if(!d)continue;let m=Fo(d)??"",y=Cm(d);(/\bartifact[-_\s]?index\b/i.test(m)||/\bartifact[-_\s]?index\b/i.test(y))&&n.set(c,y)}}for(let o of e){let r=o;if(!tn(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...n.entries()].filter(([o])=>t.has(o)).map(([,o])=>o).filter(o=>o.trim().length>0)}function jR(e){let t=Tm(e.inputMessages);if(!NR(t))return[];let n=LR(Pt(e.inputMessages,e.messages)).at(-1);if(!n)return[];let o=[],r=FR(t).filter(i=>!new RegExp(`\\b${km(i)}\\b`,"i").test(n));r.length>0&&o.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=n.split(/\r?\n/u).filter(i=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(i)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(i));return s.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${s.slice(0,3).join(" ; ")}`}),o}function DR(e){let t=[],n=o=>{let r;try{r=hm(o,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${o}/${s.name}`;if(s.isDirectory()){n(i);continue}if(s.isFile())try{Oo(i).size>0&&t.push(i)}catch{}}};try{if(!Oo(e).isDirectory())return[]}catch{return[]}return n(e),t}function Pt(e,t){if(t.length<e.length)return t;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return t;return t.slice(e.length)}function BR(e,t){if(!PR(e))return[];let n=es(e),o=n.filter(i=>!re(i).endsWith("/*"));if(o.length<2)return[];let r=IR(o);if(!r||r.split("/").length<3)return[];let s=re(r);return[...new Set([...Nc(Pt(e,t)),...DR(r)])].filter(i=>re(i).startsWith(`${s}/`)&&!OR(i,n)&&ts(i))}function vm(e,t){let n=es(e);if(n.length===0)return[];let o=ER(e),r=Pt(e,t),s=Oc(r),i=qR(r),a=UR(r);return n.filter(c=>{if(o.has(re(c))||$R(s,c))return!1;let l=re(c);return!((i.has(l)||a.has(l))&&ts(c))})}function qR(e){let t=new Set;for(let o of e){let r=o;tn(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=new Set;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.function;if(c?.name!=="read"||typeof a.id!="string"||typeof c.arguments!="string"||!t.has(a.id))continue;let l=nn(c.arguments),d=l?Fo(l):void 0;d&&n.add(re(d))}}return n}function UR(e){let t=new Set;for(let o of e){let r=o;tn(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=new Set;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.function,l=typeof c?.name=="string"?Ae(c.name):"";if(l!=="image_understand"&&l!=="video_understand"||typeof a.id!="string"||typeof c?.arguments!="string"||!t.has(a.id))continue;let d=nn(c.arguments);if(!d)continue;let m=l==="image_understand"?d.image_url:d.video_url;typeof m=="string"&&m.trim()&&n.add(re(m))}}return n}function Yr(e){return Fc(e).fail}function zR(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function Zr(e){if(!e)return!1;let t=zR(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function Fc(e){let t=r=>r.replace(/[.,;:]+$/u,""),n,o;for(let r of e)if(!(r.role!=="user"||typeof r.content!="string")){for(let s of r.content.matchAll(/\b(DONE|PASS)\s+([A-Za-z0-9_.:-]+)/gi))Zr(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))Zr(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))Zr(s[1])&&(n=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))Zr(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function Tm(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"&&typeof n.content=="string")return n.content}return""}function km(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nn(e){let t=vm(e.inputMessages,e.messages).filter(n=>!ts(n));if(t.length!==0)return`[Engine notice] ${e.reason}; explicitly requested output files still missing: ${t.join(", ")}.`}function nn(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Fo(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function Cm(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Rm(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=Fc(e.inputMessages);if(!n.done)return;let o=nn(e.toolCall.function.arguments);if(!o)return;let r=Fo(o),s=Cm(o);if(!r||!s.includes(n.done))return;let i=es(e.inputMessages);if(i.length<2)return;let a=re(r);if(!i.some(m=>re(m)===a))return;let l=Oc(e.messages),d=i.filter(m=>re(m)!==a).filter(m=>!l.includes(re(m)));if(d.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${d.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Qt(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function en(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function wm(e){try{return Oo(e).isFile()}catch{return!1}}function HR(e,t,n){let o=/[,.,。;;!?!?\n]/u,r=t;for(;r>0&&!o.test(e[r-1]);)r--;let s=t+n;for(;s<e.length&&!o.test(e[s]);)s++;if(Ic.test(e.slice(r,s)))return!0;let i=s<e.length?s+1:s,a=i;for(;a<e.length&&!o.test(e[a]);)a++;let c=e.slice(i,a);return Ic.test(c)&&/(?:这个|该|此)文件|\b(?:this|that|the)\s+file\b/i.test(c)}function VR(e,t){let n=new Map;for(let i of e){if(i.role!=="user"||typeof i.content!="string")continue;let a=Qr(i.content);if(Ic.test(a))for(let c of a.matchAll(No)){if(!HR(a,c.index??0,c[0].length))continue;let l=c[0].replace(/[),.;:,。;]+$/u,""),d=re(l);d&&n.set(d,l)}}if(n.size===0)return[];let o=Oc(Pt(e,t)),r=_m(Pt(e,t)),s=[];for(let[i,a]of n)(o.includes(i)||r&&wm(a))&&s.push(i);return s}var GR="File not found:",gm=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,WR=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function KR(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),a=s.includes(t)||n.length<=3||n===t?[t]:[n];for(let c of a){let l=0;for(;;){let d=s.indexOf(c,l);if(d===-1)break;l=d+1;let m=d;for(;m>0&&!o.test(s[m-1]);)m--;let y=d+c.length;for(;y<s.length&&!o.test(s[y]);)y++;let _=r.content.slice(m,y);if(gm.test(_))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),a=Array.from(r.content.matchAll(No)).map(l=>re(l[0])).some(l=>l!==t),c=s.includes(t)||!a&&n.length>3&&n!==t&&s.includes(n);if(!a&&c&&gm.test(r.content)&&WR.test(r.content))return!0}return!1}function JR(e){let t=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,l=a.function;if(typeof c!="string"||l?.name!=="read"||typeof l.arguments!="string")continue;let d=nn(l.arguments),m=d?Fo(d):void 0;m&&t.set(c,m)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let i=t.get(s);if(!i)continue;let a=typeof r.content=="string"?r.content:"";(r.is_error===!0||a.startsWith("Error:"))&&a.includes(GR)&&n.set(re(i),i)}return n}function XR(e,t){let n=Pt(e,t),o=JR(n);if(o.size===0)return[];let r=new Set(Nc(n).map(re)),s=[];for(let[i,a]of o)KR(e,i)||(r.has(i)||wm(a))&&s.push(i);return s}function Lc(e){let t=[...e.inputMessages].reverse().find(_=>_.role==="user"),n=typeof t?.content=="string"?t.content:"",o=_R.test(n)||vR.test(n)&&es(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit")||bm(Pt(e.inputMessages,e.messages)).length>0,s=Fc(e.inputMessages),i=s.fail!==void 0&&e.finalText.includes(s.fail)||/\bFAILED\b/.test(e.finalText),a=VR(e.inputMessages,e.messages);if(a.length>0&&!i){e.log.info(`forbidden-file-creation guard: agent wrote ${a.length} file(s) the user forbade creating`);let _=Yr(e.inputMessages),h={role:"user",content:`You created a file the request explicitly forbade creating: ${a.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${_??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return en("forbidden_file_creation",e.messages,Qt(e.finalText,e.thinkingBlocks),h)}let c=XR(e.inputMessages,e.messages);if(c.length>0&&!i){e.log.info(`self-created-read-target guard: agent created ${c.length} file(s) it had read as not-found`);let _=Yr(e.inputMessages),h={role:"user",content:"You were asked to read "+c.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${_??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return en("self_created_read_target",e.messages,Qt(e.finalText,e.thinkingBlocks),h)}let l=_m(e.messages),d=vm(e.inputMessages,e.messages).filter(_=>!(l&&ts(_)));if(d.length>0&&e.totalToolCallCount>0){if(i)return null;e.log.info(`explicit required file verification: ${d.length} file(s) missing`);let _=Yr(e.inputMessages),h={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${d.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${_??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return en("explicit_required_file_verification",e.messages,Qt(e.finalText,e.thinkingBlocks),h)}let m=BR(e.inputMessages,e.messages);if(m.length>0&&e.totalToolCallCount>0){if(i)return null;e.log.info(`explicit extra file verification: ${m.length} unexpected file(s)`);let _=Yr(e.inputMessages),h={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${m.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${_??"FAILED"} and the real reason. Do not claim completion while extra deliverables remain.`};return en("explicit_extra_file_verification",e.messages,Qt(e.finalText,e.thinkingBlocks),h)}let y=jR({inputMessages:e.inputMessages,messages:e.messages});if(y.length>0&&e.totalToolCallCount>0){if(i)return null;e.log.info(`artifact index evidence verification: ${y.length} issue(s)`);let _={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+y.map(h=>h.detail).join(" ")+" Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, finish with the final status contract."};return en("artifact_index_evidence_verification",e.messages,Qt(e.finalText,e.thinkingBlocks),_)}if(e.stopHookActive)return null;if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge");let _={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return en("file_action_verification",e.messages,Qt(e.finalText,e.thinkingBlocks),_)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")){let _=[...new Set(Nc(Pt(e.inputMessages,e.messages)).map(re))].filter(h=>YR.test(h)&&!ZR(h));if(_.length>=3){e.log.info(`AP3 verification nudge: ${_.length} code files created, injecting completeness check`);let h={role:"user",content:"You created multiple code files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. Fix anything that fails these checks. Either way, your FINAL message must answer the user's actual request \u2014 do not end on this checklist confirmation."};return en("multi_file_skeleton_verification",e.messages,Qt(e.finalText,e.thinkingBlocks),h)}}return null}var YR=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|kts|cs|cpp|cc|c|h|hpp|vue|svelte)$/i;function ZR(e){let t=re(bR());return t.length>0&&e.startsWith(`${t}/`)}function QR(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function xm(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let n=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${n}`);let o={role:"user",content:n};return{action:"continue",messages:[...e.messages,QR(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var jc="```final-status",ew=/\r?\n[ \t]*```/;function tw(e,t){let n=Math.min(e.length,t.length-1);for(let o=n;o>0;o--)if(e.endsWith(t.slice(0,o)))return o;return 0}function Sm(){let e="",t=!1;function n(){let o="";for(;;){if(t){let s=ew.exec(e);if(!s)return o;e=e.slice(s.index+s[0].length),t=!1;continue}let r=e.indexOf(jc);if(r===-1){let s=tw(e,jc);return o+=e.slice(0,e.length-s),e=e.slice(e.length-s),o}o+=e.slice(0,r),e=e.slice(r+jc.length),t=!0}}return{push(o){return o?(e+=o,n()):""},flush(){if(t)return e="","";let o=e;return e="",o},isSuppressing:()=>t}}var Em=5;function nw(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function ow(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Dc(e,t){let n=e.recoveryTrace;if(!n)return;let o=`budget_continuation_stop:${t}`;n.set(o,(n.get(o)??0)+1)}function Am(e){if(!e.tokenBudget||e.tokenBudget<=0)return null;let t=nw(e.totalUsage),n=t/e.tokenBudget*100;if(e.budgetContinuationCount>=Em)return e.log.info(`token budget continuation stop: continuation cap reached (${e.budgetContinuationCount}/${Em}) at ${Math.round(n)}% used`),Dc(e,"cap"),null;let o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=Iu&&o<pi&&e.lastBudgetDeltaTokens<pi)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),Dc(e,"diminishing_returns"),null;if(n>=90)return e.log.info(`token budget continuation stop: ${Math.round(n)}% of ${e.tokenBudget} tokens used (>=90% headroom floor), not nudging further work`),Dc(e,"headroom_floor"),null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(n)}% used`),{messages:[...e.messages,ow(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}import{createHash as $m}from"node:crypto";function Pm(e){let t=[{value:e,depth:0}],n=new Set;for(;t.length>0;){let o=t.shift();if(!(!o.value||typeof o.value!="object"||o.depth>8)&&!n.has(o.value)){if(n.add(o.value),!Array.isArray(o.value)){let r=o.value,s=Object.hasOwn(r,"billed")&&(r.billed===null||typeof r.billed=="boolean"),i=["retryable","safeToRetry","retryMode","automaticRetryAuthorized"].some(a=>Object.hasOwn(r,a));if(s&&i)return{billed:r.billed,retryable:r.retryable===!0,safeToRetry:r.safeToRetry===!0,retryMode:typeof r.retryMode=="string"?r.retryMode:"unspecified",automaticRetryAuthorized:r.automaticRetryAuthorized===!0,...typeof r.stage=="string"?{stage:r.stage}:{}}}for(let r of Array.isArray(o.value)?o.value:Object.values(o.value))t.push({value:r,depth:o.depth+1})}}}var Ln="*";function Mm(e,t,n){let o=[],r=[];for(let s of e){let i=Bc(s.function.name,s.function.arguments),a=Lm(s.function.name,Ln),c=Math.max(t.get(i)??0,t.get(a)??0);if(c>=dr){let l=rw(s);if(n.has(l)){n.delete(l),o.push(s);continue}n.add(l),r.push({call:s,failCount:c,error:`Tool "${s.function.name}" has failed ${c} times this turn with the same canonical arguments. Stop repeating that exact invocation. Correct the declared schema or parameters, switch to a verified target, or report the issue to the user. If you are certain this exact call is a deliberate retry of a transient failure, re-issue exactly the same call once more and it will run.`})}else o.push(s)}return{allowed:o,blocked:r}}function rw(e){return`${e.function.name}::${e.function.arguments}`}function Im(){return{role:"user",content:"Tool calls were blocked because the exact canonical invocation has failed too many times. Correct the arguments, use a different verified operation, or tell the user what happened."}}function Om(e){if(e.ok){e.toolFailureCounts.delete(Bc(e.toolName,e.toolArguments));return}let t=Bc(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function Nm(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=dr&&(e.snapshot.get(n)??0)<dr){let{toolName:r,target:s}=hw(n);t.push({role:"user",content:`Tool "${r}" has now failed ${o} times for target "${s}". Do not repeat the same failed invocation unchanged. A call with corrected arguments remains available. If this exact call is a deliberate retry of a transient failure, re-issue it after it is blocked and it will run once. Otherwise report the result to the user immediately.`})}return t}function Bc(e,t){return Lm(e,sw(e,t))}function sw(e,t){let n=gw(t);if(e==="read"||e==="write"||e==="edit"||e==="patch")return Fn(n?.path??n?.file_path??n?.filePath);if(e==="search")return Fn([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|"));if(e==="exec"){let o=typeof n?.command=="string"?n.command:void 0;return Fn(o?Io(o):void 0)}return cw(n)}var iw=["runtime_id","runtimeId","operation","action","method","resource_type","resourceType"],aw=["kind","interactionIntent","targetRole"];function cw(e){if(!e)return Ln;let t=iw.flatMap(i=>typeof e[i]=="string"&&e[i].trim()?[`${i}=${Fn(e[i])}`]:[]),n=mw(e);n&&t.push(n);let o=Object.keys(e).sort().join(",");o&&t.push(`shape=${o}`);for(let[i,a]of Object.entries(e)){if(!Fm(a))continue;let c=aw.flatMap(l=>typeof a[l]=="string"&&a[l].trim()?[`${i}.${l}=${Fn(a[l])}`]:[]);t.push(...c)}let r=Array.isArray(e.args)?pw(e.args):"";r&&t.push(`argv=${r}`);let s=dw(e);return s&&t.push(`payloadShape=${s}`),t.push(`arguments=${lw(e)}`),t.length>0?t.join("|"):Ln}function lw(e){return $m("sha256").update(JSON.stringify(qc(e))).digest("hex").slice(0,24)}function qc(e){return Array.isArray(e)?e.map(qc):Fm(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,qc(e[t])])):e}var uw=["stdin","input","payload","body","request","data"];function dw(e){let t=[];for(let n of uw)n in e&&t.push(`${n}:${Uc(fw(e[n]))}`);if(t.length!==0)return $m("sha256").update(t.join("|")).digest("hex").slice(0,24)}function fw(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Uc(e,t=0){if(t>=12)return"depth-limit";if(e===null)return"null";if(Array.isArray(e))return`array[${[...new Set(e.slice(0,64).map(o=>Uc(o,t+1)))].sort().join(",")}]`;if(typeof e=="object"){let n=e;return`object{${Object.keys(n).sort().map(o=>`${o}:${Uc(n[o],t+1)}`).join(",")}}`}return typeof e}function pw(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(typeof o!="string"||!o.startsWith("-"))continue;let r=o.toLowerCase(),s=e[n+1];if(typeof s=="string"&&!s.startsWith("-")){let i=s.indexOf("="),a=i>0?s.slice(0,i).trim().toLowerCase():"";a&&(r+=`:${a}`)}t.push(r)}return t.join(",")}function mw(e){for(let t of["url","uri"]){let n=e[t];if(!(typeof n!="string"||!n.trim()))try{let o=new URL(n);return`${t}=${o.origin.toLowerCase()}`}catch{return`${t}=invalid-url`}}for(let t of["path","file_path","filePath","target","resource","resource_id","resourceId"]){let n=e[t];if(typeof n=="string"&&n.trim())return`${t}=${Fn(n)}`}}function Fm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gw(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function Fn(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():Ln}function Lm(e,t){return`${e}::${t}`}function hw(e){let t=e.indexOf("::");return t<0?{toolName:e,target:Ln}:{toolName:e.slice(0,t),target:e.slice(t+2)||Ln}}var Wc=new Set(["write","edit","patch"]),Kc=new Set(["image_generate"]),qm=new Set(["cad_design","industrial_runtime","solidworks_create"]),yw=/\b(?:verify|test|check|validate)\b[\s\S]{0,48}\b(?:browser|browser-visible|playwright|visible ui)\b|\b(?:browser|browser-visible|playwright|visible ui)\b[\s\S]{0,48}\b(?:verify|test|check|validate)\b/i,bw=/\b(?:build|create|make|develop|implement|scaffold|generate|set ?up)\b[\s\S]{0,80}\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b|(?:构建|创建|开发|实现|生成|搭建)[\s\S]{0,24}(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/i,_w=/\b(?:output\s+to|save\s+to|deliver\s+to|write\s+to|generate\s+into|output\s+(?:directory|folder)\s*(?:[:=]|is)?)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:输出到|保存到|放到|交付到|生成到|输出目录)\s*[::]?\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,Jc=/https?:\/\/[^\s"'`<>),;]+/gi,vw=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|无法访问|(?:发生|出现|报|加载|请求|页面|控制台|连接|断言|验证|测试|检查|等待|打开|访问)[^\n]{0,10}(?:错误|失败|超时)|(?:错误|失败|超时)(?:[::]|码|代码|信息|堆栈)/i,Tw=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,jm=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i,kw=new Set(["browser_automation","frontend_test","user_confirmation","external_benchmark","fork_verify"]),Cw=/\b(?:i have|i've|i)\s+(?:verified|checked|confirmed|reviewed|tested)\b[\s\S]{0,80}\b(?:ui|page|screen|interface|frontend)\b[\s\S]{0,48}\b(?:works?|correct|passed|looks? good|as expected)\b|(?:我已经|我已|已经|已)(?:查看|检查|确认|验收|测试)[\s\S]{0,36}(?:页面|界面|UI|前端|截图)[\s\S]{0,24}(?:正常|通过|没问题|符合预期|正确)/i,Rw=/\b(?:vitest|jest|cypress|playwright|storybook|testing-library)\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|test:ui|test:component)\b/i,ww=/\.(?:tsx|jsx)\b|testing-library|(?:render(?:ed|ing)?|screen|dom|component|dashboard|navigation|heading|button|dialog|page|ui)\b|(?:渲染|页面|界面|组件|导航|标题|按钮)/i,xw=/\bPASS\b|(?:test files?|tests?)\s+\d+\s+passed|\b\d+\s+passed\b|(?:^|\n)\s*[✓✔]\s|(?:测试|用例).{0,12}(?:通过|成功)/i;function Sw(e){let t=tl(e),n={artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],deletedPaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]},o=[...e].reverse().find(r=>r.role==="user");for(let r of o?[o]:[]){if(r.role!=="user"||typeof r.content!="string"||!Cw.test(r.content))continue;let s=(r.imageUrls?.length??0)>0||/(?:screenshot|截图)/i.test(r.content),i=`${r.content.trim()}${s?" [screenshot-backed]":""}`;Lo(n,{source:"user_confirmation",status:"passed",summary:i})}return n}function os(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&(bw.test(t.content)||yw.test(t.content)))}var Ew=new RegExp(["\\b(?:tests?|test suite|unit tests?|the suite|build|compiles?|compilation|typecheck|lint)\\b[\\s\\S]{0,24}\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?|clean|work(?:s|ing)?)\\b","\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?)\\b[\\s\\S]{0,16}\\b(?:tests?|the suite|build)\\b","\\bfix(?:es|ing)?\\b[\\s\\S]{0,24}\\b(?:failing|broken)\\b[\\s\\S]{0,12}\\b(?:tests?|build|spec)\\b","\\bmake it (?:build|compile|pass)\\b","\\b(?:run|rerun|re-run) (?:the )?(?:tests?|test suite|build|spec)\\b","\\b(?:npm (?:test|run build)|pnpm (?:test|build)|yarn (?:test|build)|pytest|go test|cargo (?:test|build)|vitest|jest|gradle|mvn)\\b","(?:\u8BA9|\u4F7F|\u786E\u4FDD)[\\s\\S]{0,12}(?:\u6D4B\u8BD5|\u5355\u6D4B|\u7528\u4F8B|\u6784\u5EFA|\u7F16\u8BD1)[\\s\\S]{0,8}(?:\u901A\u8FC7|\u8DD1\u901A|\u6210\u529F|\u7EFF)","(?:\u4FEE\u590D|\u4FEE\u597D|\u89E3\u51B3)[\\s\\S]{0,12}(?:\u5931\u8D25\u7684?\u6D4B\u8BD5|\u6D4B\u8BD5\u5931\u8D25|\u7F16\u8BD1\u9519\u8BEF|\u6784\u5EFA\u9519\u8BEF|\u7F16\u8BD1\u62A5\u9519|\u62A5\u9519)","\u6D4B\u8BD5\u901A\u8FC7|\u8DD1\u901A\u6D4B\u8BD5|\u7F16\u8BD1\u901A\u8FC7|\u6784\u5EFA\u901A\u8FC7|\u901A\u8FC7(?:\u5168\u90E8|\u6240\u6709)?\u6D4B\u8BD5|\u8BA9\u6D4B\u8BD5\u53D8\u7EFF"].join("|"),"i");function Um(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ew.test(t.content))}var zc=/```final-status[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```/g,Aw=new Set([...Wc,...Kc,...qm,"exec","bash","shell","powershell","terminal","playwright","browser","computer"]);function zm(e){for(let t of e)if(Aw.has(Ae(t)))return!0;return!1}var Hm=["## Final status block","When this turn produced artifacts (files written, apps served), asserted verification (browser/build/tests), left requested work incomplete or blocked, or the user explicitly asked for a final status or an evidence audit, end your final message with exactly one fenced block:","","```final-status",'{"schema":1,"done":["\u2026"],"notDone":["\u2026"],"artifacts":{"root":"\u2026","files":["\u2026"],"urls":["\u2026"]},"verification":{"browser":"verified|failed|not-run","build":"passed|failed|not-run"},"sources":{"cited":["https://\u2026"]},"blockers":["\u2026"],"nextAction":"\u2026"}',"```","","Every field must reflect actual tool activity from this turn; the engine cross-checks the block against its own tool records and strips unsupported claims. Omit fields that do not apply. Omit the whole block for ordinary conversation."].join(`
28
- `);function Vm(e){zc.lastIndex=0;let t=null;for(let o=zc.exec(e);o;o=zc.exec(e))t=o;if(!t)return null;let n={start:t.index,end:t.index+t[0].length};try{let o=JSON.parse(t[1]);if(!o||typeof o!="object"||Array.isArray(o))return{claim:null,...n};let r=o;return r.schema!==1?{claim:null,...n}:{claim:r,...n}}catch{return{claim:null,...n}}}function Dm(e){return"```final-status\n"+JSON.stringify(e,null,2)+"\n```"}function Xc(e,t){let n=el(t);if(!n)return null;let o=Ae(e);if(Wc.has(o))return ns(n.path,n.file_path,n.filePath,n.filename,n.file);if(Kc.has(o))return ns(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0);if(jn(o)&&typeof n.command=="string"){let r=n.command.match(/^\s*agent-browser(?:\.exe)?\b[\s\S]*?\bscreenshot\s+(?:"([^"]+)"|'([^']+)'|(\S+))/i);return ns(r?.[1],r?.[2],r?.[3])}return null}function Gm(e){let t=Xc(e.toolName,e.rawArguments);if(!t||!os(e.inputMessages))return null;if(!e.state.artifactRoot){let r=tl(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=tg(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||og(t,n))return null;let o=`Artifact root contract blocked ${e.toolName}: attempted to write ${t}, but this deliverable root is ${n}. Keep generated app/project files inside the declared artifactRoot, or ask for explicit approval before changing scope.`;return{path:t,artifactRoot:n,error:o}}function Wm(e){let t=Xc(e.toolName,e.rawArguments);return!t||!Ww(t)?null:{path:t,error:`Read-only context-pack blocked ${e.toolName}: attempted to write ${t}. Context packs are source evidence; write document indexes, checkpoints, and maintenance updates under benchmark-state instead.`}}function Yc(e,t){e.writePaths.includes(t.path)||e.writePaths.push(t.path),e.outOfRootWrites.some(n=>n.path===t.path&&n.toolName===t.toolName)||e.outOfRootWrites.push(t)}function $w(e){if(!e)return[];let t=[],n=s=>{if(typeof s!="string")return;let i=s.trim();i&&!t.includes(i)&&t.push(i)},o=s=>{if(!s||typeof s!="object"||Array.isArray(s))return;let i=s;if(Array.isArray(i.writePaths))for(let a of i.writePaths)n(a);if(Array.isArray(i.artifacts))for(let a of i.artifacts){if(typeof a=="string"){n(a);continue}if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a;n(c.path),n(c.filePath),n(c.outputPath)}};o(e);let r=e.mcpStructuredContent;return o(r),r&&typeof r=="object"&&!Array.isArray(r)&&o(r.result),t}var Km=new Set(["exec","bash","shell","powershell","terminal"]),Bm=/\b(?:Remove-Item|rm|del|erase|unlink)\b/i;function Pw(e,t,n){if(!Km.has(e)||n.length===0)return[];let o=Do(t);if(!o||!Bm.test(o))return[];let r=o.split(/(?:;|&&|\|\||\r?\n)/u),s=r.filter(l=>Bm.test(l)).map(l=>ie(l));if(s.length===0)return[];let i=el(t),a=i?ns(i.cwd,i.workdir,i.workingDirectory):null,c=r.filter(l=>/(?:^|\s)(?:cd|chdir|pushd|Set-Location)\s/i.test(l)).map(l=>ie(l));return a&&c.push(ie(a)),n.filter(l=>{let d=ie(l);if(!d)return!1;if(s.some(h=>h.includes(d)))return!0;let m=ie(Gc(l)),y=d.slice(d.lastIndexOf("/")+1);if(!m||!y||!c.some(h=>h.includes(m)))return!1;let _=new RegExp(`(?:^|[\\s"'=])${Jw(y)}(?:$|[\\s"',])`,"i");return s.some(h=>_.test(h))})}function Jm(e){let t=Ae(e.toolName),n=Xc(e.toolName,e.rawArguments),o=e.ok?$w(e.details):[],r=e.ok?[...new Set([...n?[n]:[],...o])]:[];for(let a of r){if(Wc.has(t)&&(e.state.browserVerified=!1,e.state.browserEvidence=[],e.state.browserFailureEvidence=[]),e.state.deletedPaths=e.state.deletedPaths.filter(c=>ie(c)!==ie(a)),!e.state.artifactRoot){let c=tl(e.inputMessages);e.state.artifactRoot=c??tg(a),e.state.rootSource=c?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(a)||e.state.writePaths.push(a),os(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!og(a,e.state.artifactRoot)&&Yc(e.state,{path:a,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}if(e.ok)for(let a of Pw(t,e.rawArguments,e.state.writePaths))e.state.deletedPaths.some(c=>ie(c)===ie(a))||e.state.deletedPaths.push(a);if(Bw(e.toolName,e.inputMessages)){let a=`${e.rawArguments}
29
- ${e.content}`;for(let c of a.matchAll(Jc)){let l=jo(c[0]);l&&(e.state.devServerUrls.includes(l)||e.state.devServerUrls.push(l))}}let s=Do(e.rawArguments);!(e.ok&&/^\s*agent-browser(?:\.exe)?\b[\s\S]*?\bclose\s*$/i.test(s)&&/\bbrowser closed\b/i.test(e.content))&&zw(e.toolName,e.rawArguments,e.content)&&nl(e.content)&&Lo(e.state,{source:"browser_automation",status:"failed",summary:e.content}),e.ok&&Dw(e.toolName,e.rawArguments,e.content)&&Lo(e.state,{source:"browser_automation",status:"passed",summary:e.content}),e.ok&&qw(e.toolName,e.rawArguments,e.content)&&Lo(e.state,{source:"frontend_test",status:"passed",summary:e.content});for(let a of Uw(e.details))!e.ok&&a.status==="passed"||Lo(e.state,a);if(Vw(e.toolName,e.rawArguments))if(!e.ok||ng(e.content)){e.state.buildVerified=!1;let c=e.content.trim().slice(0,500);c&&!e.state.buildFailureEvidence.includes(c)&&e.state.buildFailureEvidence.push(c)}else{e.state.buildVerified=!0,e.state.buildFailureEvidence=[];let c=e.content.trim().slice(0,300);c&&!e.state.buildEvidence.includes(c)&&e.state.buildEvidence.push(c)}}function Lo(e,t){let n=t.summary.trim().slice(0,500);if(!n)return;let o=`[${t.source}] ${n}`;if(t.status==="failed"){e.browserVerified=!1,e.browserEvidence=[],e.browserFailureEvidence.includes(o)||e.browserFailureEvidence.push(o);return}e.browserVerified=!0,e.browserFailureEvidence=[],e.browserEvidence.includes(o)||e.browserEvidence.push(o)}function Zc(e,t){return{artifactRoot:e.artifactRoot,writePaths:[...e.writePaths],deletedPaths:[...e.deletedPaths],outOfRootWrites:[...e.outOfRootWrites],devServerUrls:[...e.devServerUrls],browserVerified:e.browserVerified,browserEvidence:[...e.browserEvidence],browserFailureEvidence:[...e.browserFailureEvidence],requiresBrowserAcceptance:os(t)}}function Xm(e){let t=Sw(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||Qc(t,n.content);return t.recoveredBaseline={writePaths:t.writePaths.length,devServerUrls:t.devServerUrls.length,artifactRoot:!!t.artifactRoot},t}function Qc(e,t){let n=Vm(t)?.claim?.artifacts;if(n){typeof n.root=="string"&&n.root&&!e.artifactRoot&&(e.artifactRoot=ht(n.root),e.rootSource="inferred");for(let o of n.files??[]){if(typeof o!="string")continue;let r=ht(o.trim());r&&!e.writePaths.includes(r)&&e.writePaths.push(r)}for(let o of n.urls??[]){if(typeof o!="string")continue;let r=jo(o);r&&!e.devServerUrls.includes(r)&&e.devServerUrls.push(r)}}for(let o of t.matchAll(Jc)){let r=jo(o[0]);r&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(r)&&(e.devServerUrls.includes(r)||e.devServerUrls.push(r))}}var Mw=/[一-鿿]/;function Ym(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(!(n.role!=="user"||typeof n.content!="string"))return Mw.test(n.content)?"zh":"en"}return"en"}var Iw={en:{doneRan:(e,t)=>`Ran ${e} tool call${e===1?"":"s"} (${t}).`,doneNoToolCalls:"No tool calls were executed; blocked requests are listed under blockers.",doneNoToolWork:"No tool work was recorded.",notDoneUnresolvedTasks:(e,t)=>`Task list still has ${e} unresolved item(s): ${t}.`,blockerResolveTasks:"Update unresolved task items to completed, cancelled, or an explicit blocker before claiming completion.",notDoneOutOfRoot:"At least one write landed outside the declared deliverable root.",blockerOutOfRoot:(e,t,n)=>`${e} attempted ${t} outside ${n}.`,notDoneBuildFailing:"A test/build run is failing; no passing test/build evidence was recorded.",blockerFixBuild:e=>`Fix the code and re-run the test/build until it passes: ${e}`,notDoneTerminalBlockers:"The turn stopped with unresolved tool-call blockers instead of completing all requested work.",blockerToolBlocked:(e,t)=>`${e} blocked by ${t}.`,nextActionResolveBlockers:"Resolve the blocker(s), then rerun verification and issue a new final status.",nextActionProceed:"Proceed with user review or requested follow-up."},zh:{doneRan:(e,t)=>`\u6267\u884C\u4E86 ${e} \u6B21\u5DE5\u5177\u8C03\u7528(${t})\u3002`,doneNoToolCalls:"\u672A\u6267\u884C\u4EFB\u4F55\u5DE5\u5177\u8C03\u7528\uFF1B\u88AB\u963B\u585E\u7684\u8BF7\u6C42\u5217\u5728\u963B\u585E\u9879\u4E2D\u3002",doneNoToolWork:"\u672A\u8BB0\u5F55\u5230\u4EFB\u4F55\u5DE5\u5177\u5DE5\u4F5C\u3002",notDoneUnresolvedTasks:(e,t)=>`\u4EFB\u52A1\u6E05\u5355\u4ECD\u6709 ${e} \u9879\u672A\u5904\u7406\uFF1A${t}\u3002`,blockerResolveTasks:"\u5728\u58F0\u660E\u5B8C\u6210\u524D\uFF0C\u5C06\u672A\u5904\u7406\u7684\u4EFB\u52A1\u9879\u66F4\u65B0\u4E3A\u5DF2\u5B8C\u6210\u3001\u5DF2\u53D6\u6D88\u6216\u660E\u786E\u7684\u963B\u585E\u9879\u3002",notDoneOutOfRoot:"\u81F3\u5C11\u6709\u4E00\u6B21\u5199\u5165\u843D\u5728\u58F0\u660E\u7684\u4EA4\u4ED8\u6839\u76EE\u5F55\u4E4B\u5916\u3002",blockerOutOfRoot:(e,t,n)=>`${e} \u5C1D\u8BD5\u5199\u5165 ${t}\uFF0C\u8D85\u51FA ${n}\u3002`,notDoneBuildFailing:"\u6D4B\u8BD5/\u6784\u5EFA\u8FD0\u884C\u5931\u8D25\uFF1B\u672A\u8BB0\u5F55\u5230\u901A\u8FC7\u7684\u6D4B\u8BD5/\u6784\u5EFA\u8BC1\u636E\u3002",blockerFixBuild:e=>`\u4FEE\u590D\u4EE3\u7801\u5E76\u91CD\u65B0\u8FD0\u884C\u6D4B\u8BD5/\u6784\u5EFA\u76F4\u5230\u901A\u8FC7\uFF1A${e}`,notDoneTerminalBlockers:"\u672C\u8F6E\u5728\u5B58\u5728\u672A\u89E3\u51B3\u7684\u5DE5\u5177\u8C03\u7528\u963B\u585E\u65F6\u505C\u6B62\uFF0C\u672A\u5B8C\u6210\u5168\u90E8\u8BF7\u6C42\u7684\u5DE5\u4F5C\u3002",blockerToolBlocked:(e,t)=>`${e} \u88AB ${t} \u963B\u585E\u3002`,nextActionResolveBlockers:"\u89E3\u51B3\u963B\u585E\u9879\u540E\uFF0C\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\u5E76\u7ED9\u51FA\u65B0\u7684\u6700\u7EC8\u72B6\u6001\u3002",nextActionProceed:"\u53EF\u4EE5\u8FDB\u884C\u7528\u6237\u5BA1\u9605\u6216\u6309\u9700\u8DDF\u8FDB\u3002"}};function Zm(e){let t=e.content.trim();if(!e.contractActive)return{content:t,malformedBlock:!1,notices:[]};let n=Vm(t);if(n?.claim){let i=t.slice(0,n.start).trimEnd(),a=t.slice(n.end).trim(),c=[i,a].filter(Boolean).join(`
30
- `),{claim:l,notices:d}=Ow(n.claim,c,e);return{content:[i,Dm(l),a].filter(Boolean).join(`
31
-
32
- `),malformedBlock:!1,notices:d}}let o=n!==null;if(Kw(t)&&e.totalToolCallCount===0)return{content:t,malformedBlock:o,notices:[]};let r=Nw(e);if(!r)return{content:t,malformedBlock:o,notices:[]};let s=Dm(r);return{content:t?`${t}
33
-
34
- ${s}`:s,malformedBlock:o,notices:[]}}function Ow(e,t,n){let o=n.artifactContract,r=[],s={...e,schema:1,author:"model"};if(s.verification){let l={...s.verification};if(l.browser==="verified"&&o.browserEvidence.length===0&&(l.browser=o.browserFailureEvidence.length>0?"failed":"not-run",r.push(`browser "verified" claim corrected to "${l.browser}" \u2014 no passing browser evidence was recorded this turn.`)),l.browser!=="verified"&&o.browserEvidence.length>0&&o.browserFailureEvidence.length===0){let d=l.browser;l.browser="verified",r.push(`browser "${d}" claim corrected to "verified" \u2014 passing browser evidence was recorded this turn.`)}l.build==="passed"&&!o.buildVerified&&(l.build=o.buildFailureEvidence.length>0?"failed":"not-run",r.push(`build "passed" claim corrected to "${l.build}" \u2014 no passing test/build run was recorded this turn.`)),s.verification=l}let i=Qm(n.activeTasks??[]);if(i.length>0&&(s.done?.length??0)>0){let l=[...s.notDone??[]];for(let d of i){let m=`Task ${eg(d)} is unresolved.`;l.includes(m)||l.push(m)}s.notDone=l,r.push(`${i.length} task item(s) remain unresolved; completion is not confirmed.`)}let a=o.recoveredBaseline?.writePaths??0,c=o.writePaths.slice(a).filter(l=>!Hc(l)&&!Vc(o,l));if((s.artifacts?.files?.length??0)>0||c.length>0){let l=o.writePaths.filter(C=>!Hc(C)&&!Vc(o,C)).map(ie),d=typeof s.artifacts?.root=="string"&&s.artifacts.root?s.artifacts.root:o.artifactRoot,m=C=>{let E=ie(C);return E?l.includes(E)||d&&l.includes(ie(`${d}/${C}`))?!0:l.some(O=>O.endsWith(`/${E}`)):!1},y=s.artifacts?.files??[],_=y.filter(C=>typeof C=="string"&&m(C)),h=y.length-_.length;h>0&&(s.artifacts={...s.artifacts,files:_},r.push(`${h} artifact file claim(s) removed \u2014 not present in the active write ledger.`));let v=0;for(let C of c){let E=ht(C),O=ie(E);_.some(M=>{let ee=ie(M);return ee===O||d&&ie(`${d}/${M}`)===O?!0:O.endsWith(`/${ee}`)})||(_.push(E),v+=1)}let k={...s.artifacts??{},files:_};!k.root&&o.artifactRoot&&(k.root=ht(o.artifactRoot)),s.artifacts=k,v>0&&r.push(`${v} artifact file(s) added from this turn's write ledger.`)}if(s.sources?.cited?.length){let l=new Set([...jw(t),...o.devServerUrls]),d=[];for(let y of s.sources.cited){if(typeof y!="string")continue;let _=jo(y);_&&l.has(_)&&!d.includes(_)&&d.push(_)}let m=s.sources.cited.length-d.length;m>0&&(s.sources={...s.sources,cited:d},r.push(`${m} cited source(s) removed \u2014 not seen in this turn's response or tool results.`))}return{claim:s,notices:r}}function Nw(e){let t=e.artifactContract,n=Iw[e.locale??"en"],o=Qm(e.activeTasks??[]),r=e.forcedStop?Lw(e.blockedToolCalls??[]):[],s=t.recoveredBaseline??{writePaths:0,devServerUrls:0,artifactRoot:!1},i=t.writePaths.slice(s.writePaths).filter(k=>!Hc(k)&&!Vc(t,k)),a=t.devServerUrls.slice(s.devServerUrls);if(!(!!t.artifactRoot&&!s.artifactRoot||i.length>0||a.length>0||t.browserVerified||t.outOfRootWrites.length>0||t.buildVerified||t.buildFailureEvidence.length>0)&&o.length===0&&r.length===0)return null;let l=[],d=[];o.length>0&&(l.push(n.notDoneUnresolvedTasks(o.length,o.map(eg).join("; "))),d.push(n.blockerResolveTasks)),t.outOfRootWrites.length>0&&(l.push(n.notDoneOutOfRoot),d.push(...t.outOfRootWrites.slice(0,3).map(k=>n.blockerOutOfRoot(k.toolName,k.path,k.artifactRoot)))),!t.buildVerified&&t.buildFailureEvidence.length>0&&(l.push(n.notDoneBuildFailing),d.push(n.blockerFixBuild(t.buildFailureEvidence[0].slice(0,200)))),r.length>0&&(l.push(n.notDoneTerminalBlockers),d.push(...r.slice(0,5).map(k=>n.blockerToolBlocked(k.name,k.reason))));let m=e.visibleToolCallCount??e.totalToolCallCount,y=[...e.visibleToolNames??e.distinctToolNames],h={schema:1,author:"engine",done:[m>0?n.doneRan(m,y.join(", ")||"unknown tools"):e.totalToolCallCount>0?n.doneNoToolCalls:n.doneNoToolWork],verification:{browser:t.browserVerified?"verified":t.browserFailureEvidence.length>0?"failed":"not-run",build:t.buildVerified?"passed":t.buildFailureEvidence.length>0?"failed":"not-run"},nextAction:d.length>0?n.nextActionResolveBlockers:n.nextActionProceed};l.length>0&&(h.notDone=l),d.length>0&&(h.blockers=d);let v={};return t.artifactRoot&&(v.root=ht(t.artifactRoot)),i.length>0&&(v.files=i.slice(0,8).map(ht)),a.length>0&&(v.urls=[...a]),Object.keys(v).length>0&&(h.artifacts=v),h}function Qm(e){return e.filter(t=>t.status!=="completed")}function eg(e){return`#${e.id} ${e.title} (${e.status})`}var Fw=new Set(["artifact-root-contract","identical-repeat-policy","invalid-arguments","not-offered","read-only-context-pack","tool-call-budget","variant-failure-policy"]);function Lw(e){return e.filter(t=>Fw.has(t.reason))}function jw(e){let t=[];for(let n of e.matchAll(Jc)){let o=jo(n[0]);o&&!t.includes(o)&&t.push(o)}return t}function el(e){try{return JSON.parse(e)}catch{return null}}function ns(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function tl(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(_w)){let o=n[1]??n[2],r=rs(o??"");if(r&&!Gw(r))return ht(r)}}function tg(e){let t=ht(rs(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Gc(t);let o=n.lastIndexOf("/src/");if(o>0)return t.slice(0,o);if(n.endsWith("/index.html")||n.endsWith("/vite.config.ts")||n.endsWith("/vite.config.js"))return Gc(t)}function Dw(e,t,n){let o=Ae(e);if(!(jn(o)||/^(?:preview_browser|computer_(?:act|observe)|browser(?:_.+)?)$/i.test(o))||/^read$/i.test(o)||n.includes("<persisted-output>")||nl(n)||/\b(?:syntax error|command not found|cannot find|not recognized|failed|failure|exception|traceback|eaddrinuse)\b|无法将|(?:发生|出现|报|加载|请求|页面|控制台|连接|断言|验证|测试|检查|等待|打开|访问)[^\n]{0,10}(?:错误|失败)|(?:错误|失败)(?:[::]|码|代码|信息|堆栈)/i.test(n))return!1;let s=Do(t);if(/^\s*agent-browser(?:\.exe)?\b/i.test(s)&&/\b(?:snapshot|get\s+(?:text|value)|screenshot)\b/i.test(s)&&n.trim().length>0)return!0;let i=jm.test(n),a=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
35
- ${n}`),c=jn(e)&&jm.test(t)&&i&&a&&/\b(?:ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n),l=/\b(?:200|ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n);return!(!c&&!(i&&a&&l)||Tw.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function Bw(e,t){let n=Ae(e);return Km.has(n)||Kc.has(n)||qm.has(n)||n==="send_file"?!0:os(t)&&/^(?:playwright|browser|computer|preview_browser|computer_(?:act|observe)|browser_.+)$/i.test(n)}function qw(e,t,n){if(!jn(e))return!1;let o=Do(t)||t;return!Rw.test(o)||!ww.test(`${o}
36
- ${n}`)||ng(n)||nl(n)?!1:xw.test(n)}function Uw(e){if(!e||!Array.isArray(e.uiAcceptanceEvidence))return[];let t=[];for(let n of e.uiAcceptanceEvidence){if(!n||typeof n!="object"||Array.isArray(n))continue;let o=n;typeof o.source!="string"||!kw.has(o.source)||o.status!=="passed"&&o.status!=="failed"||typeof o.summary!="string"||!o.summary.trim()||t.push({source:o.source,status:o.status,summary:o.summary})}return t}function zw(e,t,n){return/^read$/i.test(e)||!jn(e)?!1:/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion|waitforselector|test-browser|browser verification)\b|浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化/i.test(t)?!0:/\b(?:page\.waitForSelector|waitforselector|strict mode violation|browser closed|target closed|page crashed|locator\(|locator\.)\b/i.test(n)}function nl(e){return/\b(?:no failed|0 failed|without failed|no failures|failure:? none|failed checks?:? none|no errors?|0 errors?|zero errors?|error-free)\b/i.test(e)?!1:vw.test(e)?!0:/\b(?:fail(?:ed|ure)?|error)(?![\w-])/i.test(e)}function jn(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}var Hw=new RegExp(["(?:^|[\\s;&|(])(?:npm|pnpm|yarn|bun)\\s+(?:run\\s+)?(?:test|t|build|lint|typecheck|tsc|check)\\b","(?:^|[\\s;&|(])npx\\s+(?:-y\\s+)?(?:vitest|jest|mocha|tsc|playwright|ava|tap)\\b","(?:^|[\\s;&|(])(?:vitest|jest|mocha|ava|pytest|py\\.test|ctest|tsc)\\b","(?:^|[\\s;&|(])python\\s+-m\\s+(?:pytest|unittest)\\b","(?:^|[\\s;&|(])go\\s+test\\b","(?:^|[\\s;&|(])cargo\\s+(?:test|build|check)\\b","(?:^|[\\s;&|(])(?:mvn|gradle|gradlew|make|cmake)\\s+\\S","(?:^|[\\s;&|(])node\\s+(?:--test\\b|[^\\n;&|]*test[^\\n;&|]*\\.[cm]?js)"].join("|"),"i");function Do(e){let t=el(e);return t&&typeof t.command=="string"?t.command:""}function Vw(e,t){return jn(e)?Hw.test(Do(t)):!1}function ng(e){return/\[exit [1-9]\d*\b|\(exit code [1-9]\d*\b|\[interrupted — exit code [1-9]\d*/.test(e)}function Gw(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function og(e,t){let n=ie(e),o=ie(t);return n===o||n.startsWith(`${o}/`)}function Ww(e){return ie(e).split("/").includes("context-pack")}function Hc(e){return ie(e).split("/").includes(".qla-tmp")}function Vc(e,t){let n=ie(t);return e.deletedPaths.some(o=>ie(o)===n)}function ie(e){return rs(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function ht(e){return rs(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function jo(e){let t=e.replace(/[).,;]+$/u,"");if(t.endsWith(":"))return null;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"||!n.hostname?null:t}catch{return null}}function rs(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function Kw(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Gc(e){let t=ht(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Jw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zw(e,t){if(e.length!==1||!ki(e[0]?.function.name??"","stt"))return!1;let n=[...t].reverse().find(r=>r.role==="user");return n?Array.isArray(n.audioUrls)&&n.audioUrls.some(r=>typeof r=="string"&&r.trim()):!1}function Qw(e,t){let n=e0(t);if(!n)return null;let o=t0(n);if(!o)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`[transcription]
37
- AUDIO_STT_RESULT ${i[1]} ${o}`:`[transcription]
38
- ${o}`}function e0(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let o of t)if(typeof o=="string"&&o.trim())return o.trim();let n=e.message?.content;return typeof n=="string"?n.trim():""}function t0(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function $(e){return[...new Set(e.map(t=>t.function.name))].sort()}function ss(e){let t=new Set,n=[];for(let o of e){let r=`${o.name}\0${o.reason}`;t.has(r)||(t.add(r),n.push(o))}return n.sort((o,r)=>`${o.name}:${o.reason}`.localeCompare(`${r.name}:${r.reason}`))}function n0(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>rg(i.reason)-rg(a.reason))[0];return t.includes(e)?s?`${e}=policy-filtered:${s.reason}`:n.includes(e)?o.includes(e)?`${e}=called`:`${e}=enabled-not-used`:`${e}=policy-filtered:not-enabled`:`${e}=not-exposed`}function rg(e){return e==="invalid-arguments"?0:e==="blocked-by-policy"||e.startsWith("policy-suppressed:")?1:e==="confirmation-timeout"?2:e==="read-only-context-pack"?4:e==="not-offered"?5:e==="read-cycle-policy"?6:e==="identical-repeat-policy"?7:e==="variant-failure-policy"?8:10}function sg(e){let t=typeof e.blockReason=="string"?e.blockReason:void 0;if(e.blocked&&/confirmation timed out/i.test(t??""))return"confirmation-timeout";if(e.blocked)return"blocked-by-policy";let n=Cg(e.details);if(n==="not-applied")return"mcp-outcome-not-applied";if(n==="indeterminate")return"mcp-outcome-indeterminate";let o=typeof e.details?.error=="string"?e.details.error:void 0;if(o==="existing_file_update_tool_required")return"existing-file-update-tool-required";if(o==="invalid_arguments")return"invalid-arguments";if(o==="blocked_global_process_kill")return"global-process-kill-blocked";if(o==="blocked_by_guard")return"blocked-by-policy";if(o==="semantic_quality_failed")return"semantic-quality-failed"}function o0(e,t){let n=e.failedCallIds.length+e.blockedCallIds.length;return t==="zh"?n>0?`\u26A0\uFE0F \u65E0\u6CD5\u63D0\u4F9B\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7B54\u6848\uFF1A\u672C\u8F6E\u8981\u6C42\u4F7F\u7528\u6700\u65B0\u5DE5\u5177\u8BC1\u636E\uFF0C\u4F46 ${n} \u6B21\u5B9E\u9645\u8C03\u7528\u5747\u5931\u8D25\u6216\u88AB\u963B\u6B62\u3002\u4E3A\u907F\u514D\u8F93\u51FA\u672A\u7ECF\u9A8C\u8BC1\u7684\u4E8B\u5B9E\uFF0C\u672C\u8F6E\u5DF2\u505C\u6B62\u4F5C\u7B54\u3002`:"\u26A0\uFE0F \u65E0\u6CD5\u63D0\u4F9B\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7B54\u6848\uFF1A\u672C\u8F6E\u8981\u6C42\u4F7F\u7528\u6700\u65B0\u5DE5\u5177\u8BC1\u636E\uFF0C\u4F46\u6CA1\u6709\u6210\u529F\u5B8C\u6210\u4EFB\u4F55\u5DE5\u5177\u8C03\u7528\u3002\u4E3A\u907F\u514D\u8F93\u51FA\u672A\u7ECF\u9A8C\u8BC1\u7684\u4E8B\u5B9E\uFF0C\u672C\u8F6E\u5DF2\u505C\u6B62\u4F5C\u7B54\u3002":n>0?`\u26A0\uFE0F I could not produce a verified answer: this turn required fresh tool evidence, but all ${n} attempted calls failed or were blocked. I stopped instead of returning unverified facts.`:"\u26A0\uFE0F I could not produce a verified answer: this turn required fresh tool evidence, but no tool call completed successfully. I stopped instead of returning unverified facts."}function us(e){return Fu(e.function.name,e.meta?.identity)}function yt(e,t){let n=new Map(e.map(o=>[o.function.name,o]));for(let o of t)us(o)&&n.set(o.function.name,o);return[...n.values()]}function bt(e,...t){return e.filter(n=>us(n)||t.every(o=>!o.has(n.function.name)))}function ol(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function r0(e){if(!e)return;let t=e.trim();return(t.match(/Last error:\s*(.+?)\.\s*Do not retry\./s)?.[1]?.trim()??t).slice(0,600).trim()||void 0}function s0(e){let n=We(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var ds=5174;function ig(e,t){let n=String(t);return[new RegExp(`(?:^|\\s)--port(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:^|\\s)-p(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[?::1\\]?):${n}\\b`,"i")].some(r=>r.test(e))}function i0(e){return/\b(vite|npx\s+vite|pnpm\s+(?:run\s+)?dev|npm\s+(?:run\s+)?dev|yarn\s+(?:run\s+)?dev)\b/i.test(e)}function vg(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function a0(e){if(vg(e))return e;let t=/\s+(?:\d?>&\d|\d?>\s*\S+|>\s*\S+|<\s*\S+).*$/.exec(e);return!t||t.index===void 0?`${e.trim()} --strictPort`:`${e.slice(0,t.index).trim()} --strictPort${e.slice(t.index)}`}function ag(e,t){let n=We(e)??{};return JSON.stringify({...n,command:t})}function c0(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function l0(e){return ig(e,ds)?{action:"block",error:"Command blocked: port 5174 is reserved for the Xiaozhi Claw frontend. Start generated apps on an explicit non-5174 port and include --strictPort when using Vite."}:i0(e)&&ig(e,ds-1)&&!vg(e)?{action:"rewrite",command:a0(e)}:null}function u0(e){let t=e.buildFailureEvidence[0];return"The test/build you ran is still FAILING, so the task is not complete. "+(t?`Last failing output:
39
- ${t.slice(0,600)}
40
- `:"")+"Do not finish or claim success from source inspection. Diagnose the failure, edit the source to fix the root cause, then RE-RUN the same test/build command via exec. Repeat until the command exits 0 (passes), then report the passing output. Do NOT modify, weaken, or delete the test/assertions to force a pass."}function Tg(e){let n=We(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var is=4;function cg(e,t){if(/^(?:write|edit|patch)$/i.test(e)){let n=We(t),o=n?["path","file_path","filePath","filename","file"].map(r=>n[r]).find(r=>typeof r=="string"):void 0;return o?`edit:${o.replace(/\\/g,"/").toLowerCase()}`:null}if(/^exec$/i.test(e)){let n=Tg(t);if(!n||sm(n))return null;let o=Io(n);return rm(o)?null:`exec:${o}`}if(/^task$/i.test(e)){let n=We(t);if(n?.action!=="output")return null;let o=[...typeof n.taskId=="string"?[n.taskId]:[],...Array.isArray(n.taskIds)?n.taskIds.filter(r=>typeof r=="string"):[]].map(r=>r.trim()).filter(Boolean).sort();return o.length>0?`task-output:${[...new Set(o)].join(",")}`:null}return null}function d0(e){return e.split(/\r?\n/u).filter(t=>!/\b__dirlock\b/iu.test(t)).map(t=>t.replace(/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b/gu,"<timestamp>").replace(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}\s+\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AP]M)?\b/giu,"<timestamp>").replace(/\b\d{1,2}:\d{2}:\d{2}(?:\.\d+)?\b/gu,"<time>").replace(/\b(elapsed(?:Ms|Seconds)?|duration(?:Ms|Seconds)?)\s*[:=]\s*\d+(?:\.\d+)?\b/giu,"$1=<elapsed>").replace(/\b(?:running\s+for|elapsed)\s+\d+(?:\.\d+)?\s*(?:ms|s|sec(?:onds?)?|m|min(?:utes?)?)\b/giu,"elapsed <elapsed>").replace(/\s+/gu," ").trim()).filter(Boolean).join(`
41
- `)}function f0(e,t,n){if(/^exec$/i.test(e))return`exec:${d0(n)||"<empty-observation>"}`;if(/^task$/i.test(e)&&t&&typeof t=="object"){let o=t;if(o.action!=="output")return null;let s=(Array.isArray(o.tasks)?o.tasks:[o]).filter(i=>i!==null&&typeof i=="object").map(i=>({taskId:typeof i.taskId=="string"?i.taskId:"",lifecycle:typeof i.lifecycle=="string"?i.lifecycle:"",running:i.running===!0,stateRevision:typeof i.stateRevision=="number"?i.stateRevision:0,outputBytes:typeof i.outputBytes=="number"?i.outputBytes:0,outputDigest:typeof i.outputDigest=="string"?i.outputDigest:""})).filter(i=>i.taskId).sort((i,a)=>i.taskId.localeCompare(a.taskId));return s.length>0?`task:${JSON.stringify(s)}`:null}return null}function lg(e){let t=Tg(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function p0(){return"Browser automation prerequisites are already installed, so do not repeat the installation. If visible-UI acceptance is relevant, first reuse any reliable evidence already present: browser automation, passing frontend UI/component tests, explicit user screenshot or confirmation, external benchmark UI events, or a verifier sub-agent's structured UI evidence. If evidence is still missing, choose the smallest proportionate validation method for this task. Browser automation is one option, not a required tool."}function m0(e){return[`Quick task-list status sync: the list still shows unresolved item(s): ${e.filter(n=>n.status!=="completed").map(n=>`#${n.id} ${n.title} (${n.status})`).join("; ")}.`,"If your final answer already shows these are done, just mark them completed with the task tool to match \u2014 this is a status sync, not a request to redo work.","Mark items completed only if the work is actually done and verified; otherwise mark them blocked/cancelled if the task tool supports that status, or keep them unresolved and report the blocker.","Do not produce a final completion claim until task status and the final answer agree."].join(" ")}function g0(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function ug(e,t){let n=t.blockedToolCalls.length>0?t.blockedToolCalls.map(s=>`${s.name}:${s.reason}`).join(", "):"none",r=[...new Set([...t.toolCallNames,"write","edit","patch"])].sort().map(s=>n0(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
42
-
43
- Tool availability diagnostics:
44
- availableToolNames: ${t.availableToolNames.join(", ")}
45
- enabledToolNames: ${t.enabledToolNames.join(", ")}
46
- toolCallNames: ${t.toolCallNames.join(", ")||"none"}
47
- blockedToolCalls: ${n}
48
- attribution: ${r}`}function Oe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function il(e,t){if(!e)return null;let n=Oe(e.function.parameters),o=Oe(n?.properties)??{},r=Array.isArray(n?.required)?n.required.filter(a=>typeof a=="string"&&a.trim().length>0):[],s=We(t);if(!s)return`Tool "${e.function.name}" arguments must be a JSON object.`;for(let a of r){let c=s[a];if(typeof c=="string"?c.trim().length===0:c==null)return`Tool "${e.function.name}" missing required field \`${a}\`. Use the tool schema exactly instead of substituting another field.${y0(e.function.name)}`}if(n?.additionalProperties===!1){let a=new Set(Object.keys(o)),c=Object.keys(s).filter(l=>!a.has(l));if(c.length>0){let l=[...a].map(d=>`\`${d}\``).join(", ")||"none";return`Tool "${e.function.name}" has unexpected field${c.length===1?"":"s"} ${c.map(d=>`\`${d}\``).join(", ")}. Remove ${c.length===1?"it":"them"}; the only allowed fields are ${l}. Use the canonical tool schema exactly and do not retry the rejected arguments unchanged.`}}let i=Qp(e.function.name,n??void 0,t);return i.ok?null:i.error??`Tool "${e.function.name}" arguments do not match the offered schema.`}function dg(e,t){let n=Oe(e.function.parameters),o=Oe(n?.properties),r=We(t);if(!n||!o||!r||il(e,t)||Object.keys(r).some(s=>!Object.hasOwn(o,s)))return!1;for(let[s,i]of Object.entries(r)){let a=Oe(o[s]);if(!a)continue;let c=a.type;if(c==="string"&&typeof i!="string"||c==="array"&&!Array.isArray(i)||c==="object"&&Oe(i)===null||c==="boolean"&&typeof i!="boolean"||c==="number"&&typeof i!="number"||c==="integer"&&!Number.isInteger(i)||Array.isArray(a.enum)&&!a.enum.some(l=>Object.is(l,i)))return!1}return!0}function h0(e,t){let n=t.find(r=>r.function.name===e.function.name);if(!n||dg(n,e.function.arguments))return{call:e};let o=t.filter(r=>r.function.name!==e.function.name&&dg(r,e.function.arguments));return o.length!==1?{call:e}:{originalName:e.function.name,call:{...e,function:{...e.function,name:o[0].function.name}}}}function y0(e){return e==="search"?' Retry search with `mode` and `pattern`, for example {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}.':e==="exec"?" Retry exec with `command` only, or switch to read/search/write/edit/patch for file paths and file maintenance.":""}function on(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="string"?n:void 0}var b0=new Set(["astraclaw","astraclaw_developer","astraclaw_media","astraclaw_memory","astraclaw_workflow"]);function fg(e,t){let n=e?.meta?.identity;if(n?.schemaVersion===1&&n.wireName===t)return n;let o=e?.meta?.category,r=Ae(t),s=Lu(t),a=o==="orchestration"?"orchestration":r==="skill_search"||r==="skill_load"||r==="skill_resource_read"?"skill":s!==void 0||o==="mcp"?"mcp":"builtin",c=s!==void 0&&b0.has(s)?"host":"agent";return{schemaVersion:1,wireName:t,logicalName:r,family:a,owner:c,...s?{serverId:s}:{},capabilityId:`${c}:${s??"native"}:${r}`}}function cs(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function _0(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function kg(e){if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.mcpStructuredContent;if(!t||typeof t!="object"||Array.isArray(t))return[];let n=[],o=t;for(let r=0;r<3&&!(!o||typeof o!="object"||Array.isArray(o));r+=1){let s=o;n.push(s),o=s.structuredContent}return n}function Cg(e){for(let t of kg(e)){let n=t.outcome??t.status;if(n==="committed"||n==="not-applied"||n==="indeterminate")return n}}function v0(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e.mcpExecutionControl;if((!n||typeof n!="object"||Array.isArray(n))&&(n=kg(e).map(s=>s.executionControl).find(s=>s&&typeof s=="object"&&!Array.isArray(s))),!n||typeof n!="object"||Array.isArray(n))return;let o=n;if(o.status!=="blocked"||o.scope!=="turn"&&o.scope!=="interaction-step"||o.retryable!==!1||typeof o.reason!="string"||!o.reason.trim()||!Array.isArray(o.allowedNextTools)||o.allowedNextTools.length===0||!o.allowedNextTools.every(s=>typeof s=="string"&&s.trim()))return;let r=[...new Set(o.allowedNextTools.map(s=>fl(s)).filter(Boolean))];if(r.length!==0)return{status:"blocked",scope:o.scope,retryable:!1,reason:o.reason.trim().slice(0,160),allowedNextTools:r}}function fl(e){return e.trim().toLowerCase().replace(/[^a-z0-9_]/gu,"_")}function rl(e,t){return t.allowedNextTools.includes(fl(Ae(e)))}function pg(e){return{role:"system",content:`Background sub-agent result(s) became available while you continued the main task. The bounded structured results are included below; incorporate them when useful. Do not poll, cancel, or relaunch these tasks merely to acknowledge this update.
8
+ deps: ${n}}`};var Eg={keyword:"dependencies",type:"object",schemaType:"object",error:Oe.error,code(e){let[t,n]=wg(e);ac(e,t),lc(e,n)}};function wg({schema:e}){let t={},n={};for(let r in e){if(r==="__proto__")continue;let o=Array.isArray(e[r])?t:n;o[r]=e[r]}return[t,n]}function ac(e,t=e.schema){let{gen:n,data:r,it:o}=e;if(Object.keys(t).length===0)return;let s=n.let("missing");for(let i in t){let l=t[i];if(l.length===0)continue;let a=(0,bn.propertyInData)(n,r,i,o.opts.ownProperties);e.setParams({property:i,depsCount:l.length,deps:l.join(", ")}),o.allErrors?n.if(a,()=>{for(let c of l)(0,bn.checkReportMissingProp)(e,c)}):(n.if((0,ws._)`${a} && (${(0,bn.checkMissingProp)(e,l,s)})`),(0,bn.reportMissingProp)(e,s),n.else())}}Oe.validatePropertyDeps=ac;function lc(e,t=e.schema){let{gen:n,data:r,keyword:o,it:s}=e,i=n.name("valid");for(let l in t)(0,Rg.alwaysValidSchema)(s,t[l])||(n.if((0,bn.propertyInData)(n,r,l,s.opts.ownProperties),()=>{let a=e.subschema({keyword:o,schemaProp:l},i);e.mergeValidEvaluated(a,i)},()=>n.var(i,!0)),e.ok(i))}Oe.validateSchemaDeps=lc;Oe.default=Eg});var uc=v($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var cc=S(),$g=M(),Sg={message:"property name must be valid",params:({params:e})=>(0,cc._)`{propertyName: ${e.propertyName}}`},xg={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Sg,code(e){let{gen:t,schema:n,data:r,it:o}=e;if((0,$g.alwaysValidSchema)(o,n))return;let s=t.name("valid");t.forIn("key",r,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,cc.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};$s.default=xg});var xs=v(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var hr=me(),Ee=S(),Pg=pe(),gr=M(),Ag={message:"must NOT have additional properties",params:({params:e})=>(0,Ee._)`{additionalProperty: ${e.additionalProperty}}`},Mg={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Ag,code(e){let{gen:t,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:l,opts:a}=i;if(i.props=!0,a.removeAdditional!=="all"&&(0,gr.alwaysValidSchema)(i,n))return;let c=(0,hr.allSchemaProperties)(r.properties),u=(0,hr.allSchemaProperties)(r.patternProperties);d(),e.ok((0,Ee._)`${s} === ${Pg.default.errors}`);function d(){t.forIn("key",o,m=>{!c.length&&!u.length?p(m):t.if(h(m),()=>p(m))})}function h(m){let _;if(c.length>8){let E=(0,gr.schemaRefOrVal)(i,r.properties,"properties");_=(0,hr.isOwnProperty)(t,E,m)}else c.length?_=(0,Ee.or)(...c.map(E=>(0,Ee._)`${m} === ${E}`)):_=Ee.nil;return u.length&&(_=(0,Ee.or)(_,...u.map(E=>(0,Ee._)`${(0,hr.usePattern)(e,E)}.test(${m})`))),(0,Ee.not)(_)}function T(m){t.code((0,Ee._)`delete ${o}[${m}]`)}function p(m){if(a.removeAdditional==="all"||a.removeAdditional&&n===!1){T(m);return}if(n===!1){e.setParams({additionalProperty:m}),e.error(),l||t.break();return}if(typeof n=="object"&&!(0,gr.alwaysValidSchema)(i,n)){let _=t.name("valid");a.removeAdditional==="failing"?(f(m,_,!1),t.if((0,Ee.not)(_),()=>{e.reset(),T(m)})):(f(m,_),l||t.if((0,Ee.not)(_),()=>t.break()))}}function f(m,_,E){let w={keyword:"additionalProperties",dataProp:m,dataPropType:gr.Type.Str};E===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(w,_)}}};Ss.default=Mg});var pc=v(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Og=sn(),dc=me(),Ps=M(),fc=xs(),Ig={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&fc.default.code(new Og.KeywordCxt(s,fc.default,"additionalProperties"));let i=(0,dc.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Ps.mergeEvaluated.props(t,(0,Ps.toHash)(i),s.props));let l=i.filter(d=>!(0,Ps.alwaysValidSchema)(s,n[d]));if(l.length===0)return;let a=t.name("valid");for(let d of l)c(d)?u(d):(t.if((0,dc.propertyInData)(t,o,d,s.opts.ownProperties)),u(d),s.allErrors||t.else().var(a,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(a);function c(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},a)}}};As.default=Ig});var yc=v(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var mc=me(),yr=S(),hc=M(),gc=M(),Ng={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,data:r,parentSchema:o,it:s}=e,{opts:i}=s,l=(0,mc.allSchemaProperties)(n),a=l.filter(f=>(0,hc.alwaysValidSchema)(s,n[f]));if(l.length===0||a.length===l.length&&(!s.opts.unevaluated||s.props===!0))return;let c=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=t.name("valid");s.props!==!0&&!(s.props instanceof yr.Name)&&(s.props=(0,gc.evaluatedPropsToName)(t,s.props));let{props:d}=s;h();function h(){for(let f of l)c&&T(f),s.allErrors?p(f):(t.var(u,!0),p(f),t.if(u))}function T(f){for(let m in c)new RegExp(f).test(m)&&(0,hc.checkStrictMode)(s,`property ${m} matches pattern ${f} (use allowMatchingProperties)`)}function p(f){t.forIn("key",r,m=>{t.if((0,yr._)`${(0,mc.usePattern)(e,f)}.test(${m})`,()=>{let _=a.includes(f);_||e.subschema({keyword:"patternProperties",schemaProp:f,dataProp:m,dataPropType:gc.Type.Str},u),s.opts.unevaluated&&d!==!0?t.assign((0,yr._)`${d}[${m}]`,!0):!_&&!s.allErrors&&t.if((0,yr.not)(u),()=>t.break())})})}}};Ms.default=Ng});var _c=v(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var jg=M(),Lg={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:n,it:r}=e;if((0,jg.alwaysValidSchema)(r,n)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Os.default=Lg});var Tc=v(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var qg=me(),Dg={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:qg.validateUnion,error:{message:"must match a schema in anyOf"}};Is.default=Dg});var vc=v(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var _r=S(),Fg=M(),Ug={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,_r._)`{passingSchemas: ${e.passing}}`},Bg={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Ug,code(e){let{gen:t,schema:n,parentSchema:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,i=t.let("valid",!1),l=t.let("passing",null),a=t.name("_valid");e.setParams({passing:l}),t.block(c),e.result(i,()=>e.reset(),()=>e.error(!0));function c(){s.forEach((u,d)=>{let h;(0,Fg.alwaysValidSchema)(o,u)?t.var(a,!0):h=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},a),d>0&&t.if((0,_r._)`${a} && ${i}`).assign(i,!1).assign(l,(0,_r._)`[${l}, ${d}]`).else(),t.if(a,()=>{t.assign(i,!0),t.assign(l,d),h&&e.mergeEvaluated(h,_r.Name)})})}}};Ns.default=Bg});var bc=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var zg=M(),Vg={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=t.name("valid");n.forEach((s,i)=>{if((0,zg.alwaysValidSchema)(r,s))return;let l=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(l)})}};js.default=Vg});var Rc=v(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var Tr=S(),Cc=M(),Kg={message:({params:e})=>(0,Tr.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Tr._)`{failingKeyword: ${e.ifClause}}`},Gg={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Kg,code(e){let{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,Cc.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=kc(r,"then"),s=kc(r,"else");if(!o&&!s)return;let i=t.let("valid",!0),l=t.name("_valid");if(a(),e.reset(),o&&s){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(l,c("then",u),c("else",u))}else o?t.if(l,c("then")):t.if((0,Tr.not)(l),c("else"));e.pass(i,()=>e.error(!0));function a(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},l);e.mergeEvaluated(u)}function c(u,d){return()=>{let h=e.subschema({keyword:u},l);t.assign(i,l),e.mergeValidEvaluated(h,i),d?t.assign(d,(0,Tr._)`${u}`):e.setParams({ifClause:u})}}}};function kc(e,t){let n=e.schema[t];return n!==void 0&&!(0,Cc.alwaysValidSchema)(e,n)}Ls.default=Gg});var Ec=v(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var Hg=M(),Wg={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,Hg.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};qs.default=Wg});var wc=v(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var Jg=bs(),Yg=rc(),Xg=ks(),Qg=sc(),Zg=ic(),ey=mr(),ty=uc(),ny=xs(),ry=pc(),oy=yc(),sy=_c(),iy=Tc(),ay=vc(),ly=bc(),cy=Rc(),uy=Ec();function dy(e=!1){let t=[sy.default,iy.default,ay.default,ly.default,cy.default,uy.default,ty.default,ny.default,ey.default,ry.default,oy.default];return e?t.push(Yg.default,Qg.default):t.push(Jg.default,Xg.default),t.push(Zg.default),t}Ds.default=dy});var Us=v(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.dynamicAnchor=void 0;var Fs=S(),fy=pe(),$c=ln(),py=lr(),my={keyword:"$dynamicAnchor",schemaType:"string",code:e=>Sc(e,e.schema)};function Sc(e,t){let{gen:n,it:r}=e;r.schemaEnv.root.dynamicAnchors[t]=!0;let o=(0,Fs._)`${fy.default.dynamicAnchors}${(0,Fs.getProperty)(t)}`,s=r.errSchemaPath==="#"?r.validateName:hy(e);n.if((0,Fs._)`!${o}`,()=>n.assign(o,s))}kn.dynamicAnchor=Sc;function hy(e){let{schemaEnv:t,schema:n,self:r}=e.it,{root:o,baseId:s,localRefs:i,meta:l}=t.root,{schemaId:a}=r.opts,c=new $c.SchemaEnv({schema:n,schemaId:a,root:o,baseId:s,localRefs:i,meta:l});return $c.compileSchema.call(r,c),(0,py.getValidate)(e,c)}kn.default=my});var Bs=v(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.dynamicRef=void 0;var xc=S(),gy=pe(),Pc=lr(),yy={keyword:"$dynamicRef",schemaType:"string",code:e=>Ac(e,e.schema)};function Ac(e,t){let{gen:n,keyword:r,it:o}=e;if(t[0]!=="#")throw new Error(`"${r}" only supports hash fragment reference`);let s=t.slice(1);if(o.allErrors)i();else{let a=n.let("valid",!1);i(a),e.ok(a)}function i(a){if(o.schemaEnv.root.dynamicAnchors[s]){let c=n.let("_v",(0,xc._)`${gy.default.dynamicAnchors}${(0,xc.getProperty)(s)}`);n.if(c,l(c,a),l(o.validateName,a))}else l(o.validateName,a)()}function l(a,c){return c?()=>n.block(()=>{(0,Pc.callRef)(e,a),n.let(c,!0)}):()=>(0,Pc.callRef)(e,a)}}Cn.dynamicRef=Ac;Cn.default=yy});var Mc=v(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var _y=Us(),Ty=M(),vy={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,_y.dynamicAnchor)(e,""):(0,Ty.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};zs.default=vy});var Oc=v(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var by=Bs(),ky={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,by.dynamicRef)(e,e.schema)};Vs.default=ky});var Ic=v(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Cy=Us(),Ry=Bs(),Ey=Mc(),wy=Oc(),$y=[Cy.default,Ry.default,Ey.default,wy.default];Ks.default=$y});var jc=v(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var Nc=mr(),Sy={keyword:"dependentRequired",type:"object",schemaType:"object",error:Nc.error,code:e=>(0,Nc.validatePropertyDeps)(e)};Gs.default=Sy});var Lc=v(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var xy=mr(),Py={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,xy.validateSchemaDeps)(e)};Hs.default=Py});var qc=v(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var Ay=M(),My={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){t.contains===void 0&&(0,Ay.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};Ws.default=My});var Dc=v(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Oy=jc(),Iy=Lc(),Ny=qc(),jy=[Oy.default,Iy.default,Ny.default];Js.default=jy});var Uc=v(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var He=S(),Fc=M(),Ly=pe(),qy={message:"must NOT have unevaluated properties",params:({params:e})=>(0,He._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},Dy={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:qy,code(e){let{gen:t,schema:n,data:r,errsCount:o,it:s}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:i,props:l}=s;l instanceof He.Name?t.if((0,He._)`${l} !== true`,()=>t.forIn("key",r,d=>t.if(c(l,d),()=>a(d)))):l!==!0&&t.forIn("key",r,d=>l===void 0?a(d):t.if(u(l,d),()=>a(d))),s.props=!0,e.ok((0,He._)`${o} === ${Ly.default.errors}`);function a(d){if(n===!1){e.setParams({unevaluatedProperty:d}),e.error(),i||t.break();return}if(!(0,Fc.alwaysValidSchema)(s,n)){let h=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Fc.Type.Str},h),i||t.if((0,He.not)(h),()=>t.break())}}function c(d,h){return(0,He._)`!${d} || !${d}[${h}]`}function u(d,h){let T=[];for(let p in d)d[p]===!0&&T.push((0,He._)`${h} !== ${p}`);return(0,He.and)(...T)}}};Ys.default=Dy});var zc=v(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var dt=S(),Bc=M(),Fy={message:({params:{len:e}})=>(0,dt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,dt._)`{limit: ${e}}`},Uy={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Fy,code(e){let{gen:t,schema:n,data:r,it:o}=e,s=o.items||0;if(s===!0)return;let i=t.const("len",(0,dt._)`${r}.length`);if(n===!1)e.setParams({len:s}),e.fail((0,dt._)`${i} > ${s}`);else if(typeof n=="object"&&!(0,Bc.alwaysValidSchema)(o,n)){let a=t.var("valid",(0,dt._)`${i} <= ${s}`);t.if((0,dt.not)(a),()=>l(a,s)),e.ok(a)}o.items=!0;function l(a,c){t.forRange("i",c,i,u=>{e.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:Bc.Type.Num},a),o.allErrors||t.if((0,dt.not)(a),()=>t.break())})}}};Xs.default=Uy});var Vc=v(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var By=Uc(),zy=zc(),Vy=[By.default,zy.default];Qs.default=Vy});var Kc=v(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var G=S(),Ky={message:({schemaCode:e})=>(0,G.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,G._)`{format: ${e}}`},Gy={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Ky,code(e,t){let{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:l}=e,{opts:a,errSchemaPath:c,schemaEnv:u,self:d}=l;if(!a.validateFormats)return;o?h():T();function h(){let p=n.scopeValue("formats",{ref:d.formats,code:a.code.formats}),f=n.const("fDef",(0,G._)`${p}[${i}]`),m=n.let("fType"),_=n.let("format");n.if((0,G._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>n.assign(m,(0,G._)`${f}.type || "string"`).assign(_,(0,G._)`${f}.validate`),()=>n.assign(m,(0,G._)`"string"`).assign(_,f)),e.fail$data((0,G.or)(E(),w()));function E(){return a.strictSchema===!1?G.nil:(0,G._)`${i} && !${_}`}function w(){let q=u.$async?(0,G._)`(${f}.async ? await ${_}(${r}) : ${_}(${r}))`:(0,G._)`${_}(${r})`,R=(0,G._)`(typeof ${_} == "function" ? ${q} : ${_}.test(${r}))`;return(0,G._)`${_} && ${_} !== true && ${m} === ${t} && !${R}`}}function T(){let p=d.formats[s];if(!p){E();return}if(p===!0)return;let[f,m,_]=w(p);f===t&&e.pass(q());function E(){if(a.strictSchema===!1){d.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${s}" ignored in schema at path "${c}"`}}function w(R){let Q=R instanceof RegExp?(0,G.regexpCode)(R):a.code.formats?(0,G._)`${a.code.formats}${(0,G.getProperty)(s)}`:void 0,W=n.scopeValue("formats",{key:s,ref:R,code:Q});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,G._)`${W}.validate`]:["string",R,W]}function q(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!u.$async)throw new Error("async format in sync schema");return(0,G._)`await ${_}(${r})`}return typeof m=="function"?(0,G._)`${_}(${r})`:(0,G._)`${_}.test(${r})`}}}};Zs.default=Gy});var Gc=v(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});var Hy=Kc(),Wy=[Hy.default];ei.default=Wy});var Hc=v(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.contentVocabulary=Mt.metadataVocabulary=void 0;Mt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Mt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Jc=v(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});var Jy=Dl(),Yy=Zl(),Xy=wc(),Qy=Ic(),Zy=Dc(),e_=Vc(),t_=Gc(),Wc=Hc(),n_=[Qy.default,Jy.default,Yy.default,(0,Xy.default)(!0),t_.default,Wc.metadataVocabulary,Wc.contentVocabulary,Zy.default,e_.default];ti.default=n_});var Xc=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.DiscrError=void 0;var Yc;(function(e){e.Tag="tag",e.Mapping="mapping"})(Yc||(vr.DiscrError=Yc={}))});var Zc=v(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var Ot=S(),ni=Xc(),Qc=ln(),r_=an(),o_=M(),s_={message:({params:{discrError:e,tagName:t}})=>e===ni.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Ot._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},i_={keyword:"discriminator",type:"object",schemaType:"object",error:s_,code(e){let{gen:t,data:n,schema:r,parentSchema:o,it:s}=e,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let l=r.propertyName;if(typeof l!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let a=t.let("valid",!1),c=t.const("tag",(0,Ot._)`${n}${(0,Ot.getProperty)(l)}`);t.if((0,Ot._)`typeof ${c} == "string"`,()=>u(),()=>e.error(!1,{discrError:ni.DiscrError.Tag,tag:c,tagName:l})),e.ok(a);function u(){let T=h();t.if(!1);for(let p in T)t.elseIf((0,Ot._)`${c} === ${p}`),t.assign(a,d(T[p]));t.else(),e.error(!1,{discrError:ni.DiscrError.Mapping,tag:c,tagName:l}),t.endIf()}function d(T){let p=t.name("valid"),f=e.subschema({keyword:"oneOf",schemaProp:T},p);return e.mergeEvaluated(f,Ot.Name),p}function h(){var T;let p={},f=_(o),m=!0;for(let q=0;q<i.length;q++){let R=i[q];if(R?.$ref&&!(0,o_.schemaHasRulesButRef)(R,s.self.RULES)){let W=R.$ref;if(R=Qc.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,W),R instanceof Qc.SchemaEnv&&(R=R.schema),R===void 0)throw new r_.default(s.opts.uriResolver,s.baseId,W)}let Q=(T=R?.properties)===null||T===void 0?void 0:T[l];if(typeof Q!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${l}"`);m=m&&(f||_(R)),E(Q,q)}if(!m)throw new Error(`discriminator: "${l}" must be required`);return p;function _({required:q}){return Array.isArray(q)&&q.includes(l)}function E(q,R){if(q.const)w(q.const,R);else if(q.enum)for(let Q of q.enum)w(Q,R);else throw new Error(`discriminator: "properties/${l}" must have "const" or "enum"`)}function w(q,R){if(typeof q!="string"||q in p)throw new Error(`discriminator: "${l}" values must be unique strings`);p[q]=R}}}};ri.default=i_});var eu=v((p0,a_)=>{a_.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var tu=v((m0,l_)=>{l_.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var nu=v((h0,c_)=>{c_.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var ru=v((g0,u_)=>{u_.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var ou=v((y0,d_)=>{d_.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var su=v((_0,f_)=>{f_.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var iu=v((T0,p_)=>{p_.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var au=v((v0,m_)=>{m_.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var lu=v(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var h_=eu(),g_=tu(),y_=nu(),__=ru(),T_=ou(),v_=su(),b_=iu(),k_=au(),C_=["/properties"];function R_(e){return[h_,g_,y_,__,T_,t(this,v_),b_,t(this,k_)].forEach(n=>this.addMetaSchema(n,void 0,!1)),this;function t(n,r){return e?n.$dataMetaSchema(r,C_):r}}oi.default=R_});var cu=v((K,ii)=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.MissingRefError=K.ValidationError=K.CodeGen=K.Name=K.nil=K.stringify=K.str=K._=K.KeywordCxt=K.Ajv2020=void 0;var E_=Il(),w_=Jc(),$_=Zc(),S_=lu(),si="https://json-schema.org/draft/2020-12/schema",It=class extends E_.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),w_.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword($_.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:n}=this.opts;n&&(S_.default.call(this,t),this.refs["http://json-schema.org/schema"]=si)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(si)?si:void 0)}};K.Ajv2020=It;ii.exports=K=It;ii.exports.Ajv2020=It;Object.defineProperty(K,"__esModule",{value:!0});K.default=It;var x_=sn();Object.defineProperty(K,"KeywordCxt",{enumerable:!0,get:function(){return x_.KeywordCxt}});var Nt=S();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return Nt._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return Nt.str}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return Nt.stringify}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return Nt.nil}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return Nt.Name}});Object.defineProperty(K,"CodeGen",{enumerable:!0,get:function(){return Nt.CodeGen}});var P_=er();Object.defineProperty(K,"ValidationError",{enumerable:!0,get:function(){return P_.default}});var A_=an();Object.defineProperty(K,"MissingRefError",{enumerable:!0,get:function(){return A_.default}})});function Lr(e,t,n,r){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...r?{reasoning_content:r}:{}}}function Bt(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var Hu=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Xe={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Wu=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ju=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Yu=512,Xu=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Qu=new Set([500,502,503,504,521,522,523,524,529]),Zu=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],ed=["upgrade your plan","upgrade plan","current plan","subscription"],td=["daily","weekly","monthly"],nd=["try again","retry","temporary","cooldown"],rd=["usage limit","rate limit","organization usage"],od=["organization","workspace"],sd=["billing period","exceeded","reached","exhausted"],id=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,ad=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function Qe(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(r=>r instanceof RegExp?r.test(n):n.includes(r))}function ld(e){return Qe(e,Xe.format)}function ji(e){return Qe(e,Xe.rateLimit)}function cd(e){return Qe(e,Xe.timeout)}function ud(e){return Hu.test(e)}function qr(e){let t=e.toLowerCase();return t?e.length>Yu?Ju.test(t):Qe(t,Xe.billing)?!0:Wu.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Li(e){return Qe(e,Xe.authPermanent)}function dd(e){return Qe(e,Xe.auth)}function qi(e){return Qe(e,Xe.overloaded)}function Ye(e,t){return t.some(n=>e.includes(n))}function fd(e){return Ye(e,Zu)||Ye(e,ed)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function pd(e){let t=Ye(e,td),n=e.includes("spend limit")||e.includes("spending limit"),r=Ye(e,od);return Ye(e,nd)&&Ye(e,rd)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||r&&e.includes("limit")&&(n||Ye(e,sd))}function md(e){return e.trim().toLowerCase().replace(ad,"").trim()}function Di(e){let t=md(e);return!t||fd(t)?"billing":ji(t)||pd(t)?"rate_limit":"billing"}function hd(e){return id.test(e)?Di(e):null}function Fi(e){let t=e.match(Xu);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function gd(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function yd(e){let t=e.trim();if(!t)return!1;let n=Fi(t);return n?Qu.has(n.code):!1}function Ui(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Di(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Li(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&qi(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&qr(t)?"billing":"format":null}function _d(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Td(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function Bi(e){if(Td(e))return"session_expired";if(_d(e))return"model_not_found";let t=hd(e);return t||(ud(e)?qr(e)?"billing":"rate_limit":ji(e)?"rate_limit":qi(e)?"overloaded":yd(e)?Fi(e.trim())?.code===529?"overloaded":"timeout":gd(e)?"timeout":ld(e)?"format":qr(e)?"billing":cd(e)?"timeout":Li(e)?"auth_permanent":dd(e)?"auth":null)}var vd=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Ln(e){return vd.has(e)}var bd={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function Tt(e,t){let n=Ui(e,t)??(t?Bi(t):null);return n?bd[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function zi(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var kd=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]);function Cd(e){let t=e;for(let n=0;n<3;n+=1){if(!t||typeof t!="object"||Array.isArray(t))return;let r=t,o=r.outcome??r.status;if(o==="committed"||o==="not-applied"||o==="indeterminate")return o;t=r.structuredContent}}var zt=class{constructor(t=20,n=zi){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let r=new Map;for(let a of t){let c=a.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&r.set(u.id,u.function.name)}let o=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((a,c)=>{if(c>=o||a.role!=="tool"||typeof a.content!="string")return a;let u=a.name??r.get(a.tool_call_id??""),d=Cd(a.structuredContent);if(!d&&(!u||!kd.has(u)))return a;let h=a.structuredContent?JSON.stringify(a.structuredContent).length:0;if(a.content.length<=200&&h<=200)return a;let T=this.estimateTokens(a);return i+=T,s++,{...a,content:`[result cleared \u2014 ${a.content.length+h} chars]`,...d?{structuredContent:{status:d,outcome:d}}:{}}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Dr(e,t,n=zi){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let r=0,o=0,s=[];for(let l of e){let a=l.tool_call_id??"";if(a&&t.has(a)){r+=n(l),o++,t.delete(a);continue}s.push(l)}let i=o>0?{role:"system",content:`[${o} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:r,removedCount:o,boundaryMessage:i}}function Fr(){return{stages:[]}}function Ur(e,t,n){let r=n?.thresholdMessages??40;if(e.filter(l=>l.role!=="system").length<=r)return{messages:e,stagedCount:0};let s=Vi(e,t),i=Rd(s,t,r);if(i.length===0)return{messages:s,stagedCount:0};for(let l of i)t.stages.push(l);return s=Vi(e,t),{messages:s,stagedCount:i.length}}function Br(e,t){let n=0;for(let r of t.stages)r.committed||(r.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:Ki(e,t),committed:n}}function Vi(e,t){return t.stages.filter(r=>r.committed).length===0?e:Ki(e,t)}function Ki(e,t){let n=t.stages.filter(o=>o.committed).sort((o,s)=>s.range[0]-o.range[0]),r=[...e];for(let o of n){let[s,i]=o.range;if(s>=r.length)continue;let l=Math.min(i,r.length),a={role:"system",content:o.summary};r.splice(s,l-s,a)}return r}function Rd(e,t,n){let r=Math.max(0,e.length-Math.floor(n/2)),o=[],s=new Set(t.stages.map(a=>`${a.range[0]}-${a.range[1]}`)),i=-1,l=0;for(let a=0;a<r;a++){let c=e[a];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=a),l++;else{if(l>=3){let d=`${i}-${i+l}`;s.has(d)||o.push({id:`collapse_${i}_${i+l}`,range:[i,i+l],summary:`[${l} tool results collapsed]`,committed:!1})}i=-1,l=0}}if(l>=3){let a=`${i}-${i+l}`;s.has(a)||o.push({id:`collapse_${i}_${i+l}`,range:[i,i+l],summary:`[${l} tool results collapsed]`,committed:!1})}return o}function Gi(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Ed(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function wd(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function $d(e){if(!e.eligibility?.length)return[...e.tools];let t=wd(e.eligibility);return e.tools.filter(n=>{let r=Gi(n);if(!r)return!1;let o=t.get(r);return!o||Ed(o.status)})}function Sd(e){let t=[],n=e.compatibility??{},r=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let o=typeof r=="object"&&r&&!Array.isArray(r)?String(r.type??""):r;o&&o!=="auto"&&o!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),r="auto")}if(r==="required"&&n.allowRequiredToolChoice===!1){let o=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${o}.`),r=o}if(r&&typeof r=="object"&&!Array.isArray(r)&&r.type==="function"&&n.allowNamedToolChoice===!1){let o=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${o}.`),r=o}return{normalizedToolChoice:r,warnings:t}}function zr(e){let t=Sd({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,r=[...t.warnings],o=$d({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:o,normalizedToolChoice:n,warnings:r};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:r};if(n==="required"){if(o.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:o,normalizedToolChoice:"required",warnings:r}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let l=o.filter(a=>Gi(a)===i);if(l.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:l,normalizedToolChoice:{type:"function",function:{name:i}},warnings:r}}return{tools:o,normalizedToolChoice:n,warnings:r}}var xd=["stop","aborted","timeout","cancelled","interrupted","error"],Pd=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Hi(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Ad(e,t){return{...e,content:[...Hi(e.content),...Hi(t.content)]}}function Md(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Od(e){let t=new Set,n=[];for(let r=0;r<e.length;r+=1){if(t.has(r))continue;let o=e[r];if(!o)continue;n.push(o);let s=Md(o);if(s.size!==0)for(let i=r+1;i<e.length;i+=1){if(t.has(i))continue;let l=e[i];l?.role==="tool"&&typeof l.tool_call_id=="string"&&s.has(l.tool_call_id)&&(n.push(l),t.add(i))}}return n}function Id(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Nd(e){return new Set((e??xd).map(t=>t.trim().toLowerCase()))}function jd(e,t){return e?Nd(t).has(e.trim().toLowerCase()):!1}function Vr(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let c=a.tool_calls.filter(u=>Id(u));return{...a,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...a}}),n=new Set;for(let a of t)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let c of a.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let r=t.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&n.has(a.tool_call_id))),o=new Set;for(let a of r)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let s=[];for(let a of r){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let c=a.tool_calls.filter(u=>typeof u.id=="string"&&o.has(u.id));if(c.length===0){let{tool_calls:u,...d}=a;d.content!=null&&d.content!==""&&s.push(d);continue}if(c.length<a.tool_calls.length){s.push({...a,tool_calls:c});continue}}s.push(a)}let i=Od(s),l=[];for(let a of i){let c=l.length>0?l[l.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){l[l.length-1]=Ad(c,a);continue}l.push(a)}return l}function Kr(e,t){return jd(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let r={...n};for(let o of Pd)delete r[o];return r}):[...e]}function Gr(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",r=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let o=[];for(let s of e)if(o.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||r.has(i.id)||(r.add(i.id),o.push({role:"tool",tool_call_id:i.id,content:n}));return o}function Hr(e,t){let n=Vr(e),r=Kr(n,t);return Gr(r,t)}function Ld(e){let t=new Set,n=new Set;for(let r of e){if(r.role==="assistant"&&Array.isArray(r.tool_calls))for(let o of r.tool_calls)typeof o.id=="string"&&o.id&&t.add(o.id);r.role==="tool"&&typeof r.tool_call_id=="string"&&r.tool_call_id&&n.add(r.tool_call_id)}return[...t].filter(r=>!n.has(r))}function qd(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function Dd(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Wr(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function qn(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Dn(e){let t=[],n=Vr(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let r=Kr(n,e.options);r.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let o=Gr(r,e.options);return o.length>r.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Dd({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:o,pendingToolCallIds:Ld(o),completedToolCallIds:qd(o)}),recoveryActions:t}}var Fd=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Jr(e){return e?Fd.has(e):!0}function Yr(e){return e===429||e===529}function Fn(e,t=500,n=32e3){let r=Math.min(t*Math.pow(2,e-1),n);return r+Math.floor(Math.random()*r*.25)}var uT={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Un(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Vt=class extends Error{constructor(n,r){super(`Model fallback triggered: ${n} -> ${r}`);this.originalModel=n;this.fallbackModel=r;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var Wi=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Ji=128e3,Yi=13e3,Xi=16384,Qi=65536,Zi=3;var ea=3e4,ta=3,Ze=2;var fT=50*1024,pT=500*1024,mT=500*1024*1024,hT=50*1024*1024;function Xr(e){let t=Number.isFinite(e.totalPromptTokens)&&(e.totalPromptTokens??0)>0?Math.floor(e.totalPromptTokens):0,n=Number.isFinite(e.promptTokens)&&e.promptTokens>0?Math.floor(e.promptTokens):0,r=Number.isFinite(e.cacheReadTokens)&&(e.cacheReadTokens??0)>0?Math.floor(e.cacheReadTokens):0,o=Number.isFinite(e.cacheCreationTokens)&&(e.cacheCreationTokens??0)>0?Math.floor(e.cacheCreationTokens):0,s=r+o,i=s>n?n+s:n;return Math.max(t,i)}function Qr(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Zr(e,t){let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,r=n>0?e.promptTokens/n*100:100;return r>=85?{level:"warning",usagePercent:r,remainingTokens:Math.max(0,n-e.promptTokens)}:{level:"ok"}}function eo(e,t,n){let r=e.message?.toLowerCase()??"",o=e.status??0;return o===413||r.includes("prompt_too_long")||r.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:o>=500&&o<600?{action:"retry",reason:`server_error_${o}`}:o===429?{action:"retry",reason:"rate_limited"}:o===401||o===403?{action:"abort",reason:"auth_error"}:o===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:r||"unknown_error"}}function to(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let r=Math.min(e.currentMaxOutputTokens*2,n);return r<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:r}}function no(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function ro(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Kt(e){return!e.attemptedThisTurn}import{createHash as ui}from"node:crypto";function oo(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function na(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?e:e.slice(t+2)}function ra(e){let t=e.indexOf("__");if(!(t<=0||t+2>=e.length))return e.slice(0,t)}var so="tool_schema_load";function oa(e){return e?.type!=="tool_schema_load"||!Array.isArray(e.requestedToolNames)?[]:[...new Set(e.requestedToolNames.filter(t=>typeof t=="string"&&t.trim().length>0))]}function H(e,t,n,r){e?.invoke(t,n).catch(o=>{let s=o instanceof Error?o.message:String(o);r.warn(`[hook:${t}] handler failed: ${s}`)})}function sa(e){if(e.blocked)return"policy_blocked";let t=typeof e.details?.error=="string"?e.details.error:"",n=`${t} ${e.error??""}`;return t==="semantic_quality_failed"?"semantic_quality_failed":/MCP_START_FAILED/iu.test(n)?"mcp_start_failed":/mcp_not_connected|mcp_unavailable/iu.test(n)?"mcp_unavailable":/\bTIMEOUT\b|timed out/iu.test(n)?"timeout":"tool_execution_failed"}function ia(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",r=n?n.slice(0,2e3):void 0,o=t.details,s=typeof o?.stdout=="string"?o.stdout.slice(0,8e3):void 0,i=typeof o?.stderr=="string"?o.stderr.slice(0,4e3):void 0,l=typeof o?.exitCode=="number"?o.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:r,durationMs:t.durationMs,exitCode:l,stdout:s,stderr:i,details:o}}function aa(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let r=[],o=Array.isArray(n.inlineImageUrls)?n.inlineImageUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[];for(let s of o)r.push(Bd(e,"image",s,n));return r}function Bd(e,t,n,r){return{type:"media_result",turnId:e,mediaType:t,url:n,model:typeof r.model=="string"?r.model:void 0,provider:typeof r.provider=="string"?r.provider:void 0,durationSeconds:typeof r.durationMs=="number"?r.durationMs/1e3:void 0,...typeof r.mimeType=="string"?{mimeType:r.mimeType}:{},...typeof r.filename=="string"?{filename:r.filename}:{},...typeof r.size=="number"?{size:r.size}:{},taskId:typeof r.taskId=="string"?r.taskId:void 0}}var zd=new Set(["write","edit","patch"]);function la(e){let{turnId:t,result:n,toolCalls:r}=e;if(!n.ok)return[];let o=r.find(l=>l.id===n.callId);if(!o)return[];let s=[],i=Vd(o.function.arguments);if(!i)return s;if(zd.has(n.toolName)){let l=Kd(i);l&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Gd(l),title:l.split(/[\\/]/).pop()||l,filePath:l,language:Hd(l)})}return s}function Vd(e){try{return JSON.parse(e)}catch{return null}}function Kd(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function Gd(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function Hd(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}var du=Gu(cu(),1),M_=new du.Ajv2020({allErrors:!0,allowUnionTypes:!0,strict:!1,validateFormats:!1}),uu=new WeakMap;function O_(e){let t=uu.get(e);if(t)return t;let n=M_.compile(e);return uu.set(e,n),n}function I_(e){return e.instancePath?`arguments${e.instancePath}`:e.keyword==="required"&&typeof e.params.missingProperty=="string"?`arguments/${e.params.missingProperty}`:"arguments"}function N_(e){return(e??[]).slice(0,4).map(t=>`${I_(t)} ${t.message??`violates ${t.keyword}`}`).join("; ")}function fu(e,t,n){let r;try{r=JSON.parse(n)}catch{return{ok:!1,error:`Tool "${e}" arguments must be valid JSON.`}}if(!r||typeof r!="object"||Array.isArray(r))return{ok:!1,error:`Tool "${e}" arguments must be a JSON object.`};if(!t)return{ok:!0};try{let o=O_(t);return o(r)?{ok:!0}:{ok:!1,error:`Tool "${e}" arguments do not match the offered schema: ${N_(o.errors)}.`}}catch(o){return{ok:!1,error:`Tool "${e}" has an invalid offered JSON Schema: ${o instanceof Error?o.message:String(o)}.`}}}function br(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.round(e):0}function kr(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.round(e)}function pu(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function mu(e){try{let t=JSON.parse(e),r=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(s=>typeof s=="string"&&s.trim().length>0);if(typeof r=="string")return r.trim().slice(0,240);let o=Object.keys(t);return o.length>0?o.slice(0,5).join(" / "):void 0}catch{return}}function ai(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function li(e){return e==="length"||e==="max_tokens"}function ci(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function hu(e){let t=e.headers;if(!t)return null;let n=t["retry-after"]??t["Retry-After"];if(!n)return null;let r=parseInt(n,10);return!isNaN(r)&&r>0?r*1e3:null}function gu(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let n=parseInt(t[1],10),r=parseInt(t[3],10);if(isNaN(n)||isNaN(r))return null;let o=r-n-1e3;return o>=3e3?o:null}async function*yu(e){let{messages:t,contentReplacementState:n,snipRemovedIds:r,collapseStore:o,guardConfig:s,runtimePorts:i,hooks:l,hookCtx:a,sessionId:c,currentModel:u,log:d,recovery:h,onAutocompact:T}=e,p;{let f=await i.enforceToolResultBudget(t,n,c);if(p=f.messages,f.newlyReplacedCount>0){let m=f.newlyPersistedBytes??0,_=m>0?` (~${Math.max(1,Math.round(m/1024))} KB)`:"";d.info(`tool-result-budget: persisted ${f.newlyReplacedCount} oversized tool results${_}`),yield h("tool_result_budget",`${f.newlyReplacedCount} persisted${_}`)}}{let f=Dr(p,r);if(p=f.messages,f.removedCount>0){if(f.boundaryMessage){let m=p,_=0;for(;_<m.length&&m[_]?.role==="system";)_++;p=[...m.slice(0,_),f.boundaryMessage,...m.slice(_)]}d.info(`snip: removed ${f.removedCount} messages, freed ~${f.tokensFreed} tokens`),yield h("snip",`${f.removedCount} messages`)}}{let m=new zt().compress(p,0);m.droppedCount>0&&(p=m.messages,d.info(`microcompact: cleared ${m.droppedCount} old tool results`),yield h("microcompact",`${m.droppedCount} old tool results cleared`))}if(p=Ur(p,o).messages,s.contextWindowTokens>0){let f=s.contextWindowTokens*.75,m=i.getActiveContextCompressionEngine(),_;m?_=await m.compressAsync(p,f,{model:u,sessionId:c}):_=i.compressMessages(p,{budget:f,model:u}),_.droppedCount>0&&(p=_.messages,d.info(`autocompact: ${_.strategy}, dropped ${_.droppedCount}`),yield h("autocompact",`${_.strategy}: ${_.droppedCount} dropped`),yield{type:"lifecycle",turnId:a.turnId,kind:"context_compression",status:"completed",detail:`${_.strategy}: ${_.droppedCount} dropped`},T(),H(l,"context.after_compact",{...a,removedCount:_.droppedCount},d))}if(i.restoreRequiredContextMessages){let f=i.restoreRequiredContextMessages(t,p,n);p=f.messages,f.recoveredCount>0&&(d.info(`typed-context-budget: recovered ${f.recoveredCount} required skill context message(s)`),yield h("typed_context_recovery",`${f.recoveredCount} required skill context message(s)`))}return p=pu(p),p}async function*_u(e,t){let{state:n,guardState:r,fallbackModel:o,signal:s,querySource:i,turnId:l,log:a,emitRecovery:c}=t;if(e instanceof Vt&&o)return a.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield c("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let u=e instanceof Error?e.message:String(e),d=typeof e?.status=="number"?e.status:void 0;if(!d&&u&&(u.includes("ECONNRESET")||u.includes("EPIPE"))){let T=(n.consecutiveApiRetries??0)+1;return T>Ze?(a.info(`stale connection retry limit reached (${Ze}), aborting`),yield{type:"error",turnId:l,error:u,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(a.info(`stale connection (${u.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield c("stale_connection_retry",u.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:T,transition:void 0}})}let h=gu({status:d,message:u});if(h!==null)return a.info(`max_tokens overflow: adjusting to ${h}`),r.currentMaxOutputTokens=h,{kind:"continue",patch:{maxOutputTokensOverride:h,transition:void 0}};if(Yr(d)){n.consecutive529Errors++;let T=2,p=o&&n.currentModel!==o;if(n.consecutive529Errors>T&&!p&&!Un())return a.info(`transient ${d} \xD7 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:l,error:`API unavailable after ${n.consecutive529Errors} consecutive ${d} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=ta&&o&&n.currentModel!==o)return a.info(`529 \xD7 ${n.consecutive529Errors}: triggering fallback to ${o}`),yield c("model_fallback",`529 \xD7 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:o,consecutive529Errors:0,transition:void 0}};if(Un()){let f=Fn(n.consecutive529Errors);a.info(`persistent retry: waiting ${f}ms (attempt ${n.consecutive529Errors})`);let m=f;for(;m>0;){if(s?.aborted)return yield{type:"error",turnId:l,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:l,message:`Retrying in ${Math.ceil(m/1e3)}s (${d})`};let _=Math.min(m,ea);await new Promise(E=>setTimeout(E,_)),m-=_}return{kind:"continue",patch:{transition:void 0}}}if(Jr(i)){let m=hu({status:d,message:u})??Fn(n.consecutive529Errors);return a.info(`transient ${d}: retry in ${m}ms`),yield c("retry",`${d} retry in ${m}ms`),await new Promise(_=>setTimeout(_,m)),{kind:"continue",patch:{transition:void 0}}}a.info(`background source ${i}: not retrying ${d}`)}return{kind:"streamError",streamError:{status:d,message:u}}}function Tu(e){return[...new Set(e.map(t=>t.function.name))].sort()}function L_(e){let t=new Set,n=[];for(let r of e){let o=`${r.name}\0${r.reason}`;t.has(o)||(t.add(o),n.push(r))}return n.sort((r,o)=>`${r.name}:${r.reason}`.localeCompare(`${o.name}:${o.reason}`))}function q_(e){let t=typeof e.blockReason=="string"?e.blockReason:void 0;if(e.blocked&&/confirmation timed out/i.test(t??""))return"confirmation-timeout";if(e.blocked)return"blocked-by-policy";let n=typeof e.details?.error=="string"?e.details.error:void 0;if(n==="write.target_exists")return"existing-file-update-tool-required";if(n==="invalid_arguments")return"invalid-arguments";if(n==="blocked_global_process_kill")return"global-process-kill-blocked";if(n==="blocked_by_guard")return"blocked-by-policy";if(n==="semantic_quality_failed")return"semantic-quality-failed"}function D_(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(!(n.role!=="user"||typeof n.content!="string"))return/[\u3400-\u9fff]/u.test(n.content)?"zh":"en"}return"en"}function vu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function F_(e,t){if(!e)return null;let n=vu(e.function.parameters),r=vu(n?.properties)??{},o=Array.isArray(n?.required)?n.required.filter(l=>typeof l=="string"&&l.trim().length>0):[],s=K_(t);if(!s)return`Tool "${e.function.name}" arguments must be a JSON object.`;for(let l of o){let a=s[l];if(typeof a=="string"?a.trim().length===0:a==null)return`Tool "${e.function.name}" missing required field \`${l}\`. Use the offered tool schema exactly.`}if(n?.additionalProperties===!1){let l=new Set(Object.keys(r)),a=Object.keys(s).filter(c=>!l.has(c));if(a.length>0){let c=[...l].map(u=>`\`${u}\``).join(", ")||"none";return`Tool "${e.function.name}" has unexpected field${a.length===1?"":"s"} ${a.map(u=>`\`${u}\``).join(", ")}. Remove ${a.length===1?"it":"them"}; the only allowed fields are ${c}. Use the canonical tool schema exactly and do not retry the rejected arguments unchanged.`}}let i=fu(e.function.name,n??void 0,t);return i.ok?null:i.error??`Tool "${e.function.name}" arguments do not match the offered schema.`}function U_(e,t){let n=e?.meta?.identity;if(n?.schemaVersion===1&&n.wireName===t)return n;let r=e?.meta?.category,o=na(t),s=ra(t),l=r==="orchestration"?"orchestration":o==="skill_search"||o==="skill_load"||o==="skill_resource_read"?"skill":s!==void 0||r==="mcp"?"mcp":"builtin",a="agent";return{schemaVersion:1,wireName:t,logicalName:o,family:l,owner:a,...s?{serverId:s}:{},capabilityId:`${a}:${s??"native"}:${o}`}}function bu(e){return{role:"system",content:`Background sub-agent result(s) became available while you continued the main task. The bounded structured results are included below; incorporate them when useful. Do not poll, cancel, or relaunch these tasks merely to acknowledge this update.
49
9
  `+e.join(`
50
- `)}}function mg(e,t){for(let n of t)for(let o of n.matchAll(/<task_id>([^<]+)<\/task_id>/gu)){let r=o[1]?.trim();r&&(rn(e).delete(r),e.backgroundAgentPollCounts.delete(r),e.backgroundAgentNoOutputPollCounts.delete(r),e.stalledBackgroundAgentTasks.delete(r))}}function gg(e,t){if(e.function.name!=="task")return!1;let n=We(e.function.arguments);if(n?.action!=="output")return!1;let o=n.taskId;return typeof o=="string"&&rn(t).has(o)}function T0(e,t){if(e.toolName!=="task")return!1;let n=on(e.details,"taskId");return!n||!rn(t).has(n)?!1:on(e.details,"action")==="output"&&cs(e.details,"running")===!0}var k0=180,C0=12,hg=12;function R0(e){return Math.min(5e3,250*2**Math.max(0,e))}function w0(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function x0(e){let t=e.match(/\brunning for\s+(\d+)s\b/i);if(!t?.[1])return;let n=Number(t[1]);return Number.isFinite(n)?n:void 0}function Rg(e){return ls("sha256").update(JSON.stringify(e)).digest("hex")}function S0(e,t){let n=-1;for(let r=e.length-1;r>=0;r--)if(e[r]?.role==="assistant"){n=r;break}if(n<0||Rg(e.slice(0,n+1))!==t)return;let o=e.slice(n+1);return o.length>0?o:void 0}function rn(e){return e.backgroundAgentTaskIds??(e.backgroundAgentTaskIds=new Set)}function E0(e){if(!e||typeof e!="object")return null;let t=e.taskList;if(!Array.isArray(t))return null;let n=[];for(let o of t){if(!o||typeof o!="object")continue;let r=o,s=r.id,i=r.title,a=r.status;typeof s!="number"||!Number.isFinite(s)||typeof i!="string"||!i.trim()||typeof a!="string"||!a.trim()||n.push({id:s,title:i,status:a})}return n}var al=new Set(["read","search"]),A0=new Set(["write","edit","patch","image_generate"]),$0=18e4,P0=3,Bo=1,M0=1,I0=1,O0=4,N0=2,Le=new Map([["requirements.md","requirements"],["decisions.md","decisions"],["defects.md","defects"],["acceptance.md","acceptance"]]),pl=new Set(["document-index.json","decision-state-table.json","context-pack-evidence.json"]),wg=[{id:"D001",decision:"artifact root must remain stable for the whole scenario",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D002",decision:"every browser checkpoint must use the real Xiaozhi Claw frontend",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D003",decision:"unsupported facts are assumptions until verified",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D004",decision:"defects and decisions must be maintained as separate artifacts",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D005",decision:"final release requires initial version, acceptance, rework, second review, and release candidate",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D006",decision:"after every reopen, reconstruct goal, artifacts, decisions, defects, acceptance criteria, blockers, and next action",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0}],cl=new Set(["write","edit","patch"]),F0=new Set(["read","search","exec"]);function xg(e){let t=ke(e),n=Mt(t);return t.split("/").includes("context-pack")&&Le.has(n)?Bo:t.split("/").includes("benchmark-state")&&pl.has(n)?I0:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?M0:P0}function yg(e){try{let t=Yw(e);return t.isFile()?{mtimeMs:t.mtimeMs,sizeBytes:t.size}:null}catch{return null}}function sl(e){let t=ke(e);if(t.split("/").includes("context-pack")){let n=t.split("/context-pack/")[0];return`Use benchmark-state summaries instead: ${n}/benchmark-state/document-index.json, ${n}/benchmark-state/decision-state-table.json, and ${n}/benchmark-state/context-pack-evidence.json. If those summaries are stale, update compact checkpoint files under benchmark-state; do not reread or rewrite context-pack.`}return t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?"This is a persisted large tool-result preview. Use the first read, the original tool_result preview, and maintained benchmark-state summaries; do not reread tool-result cache files.":t.split("/").includes("benchmark-state")&&pl.has(Mt(t))?"This compact benchmark-state file was already read this turn. Use the in-turn tool result, prior maintained summary, and decision state already in conversation; do not reread compact state files in a loop.":"Use the maintained index, prior tool results, or a narrow section-specific read instead of rereading the same file."}function ml(e){let t=ke(e);return t.split("/").includes("context-pack")&&Le.has(Mt(t))}function Sg(e){let t=ke(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function L0(e){let t=[...e].filter(ml).map(Sg).filter(o=>!!o);if(t.length===0)return!1;let n=t[0];return[`${n}/benchmark-state/document-index.json`,`${n}/benchmark-state/decision-state-table.json`,`${n}/benchmark-state/context-pack-evidence.json`].every(o=>{try{return sn(o)}catch{return!1}})}function Eg(e){return[...Le.keys()].every(t=>e.has(t))}function gl(e){for(let t of e.values()){if(!t.path)continue;let n=Sg(t.path);if(n)return`${n}/benchmark-state`}return null}function Ag(e){if(!Eg(e))return[];let t=gl(e);return t?[...pl].map(n=>`${t}/${n}`).filter(n=>{try{return!sn(n)}catch{return!0}}):[]}function j0(e,t){let n=Ag(e);if(n.length===0)return null;let o=gl(e);if(!o)return null;let s=[...Le.keys()].map(a=>{let c=e.get(a);return`${a}: path=${c?.path??"unknown"}, contentHash=${c?.contentHash??"unknown"}, fileSizeBytes=${c?.fileSizeBytes??"unknown"}, recordCount=${c?.recordCount??"unknown"}, summary=${c?.summary??""}`}).join(`
51
- `),i=wg.map(a=>`${a.id}: ${a.decision}`).join(`
52
- `);return["You have already read and indexed requirements.md, decisions.md, defects.md, and acceptance.md for this long-horizon benchmark.","Do not read context-pack, persisted tool-result previews, or compact benchmark-state files again in this turn.","Before any more analysis or final answer, maintain the benchmark state files using write/edit/patch only.",`Benchmark-state directory: ${o}.`,`Missing files: ${n.join(", ")}.`,"Create missing files with write. If any target already exists, update it with edit or patch instead of write.","For every contentHash and fileSizeBytes you write, copy the EXACT value from the 'Document evidence already available' section below. Do NOT compute, approximate, or invent a hash \u2014 you must not re-read the large read-only context-pack files to produce one.","The context-pack inputs (requirements.md, decisions.md, defects.md, acceptance.md) are READ-ONLY and immutable: their content and contentHash cannot change between turns. If a hash ever appears to differ from what you recorded, the source did NOT change \u2014 suspect your own recorded value first (stale, or never tool-derived). Never raise a 'source changed' blocker for these files.","Acceptance verdicts are monotonic unless re-derived from primary evidence: do NOT flip a previously-PASSing criterion to FAIL on a derived/secondary signal such as a hash diff. Change a PASS to FAIL only after re-checking the actual acceptance condition against primary evidence, and cite that evidence.","Required files:","- document-index.json: include contextPackPath and a documents object keyed by requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, fileSizeBytes, recordCount, indexVersion, summary, and lastReviewedTurn.","- decision-state-table.json: include D001-D006 with id, decision, status, evidence, and lastConfirmedTurn.","- context-pack-evidence.json: include turn and fileVerification for requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, and fileSizeBytes.",`Current turn: ${t}.`,"Document evidence already available:",s,"Decision records to preserve:",i].join(`
53
- `)}function bg(e){return cl.has(e)}function D0(e){return e.longHorizonStateMaintenanceRequiredFiles.size>0&&[...e.longHorizonStateMaintenanceRequiredFiles].every(t=>B0(e,t))}function B0(e,t){if(e.longHorizonStateMaintenanceWrittenFiles.has(t))return!0;try{if(!sn(t))return!1;let n=Mt(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=ms(t,"utf8");return hl(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function hl(e,t,n){let o=Mt(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=nx(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=We(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=Oe(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let c of Le.keys()){let l=e.get(c),d=Oe(a[c]);if(!l||!d)return{ok:!1,reason:`document-index.json missing ${c}`};if(d.contentHash!==l.contentHash)return{ok:!1,reason:`document-index.json ${c} contentHash does not match read.details`};if(d.fileSizeBytes!==l.fileSizeBytes)return{ok:!1,reason:`document-index.json ${c} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=Oe(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of Le.keys()){let c=e.get(a),l=Oe(i[a]);if(!c||!l)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(l.contentHash!==c.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(l.fileSizeBytes!==c.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function q0(e){if(!Eg(e))return[];let t=gl(e);if(!t)return[];let n=[];for(let o of["document-index.json","context-pack-evidence.json"]){let r=`${t}/${o}`,s;try{if(!sn(r))continue;s=ms(r,"utf8")}catch{continue}let i=hl(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function U0(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<O0)return!1;let s=new Set([...t].filter(ml).map(Mt));return[...Le.keys()].every(a=>s.has(a))?[...Le.keys()].every(a=>o.has(a))||n||L0(t):!1}function $g(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=ps(t);if(!o)return null;try{if(!sn(o))return null}catch{return null}return{path:o,error:`Existing file update blocked for "${o}". Use edit or patch for existing files so the event stream can distinguish file creation from incremental maintenance. If you are certain a full-file write is the right action here (not an incremental edit), re-issue exactly the same write call once write is offered again and it will run once.`}}var fs=class extends Error{constructor(n){super(`LLM stream idle timeout after ${n}ms without a chunk.`);this.timeoutMs=n;this.name="LLMStreamIdleTimeoutError"}timeoutMs;code="LLM_STREAM_TIMEOUT"};async function*z0(e,t){if(!Number.isFinite(t)||t<=0){yield*e;return}let n=e[Symbol.asyncIterator]();try{for(;;){let o,r=await Promise.race([n.next(),new Promise(s=>{o=setTimeout(()=>s("timeout"),t)})]);if(o&&clearTimeout(o),r==="timeout")throw new fs(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function ll(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function ps(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function H0(e){return e.flatMap(t=>{if(V0(t.function.arguments))return[t];let n=G0(t.function.arguments);return n.length<2?[t]:n.map((o,r)=>({...t,id:`${t.id}__json_${r+1}`,function:{...t.function,arguments:JSON.stringify(o)}}))})}function V0(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function G0(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let a=0;a<e.length;a+=1){let c=e[a];if(r){s?s=!1:c==="\\"?s=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){if(n===0){if(e.slice(i,a).trim())return[];o=a}n+=1;continue}if(c!=="}"||(n-=1,n!==0||o<0))continue;let l=We(e.slice(o,a+1));if(!l)return[];t.push(l),i=a+1,o=-1}return n!==0||r||e.slice(i).trim()?[]:t}function We(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function ke(e){let t=e.trim().replace(/\\/g,"/");for(t=t.replace(/\/{2,}/g,"/");t.includes("/./");)t=t.replace(/\/\.\//g,"/");return t=t.replace(/\/\.$/,""),/^[a-z]:\//i.test(t)&&(t=t.toLowerCase()),t.replace(/\/$/,"")}function Mt(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function yl(e){return`sha256:${ls("sha256").update(e).digest("hex")}`}function W0(e,t){let n=t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean),o=n[0]??e,r=n.find(a=>/record\s+0*1\b/i.test(a)),s=r&&r!==o?`${o}; ${r}`:o,i=s.length>180?`${s.slice(0,177)}...`:s;return i.toLowerCase().includes(e.toLowerCase())?i:`${e}: ${i}`}function K0(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function J0(e,t,n,o){let r=[...t.values()].sort((c,l)=>(c.name??"").localeCompare(l.name??""));if(r.length===0)return null;let s=r.map(c=>`${c.name??"document"}:${c.contentHash??"unknown"}`).join("|"),i=wg.map(c=>({...c,evidence:`read:long-horizon-documents:${yl(`${c.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:Bo,observedReadsByPath:K0(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function X0(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function as(e,t){return e.get(t)??null}function Y0(e){let t=as(e,"requirements.md"),n=as(e,"decisions.md"),o=as(e,"defects.md"),r=as(e,"acceptance.md");if(!t||!n||!o||!r)return null;let s=[t,n,o,r];return{goal:`Maintain long-horizon project state from ${t.name}, ${n.name}, ${o.name}, and ${r.name}`,artifactRoot:X0(s),decisions:[n.summary],defects:[o.summary],acceptanceCriteria:[r.summary],blockers:[],nextAction:"Continue from the maintained document index and read only explicitly missing sections"}}function Z0(e,t){let n=Y0(t);return n?[{type:"lifecycle",turnId:e,kind:"goal_reconstruction",reconstruction:n},{type:"lifecycle",turnId:e,kind:"memory_drift",status:"none",detail:"No memory drift detected against the maintained document index."}]:[]}function Q0(e,t,n,o,r){let s=ul(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function ul(e,t,n,o){let r=Mt(e);if(!Le.has(r))return null;let s=rx(t)??t,i=ox(o,"contentHash"),a=Dn(o??null,"fileSizeBytes"),c=i??yl(s);return{name:r,path:ke(e),indexed:!0,maintained:!0,indexVersion:c,contentHash:c,summary:W0(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:Pg(s)}}function ex(e,t){return $g(e.function.name,e.function.arguments,t)!==null}function tx(e,t){let n=ps(t.function.arguments);return`This exact write call to an existing file has been attempted ${e} times${n?` for "${n}"`:""}. Do not call write again for this existing file. Use edit or patch for the existing-file update, then continue verification.`}function nx(e){let n=We(e)?.content;return typeof n=="string"?n:void 0}function ox(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Pg(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function rx(e){if(!e.includes("<persisted-output>"))return null;let n=e.match(/Full output saved to:\s*(.+?)(?:\r?\n|$)/)?.[1]?.trim();if(!n)return null;try{return sn(n)?ms(n,"utf8"):null}catch{return null}}function sx(e){let t=new Map;for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let i of s.tool_calls){if(i.function?.name!=="read"||typeof i.id!="string"||typeof i.function.arguments!="string")continue;let a=ll(i.function.arguments);if(!a)continue;let c=ke(a);xg(c)===Bo&&t.set(i.id,{path:c})}let n=new Map,o=new Map,r=!1;for(let s of e){if(s.role!=="tool"||typeof s.tool_call_id!="string"||s.is_error===!0)continue;let i=t.get(s.tool_call_id);if(!i)continue;let a=typeof s.content=="string"?s.content:"";if(!a||/^Error:/i.test(a.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let c=ul(i.path,a,0);c?.name&&o.set(c.name,c)}for(let s of ux(e)){r=!0;for(let i of Le.keys()){let a=ke(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,Bo)),!o.has(i)){let c=ul(a,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);c?.name&&o.set(c.name,c)}}}for(let s of ix(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,Bo)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedLongHorizonStateRecovered:r}}function ix(e){let t=[];for(let n of ax(e)){let o=_g(`${n}/document-index.json`),r=_g(`${n}/context-pack-evidence.json`),s=Bn(o,"contextPackPath")??cx(r);if(!s)continue;let i=lx(s,o,r);i.length===Le.size&&t.push({documents:i})}return t}function ax(e){let t=new Set;for(let n of e){if(typeof n.content!="string")continue;let r=n.content.replace(/\\/g,"/").matchAll(/([a-zA-Z]:\/[^\s"'`<>]*?\/benchmark-state)(?=\/|[\s.,;:)\]}]|$)/g);for(let s of r){let i=ke(s[1]??"");i&&t.add(i)}}return[...t]}function _g(e){try{if(!sn(e))return null;let t=JSON.parse(ms(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Bn(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?ke(n):void 0}function cx(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of Le.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=Bn(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function lx(e,t,n){let o=Oe(t?.documents),r=Oe(n?.fileVerification),s=[];for(let i of Le.keys()){let a=Oe(o?.[i]),c=Oe(r?.[i]);if(!a&&!c)return[];let l=Bn(a,"path"),m=Bn(c,"path")??(l?.includes("/context-pack/")?l:ke(`${e}/${i}`)),y=Bn(a,"contentHash")??Bn(c,"contentHash")??yl(`${i}:${m}`),_=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:ke(m),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??y),contentHash:y,summary:_,lastReviewedTurn:dl(a,"lastReviewedTurn")??dl(n,"turn")??0,fileSizeBytes:Dn(a,"fileSizeBytes")??Dn(c,"fileSizeBytes")??Dn(c,"sizeBytes")??Buffer.byteLength(_,"utf8"),recordCount:Dn(a,"recordCount")??Dn(c,"recordCount")??Pg(_)})}return s}function dl(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Dn(e,t){let n=dl(e,t);return n&&n>0?n:void 0}function ux(e){let t=e.slice(0,Math.max(0,e.length-1)),n=new Set;for(let o of t){if(typeof o.content!="string")continue;let r=o.content.replace(/\\/g,"/").toLowerCase();if(!r.includes("benchmark-state/document-index")&&!r.includes("benchmark-state/context-pack-evidence")&&!r.includes("maintained document index"))continue;let s=r.matchAll(/([a-z]:\/[^\s"'`<>]*?\/context-pack)(?=\/|[\s.,;:)\]}]|$)/gi);for(let i of s){let a=ke(i[1]??"");a&&n.add(a)}}return[...n]}function dx(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));al.has(n)&&(e.identicalCallCounts.delete(t),e.identicalFailureCounts.delete(t))}}async function*Mg(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:c,model:l,apiKey:d,temperature:m=0,hooks:y,signal:_}=e,h=(b,H)=>{b.push(H)},v={sessionId:s,turnId:r},k=e.maxTurns??0,C=e.querySource,E=a??c,O=e.runtimePorts.resolveToolEligibility(E,e.toolEligibilityContext),z=new Set(c.map(b=>b.function.name)),M=yt(O.eligibleTools,E),ee=new Map(M.map(b=>[b.function.name,b])),Ne=yt(O.eligibleTools.filter(b=>z.has(b.function.name)),E),Q=[];for(let b of O.blockedTools){let H=E.find(oe=>oe.function.name===b.toolName);H&&us(H)||(Q.push({name:b.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:b.toolName,reason:"blocked-by-policy"})}let Ke=Jr(e.maxRounds,i),nt=Xr(e.maxToolCalls),an=tm(i),lt={contextWindowTokens:e.contextWindowTokens??Eu,responseBufferTokens:Au,maxOutputTokens:e.maxOutputTokens??$u,abortSignal:_,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},Fe=new Set,ut=[],bl=new Map,_t=0,_l=new Set,vl=0,gs=new Map,Tl=new Set,kl=new Map,Cl=new Set,hs,qn=0,je,cn=!1,ln=!1,un,Rl=!1,wl=!1,ys=new Set,De=new Set,qo=new Set(e.deferredToolNames??[]),dn=new Set;for(let b of e.loadedDeferredToolNames??[])qo.has(b)&&ee.has(b)?dn.add(b):e.loadedDeferredToolNames?.delete(b);let Je=()=>{let b=new Map(Ne.map(H=>[H.function.name,H]));for(let H of dn){let oe=ee.get(H);oe&&b.set(H,oe)}return[...b.values()]},xl=(b,H)=>H?b.filter(oe=>H.has(oe.function.name)):[...b],S=Je(),Un=!1,bs=()=>$(S),Ng=Zw(Ne,i),_s=!1,Sl=0,El=0,vs=0,Al=0,$l=0,Pl=0,Ml=new Set,zn=new Map,fe=!1,fn=!1,Uo,zo,Ts=sx(i),f={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:gi(lt),reactiveCompactState:vi(),toolLoopState:cr({maxRounds:Ke,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:ni(),currentModel:l,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalFailureCounts:new Map,commercialRetryBlocks:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,variantReassertedSignatures:new Set,fileReadCounts:Ts.fileReadCounts,fileReadSignatures:new Map,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:Ts.maintainedDocuments,persistedLongHorizonStateRecovered:Ts.persistedLongHorizonStateRecovered,longHorizonStateMaintenanceRequiredFiles:new Set,longHorizonStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Xm(i),buildVerificationRecoveryCount:0,longHorizonStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentPollCounts:new Map,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},Fg=4,Lg=4,Il=0,ks=!1,Ol=new Map,Cs,B=(b,H)=>{let oe=`${b}:${H??""}`,pe=(Ol.get(oe)??0)+1;if(Ol.set(oe,pe),b==="autocompact"){let J=f.recoveryTrace.get("autocompact")??0;if(pe>Fg||J>=Lg){let ot=`Repeated context compression made no forward progress: ${H??"autocompact"}`;return Cs=ot,f.recoveryTrace.set("compression_loop_guard",(f.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:ot}}}return f.recoveryTrace.set(b,(f.recoveryTrace.get(b)??0)+1),{type:"recovery",turnId:r,action:b,detail:H}},It={roleAlias:0,promptAlias:0,backgroundAlias:0,agentValue:0,backgroundValue:0},Nl=b=>({type:"tool_use_summary",turnId:r,ledgerSchemaVersion:4,toolCalls:ut.map(H=>({...H})),finalAnswerEvidence:b,availableToolNames:$(a??c),enabledToolNames:bs(),toolCallNames:[...Fe].sort(),blockedToolCalls:ss(Q),...Object.values(It).some(H=>H>0)?{argumentCorrections:{...It}}:{}}),Fl=zm((a??c).map(b=>b.function.name)),Rs=!1,Ho=Ym(i),jg=b=>({type:"end",turnId:r,content:b,usage:f.totalUsage,model:f.currentModel,...f.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(f.recoveryTrace)}:{}});function*Be(b,H){let oe=Qn(e.freshEvidenceRequired===!0,ut,[]),pe=oe.disposition.startsWith("blocked-")?o0(oe,Ho):b,J=Zm({content:pe,contractActive:Fl,totalToolCallCount:_t,distinctToolNames:Fe,visibleToolCallCount:vl,visibleToolNames:_l,artifactContract:f.artifactContract,blockedToolCalls:ss(Q),activeTasks:f.lastTaskList,forcedStop:H?.forcedStop??Rs,locale:Ho});J.malformedBlock&&(yield B("final_status_block_malformed","final-status block was not valid schema-1 JSON; treated as absent")),Qc(f.artifactContract,J.content),xs()&&(yield ws()),yield Nl(oe),yield jg(J.content)}function*Xe(b,H){let oe=Qn(e.freshEvidenceRequired===!0,ut,[]);yield Nl(oe),yield{type:"error",turnId:r,error:b,code:H,usage:f.totalUsage}}let ws=()=>({type:"artifact_contract",turnId:r,...Zc(f.artifactContract,i)}),xs=()=>{let b=Zc(f.artifactContract,i);return!!(b.requiresBrowserAcceptance||b.artifactRoot||b.writePaths.length>0||b.outOfRootWrites.length>0||b.devServerUrls.length>0||b.browserVerified)},Ss=(b,H,oe)=>{if(oe?.cleanStopWithFinalText&&f.finalText)return f.finalText;Rs=!0;let pe=f.finalText||xc(b,o),J=Ho==="zh"?`\u26A0\uFE0F \u672C\u8F6E\u88AB\u5F15\u64CE\u9650\u5236\u63D0\u524D\u4E2D\u6B62,\u4E0B\u9762\u7684\u7ED3\u679C\u53EF\u80FD\u4E0D\u5B8C\u6574\u3002(${H})`:`\u26A0\uFE0F This turn was stopped early by an engine limit; the result below may be incomplete. (${H})`;return pe?`${J}
54
-
55
- ${pe}`:J},Dg=(b,H,oe)=>{Rs=!0;let pe=b||xc(H,o),J=Nn({inputMessages:i,messages:H,reason:oe});return J?pe?`${pe}
56
-
57
- ${J}`:J:pe},Ot=0,Hn=0;function*Bg(b){Ot<=Hn||(yield{type:"text_rollback",turnId:r,keepLength:Hn,reason:b},Ot=Hn)}for(S=bt(Je(),De);;){yield*Bg("round_restart"),Il++,ks=!1;let{messages:b,maxOutputTokensRecoveryCount:H,maxOutputTokensOverride:oe,turnCount:pe,guardState:J,reactiveCompactState:ot,collapseStore:Es}=f,{toolLoopState:qe}=f;if(e.refreshTools&&Il>1){let u=e.refreshTools(),p=new Set(u.map(P=>P.function.name)),T=xl(M.filter(P=>!qo.has(P.function.name)||dn.has(P.function.name)),p),g=yt(bt(T,De),Je());g!==S&&(S=g,o.debug(`tools refreshed within initial turn snapshot: ${T.length}/${M.length} tools`))}if(je&&(S=S.filter(u=>rl(u.function.name,je))),e.drainPendingGuidance)for(let u of e.drainPendingGuidance()){let p=u.trim();p&&(b.push({role:"user",content:p}),o.info(`mid-turn guidance injected (${p.length} chars)`))}if(e.drainPendingTaskNotifications){let u=e.drainPendingTaskNotifications().filter(p=>p.trim());u.length>0&&(mg(f,u),b.push(pg(u)),o.info(`background task result injected (${u.length} item(s))`))}if(_i(J,lt)){o.info(`turn aborted by guard at turn ${pe}`),yield*Xe("Turn aborted","ABORTED");return}let pn=yield*cm({messages:b,contentReplacementState:f.contentReplacementState,snipRemovedIds:f.snipRemovedIds,collapseStore:Es,guardState:J,guardConfig:lt,runtimePorts:e.runtimePorts,hooks:y,hookCtx:v,sessionId:s,currentModel:f.currentModel,log:o,recovery:(u,p)=>B(u,p),onAutocompact:()=>{f.hasAttemptedReactiveCompact=!1}});if(pn!==b&&b.splice(0,b.length,...pn),Cs){yield*Be(`${Cs}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`,{forcedStop:!0});return}let As=hi(J,lt);As.level==="warning"&&o.info(`token budget warning: ${As.usagePercent}% used, ${As.remainingTokens} remaining`);for(let u of Ne)us(u)&&De.delete(u.function.name);S=yt(S,Je()),wl&&(S=yt([],E),fe=!1);let Ll=fe?"required":e.toolChoice==="required"&&_s?"auto":e.toolChoice??"auto";fe=!1;let dt=si({tools:S,toolChoice:Ll}),qg=ls("sha256").update(JSON.stringify([...dt.tools].sort((u,p)=>u.function.name.localeCompare(p.function.name)))).digest("hex"),Vo=cr({maxRounds:Ke,replayMessages:pn,lastStopReason:qe.lastStopReason,options:{stopReason:qe.lastStopReason}}),$s=[dt.extraSystemPrompt,Fl?Hm:void 0].filter(u=>!!u).join(`
58
-
59
- `),jl=ls("sha256").update(JSON.stringify({model:f.currentModel,toolRequestSignature:qg,toolChoice:dt.normalizedToolChoice,extraSystemPromptForRound:$s,reasoning:e.reasoning,openaiBuiltinTools:e.openaiBuiltinTools,parallelToolCalls:e.parallelToolCalls})).digest("hex"),Dl=Uo!==void 0&&Uo!==jl,Ps=Vo.state.replayMessages,Bl=!fn&&!Dl&&f.lastResponseId&&zo?S0(Ps,zo):void 0,Go=Bl?f.lastResponseId:void 0;f.lastResponseId&&!fn&&!Go&&(yield B("stateless_retry",Dl?"request context changed; replaying full history without previous_response_id":"local transcript changed; replaying full history without previous_response_id"));let Ug=$s?[{role:"system",content:$s},...Ps]:Ps,ql=Bl??Ug;qe=Vo.state,Vo.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Vo.recoveryActions.map(u=>u.detail??u.kind).join("; ")}`),o.debug(`turn ${pe}, messages: ${ql.length}`),ue(y,"turn.before_inference",{...v,model:f.currentModel},o);let Vn=!1,Ul=[],Ms=Ll==="required"||e.freshEvidenceRequired===!0&&_t===0&&vs===0,Is=Sm(),Os=e.toolChoice==="none"?Vu():null,Wo=0,mn="";function*zg(u){if(!u)return;let p=Os?Os.push(u):u,T=Is.push(p);if(T){if(Ms){mn+=T;return}Wo+=T.length,Ot+=T.length,yield{type:"delta",turnId:r,text:T}}}function*Hg(){let u=Os?.flush()??"",T=(u?Is.push(u):"")+Is.flush();if(T){if(Ms){mn+=T;return}Wo+=T.length,Ot+=T.length,yield{type:"delta",turnId:r,text:T}}}function*Vg(){if(!mn)return;let u=mn;mn="",Wo+=u.length,Ot+=u.length,yield{type:"delta",turnId:r,text:u}}let zl=new Map,Ns="stop",xe,Ko,K=null,Jo=null,Gg=performance.now(),Fs,Hl=0,Vl=0,Gl=0,Ls=0,js,Nt,Wl=!1,Xo=!1,Kl=!1,gn=[],rt=[];try{let u=t.stream({model:f.currentModel,messages:ql,...dt.tools.length>0?{tools:dt.tools,toolChoice:dt.normalizedToolChoice??"auto"}:{},temperature:m,maxTokens:(oe??J.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Go,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:nt,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},d,_);for await(let p of z0(u,e.llmStreamIdleTimeoutMs??$0))switch(Fs===void 0&&p.type!=="usage"&&p.type!=="response_id"&&(Fs=Math.max(0,Math.round(performance.now()-Gg))),p.type){case"delta":Hl+=1,Vl+=p.text.length,Nt===void 0&&(Nt="text"),Ls===0&&(Wl=!0),Ul.push(p.text),yield*zg(p.text);break;case"tool_call_delta":Ls+=1,Nt===void 0&&(Nt="tool_call"),Vn=!0,Ti(zl,p);break;case"reasoning_delta":Gl+=1,Nt===void 0&&(Nt="reasoning"),gn.push(p.text);break;case"reasoning_block_complete":p.signature&&rt.push({thinking:gn.join(""),signature:p.signature}),gn.length=0;break;case"usage":Ko=mi(p),xe={inputTokens:p.promptTokens,outputTokens:p.completionTokens,reasoningTokens:p.reasoningTokens,cacheRead:p.cacheReadTokens,cacheWrite:p.cacheCreationTokens};break;case"response_id":js=p.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:p.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${p.toolType}: ${p.event}`};break;case"error":Jo=p.message||"LLM provider returned an error chunk";break;case"done":Kl=!0,Ns=p.finishReason;break}if(yield*Hg(),Jo){ue(y,"stop.failure",{sessionId:s,reason:"PROVIDER_STREAM_ERROR",error:Jo},o),yield*Xe(Jo,"PROVIDER_STREAM_ERROR");return}if(Vn||ue(y,"turn.after_inference",{...v,model:f.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let p=f.currentModel;for(let T of e.postSamplingHooks)try{T({messages:[...pn],model:p,sessionId:s})}catch{}}}catch(u){if(u instanceof fs){ue(y,"stop.failure",{sessionId:s,reason:u.code,error:u.message},o),yield*Xe(u.message,u.code);return}let p=yield*lm(u,{state:f,guardState:J,fallbackModel:e.fallbackModel,signal:_,querySource:C,turnId:r,log:o,emitRecovery:B});if(p.kind==="return")return;if(p.kind==="continue"){f={...f,...p.patch};continue}K=p.streamError}if(!K&&!Kl){let u="LLM stream closed before a terminal event; the response was likely truncated upstream.";ue(y,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:u},o),yield*Xe(u,"RETRYABLE_TRANSIENT");return}if(K&&ue(y,"turn.after_inference",{...v,model:f.currentModel,response:{error:K.message}},o),K){if(!fn&&Go&&/previous_response_id not found/i.test(K.message)){let u=(f.consecutiveApiRetries??0)+1;if(u<=Bt){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield B("stateless_retry","previous_response_id not found; replaying full history"),fn=!0,f={...f,lastResponseId:void 0,consecutiveApiRetries:u,transition:void 0};continue}}if(Ac(K))Xo=!0,o.info(`withheld prompt_too_long error (status=${K.status})`);else if(Pc(K))Xo=!0,o.info(`withheld media_size error (status=${K.status})`);else{let u=yi({status:K.status??500,message:K.message},J,lt);if(u.action==="reactive_compact"&&Zn(ot)&&(ot.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,yield B("reactive_compact",`API ${K.status??500}: ${K.message}`)),u.action==="retry"){let T=(f.consecutiveApiRetries??0)+1;if(T>Bt){o.info(`API retry limit reached (${Bt}), aborting`);let g=yn(K.status,K.message);yield*Xe(K.message,g);return}yield B("retry",u.reason),f={...f,consecutiveApiRetries:T,transition:void 0};continue}let p=yn(K.status,K.message);ue(y,"stop.failure",{sessionId:s,reason:p,error:K.message},o),yield*Xe(K.message,p);return}}xe&&(f.totalUsage.inputTokens+=xe.inputTokens,f.totalUsage.outputTokens+=xe.outputTokens,xe.reasoningTokens&&(f.totalUsage.reasoningTokens=(f.totalUsage.reasoningTokens??0)+xe.reasoningTokens),xe.cacheRead&&(f.totalUsage.cacheRead=(f.totalUsage.cacheRead??0)+xe.cacheRead),xe.cacheWrite&&(f.totalUsage.cacheWrite=(f.totalUsage.cacheWrite??0)+xe.cacheWrite)),o.info(`[provider-context] ${JSON.stringify({event:"context_ledger_round",turnId:r,round:pe,ttftMs:Fs,inputTokens:xe?.inputTokens??0,outputTokens:xe?.outputTokens??0,cacheReadTokens:xe?.cacheRead??0,cacheWriteTokens:xe?.cacheWrite??0,totalPromptTokens:Ko??0,previousResponseIdUsed:Go!==void 0,toolDefinitionCount:S.length,providerTextChunkCount:Hl,providerTextChars:Vl,providerReasoningChunkCount:Gl,providerToolCallDeltaCount:Ls,firstSemanticProviderEvent:Nt??"none",textBeforeFirstToolCall:Wl,suppressLiveText:Ms,liveEmittedTextChars:Wo,bufferedSuppressedTextChars:mn.length})}`),Ko&&(J.promptTokens=Ko);let me=Ul.join(""),ae=[...zl.values()].map((u,p)=>({id:u.id||`tc_${r}_${pe}_${p}`,type:"function",function:{name:u.name,arguments:u.arguments}}));ae=H0(ae),ae=ae.map(u=>{let p=Ku(u.function.name,u.function.arguments);if(p.corrections.length===0)return u;for(let T of p.corrections)T==="agent-value"?It.agentValue+=1:T==="background-value"?It.backgroundValue+=1:T.endsWith("->agent")?It.roleAlias+=1:T.endsWith("->prompt")?It.promptAlias+=1:T.endsWith("->background")&&(It.backgroundAlias+=1);return o.info({event:"tool_argument_normalized",toolName:u.function.name,corrections:p.corrections,turnId:r},`host normalized ${u.function.name} arguments`),{...u,function:{...u.function,arguments:p.rawArguments}}});let Jl=[];ae=ae.map(u=>{let p=h0(u,dt.tools);return p.originalName&&(Jl.push({originalName:p.originalName,reboundName:p.call.function.name,callId:p.call.id}),o.warn({event:"tool_call_schema_rebound",turnId:r,callId:p.call.id,originalName:p.originalName,reboundName:p.call.function.name},"rebound malformed tool call to its unique declared schema")),p.call});for(let u of Jl)yield B("unique_schema_tool_rebind",`${u.callId}:${u.originalName}->${u.reboundName}`);let vt=ae.flatMap(u=>{let p=dt.tools.find(g=>g.function.name===u.function.name),T=il(p,u.function.arguments);return T?[{call:u,error:T}]:[]});if(vt.length>0){for(let{call:p}of vt){let T=`${p.function.name}::${p.function.arguments}`;zn.set(T,(zn.get(T)??0)+1)}let u=vt.map(({call:p,error:T})=>`${p.function.name}:${p.function.arguments}:${T}`).sort().join("\0");if(!Ml.has(u)){Ml.add(u),fn=!0,fe=!0;for(let{call:T}of vt)Fe.add(T.function.name);let p=vt.map(({call:T,error:g})=>`${T.function.name} (${T.id}): ${g}`).join(`
60
- `);o.warn({event:"tool_schema_preflight_rejected",turnId:r,rejectedCallCount:vt.length,rejectedToolNames:vt.map(({call:T})=>T.function.name)},"rejected a malformed tool batch before execution"),yield B("tool_schema_preflight_retry",`${vt.length} malformed call(s) rejected before execution`),f={...f,messages:[...b,{role:"user",content:`The previous proposed tool batch was not executed because one or more calls violated the exact JSON Schemas offered for this round. Correct the whole batch and call the tools again. Do not repeat the rejected arguments unchanged.
61
- `+p}],finalText:"",transition:{reason:"next_turn"}};continue}}if(e.toolChoice==="none"&&ae.length===0&&Hu(me)){if(Pl<1){Pl++,yield B("direct_response_protocol_retry","no-tool answer leaked tool-protocol markup; retrying once"),f={...f,messages:[...b,{role:"user",content:"Your previous response used forbidden tool-call protocol text. This is a direct-response turn: perform the operation mentally and reply with only the requested result. Do not call, describe, or imitate any tool."}],finalText:"",transition:{reason:"next_turn"}};continue}let u="The model repeatedly emitted tool-call protocol during a direct-response turn.";ue(y,"stop.failure",{sessionId:s,reason:"MODEL_PROTOCOL_VIOLATION",error:u},o),yield*Xe(u,"MODEL_PROTOCOL_VIOLATION");return}if(!K&&_t===0&&ae.length===0&&!Vn&&me.trim()===""&&gn.join("").trim()===""&&rt.length===0){if(Al<1){Al++,yield B("empty_response_retry","model returned an empty response; retrying once"),f={...f,messages:[...b,{role:"user",content:"Your previous response was empty. Reply with a substantive answer now. If you cannot complete the request, explain the blocker plainly instead of returning no content."}],finalText:"",transition:{reason:"next_turn"}};continue}let u="LLM returned an empty response twice before any tool use.";ue(y,"stop.failure",{sessionId:s,reason:"EMPTY_MODEL_RESPONSE",error:u},o),yield*Xe(u,"EMPTY_MODEL_RESPONSE");return}if(!K&&_t>0&&Rl&&ae.length===0&&!Vn&&me.trim()===""&&!$c(Ns)&&$l<1){$l++,yield B("post_tool_empty_response_retry","model returned no user-visible response after tool use; retrying once with preserved evidence"),f={...f,messages:[...b,{role:"user",content:"The tool evidence is preserved, but your previous response contained no user-visible answer. Continue from that evidence now: either take the next necessary action or give the user a concise, honest result. Do not repeat a completed or uncertain action merely to produce text."}],finalText:"",transition:{reason:"next_turn"}};continue}if(ae.length===0&&!Vn){if(e.drainPendingTaskNotifications){let w=e.drainPendingTaskNotifications().filter(I=>I.trim());if(w.length>0){mg(f,w),f={...f,messages:[...b,...me?[{role:"assistant",content:me}]:[],pg(w)]},o.info(`late background task result consumed at completion (${w.length} item(s)) \u2014 running another round`);continue}}if(e.drainPendingGuidance){let w=e.drainPendingGuidance().map(I=>I.trim()).filter(Boolean);if(w.length>0){f={...f,messages:[...b,...me?[{role:"assistant",content:me}]:[],...w.map(I=>({role:"user",content:I}))]},o.info(`late mid-turn guidance consumed at completion (${w.length} item(s)) \u2014 running another round`);continue}}if(me){let w=f.transition?.reason==="max_output_tokens_escalate"||f.transition?.reason==="max_output_tokens_recovery";f.finalText=w?`${f.finalText}${me}`:me}if(e.toolChoice==="required"&&!_s&&S.length>0&&Sl<2){Sl++;let w=S.map(I=>I.function.name).filter(Boolean).slice(0,8).join(", ");f={...f,messages:[...b,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${w}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(Xo&&K&&Ac(K)){if(f.transition?.reason!=="collapse_drain_retry"){let w=ri(pn,Es);if(w.committed>0){o.info(`collapse drain: committed ${w.committed} stages`),yield B("collapse_drain",`${w.committed} stages committed`),f={...f,messages:w.messages,transition:{reason:"collapse_drain_retry",committed:w.committed}};continue}}if(Zn(ot)){ot.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield B("reactive_compact","withheld prompt_too_long"),f={...f,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),ue(y,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:K.message},o),yield*Xe(K.message,"PROMPT_TOO_LONG");return}if(Xo&&K&&Pc(K)){if(Zn(ot)){ot.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield B("reactive_compact","media error strip-retry"),f={...f,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),ue(y,"stop.failure",{sessionId:s,reason:"media_error",error:K.message},o),yield*Xe(K.message,"IMAGE_ERROR");return}if($c(Ns)){J.consecutiveTruncations+=1;let w=e.modelMaxOutputTokens??Pu,I=bi(J,lt,w),Ce={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."},de=[...pn,...me?[{role:"assistant",content:me}]:[],Ce];if(I.shouldEscalate&&oe===void 0){J.currentMaxOutputTokens=I.newMax,o.info(`max_output_tokens escalate: ${I.newMax} tokens`),yield B("output_escalation",`${I.newMax} tokens`),f={...f,messages:de,maxOutputTokensOverride:I.newMax,transition:{reason:"max_output_tokens_escalate"}};continue}if(H<Mu){o.info(`max_output_tokens recovery #${H+1}`),yield B("max_output_tokens_recovery",`attempt ${H+1}`),f={...f,messages:de,maxOutputTokensRecoveryCount:H+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:H+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content"),ks=!0}else J.consecutiveTruncations=0;qe=ar(qe,{replayMessages:b,lastStopReason:"completed"});let u=await xm({hooks:y,sessionId:s,messages:b,finalText:f.finalText,thinkingBlocks:rt,log:o});if(u?.action==="end"){let w=Dg(u.content,b,"stop hook prevented continuation before completing the final status contract");yield*Be(w);return}if(u?.action==="continue"){f={...f,messages:u.messages,stopHookActive:u.stopHookActive,transition:u.transition};continue}let p=Am({tokenBudget:e.tokenBudget,totalUsage:f.totalUsage,budgetContinuationCount:f.budgetContinuationCount,lastBudgetDeltaTokens:f.lastBudgetDeltaTokens,lastBudgetGlobalTokens:f.lastBudgetGlobalTokens,messages:b,finalText:f.finalText,thinkingBlocks:rt,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o,recoveryTrace:f.recoveryTrace});if(p){yield B("budget_continuation",p.recoveryDetail),f={...f,messages:p.messages,budgetContinuationCount:p.budgetContinuationCount,lastBudgetDeltaTokens:p.lastBudgetDeltaTokens,lastBudgetGlobalTokens:p.lastBudgetGlobalTokens,transition:p.transition};continue}if(f.finalText.trim()&&g0(f.lastTaskList)&&f.taskListReconciliationCount<1){let w=S.find(I=>I.function.name==="task")??(a??c).find(I=>I.function.name==="task");if(w){let I=m0(f.lastTaskList),Ce=$(S),de=bt(Je(),De);S=de.some(or=>or.function.name==="task")?de:[...de,w],f={...f,taskListReconciliationCount:f.taskListReconciliationCount+1,messages:[...b,{role:"assistant",content:f.finalText},{role:"user",content:I}],transition:{reason:"next_turn"}},fe=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:$(a??c),enabledToolNamesBefore:Ce,enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield B("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if((e.buildVerificationGate??!0)&&Um(i)&&!f.artifactContract.buildVerified&&f.artifactContract.buildFailureEvidence.length>0&&S.some(w=>w.function.name==="exec")&&f.buildVerificationRecoveryCount<3){let w=u0(f.artifactContract);f={...f,buildVerificationRecoveryCount:f.buildVerificationRecoveryCount+1,messages:[...b,{role:"assistant",content:f.finalText},{role:"user",content:w}],transition:{reason:"next_turn"}},fe=!0,yield B("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let T=Lc({inputMessages:i,messages:b,finalText:f.finalText,thinkingBlocks:rt,stopHookActive:f.stopHookActive,totalToolCallCount:_t,distinctToolNames:Fe,log:o});if(T){if(f.stopHookActive&&f.finalText.trim()===""){let w=Nn({inputMessages:i,messages:T.messages,reason:"stop hook produced an empty response after tool use"});if(w){yield*Be(w,{forcedStop:!0});return}}f={...f,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition};continue}if(_t===0&&e.toolChoice!=="none"&&El<1&&em(me)){El++;let w=$(a??c).join(", ");yield B("capability_denial_review","unverified capability denial; asking for verification or honest escalation"),f={...f,messages:[...b,{role:"assistant",content:me},{role:"user",content:`Before declaring a capability missing, verify it. Your full tool list: [${w}]. If any tool there can fulfil the request \u2014 including exec running a script or OS command (e.g. PowerShell) \u2014 use it NOW. Only if none of these can work, state plainly WHICH capability is missing and what the user could enable \u2014 do not just refuse.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(e.freshEvidenceRequired&&!Du(ut)&&S.some(w=>fr({identity:fg(w,w.function.name)}))&&e.toolChoice!=="none"&&vs<1&&me.trim()!==""){vs++,fe=!0,yield B("fresh_evidence_required","evidence turn answered with no tool call; forcing one grounded retry"),f={...f,messages:[...b,{role:"assistant",content:me},{role:"user",content:"This request requires FRESH tool evidence from this turn (reading the actual file, running the actual command, or generating the actual media). Do not answer from memory or invent content. Call the appropriate tool NOW and base your answer on its result."}],finalText:"",transition:{reason:"next_turn"}};continue}let g=Ss(b,"the model ended with an empty response after tool use before completing the final status contract",{cleanStopWithFinalText:!0}),P=ks?Ho==="zh"?"\u26A0\uFE0F \u8F93\u51FA\u7ECF\u591A\u6B21\u7EED\u5199\u540E\u4ECD\u88AB\u957F\u5EA6\u4E0A\u9650\u622A\u65AD,\u4EE5\u4E0B\u5185\u5BB9\u53EF\u80FD\u4E0D\u5B8C\u6574\u3002":"\u26A0\uFE0F Output was still cut off by the length limit after multiple continuation attempts; the content below may be incomplete.":null;yield*Be(P&&g?`${P}
62
-
63
- ${g}`:g);return}let Wg=rt.length===0&&gn.length>0?gn.join(""):void 0;Hn=Ot,h(b,Qs(ae,me||void 0,rt.length>0?rt:void 0,Wg)),!fn&&js?(f.lastResponseId=js,Uo=jl,zo=Rg(b)):(f.lastResponseId=void 0,Uo=void 0,zo=void 0),qe=ui(qe,{replayMessages:b,pendingToolCallIds:ae.map(u=>u.id),completedToolCallIds:qe.completedToolCallIds,lastStopReason:"tool_calls"});let Ds=f.identicalCallCounts,Bs=f.identicalFailureCounts,Gn=[],ft=[],Xl=[],Wn=[],Yl=!1;for(let u of ae){if(gg(u,f)){Gn.push(u);continue}let p=`${u.function.name}::${u.function.arguments}`;if(f.commercialRetryBlocks.has(p)){Xl.push(u);continue}let T=Ds.get(p)??0;Ds.set(p,T+1);let g=Bs.get(p)??0,P=zn.get(p)??0,w=al.has(u.function.name)||u.function.name==="exec"?f.identicalSuccessfulToolResults.get(p):void 0;g>=bn||P>=bn?(ft.push(u),Yl||(Yl=!0,o.info(P>=bn?`AP4 blocked: ${u.function.name} proposed invalid identical arguments ${P}x`:`AP4 blocked: ${u.function.name} failed ${g}x with identical arguments`))):T+1>bn&&w?Wn.push({call:u,result:w,repeatCount:T+1}):Gn.push(u)}let ye=[],Kg=new Set(S.map(u=>u.function.name)),Zl=new Set(ft.filter(u=>ex(u,Kg)).map(u=>u.id));for(let u of Wn){let p=u.call;Bs.delete(`${p.function.name}::${p.function.arguments}`);let T=`Reused previous successful ${p.function.name} result for identical arguments (attempt ${u.repeatCount}); no additional tool execution was performed.
64
-
65
- ${u.result.content}`,g=be(p.id,{ok:!0,payload:T,imageUrls:u.result.imageUrls,toolReferences:u.result.toolReferences,contentBlocks:u.result.contentBlocks,structuredContent:u.result.structuredContent,mcpMeta:u.result.mcpMeta,mcpIsError:u.result.mcpIsError});h(b,g),ye.push(p.id),yield{type:"tool_result",turnId:r,callId:p.id,name:p.function.name,ok:!0,outputPreview:T.slice(0,2e3),durationMs:0,details:{type:p.function.name,reusedIdenticalCall:!0,repeatCount:u.repeatCount}}}if(Wn.some(u=>u.call.function.name==="exec"&&lg(u.call.function.arguments))){let u=$(S);b.push({role:"user",content:p0()}),yield{type:"tool_selection_policy",turnId:r,policyId:"ui_acceptance_after_preparation_guidance",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:$(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:u,suppressedToolNames:[],nextAction:"reuse-or-collect-reliable-ui-evidence"},yield B("ui_acceptance_after_preparation_guidance","reused successful browser preparation command")}for(let u of ft){let p=`${u.function.name}::${u.function.arguments}`;(zn.get(p)??0)>=bn&&Q.push({name:u.function.name,reason:"invalid-arguments"}),Q.push({name:u.function.name,reason:"identical-repeat-policy"});let T=Math.max(Bs.get(p)??0,zn.get(p)??0),g=Kr(b,u.function.name,u.function.arguments),P=r0(g),w=Zl.has(u.id)?tx(T,u):P?`This exact tool call has been attempted ${T} times. Last error: ${P}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${T} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,I=be(u.id,{ok:!1,error:w});h(b,I),ye.push(u.id),yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:w}}for(let u of Xl){let p=`${u.function.name}::${u.function.arguments}`,T=f.commercialRetryBlocks.get(p);Q.push({name:u.function.name,reason:"commercial-retry-not-authorized"});let g=`This exact commercial tool call was not executed again because its typed failure contract did not authorize an automatic retry${T.stage?` at stage ${T.stage}`:""}. Billing state: ${T.billed===null?"unconfirmed":T.billed?"billed":"not billed"}; retry mode: ${T.retryMode}. Correct the request or prerequisite, obtain a new explicit user action when required, or report the blocker.`;h(b,be(u.id,{ok:!1,error:g})),ye.push(u.id),yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:g,details:{type:"commercial_retry_not_authorized",...T}}}if(ft.length>0&&Gn.length===0&&Wn.length===0&&ft.every(u=>Zl.has(u.id))&&f.existingFileUpdateRecoveryCount<2){let u=$(S);S=bt(Je(),De);let p=$(S);Un=!0,fe=!0;let T=[...new Set(ft.map(g=>ps(g.function.arguments)).filter(g=>!!g))];b.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${T.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:$(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:p,suppressedToolNames:[],nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield B("existing_file_update_recovery",T.join(",")||"unknown"),f={...f,messages:b,existingFileUpdateRecoveryCount:f.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(ft.length>0){let u=ft[0],p=Kr(b,u.function.name,u.function.arguments),T={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(p?`The error was: "${p}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};b.push(T)}let Jg=an>=3&&f.repeatedToolFailureRecoveryCount<1;if(ft.length>0&&Gn.length===0&&Wn.length===0&&!Jg){let u=ug(Sc(b,1),{availableToolNames:$(a??c),enabledToolNames:bs(),toolCallNames:[...Fe].sort(),blockedToolCalls:ss(Q)});yield*Be(u);return}let Ql=[],qs=[];for(let u of Gn){let p=Wm({toolName:u.function.name,rawArguments:u.function.arguments});p?qs.push({call:u,...p}):Ql.push(u)}for(let u of qs){let p=u.call;Q.push({name:p.function.name,reason:"read-only-context-pack"}),h(b,be(p.id,{ok:!1,error:u.error})),ye.push(p.id),yield{type:"tool_result",turnId:r,callId:p.id,name:p.function.name,ok:!1,error:u.error},o.warn(`read-only context-pack blocked: ${p.function.name} ${u.path}`)}qs.length>0&&b.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let Xg=new Set(S.map(u=>u.function.name)),Us=[],Yo=[];for(let u of Ql){let p=$g(u.function.name,u.function.arguments,Xg);if(p){let T=`${u.function.name}::${u.function.arguments}`;if(ys.has(T)){ys.delete(T),o.info(`existing-file-update guard: verbatim re-issue admitted once for ${p.path}`),Us.push(u);continue}ys.add(T),Yo.push({call:u,...p})}else Us.push(u)}for(let u of Yo){let p=u.call;Q.push({name:p.function.name,reason:"existing-file-update-tool-required"}),h(b,be(p.id,{ok:!1,error:u.error})),ye.push(p.id),yield{type:"tool_result",turnId:r,callId:p.id,name:p.function.name,ok:!1,error:u.error},o.info(`existing file update blocked: ${p.function.name} ${u.path}`)}if(Yo.length>0){let u=$(S);S=bt(Je(),De);let p=$(S);Un=!0,fe=!0;let T=[...new Set(Yo.map(g=>g.path))];b.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${T.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:$(a??c),enabledToolNamesBefore:u,enabledToolNamesAfter:p,suppressedToolNames:[],nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield B("existing_file_update_recovery",T.join(",")||"unknown"),f={...f,messages:b,existingFileUpdateRecoveryCount:f.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let eu=[],zs=[];for(let u of Us){let p=Gm({state:f.artifactContract,inputMessages:i,toolName:u.function.name,rawArguments:u.function.arguments});p?zs.push({call:u,...p}):eu.push(u)}for(let u of zs){let p=u.call;Q.push({name:p.function.name,reason:"artifact-root-contract"}),Yc(f.artifactContract,{path:u.path,artifactRoot:u.artifactRoot,toolName:p.function.name}),h(b,be(p.id,{ok:!1,error:u.error})),ye.push(p.id),yield{type:"tool_result",turnId:r,callId:p.id,name:p.function.name,ok:!1,error:u.error},xs()&&(yield ws()),o.warn(`artifact root contract blocked: ${p.function.name}`)}zs.length>0&&b.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let tu=[],Hs=[];for(let u of eu){let p=Rm({inputMessages:i,messages:b,toolCall:u});p?Hs.push({call:u,error:p}):tu.push(u)}for(let u of Hs){let p=u.call;Q.push({name:p.function.name,reason:"premature-completion-artifact"}),h(b,be(p.id,{ok:!1,error:u.error})),ye.push(p.id),yield{type:"tool_result",turnId:r,callId:p.id,name:p.function.name,ok:!1,error:u.error},o.info(`premature completion artifact blocked: ${p.function.name}`)}Hs.length>0&&b.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let Yg=new Set(S.map(u=>u.function.name)),nu=[],Zo=[];for(let u of tu)Yg.has(u.function.name)?nu.push(u):Zo.push(u);for(let u of Zo){let p=`Tool "${u.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;Q.push({name:u.function.name,reason:"not-offered"}),h(b,be(u.id,{ok:!1,error:p})),ye.push(u.id),Fe.add(u.function.name),o.warn(`unoffered tool call suppressed: ${u.function.name}`)}if(Zo.length>0&&f.notOfferedToolRecoveryCount<1){let u=[...new Set(Zo.map(I=>I.function.name))].sort(),p=u.filter(I=>qo.has(I)&&!dn.has(I)),T=Un&&u.includes("write"),g=u.filter(I=>De.has(I)),w=(a??c).filter(I=>u.includes(I.function.name));if(p.length>0)f.notOfferedToolRecoveryCount+=1,fe=!0,b.push({role:"user",content:`The full schema for ${p.map(I=>`\`${I}\``).join(", ")} was not loaded. If you still select that capability, call \`${Ci}\` with the exact name first; do not guess its arguments.`}),yield B("deferred_tool_schema_not_loaded",p.join(","));else if(g.length>0)f.notOfferedToolRecoveryCount+=1,fe=!0,b.push({role:"user",content:`You retried ${g.map(I=>`\`${I}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:$(a??c),enabledToolNamesBefore:$(S),enabledToolNamesAfter:$(S),suppressedToolNames:g,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield B("policy_suppressed_tool_retry_blocked",g.join(","));else if(!T&&w.length>0){let I=$(S),Ce=new Map(S.map(de=>[de.function.name,de]));for(let de of w)Ce.set(de.function.name,de);S=[...Ce.values()],f.notOfferedToolRecoveryCount+=1,fe=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:$(a??c),enabledToolNamesBefore:I,enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},b.push({role:"user",content:`You called ${u.map(de=>`\`${de}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield B("available_tool_reenabled_after_not_offered_call",u.join(","))}}let ou=[],Vs=[];for(let u of nu){let p=dt.tools.find(g=>g.function.name===u.function.name),T=il(p,u.function.arguments);T?Vs.push({call:u,error:T}):ou.push(u)}for(let u of Vs){let p=u.call;Q.push({name:p.function.name,reason:"invalid-arguments"}),h(b,be(p.id,{ok:!1,error:u.error})),ye.push(p.id),Fe.add(p.function.name),o.info(`invalid tool arguments blocked: ${p.function.name}`)}Vs.length>0&&b.push({role:"user",content:"Some tool calls were blocked before execution because they did not match the tool schema. Do not retry the same tool with substituted fields. Use the required field names exactly, switch to the correct tool, or stop and report the invalid tool input."});let Qo=[],Gs=[],ru=[],su=[],Ws=new Map,iu=(u,p)=>{let T=Ws.get(u);Ws.set(u,T?`${T}
66
- ${p}`:p)};for(let u of ou){if(u.function.name!=="exec"){Qo.push(u);continue}let p=u,T=s0(p.function.arguments),g=T?c0(T):null;g&&(p={...p,function:{...p.function,arguments:ag(p.function.arguments,g)}},su.push({originalCommand:T??"",rewrittenCommand:g}),iu(u.id,`[Engine notice] Adjusted this command before execution: removed the blocking sleep prefix (a foreground sleep stalls the turn). Executed: ${g}`),T=g);let P=T?l0(T):null;if(P?.action==="block")Gs.push({call:p,error:P.error});else if(P?.action==="rewrite"){let w={...p,function:{...p.function,arguments:ag(p.function.arguments,P.command)}};ru.push({call:w,originalCommand:T??"",rewrittenCommand:P.command}),iu(u.id,`[Engine notice] Adjusted this command before execution: appended --strictPort so a busy port cannot fall back onto reserved frontend port ${ds}. Executed: ${P.command}`),Qo.push(w)}else Qo.push(p)}for(let u of su)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:$(a??c),enabledToolNamesBefore:$(S),enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${u.originalCommand} -> ${u.rewrittenCommand}`);for(let u of ru){let p=$(S);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:$(a??c),enabledToolNamesBefore:p,enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${u.originalCommand} -> ${u.rewrittenCommand}`)}for(let u of Gs){let p=u.call;Q.push({name:p.function.name,reason:"reserved-frontend-port"});let T=$(S);h(b,be(p.id,{ok:!1,error:u.error})),ye.push(p.id),yield{type:"tool_result",turnId:r,callId:p.id,name:p.function.name,ok:!1,error:u.error,details:{type:p.function.name,error:"reserved_frontend_port",reservedPort:ds}},o.info(`reserved frontend port preflight blocked: ${p.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:$(a??c),enabledToolNamesBefore:T,enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}Gs.length>0&&b.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let Kn=[],hn=[];for(let u of Qo){if(u.function.name!=="read"){Kn.push(u);continue}let p=ll(u.function.arguments);if(!p){Kn.push(u);continue}let T=ke(p),g=xg(T);if((f.fileReadCounts.get(T)??0)>=g){let P=f.fileReadSignatures.get(T),w=yg(p);if(P&&w&&(w.mtimeMs!==P.mtimeMs||w.sizeBytes!==P.sizeBytes)){o.info(`read cycle exemption: ${T} changed since last counted read, cap reset`),f.fileReadCounts.set(T,0),Kn.push(u);continue}hn.push({call:u,filePath:T,maxReads:g})}else Kn.push(u)}for(let u of hn){let p=u.call,T=`Read cycle policy blocked another read of "${u.filePath}" after ${u.maxReads} successful reads in this turn. Stop rereading the same large document. ${sl(u.filePath)}`;Q.push({name:p.function.name,reason:"read-cycle-policy"}),f.fileReadCycleBlockedPaths.add(u.filePath),h(b,be(p.id,{ok:!1,error:T})),ye.push(p.id),yield{type:"tool_result",turnId:r,callId:p.id,name:p.function.name,ok:!1,error:T},o.info(`read cycle blocked: ${u.filePath}`)}if(hn.length>0){let u=[...new Set(hn.map(g=>`${g.filePath} (max ${g.maxReads})`))].join(", "),p=[...new Set(hn.map(g=>sl(g.filePath)))].join(" ");if(b.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${u}. Do not retry the read with a different path spelling. ${p} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),S.some(g=>bg(g.function.name))&&(f.persistedLongHorizonStateRecovered||hn.some(g=>ml(g.filePath)))){let g=$(S),P=g.filter(w=>F0.has(w)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:$(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},b.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${P.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield B("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(U0(Q,f.fileReadCycleBlockedPaths,f.persistedLongHorizonStateRecovered,f.maintainedDocuments)){yield*Be("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.",{forcedStop:!0});return}}let au=[],er=[];for(let u of Kn){let p=cg(u.function.name,u.function.arguments);p&&Cl.has(p)?er.push({call:u,key:p}):au.push(u)}for(let u of er){let p=`No-progress stop: ${u.key} already crossed the material-progress threshold. The same observation cannot run again in this turn because task state revision and output identity did not change.`;Q.push({name:u.call.function.name,reason:"no-progress-stop"}),h(b,be(u.call.id,{ok:!1,error:p})),ye.push(u.call.id),yield{type:"tool_result",turnId:r,callId:u.call.id,name:u.call.function.name,ok:!1,error:p}}if(er.length>0){yield*Be(`Stopped a repeated no-progress action after ${is} unchanged observations. Blocked target(s): ${[...new Set(er.map(u=>u.key))].join(", ")}. No material task-state revision or new output was observed, so continuing the same action would only spin. Try a fundamentally different approach in a new turn or inspect the underlying task directly.`,{forcedStop:!0});return}let Ks=Mm(au,f.toolFailureCounts,f.variantReassertedSignatures),cu=Ks.allowed,st=cu.slice(0,nt);st.length>0&&(yield*Vg(),Hn=Ot);for(let u of st){if(!gg(u,f))continue;let p=We(u.function.arguments),T=typeof p?.taskId=="string"?p.taskId:void 0;!p||!T||typeof p.waitMs=="number"||(u.function.arguments=JSON.stringify({...p,waitMs:R0(f.backgroundAgentPollCounts.get(T)??0)}))}let lu=cu.slice(st.length);if(Ks.blocked.length>0){for(let u of Ks.blocked){let p=u.call;Q.push({name:p.function.name,reason:"variant-failure-policy"});let T=be(p.id,{ok:!1,error:u.error});h(b,T),ye.push(p.id),yield{type:"tool_result",turnId:r,callId:p.id,name:p.function.name,ok:!1,error:u.error},o.info(`variant tool blocked: ${p.function.name} failed ${u.failCount}x with different args`)}b.push(Im())}if(lu.length>0){let u=`This model round proposed more than ${nt} tool calls. Only the first ${nt} were executed; re-issue any still-needed calls in the next round.`;for(let p of lu){Q.push({name:p.function.name,reason:"per-round-tool-call-limit"});let T=be(p.id,{ok:!1,error:u});h(b,T),ye.push(p.id)}b.push({role:"user",content:u})}for(let u of st){let p=u.function.arguments,T=S.find(P=>P.function.name===u.function.name);if(T?.backfillObservableInput)try{let P=JSON.parse(u.function.arguments),w={...P};T.backfillObservableInput(w),Object.keys(w).some(Ce=>!(Ce in P))&&(p=JSON.stringify(w))}catch{}let g={sequence:ut.length,callId:u.id,name:u.function.name,identity:fg(T,u.function.name),status:"running",arguments:p};ut.push(g),bl.set(u.id,g),yield{type:"tool_call",turnId:r,callId:u.id,name:u.function.name,...T?.meta?.displayName?.fallback?.trim()?{displayName:T.meta.displayName.fallback.trim()}:{},arguments:p,inputSummary:Ec(p)},_l.add(u.function.name),vl++}let Zg=new Map(f.toolFailureCounts),tr=null,Tt;try{let u=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:y,sessionId:s,turnId:r,log:o,signal:_,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:xu,executionTimeoutMsByTool:new Map(S.flatMap(g=>{let P=g.meta?.executionTimeoutMs;return typeof P=="number"&&Number.isFinite(P)&&P>0?[[g.function.name,P]]:[]})),contextState:f.contentReplacementState});for(let g of st)u.addTool(g);let p=!1;for await(let g of u.getRemainingResults()){let P=v0(g.details),w=Cg(g.details);if(w==="committed")Rl=!0,hs=void 0,qn=0;else if(w==="indeterminate")un=`${g.toolName}:indeterminate`;else if(w==="not-applied"){let x=`${g.toolName}:${P?.reason??"not-applied"}`;x===hs?qn+=1:(hs=x,qn=1),qn>=is&&(un=`${x}:repeated-${qn}`)}let I=un?void 0:P,Ce=bl.get(g.callId);Ce&&(Ce.status=g.blocked||w==="not-applied"?"blocked":!g.ok||w==="indeterminate"?"failed":"succeeded",!g.ok&&typeof g.error=="string"&&g.error.trim()&&(Ce.error=g.error),w==="indeterminate"&&!Ce.error&&(Ce.error="MCP action outcome is indeterminate; completion is not verified."),(!g.ok||w==="indeterminate")&&(Ce.failureKind=Bu(g)));let de=sg(g);if(de){if(Q.push({name:g.toolName,reason:de}),g.toolName==="exec"&&de==="confirmation-timeout"){let x=$(S);b.push({role:"user",content:"Exec confirmation timed out. The built-in tool remains available, but this exact action did not receive approval. Do not claim it succeeded. Continue with another authorized approach only when it can genuinely complete the same user goal, ask_user when approval is required, or report the confirmation blocker."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:$(a??c),enabledToolNamesBefore:x,enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"use-an-authorized-approach-or-report-confirmation-blocker"}}if(g.toolName==="exec"&&de==="global-process-kill-blocked"){let x=$(S);b.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:$(a??c),enabledToolNamesBefore:x,enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}g.blocked&&(yield{type:"tool_blocked",turnId:r,callId:g.callId,name:g.toolName,reason:g.blockReason??"blocked"});let or=Ws.get(g.callId);if(or){let x=g.message;typeof x.content=="string"&&(x.content=`${or}
67
-
68
- ${x.content}`)}if(g.ok&&g.toolName===Ci){let x=ju(g.details),j=e.refreshTools?new Set(e.refreshTools().map(le=>le.function.name)):void 0,Y=[],ce=[],Se=[];for(let le of x)!ee.get(le)||j&&!j.has(le)?Se.push(le):!qo.has(le)||dn.has(le)?ce.push(le):(dn.add(le),e.loadedDeferredToolNames?.add(le),Y.push(le));let Ee=xl(Je(),j);S=yt(bt(Ee,De),Je());let Ye=g.message;Ye.content=JSON.stringify({loaded:Y,alreadyResident:ce,unavailable:Se}),g.details={type:"tool_schema_load",requestedToolNames:x,loaded:Y,alreadyResident:ce,unavailable:Se},o.info({turnId:r,loaded:Y,alreadyResident:ce,unavailable:Se},"tool schemas materialized by Agent selection")}{let x=g.message;e.sanitizeToolResultMedia&&(Array.isArray(x.imageUrls)||Array.isArray(x.audioUrls)||Array.isArray(x.videoUrls))&&await e.sanitizeToolResultMedia(x)}if(h(b,g.message),je&&rl(g.toolName,je)){let x=fl(Ae(g.toolName));je.scope==="interaction-step"?I?.scope==="interaction-step"?(je=I,cn=!1,ln=!1):w==="committed"||w===void 0&&(x==="computer_act"||x==="act")?ln=!0:cn=!0:cn=!0}!Tt&&I&&(Tt=I,Tt&&(je=Tt)),ye.push(g.callId);let eh=T0(g,f);g.blocked||(Fe.add(g.toolName),_t++);let uu=g.ok&&Gr(g);eh||Om({toolFailureCounts:f.toolFailureCounts,toolName:g.toolName,toolArguments:st.find(x=>x.id===g.callId)?.function.arguments,ok:g.ok,softEmpty:uu});let kt=ae.find(x=>x.id===g.callId);if(!g.ok&&kt){let x=Pm(g.details),j=`${kt.function.name}::${kt.function.arguments}`;g.blocked||f.identicalFailureCounts.set(j,(f.identicalFailureCounts.get(j)??0)+1),x&&!(x.retryable&&x.safeToRetry&&x.automaticRetryAuthorized)&&f.commercialRetryBlocks.set(j,{billed:x.billed,retryMode:x.retryMode,...x.stage?{stage:x.stage}:{}})}if(g.ok&&kt&&(f.commercialRetryBlocks.delete(`${kt.function.name}::${kt.function.arguments}`),f.identicalFailureCounts.delete(`${kt.function.name}::${kt.function.arguments}`)),g.ok&&A0.has(Ae(g.toolName))&&dx(f),g.ok&&bg(g.toolName)){let x=st.find(Y=>Y.id===g.callId),j=x?ps(x.function.arguments):void 0;if(j){let Y=ke(j);if(f.longHorizonStateMaintenanceRequiredFiles.has(Y)){let ce=hl(f.maintainedDocuments,Y,x?.function.arguments??"");ce.ok?f.longHorizonStateMaintenanceWrittenFiles.add(Y):(Q.push({name:g.toolName,reason:"benchmark-state-invalid-content"}),b.push({role:"user",content:`Benchmark-state maintenance write for ${Y} is incomplete: ${ce.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(g.ok&&!uu&&(al.has(g.toolName)||g.toolName==="exec"&&g.details?.type==="exec_background"||g.toolName==="exec"&&lg(st.find(x=>x.id===g.callId)?.function.arguments??""))){let x=st.find(Y=>Y.id===g.callId),j=typeof g.message?.content=="string"?g.message.content:"";if(x&&j){let Y=Array.isArray(g.message.imageUrls)?g.message.imageUrls.filter(Jn=>typeof Jn=="string"):void 0,ce=Array.isArray(g.message.toolReferences)?g.message.toolReferences.filter(Jn=>typeof Jn=="string"):void 0,Se=Array.isArray(g.message.contentBlocks)?g.message.contentBlocks:void 0,Ee=g.message.structuredContent,Ye=g.message.mcpMeta,le=g.message.mcpIsError;f.identicalSuccessfulToolResults.set(`${x.function.name}::${x.function.arguments}`,{content:j,imageUrls:Y,toolReferences:ce,contentBlocks:Se,...Ee!==void 0?{structuredContent:Ee}:{},...Ye!==void 0?{mcpMeta:Ye}:{},...typeof le=="boolean"?{mcpIsError:le}:{}})}}if(g.toolName==="agent"){let x=on(g.details,"agentId"),j=on(g.details,"status"),Y=cs(g.details,"background");g.ok&&x&&Y===!0&&j==="running"&&rn(f).add(x)}if(g.toolName==="task"){let x=E0(g.details);x&&(f.lastTaskList=x);let j=on(g.details,"taskId"),Y=cs(g.details,"running"),ce=on(g.details,"lifecycle"),Se=on(g.details,"action");if(j&&(Se==="cancel"||Y===!1||ce&&ce!=="running"&&ce!=="pending"))rn(f).delete(j),f.backgroundAgentPollCounts.delete(j),f.backgroundAgentNoOutputPollCounts.delete(j),f.stalledBackgroundAgentTasks.delete(j);else if(j&&Se==="output"&&Y===!0&&rn(f).has(j)){let Ee=(f.backgroundAgentPollCounts.get(j)??0)+1;f.backgroundAgentPollCounts.set(j,Ee),Ee>=hg&&f.stalledBackgroundAgentTasks.set(j,`still running after ${Ee} bounded poll(s)`);let Ye=typeof g.message?.content=="string"?g.message.content:"",le=cs(g.details,"hasOutput");if(le!==void 0?le===!1:w0(Ye)){let Zs=(f.backgroundAgentNoOutputPollCounts.get(j)??0)+1;f.backgroundAgentNoOutputPollCounts.set(j,Zs);let rr=_0(g.details,"elapsedSeconds")??x0(Ye);(rr!==void 0&&rr>=k0||rr===void 0&&Zs>=C0)&&f.stalledBackgroundAgentTasks.set(j,`no output after ${rr??"unknown"}s across ${Zs} poll(s)`)}else f.backgroundAgentNoOutputPollCounts.delete(j),Ee<hg&&f.stalledBackgroundAgentTasks.delete(j)}}if(g.ok&&g.toolName==="read"){let x=st.find(j=>j.id===g.callId);if(x){let j=ll(x.function.arguments);if(j){let Y=ke(j),ce=f.fileReadCounts.get(Y)??0;f.fileReadCounts.set(Y,ce+1);let Se=yg(j);Se&&f.fileReadSignatures.set(Y,Se);let Ee=typeof g.message?.content=="string"?g.message.content:"";p=Q0(f,j,Ee,f.turnCount,g.details)||p}}}yield qu(r,g);for(let x of Uu(r,g))yield x;for(let x of Gu({turnId:r,result:g,toolCalls:ae}))yield x;let Ys=ae.find(x=>x.id===g.callId),du=typeof g.message?.content=="string"?g.message.content:"";if(Ys){Jm({state:f.artifactContract,inputMessages:i,toolName:g.toolName,rawArguments:Ys.function.arguments,ok:g.ok,content:du,details:g.details}),xs()&&(yield ws());let x=cg(g.toolName,Ys.function.arguments);if(x){let j=sg(g),Y=g.ok&&!Gr(g),ce=Y?f0(g.toolName,g.details,du):null,Se=ce!==null&&kl.get(x)===ce;ce!==null&&kl.set(x,ce);let Ee=Y&&!Se;Ee&&gs.delete(x);let Ye=Ee||j?0:(gs.get(x)??0)+1;if(Ye>0&&gs.set(x,Ye),Ye===is){Cl.add(x);let le=x.startsWith("exec:")?"exec":x.startsWith("task-output:")?"task":"edit";f.recoveryTrace.set(`no_progress_observed:${le}`,(f.recoveryTrace.get(`no_progress_observed:${le}`)??0)+1),Tl.has(x)||(Tl.add(x),b.push({role:"user",content:`You have now repeated the same action (${x}) ${is} times without material task-state or output progress. Stop this approach: summarize what you tried and why it failed, then either take a FUNDAMENTALLY different route or report the blocker honestly. Do not run another variation of the same command family.`}),yield B("no_progress_nudge",x))}}}!tr&&Ng&&ki(g.toolName,"stt")&&g.ok&&(tr=Qw(i,g))}if(Un&&(S=bt(Je(),De),Un=!1),un){let g=$(S);S=yt([],E),fe=!1,b.push({role:"user",content:"The selected MCP action returned an indeterminate outcome or repeated the same not-applied state without progress. Do not invoke another tool in this turn. Report only verified evidence and the remaining blocker; do not claim completion or replay an uncertain action."}),yield{type:"tool_selection_policy",turnId:r,policyId:"mcp_terminal_no_progress",intent:"tool_recovery",reason:un,availableToolNames:$(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:$(S),suppressedToolNames:ol(g,$(S)),nextAction:"report-verified-evidence-and-blocker"},yield B("mcp_terminal_no_progress",un),je=void 0,Tt=void 0,cn=!1,ln=!1,wl=!0}else if(ln&&!Tt){let g=$(S);S=bt(Je(),De),fe=!1,b.push({role:"user",content:"The grounded action allowed by the connector's interaction-step control has returned. Continue from that action result. A new observation is allowed only if the action advanced the interaction step; do not repeat the exhausted observation step."}),yield{type:"tool_selection_policy",turnId:r,policyId:"mcp_interaction_step_advanced",intent:"tool_recovery",reason:"mcp-interaction-step-action-returned",availableToolNames:$(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:$(S),suppressedToolNames:[],nextAction:"continue-from-grounded-action-result"},yield B("mcp_interaction_step_advanced",je?.reason??"mcp-interaction-step-blocked"),je=void 0,ln=!1}else if(cn){let g=$(S);S=yt([],E),fe=!1,b.push({role:"user",content:"The selected MCP connector's bounded cleanup tool has now returned. Do not invoke another tool in this turn. Summarize only the verified evidence already returned, report the remaining blocker clearly, and do not claim the requested action completed."}),yield{type:"tool_selection_policy",turnId:r,policyId:"mcp_turn_cleanup_completed",intent:"tool_recovery",reason:"mcp-turn-cleanup-returned",availableToolNames:$(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:$(S),suppressedToolNames:ol(g,$(S)),nextAction:"report-verified-evidence-and-blocker"},yield B("mcp_turn_cleanup_completed",je?.reason??"mcp-turn-blocked"),je=void 0,cn=!1}else if(Tt){let g=Tt;ln=!1;let P=$(S),w=S.filter(I=>rl(I.function.name,g));S=yt(w,E),fe=w.length>0,b.push({role:"user",content:g.scope==="interaction-step"?w.length>0?g.reason.includes("observation")?"The selected MCP connector exhausted the current interaction step's observation budget. Do not observe again. Use exactly one protocol-declared continuation: perform a grounded action from existing evidence, or release control when no safe grounded action exists. Never claim completion without verified action evidence.":"The selected MCP connector requires another bounded interaction step. Continue only through one protocol-declared tool using the structured state returned by the connector. Do not switch to an undeclared fallback or claim completion before the connector returns verified completion evidence.":"The selected MCP connector blocked the current interaction step and exposed no available continuation tool. Report the incomplete state and blocker explicitly; do not claim completion.":S.length>0?"The selected MCP connector returned a structured, turn-scoped, non-retryable block. Invoke the single remaining connector cleanup tool exactly once, then report only verified evidence and the blocker. Do not retry the blocked operation or claim completion.":"The selected MCP connector returned a structured, turn-scoped, non-retryable block and exposed no available cleanup tool. Do not invoke another tool in this turn. Report only verified evidence and the blocker; do not claim completion."}),yield{type:"tool_selection_policy",turnId:r,policyId:g.scope==="interaction-step"?"mcp_interaction_step_execution_block":"mcp_turn_execution_block",intent:"tool_recovery",reason:g.scope==="interaction-step"?"mcp-interaction-step-non-retryable":"mcp-turn-non-retryable",availableToolNames:$(a??c),enabledToolNamesBefore:P,enabledToolNamesAfter:$(S),suppressedToolNames:ol(P,$(S)),nextAction:w.length>0?g.scope==="interaction-step"?"invoke-grounded-action-or-release":"invoke-bounded-connector-cleanup":"report-verified-evidence-and-blocker"},yield B(g.scope==="interaction-step"?"mcp_interaction_step_execution_block":"mcp_turn_execution_block",g.reason)}if(p){let g=J0(r,f.maintainedDocuments,f.fileReadCounts,f.turnCount);g&&(yield g);for(let I of Z0(r,f.maintainedDocuments))yield I;let P=j0(f.maintainedDocuments,f.turnCount),w=S.some(I=>cl.has(I.function.name));if(P&&w){f.longHorizonStateMaintenanceRequiredFiles=new Set(Ag(f.maintainedDocuments).map(ke));for(let I of S)cl.has(I.function.name)||De.add(I.function.name);S=bt(S,De),fe=!0,b.push({role:"user",content:P}),yield B("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let T=q0(f.maintainedDocuments);if(T.length>0&&f.longHorizonStateIntegrityRecoveryCount<N0){let g=T.map(P=>`${Mt(P.path)}: ${P.reason}`).join("; ");f={...f,longHorizonStateIntegrityRecoveryCount:f.longHorizonStateIntegrityRecoveryCount+1,messages:[...b,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+g+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},fe=!0,yield B("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(D0(f)){yield*Be("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(u){let p=u instanceof Error?u.message:String(u);yield*Xe(p,"TOOL_EXECUTION_ERROR");return}if(tr){yield*Be(tr);return}b.push(...Nm({toolFailureCounts:f.toolFailureCounts,snapshot:Zg})),qe=ar(qe,{replayMessages:b,completedToolCallIds:[...qe.completedToolCallIds,...ye],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&ae.length>0&&(_s=!0);let Qg=ae.length>0&&ae.every(u=>{let p=b.find(g=>g?.role==="tool"&&g?.tool_call_id===u.id);if(!p)return!0;let T=p.content;return typeof T=="string"&&T.startsWith("Error: ")}),Ft=f.consecutiveFailedRounds,Js=f.repeatedToolFailureRecoveryCount;if(Qg){if(Ft+=1,Ft>=Su){if(an>=3&&f.repeatedToolFailureRecoveryCount<1){let w=Lc({inputMessages:i,messages:b,finalText:f.finalText,thinkingBlocks:[],stopHookActive:f.stopHookActive,totalToolCallCount:_t,distinctToolNames:Fe,log:o});if(w?.reason==="explicit_required_file_verification"||w?.reason==="explicit_extra_file_verification"){yield B("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),f={...f,messages:w.messages,stopHookActive:w.stopHookActive,transition:w.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:f.repeatedToolFailureRecoveryCount+1};continue}}if(f.repeatedToolFailureRecoveryCount<1){let w=om(b,ut.at(-1)?.failureKind);if(w){yield B("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),f={...f,messages:[...b,w],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:f.repeatedToolFailureRecoveryCount+1};continue}}let u=`repeated tool failures (${Ft} rounds in a row)`,p=Nn({inputMessages:i,messages:b,reason:`${u} before all required files were produced`}),T=f.finalText.trim()?f.finalText:Sc(b,Ft),g=p?`${T}
69
-
70
- ${p}`:T,P=ug(g,{availableToolNames:$(a??c),enabledToolNames:bs(),toolCallNames:[...Fe].sort(),blockedToolCalls:ss(Q)});o.info(`early exit: ${Ft} consecutive failed rounds, returning ${f.finalText?"partial":"fallback"} response`),yield*Be(P,{forcedStop:!0});return}}else Ft=0,Js>0&&(o.info("tool-failure self-correction re-armed after a successful round"),Js=0);let nr=[...f.fileReadCycleBlockedPaths].filter(u=>!f.fileReadCycleNudgedPaths.has(u));if(nr.length>0){let u=nr.join(", "),p=[...new Set(nr.map(sl))].join(" ");o.info(`AP5: file read cycle detected on ${u}, injecting nudge`);let T={role:"user",content:`Read-cycle guard blocked repeated reads for: ${u}. ${p} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};b.push(T);for(let g of nr)f.fileReadCycleNudgedPaths.add(g)}let Xs=pe+1;if(k>0&&Xs>k){if(o.info(`max turns reached (${k}), completing`),y){let T=await y.invoke("stop",{sessionId:s,reason:"max_turns"});if(T.action==="abort"){let g=T.reason??"Stop hook requested continuation after max_turns",P={role:"assistant",content:f.finalText,...rt.length>0&&{thinkingBlocks:[...rt]}};f={...f,messages:[...b,P,{role:"user",content:g}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let u=Nn({inputMessages:i,messages:b,reason:`tool loop max turns reached (${k}) before completing all required files`}),p=Ss(b,`tool loop max turns reached (${k}) before completing the final status contract`);yield*Be(u?`${p}
10
+ `)}}function ku(e){return ui("sha256").update(JSON.stringify(e)).digest("hex")}function B_(e,t){let n=-1;for(let o=e.length-1;o>=0;o--)if(e[o]?.role==="assistant"){n=o;break}if(n<0||ku(e.slice(0,n+1))!==t)return;let r=e.slice(n+1);return r.length>0?r:void 0}var z_=18e4,Cr=class extends Error{constructor(n){super(`LLM stream idle timeout after ${n}ms without a chunk.`);this.timeoutMs=n;this.name="LLMStreamIdleTimeoutError"}timeoutMs;code="LLM_STREAM_TIMEOUT"};async function*V_(e,t){if(!Number.isFinite(t)||t<=0){yield*e;return}let n=e[Symbol.asyncIterator]();try{for(;;){let r,o=await Promise.race([n.next(),new Promise(s=>{r=setTimeout(()=>s("timeout"),t)})]);if(r&&clearTimeout(r),o==="timeout")throw new Cr(t);if(o.done)return;yield o.value}}finally{n.return?.().catch(()=>{})}}function K_(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async function*Cu(e,t,n,r){let{turnId:o,sessionId:s,messages:i,availableTools:l,tools:a,model:c,apiKey:u,temperature:d=0,hooks:h,signal:T}=e,p=(k,U)=>{k.push(U)},f={sessionId:s,turnId:o},m=e.maxTurns??0,_=e.querySource,E=l??a,w=e.runtimePorts.resolveToolEligibility(E,e.toolEligibilityContext),q=new Set(a.map(k=>k.function.name)),R=w.eligibleTools,Q=new Map(R.map(k=>[k.function.name,k])),W=w.eligibleTools.filter(k=>q.has(k.function.name)),we=[];for(let k of w.blockedTools)we.push({name:k.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:o,callId:"",name:k.toolName,reason:"blocked-by-policy"};let $e=br(e.maxRounds,i),ye=kr(e.maxToolCalls),Se={contextWindowTokens:e.contextWindowTokens??Ji,responseBufferTokens:Yi,maxOutputTokens:e.maxOutputTokens??Xi,abortSignal:T,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},We=new Set,ft=[],Rn=new Map,Rr=0,wu=new Set,$u=0,En=new Set(e.deferredToolNames??[]),pt=new Set;for(let k of e.loadedDeferredToolNames??[])En.has(k)&&Q.has(k)?pt.add(k):e.loadedDeferredToolNames?.delete(k);let Er=()=>{let k=new Map(W.map(U=>[U.function.name,U]));for(let U of pt){let ce=Q.get(U);ce&&k.set(U,ce)}return[...k.values()]},di=(k,U)=>U?k.filter(ce=>U.has(ce.function.name)):[...k],xe=Er(),Su=()=>Tu(xe),fi=!1,jt=!1,wn,$n,b={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Qr(Se),reactiveCompactState:ro(),toolLoopState:Dn({maxRounds:$e,replayMessages:[...i]}).state,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Fr(),currentModel:c,consecutive529Errors:0,consecutiveApiRetries:0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),recoveryTrace:new Map},xu=4,Pu=4,pi=0,wr=!1,mi=new Map,$r,_e=(k,U)=>{let ce=`${k}:${U??""}`,ve=(mi.get(ce)??0)+1;if(mi.set(ce,ve),k==="autocompact"){let J=b.recoveryTrace.get("autocompact")??0;if(ve>xu||J>=Pu){let Pe=`Repeated context compression made no forward progress: ${U??"autocompact"}`;return $r=Pe,b.recoveryTrace.set("compression_loop_guard",(b.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:o,action:"compression_loop_guard",detail:Pe}}}return b.recoveryTrace.set(k,(b.recoveryTrace.get(k)??0)+1),{type:"recovery",turnId:o,action:k,detail:U}},hi=()=>({type:"tool_use_summary",turnId:o,ledgerSchemaVersion:5,toolCalls:ft.map(k=>({...k})),availableToolNames:Tu(l??a),enabledToolNames:Su(),toolCallNames:[...We].sort(),blockedToolCalls:L_(we)}),Au=(k,U)=>({type:"end",turnId:o,content:k,turnStatus:U,taskOutcome:"unverified",usage:b.totalUsage,model:b.currentModel,...b.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(b.recoveryTrace)}:{}}),gi=D_(i);function*Sn(k,U="completed"){yield hi(),yield Au(k,U)}function*Te(k,U){yield hi(),yield{type:"error",turnId:o,error:k,code:U,usage:b.totalUsage}}let Sr=(k,U)=>{if(U?.cleanStopWithFinalText&&b.finalText)return b.finalText;let ce=b.finalText,ve=gi==="zh"?`\u26A0\uFE0F \u672C\u8F6E\u88AB\u5F15\u64CE\u9650\u5236\u63D0\u524D\u4E2D\u6B62,\u4E0B\u9762\u7684\u7ED3\u679C\u53EF\u80FD\u4E0D\u5B8C\u6574\u3002(${k})`:`\u26A0\uFE0F This turn was stopped early by an engine limit; the result below may be incomplete. (${k})`;return ce?`${ve}
71
11
 
72
- ${u}`:p);return}if(Ke>0&&Xs>Ke){o.info(`tool loop budget exhausted (${Ke} rounds), returning`);let u=Nn({inputMessages:i,messages:b,reason:`explicit maxRounds reached (${Ke}) before completing all required files`}),p=Ss(b,`explicit maxRounds reached (${Ke}) before completing the final status contract`);yield*Be(u?`${p}
12
+ ${ce}`:ve},mt=0,Lt=0;function*Mu(k){mt<=Lt||(yield{type:"text_rollback",turnId:o,keepLength:Lt,reason:k},mt=Lt)}for(xe=Er();;){yield*Mu("round_restart"),pi++,wr=!1;let{messages:k,maxOutputTokensRecoveryCount:U,maxOutputTokensOverride:ce,turnCount:ve,guardState:J,reactiveCompactState:Pe,collapseStore:xr}=b,{toolLoopState:ue}=b;if(e.refreshTools&&pi>1){let g=e.refreshTools(),y=new Set(g.map(j=>j.function.name)),I=di(R.filter(j=>!En.has(j.function.name)||pt.has(j.function.name)),y),F=I;F!==xe&&(xe=F,r.debug(`tools refreshed within initial turn snapshot: ${I.length}/${R.length} tools`))}if(e.drainPendingGuidance)for(let g of e.drainPendingGuidance()){let y=g.trim();y&&(k.push({role:"user",content:y}),r.info(`mid-turn guidance injected (${y.length} chars)`))}if(e.drainPendingTaskNotifications){let g=e.drainPendingTaskNotifications().filter(y=>y.trim());g.length>0&&(k.push(bu(g)),r.info(`background task result injected (${g.length} item(s))`))}if(no(J,Se)){r.info(`turn aborted by guard at turn ${ve}`),yield*Te("Turn aborted","ABORTED");return}let ht=yield*yu({messages:k,contentReplacementState:b.contentReplacementState,snipRemovedIds:b.snipRemovedIds,collapseStore:xr,guardState:J,guardConfig:Se,runtimePorts:e.runtimePorts,hooks:h,hookCtx:f,sessionId:s,currentModel:b.currentModel,log:r,recovery:(g,y)=>_e(g,y),onAutocompact:()=>{b.hasAttemptedReactiveCompact=!1}});if(ht!==k&&k.splice(0,k.length,...ht),$r){yield*Sn(`${$r}. Stop compressing the same context repeatedly; continue from the compacted transcript or report the incomplete state explicitly.`,"stopped");return}let Pr=Zr(J,Se);Pr.level==="warning"&&r.info(`token budget warning: ${Pr.usagePercent}% used, ${Pr.remainingTokens} remaining`);let yi=e.toolChoice==="required"&&fi?"auto":e.toolChoice??"auto",gt=zr({tools:xe,toolChoice:yi}),Ou=ui("sha256").update(JSON.stringify([...gt.tools].sort((g,y)=>g.function.name.localeCompare(y.function.name)))).digest("hex"),xn=Dn({maxRounds:$e,replayMessages:ht,lastStopReason:ue.lastStopReason,options:{stopReason:ue.lastStopReason}}),_i=ui("sha256").update(JSON.stringify({model:b.currentModel,toolRequestSignature:Ou,toolChoice:gt.normalizedToolChoice,reasoning:e.reasoning,openaiBuiltinTools:e.openaiBuiltinTools,parallelToolCalls:e.parallelToolCalls})).digest("hex"),Ti=wn!==void 0&&wn!==_i,vi=xn.state.replayMessages,bi=!jt&&!Ti&&b.lastResponseId&&$n?B_(vi,$n):void 0,Pn=bi?b.lastResponseId:void 0;b.lastResponseId&&!jt&&!Pn&&(yield _e("stateless_retry",Ti?"request context changed; replaying full history without previous_response_id":"local transcript changed; replaying full history without previous_response_id"));let ki=bi??vi;ue=xn.state,xn.recoveryActions.length>0&&r.debug(`tool loop recovery: ${xn.recoveryActions.map(g=>g.detail??g.kind).join("; ")}`),r.debug(`turn ${ve}, messages: ${ki.length}`),H(h,"turn.before_inference",{...f,model:b.currentModel},r);let qt=!1,Ci=[],Ri=yi==="required",Ar=0,Dt="";function*Iu(g){if(g){if(Ri){Dt+=g;return}Ar+=g.length,mt+=g.length,yield{type:"delta",turnId:o,text:g}}}function*Nu(){if(!Dt)return;let g=Dt;Dt="",Ar+=g.length,mt+=g.length,yield{type:"delta",turnId:o,text:g}}let Ei=new Map,Mr="stop",oe,An,D=null,Mn=null,ju=performance.now(),Or,wi=0,$i=0,Si=0,Ir=0,On,Je,xi=!1,In=!1,Pi=!1,yt=[],Ft=[];try{let g=t.stream({model:b.currentModel,messages:ki,...gt.tools.length>0?{tools:gt.tools,toolChoice:gt.normalizedToolChoice??"auto"}:{},temperature:d,maxTokens:(ce??J.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Pn,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,...ye!==void 0?{maxToolCalls:ye}:{},parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},u,T);for await(let y of V_(g,e.llmStreamIdleTimeoutMs??z_))switch(Or===void 0&&y.type!=="usage"&&y.type!=="response_id"&&(Or=Math.max(0,Math.round(performance.now()-ju))),y.type){case"delta":wi+=1,$i+=y.text.length,Je===void 0&&(Je="text"),Ir===0&&(xi=!0),Ci.push(y.text),yield*Iu(y.text);break;case"tool_call_delta":Ir+=1,Je===void 0&&(Je="tool_call"),qt=!0,oo(Ei,y);break;case"reasoning_delta":Si+=1,Je===void 0&&(Je="reasoning"),yt.push(y.text),yield{type:"reasoning_delta",turnId:o,text:y.text};break;case"reasoning_block_complete":y.signature&&Ft.push({thinking:yt.join(""),signature:y.signature}),yt.length=0;break;case"usage":An=Xr(y),oe={inputTokens:y.promptTokens,outputTokens:y.completionTokens,reasoningTokens:y.reasoningTokens,cacheRead:y.cacheReadTokens,cacheWrite:y.cacheCreationTokens};break;case"response_id":On=y.id;break;case"annotations":yield{type:"annotations",turnId:o,annotations:y.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:o,message:`${y.toolType}: ${y.event}`};break;case"error":Mn=y.message||"LLM provider returned an error chunk";break;case"done":Pi=!0,Mr=y.finishReason;break}if(Mn){H(h,"stop.failure",{sessionId:s,reason:"PROVIDER_STREAM_ERROR",error:Mn},r),yield*Te(Mn,"PROVIDER_STREAM_ERROR");return}if(qt||H(h,"turn.after_inference",{...f,model:b.currentModel},r),e.postSamplingHooks&&e.postSamplingHooks.length>0){let y=b.currentModel;for(let I of e.postSamplingHooks)try{I({messages:[...ht],model:y,sessionId:s})}catch{}}}catch(g){if(g instanceof Cr){H(h,"stop.failure",{sessionId:s,reason:g.code,error:g.message},r),yield*Te(g.message,g.code);return}let y=yield*_u(g,{state:b,guardState:J,fallbackModel:e.fallbackModel,signal:T,querySource:_,turnId:o,log:r,emitRecovery:_e});if(y.kind==="return")return;if(y.kind==="continue"){b={...b,...y.patch};continue}D=y.streamError}if(!D&&!Pi){let g="LLM stream closed before a terminal event; the response was likely truncated upstream.";H(h,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:g},r),yield*Te(g,"RETRYABLE_TRANSIENT");return}if(D&&H(h,"turn.after_inference",{...f,model:b.currentModel,response:{error:D.message}},r),D){if(!jt&&Pn&&/previous_response_id not found/i.test(D.message)){let g=(b.consecutiveApiRetries??0)+1;if(g<=Ze){r.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield _e("stateless_retry","previous_response_id not found; replaying full history"),jt=!0,b={...b,lastResponseId:void 0,consecutiveApiRetries:g,transition:void 0};continue}}if(ai(D))In=!0,r.info(`withheld prompt_too_long error (status=${D.status})`);else if(ci(D))In=!0,r.info(`withheld media_size error (status=${D.status})`);else{let g=eo({status:D.status??500,message:D.message},J,Se);if(g.action==="reactive_compact"&&Kt(Pe)&&(Pe.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,yield _e("reactive_compact",`API ${D.status??500}: ${D.message}`)),g.action==="retry"){let I=(b.consecutiveApiRetries??0)+1;if(I>Ze){r.info(`API retry limit reached (${Ze}), aborting`);let F=Tt(D.status,D.message);yield*Te(D.message,F);return}yield _e("retry",g.reason),b={...b,consecutiveApiRetries:I,transition:void 0};continue}let y=Tt(D.status,D.message);H(h,"stop.failure",{sessionId:s,reason:y,error:D.message},r),yield*Te(D.message,y);return}}oe&&(b.totalUsage.inputTokens+=oe.inputTokens,b.totalUsage.outputTokens+=oe.outputTokens,oe.reasoningTokens&&(b.totalUsage.reasoningTokens=(b.totalUsage.reasoningTokens??0)+oe.reasoningTokens),oe.cacheRead&&(b.totalUsage.cacheRead=(b.totalUsage.cacheRead??0)+oe.cacheRead),oe.cacheWrite&&(b.totalUsage.cacheWrite=(b.totalUsage.cacheWrite??0)+oe.cacheWrite)),r.info(`[provider-context] ${JSON.stringify({event:"context_ledger_round",turnId:o,round:ve,ttftMs:Or,inputTokens:oe?.inputTokens??0,outputTokens:oe?.outputTokens??0,cacheReadTokens:oe?.cacheRead??0,cacheWriteTokens:oe?.cacheWrite??0,totalPromptTokens:An??0,previousResponseIdUsed:Pn!==void 0,responseIdReceived:On!==void 0,toolDefinitionCount:xe.length,providerTextChunkCount:wi,providerTextChars:$i,providerReasoningChunkCount:Si,providerToolCallDeltaCount:Ir,firstSemanticProviderEvent:Je??"none",textBeforeFirstToolCall:xi,suppressLiveText:Ri,liveEmittedTextChars:Ar,bufferedSuppressedTextChars:Dt.length})}`),An&&(J.promptTokens=An);let de=Ci.join(""),qe=[...Ei.values()].map((g,y)=>({id:g.id||`tc_${o}_${ve}_${y}`,type:"function",function:{name:g.name,arguments:g.arguments}}));if(!D&&Rr===0&&qe.length===0&&!qt&&de.trim()===""&&yt.join("").trim()===""&&Ft.length===0){let g="LLM returned an empty response before any tool use.";H(h,"stop.failure",{sessionId:s,reason:"EMPTY_MODEL_RESPONSE",error:g},r),yield*Te(g,"EMPTY_MODEL_RESPONSE");return}if(!D&&Rr>0&&qe.length===0&&!qt&&de.trim()===""&&!li(Mr)){let g="LLM returned no user-visible response after tool use.";H(h,"stop.failure",{sessionId:s,reason:"EMPTY_MODEL_RESPONSE_AFTER_TOOL",error:g},r),yield*Te(g,"EMPTY_MODEL_RESPONSE_AFTER_TOOL");return}if(qe.length===0&&!qt){if(e.drainPendingTaskNotifications){let F=e.drainPendingTaskNotifications().filter(j=>j.trim());if(F.length>0){b={...b,messages:[...k,...de?[{role:"assistant",content:de}]:[],bu(F)]},r.info(`late background task result consumed at completion (${F.length} item(s)) \u2014 running another round`);continue}}if(e.drainPendingGuidance){let F=e.drainPendingGuidance().map(j=>j.trim()).filter(Boolean);if(F.length>0){b={...b,messages:[...k,...de?[{role:"assistant",content:de}]:[],...F.map(j=>({role:"user",content:j}))]},r.info(`late mid-turn guidance consumed at completion (${F.length} item(s)) \u2014 running another round`);continue}}if(de){let F=b.transition?.reason==="max_output_tokens_escalate"||b.transition?.reason==="max_output_tokens_recovery";b.finalText=F?`${b.finalText}${de}`:de}if(In&&D&&ai(D)){if(b.transition?.reason!=="collapse_drain_retry"){let F=Br(ht,xr);if(F.committed>0){r.info(`collapse drain: committed ${F.committed} stages`),yield _e("collapse_drain",`${F.committed} stages committed`),b={...b,messages:F.messages,transition:{reason:"collapse_drain_retry",committed:F.committed}};continue}}if(Kt(Pe)){Pe.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,r.info("withheld 413: reactive compact attempt"),yield _e("reactive_compact","withheld prompt_too_long"),b={...b,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}r.info("withheld 413: recovery exhausted, surfacing error"),H(h,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:D.message},r),yield*Te(D.message,"PROMPT_TOO_LONG");return}if(In&&D&&ci(D)){if(Kt(Pe)){Pe.attemptedThisTurn=!0,J.hasAttemptedReactiveCompact=!0,r.info("withheld media error: reactive compact strip-retry"),yield _e("reactive_compact","media error strip-retry"),b={...b,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}r.info("withheld media error: recovery exhausted"),H(h,"stop.failure",{sessionId:s,reason:"media_error",error:D.message},r),yield*Te(D.message,"IMAGE_ERROR");return}if(li(Mr)){J.consecutiveTruncations+=1;let F=e.modelMaxOutputTokens??Qi,j=to(J,Se,F),Ie={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."},De=[...ht,...de?[{role:"assistant",content:de}]:[],Ie];if(j.shouldEscalate&&ce===void 0){J.currentMaxOutputTokens=j.newMax,r.info(`max_output_tokens escalate: ${j.newMax} tokens`),yield _e("output_escalation",`${j.newMax} tokens`),b={...b,messages:De,maxOutputTokensOverride:j.newMax,transition:{reason:"max_output_tokens_escalate"}};continue}if(U<Zi){r.info(`max_output_tokens recovery #${U+1}`),yield _e("max_output_tokens_recovery",`attempt ${U+1}`),b={...b,messages:De,maxOutputTokensRecoveryCount:U+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:U+1}};continue}r.info("max_output_tokens recovery exhausted, completing with partial content"),wr=!0}else J.consecutiveTruncations=0;ue=qn(ue,{replayMessages:k,lastStopReason:"completed"});let g=!b.finalText,y=Sr("the model ended with an empty response after tool use",{cleanStopWithFinalText:!0}),I=wr?gi==="zh"?"\u26A0\uFE0F \u8F93\u51FA\u7ECF\u591A\u6B21\u7EED\u5199\u540E\u4ECD\u88AB\u957F\u5EA6\u4E0A\u9650\u622A\u65AD,\u4EE5\u4E0B\u5185\u5BB9\u53EF\u80FD\u4E0D\u5B8C\u6574\u3002":"\u26A0\uFE0F Output was still cut off by the length limit after multiple continuation attempts; the content below may be incomplete.":null;yield*Sn(I&&y?`${I}
73
13
 
74
- ${u}`:p);return}f={messages:b,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Xs,transition:{reason:"next_turn"},guardState:J,reactiveCompactState:ot,toolLoopState:qe,consecutiveFailedRounds:Ft,finalText:f.finalText,totalUsage:f.totalUsage,collapseStore:Es,currentModel:f.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:f.stopHookActive,lastResponseId:f.lastResponseId,snipRemovedIds:f.snipRemovedIds,contentReplacementState:f.contentReplacementState,budgetContinuationCount:f.budgetContinuationCount,repeatedToolFailureRecoveryCount:Js,lastBudgetDeltaTokens:f.lastBudgetDeltaTokens,lastBudgetGlobalTokens:f.lastBudgetGlobalTokens,identicalCallCounts:Ds,identicalFailureCounts:f.identicalFailureCounts,commercialRetryBlocks:f.commercialRetryBlocks,identicalSuccessfulToolResults:f.identicalSuccessfulToolResults,artifactContract:f.artifactContract,toolFailureCounts:f.toolFailureCounts,variantReassertedSignatures:f.variantReassertedSignatures,fileReadCounts:f.fileReadCounts,fileReadSignatures:f.fileReadSignatures,fileReadCycleBlockedPaths:f.fileReadCycleBlockedPaths,fileReadCycleNudgedPaths:f.fileReadCycleNudgedPaths,maintainedDocuments:f.maintainedDocuments,persistedLongHorizonStateRecovered:f.persistedLongHorizonStateRecovered,longHorizonStateMaintenanceRequiredFiles:f.longHorizonStateMaintenanceRequiredFiles,longHorizonStateMaintenanceWrittenFiles:f.longHorizonStateMaintenanceWrittenFiles,recoveryTrace:f.recoveryTrace,buildVerificationRecoveryCount:f.buildVerificationRecoveryCount,longHorizonStateIntegrityRecoveryCount:f.longHorizonStateIntegrityRecoveryCount,backgroundAgentTaskIds:rn(f),backgroundAgentPollCounts:f.backgroundAgentPollCounts,backgroundAgentNoOutputPollCounts:f.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:f.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:f.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:f.existingFileUpdateRecoveryCount,taskListReconciliationCount:f.taskListReconciliationCount,lastTaskList:f.lastTaskList}}}function Ig(e){return[...new Set((e??[]).map(t=>t.function.name))].sort()}var Og=class{transport;apiKey;toolInvoker;log;hooks;configuredMaxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.configuredMaxRounds=typeof t.maxRounds=="number"&&Number.isFinite(t.maxRounds)&&t.maxRounds>=1?Math.round(t.maxRounds):void 0}async*run(t,n){let{turnId:o,messages:r,availableTools:s,tools:i,systemPrompt:a,config:c}=t,l={sessionId:t.sessionId,turnId:o},d=[...r].reverse().find(C=>C.role==="user"&&typeof C.content=="string")?.content,m=!1,y=()=>({type:"tool_use_summary",turnId:o,telemetrySource:"agent",ledgerSchemaVersion:4,toolCalls:[],finalAnswerEvidence:Qn(c?.freshEvidenceRequired===!0,[]),availableToolNames:Ig(s??i),enabledToolNames:Ig(i),toolCallNames:[],blockedToolCalls:[]}),_=typeof c?.maxRounds=="number"&&Number.isFinite(c.maxRounds)?c.maxRounds:this.configuredMaxRounds,h=_===void 0?void 0:Math.round(_),k=typeof c?.maxToolCalls=="number"&&Number.isFinite(c.maxToolCalls)?c.maxToolCalls:void 0;yield{type:"start",turnId:o,effectiveMaxRounds:Jr(h,r),effectiveMaxToolCalls:Xr(k)};try{ue(this.hooks,"turn.submitted",{...l,prompt:r[r.length-1]?.content??void 0},this.log);let C=li(r),E=[];a&&E.push({role:"system",content:a}),E.push(...C);let O=c?.model??"",z=c?.reasoning;c?.reasoning?.effort==="auto"&&(z={...c?.reasoning,effort:"medium"});let M={turnId:o,sessionId:t.sessionId,messages:E,availableTools:s,tools:i,deferredToolNames:t.deferredToolNames,loadedDeferredToolNames:t.loadedDeferredToolNames,refreshTools:t.refreshTools,drainPendingGuidance:t.drainPendingGuidance,drainPendingTaskNotifications:t.drainPendingTaskNotifications,sanitizeToolResultMedia:t.sanitizeToolResultMedia,model:O,apiKey:c?.apiKey??this.apiKey,temperature:c?.temperature,maxRounds:h,contextWindowTokens:c?.contextWindowTokens,maxOutputTokens:c?.maxOutputTokens,modelMaxOutputTokens:c?.modelMaxOutputTokens,toolChoice:c?.toolChoice,freshEvidenceRequired:c?.freshEvidenceRequired,parentDepth:c?.parentDepth,hooks:this.hooks,fallbackModel:c?.fallbackModel,maxTurns:c?.maxTurns,tokenBudget:c?.tokenBudget,maxConcurrentTools:c?.maxConcurrentTools,streamRequired:c?.streamRequired,reasoning:z,promptCacheKey:c?.promptCacheKey,promptCacheRetention:c?.promptCacheRetention,serviceTier:c?.serviceTier,openaiBuiltinTools:c?.openaiBuiltinTools,maxToolCalls:k,parallelToolCalls:c?.parallelToolCalls??!1,textVerbosity:c?.textVerbosity,projectRoot:this.projectRoot,runtimePorts:this.runtimePorts.toolLoop,signal:n};for await(let ee of Mg(M,this.transport,this.toolInvoker,this.log))ee.type==="tool_use_summary"&&(m=!0),ee.type==="end"?ue(this.hooks,"turn.completed",{...l,...d?{prompt:d}:{},response:ee.content},this.log):ee.type==="error"&&ue(this.hooks,"turn.failed",{...l,code:ee.code,error:ee.error},this.log),yield ee}catch(C){if(m||(m=!0,yield y()),n?.aborted)ue(this.hooks,"turn.failed",{...l,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let E=C instanceof Error?C.message:String(C),O=typeof C?.status=="number"?C.status:void 0,z=yn(O,E);this.log.error(`turn ${o} error [${z}, retryable=${sr(z)}]: ${E}`),ue(this.hooks,"turn.failed",{...l,code:z,error:E},this.log),yield{type:"error",turnId:o,error:E,code:z}}}}};export{Og as Agent};
14
+ ${y}`:y,I||g?"stopped":"completed");return}let Lu=Ft.length===0&&yt.length>0?yt.join(""):void 0;Lt=mt,p(k,Lr(qe,de||void 0,Ft.length>0?Ft:void 0,Lu)),!jt&&On?(b.lastResponseId=On,wn=_i,$n=ku(k)):(b.lastResponseId=void 0,wn=void 0,$n=void 0),ue=Wr(ue,{replayMessages:k,pendingToolCallIds:qe.map(g=>g.id),completedToolCallIds:ue.completedToolCallIds,lastStopReason:"tool_calls"});let Ut=[],qu=new Set(xe.map(g=>g.function.name)),Ai=[],Mi=[];for(let g of qe)qu.has(g.function.name)?Ai.push(g):Mi.push(g);for(let g of Mi){let I=En.has(g.function.name)&&!pt.has(g.function.name)?`Tool "${g.function.name}" schema is not loaded. Call "${so}" with that exact tool name before invoking it.`:`Tool "${g.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;we.push({name:g.function.name,reason:"not-offered"}),p(k,Bt(g.id,{ok:!1,error:I})),Ut.push(g.id),We.add(g.function.name),r.warn(`unoffered tool call suppressed: ${g.function.name}`)}let Nr=[],Oi=[];for(let g of Ai){let y=gt.tools.find(F=>F.function.name===g.function.name),I=F_(y,g.function.arguments);I?Oi.push({call:g,error:I}):Nr.push(g)}for(let g of Oi){let y=g.call;we.push({name:y.function.name,reason:"invalid-arguments"}),p(k,Bt(y.id,{ok:!1,error:g.error})),Ut.push(y.id),We.add(y.function.name),r.info(`invalid tool arguments blocked: ${y.function.name}`)}let Nn=Nr.slice(0,ye);Nn.length>0&&(yield*Nu(),Lt=mt);let Ii=Nr.slice(Nn.length);if(Ii.length>0){let g=`This model round proposed more than ${ye} tool calls. Only the first ${ye} were executed; re-issue any still-needed calls in the next round.`;for(let y of Ii){we.push({name:y.function.name,reason:"per-round-tool-call-limit"});let I=Bt(y.id,{ok:!1,error:g});p(k,I),Ut.push(y.id)}}for(let g of Nn){let y=g.function.arguments,I=xe.find(j=>j.function.name===g.function.name);if(I?.backfillObservableInput)try{let j=JSON.parse(g.function.arguments),Ie={...j};I.backfillObservableInput(Ie),Object.keys(Ie).some(_t=>!(_t in j))&&(y=JSON.stringify(Ie))}catch{}let F={sequence:ft.length,callId:g.id,name:g.function.name,identity:U_(I,g.function.name),status:"running",arguments:y};ft.push(F),Rn.set(g.id,F),yield{type:"tool_call",turnId:o,callId:g.id,name:g.function.name,...I?.meta?.displayName?.fallback?.trim()?{displayName:I.meta.displayName.fallback.trim()}:{},arguments:y,inputSummary:mu(y)},wu.add(g.function.name),$u++}try{let g=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:h,sessionId:s,turnId:o,log:r,signal:T,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Wi,executionTimeoutMsByTool:new Map(xe.flatMap(y=>{let I=y.meta?.executionTimeoutMs;return typeof I=="number"&&Number.isFinite(I)&&I>0?[[y.function.name,I]]:[]})),contextState:b.contentReplacementState});for(let y of Nn)g.addTool(y);for await(let y of g.getRemainingResults()){let I=Rn.get(y.callId);I&&(I.status=y.blocked?"blocked":y.ok?"succeeded":"failed",!y.ok&&typeof y.error=="string"&&y.error.trim()&&(I.error=y.error),y.ok||(I.failureKind=sa(y)));let F=q_(y);if(F&&we.push({name:y.toolName,reason:F}),y.blocked&&(yield{type:"tool_blocked",turnId:o,callId:y.callId,name:y.toolName,reason:y.blockReason??"blocked"}),y.ok&&y.toolName===so){let j=oa(y.details),Ie=e.refreshTools?new Set(e.refreshTools().map(be=>be.function.name)):void 0,De=[],_t=[],jn=[];for(let be of j)!Q.get(be)||Ie&&!Ie.has(be)?jn.push(be):!En.has(be)||pt.has(be)?_t.push(be):(pt.add(be),e.loadedDeferredToolNames?.add(be),De.push(be));xe=di(Er(),Ie);let Du=y.message;Du.content=JSON.stringify({loaded:De,alreadyResident:_t,unavailable:jn}),y.details={type:"tool_schema_load",requestedToolNames:j,loaded:De,alreadyResident:_t,unavailable:jn},r.info({turnId:o,loaded:De,alreadyResident:_t,unavailable:jn},"tool schemas materialized by Agent selection")}{let j=y.message;e.sanitizeToolResultMedia&&(Array.isArray(j.imageUrls)||Array.isArray(j.audioUrls)||Array.isArray(j.videoUrls))&&await e.sanitizeToolResultMedia(j)}p(k,y.message),Ut.push(y.callId),y.blocked||(We.add(y.toolName),Rr++),yield ia(o,y);for(let j of aa(o,y))yield j;for(let j of la({turnId:o,result:y,toolCalls:qe}))yield j}}catch(g){let y=g instanceof Error?g.message:String(g);yield*Te(y,"TOOL_EXECUTION_ERROR");return}ue=qn(ue,{replayMessages:k,completedToolCallIds:[...ue.completedToolCallIds,...Ut],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&qe.length>0&&(fi=!0);let jr=ve+1;if(m>0&&jr>m){r.info(`max turns reached (${m}), completing`);let g=Sr(`tool loop max turns reached (${m})`);yield*Sn(g,"stopped");return}if($e>0&&jr>$e){r.info(`tool loop budget exhausted (${$e} rounds), returning`);let g=Sr(`explicit maxRounds reached (${$e})`);yield*Sn(g,"stopped");return}b={messages:k,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:jr,transition:{reason:"next_turn"},guardState:J,reactiveCompactState:Pe,toolLoopState:ue,finalText:b.finalText,totalUsage:b.totalUsage,collapseStore:xr,currentModel:b.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,lastResponseId:b.lastResponseId,snipRemovedIds:b.snipRemovedIds,contentReplacementState:b.contentReplacementState,recoveryTrace:b.recoveryTrace}}}function Ru(e){return[...new Set((e??[]).map(t=>t.function.name))].sort()}var Eu=class{transport;apiKey;toolInvoker;log;hooks;configuredMaxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.configuredMaxRounds=typeof t.maxRounds=="number"&&Number.isFinite(t.maxRounds)&&t.maxRounds>=1?Math.round(t.maxRounds):void 0}async*run(t,n){let{turnId:r,messages:o,availableTools:s,tools:i,systemPrompt:l,config:a}=t,c={sessionId:t.sessionId,turnId:r},u=[...o].reverse().find(E=>E.role==="user"&&typeof E.content=="string")?.content,d=!1,h=()=>({type:"tool_use_summary",turnId:r,telemetrySource:"agent",ledgerSchemaVersion:5,toolCalls:[],availableToolNames:Ru(s??i),enabledToolNames:Ru(i),toolCallNames:[],blockedToolCalls:[]}),T=typeof a?.maxRounds=="number"&&Number.isFinite(a.maxRounds)?a.maxRounds:this.configuredMaxRounds,p=T===void 0?void 0:Math.round(T),m=typeof a?.maxToolCalls=="number"&&Number.isFinite(a.maxToolCalls)?a.maxToolCalls:void 0,_=kr(m);yield{type:"start",turnId:r,effectiveMaxRounds:br(p,o),..._!==void 0?{effectiveMaxToolCalls:_}:{}};try{H(this.hooks,"turn.submitted",{...c,prompt:o[o.length-1]?.content??void 0},this.log);let E=Hr(o),w=[];l&&w.push({role:"system",content:l}),w.push(...E);let q=a?.model??"",R=a?.reasoning;a?.reasoning?.effort==="auto"&&(R={...a?.reasoning,effort:"medium"});let Q={turnId:r,sessionId:t.sessionId,messages:w,availableTools:s,tools:i,deferredToolNames:t.deferredToolNames,loadedDeferredToolNames:t.loadedDeferredToolNames,refreshTools:t.refreshTools,drainPendingGuidance:t.drainPendingGuidance,drainPendingTaskNotifications:t.drainPendingTaskNotifications,sanitizeToolResultMedia:t.sanitizeToolResultMedia,model:q,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:p,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,maxConcurrentTools:a?.maxConcurrentTools,streamRequired:a?.streamRequired,reasoning:R,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:m,parallelToolCalls:a?.parallelToolCalls??!1,textVerbosity:a?.textVerbosity,projectRoot:this.projectRoot,runtimePorts:this.runtimePorts.toolLoop,signal:n};for await(let W of Cu(Q,this.transport,this.toolInvoker,this.log))W.type==="tool_use_summary"&&(d=!0),W.type==="end"?H(this.hooks,"turn.completed",{...c,...u?{prompt:u}:{},response:W.content},this.log):W.type==="error"&&H(this.hooks,"turn.failed",{...c,code:W.code,error:W.error},this.log),yield W}catch(E){if(d||(d=!0,yield h()),n?.aborted)H(this.hooks,"turn.failed",{...c,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};else{let w=E instanceof Error?E.message:String(E),q=typeof E?.status=="number"?E.status:void 0,R=Tt(q,w);this.log.error(`turn ${r} error [${R}, retryable=${Ln(R)}]: ${w}`),H(this.hooks,"turn.failed",{...c,code:R,error:w},this.log),yield{type:"error",turnId:r,error:w,code:R}}}}};export{Eu as Agent};